]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/ctl.c
MFC r284641:
[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  * All rights reserved.
5  *
6  * Portions of this software were developed by Edward Tomasz Napierala
7  * under sponsorship from the FreeBSD Foundation.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions, and the following disclaimer,
14  *    without modification.
15  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
16  *    substantially similar to the "NO WARRANTY" disclaimer below
17  *    ("Disclaimer") and any redistribution must be conditioned upon
18  *    including a substantially similar Disclaimer requirement for further
19  *    binary redistribution.
20  *
21  * NO WARRANTY
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
25  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
31  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGES.
33  *
34  * $Id$
35  */
36 /*
37  * CAM Target Layer, a SCSI device emulation subsystem.
38  *
39  * Author: Ken Merry <ken@FreeBSD.org>
40  */
41
42 #define _CTL_C
43
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/ctype.h>
50 #include <sys/kernel.h>
51 #include <sys/types.h>
52 #include <sys/kthread.h>
53 #include <sys/bio.h>
54 #include <sys/fcntl.h>
55 #include <sys/lock.h>
56 #include <sys/module.h>
57 #include <sys/mutex.h>
58 #include <sys/condvar.h>
59 #include <sys/malloc.h>
60 #include <sys/conf.h>
61 #include <sys/ioccom.h>
62 #include <sys/queue.h>
63 #include <sys/sbuf.h>
64 #include <sys/smp.h>
65 #include <sys/endian.h>
66 #include <sys/sysctl.h>
67 #include <vm/uma.h>
68
69 #include <cam/cam.h>
70 #include <cam/scsi/scsi_all.h>
71 #include <cam/scsi/scsi_da.h>
72 #include <cam/ctl/ctl_io.h>
73 #include <cam/ctl/ctl.h>
74 #include <cam/ctl/ctl_frontend.h>
75 #include <cam/ctl/ctl_frontend_internal.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  * Size and alignment macros needed for Copan-specific HA hardware.  These
89  * can go away when the HA code is re-written, and uses busdma for any
90  * hardware.
91  */
92 #define CTL_ALIGN_8B(target, source, type)                              \
93         if (((uint32_t)source & 0x7) != 0)                              \
94                 target = (type)(source + (0x8 - ((uint32_t)source & 0x7)));\
95         else                                                            \
96                 target = (type)source;
97
98 #define CTL_SIZE_8B(target, size)                                       \
99         if ((size & 0x7) != 0)                                          \
100                 target = size + (0x8 - (size & 0x7));                   \
101         else                                                            \
102                 target = size;
103
104 #define CTL_ALIGN_8B_MARGIN     16
105
106 /*
107  * Template mode pages.
108  */
109
110 /*
111  * Note that these are default values only.  The actual values will be
112  * filled in when the user does a mode sense.
113  */
114 const static struct copan_debugconf_subpage debugconf_page_default = {
115         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
116         DBGCNF_SUBPAGE_CODE,            /* subpage */
117         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
118          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
119         DBGCNF_VERSION,                 /* page_version */
120         {CTL_TIME_IO_DEFAULT_SECS>>8,
121          CTL_TIME_IO_DEFAULT_SECS>>0},  /* ctl_time_io_secs */
122 };
123
124 const static struct copan_debugconf_subpage debugconf_page_changeable = {
125         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
126         DBGCNF_SUBPAGE_CODE,            /* subpage */
127         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
128          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
129         0,                              /* page_version */
130         {0xff,0xff},                    /* ctl_time_io_secs */
131 };
132
133 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
134         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
135         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
136         /*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
137         /*read_retry_count*/0,
138         /*correction_span*/0,
139         /*head_offset_count*/0,
140         /*data_strobe_offset_cnt*/0,
141         /*byte8*/SMS_RWER_LBPERE,
142         /*write_retry_count*/0,
143         /*reserved2*/0,
144         /*recovery_time_limit*/{0, 0},
145 };
146
147 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
148         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
149         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
150         /*byte3*/0,
151         /*read_retry_count*/0,
152         /*correction_span*/0,
153         /*head_offset_count*/0,
154         /*data_strobe_offset_cnt*/0,
155         /*byte8*/0,
156         /*write_retry_count*/0,
157         /*reserved2*/0,
158         /*recovery_time_limit*/{0, 0},
159 };
160
161 const static struct scsi_format_page format_page_default = {
162         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
163         /*page_length*/sizeof(struct scsi_format_page) - 2,
164         /*tracks_per_zone*/ {0, 0},
165         /*alt_sectors_per_zone*/ {0, 0},
166         /*alt_tracks_per_zone*/ {0, 0},
167         /*alt_tracks_per_lun*/ {0, 0},
168         /*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
169                                 CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
170         /*bytes_per_sector*/ {0, 0},
171         /*interleave*/ {0, 0},
172         /*track_skew*/ {0, 0},
173         /*cylinder_skew*/ {0, 0},
174         /*flags*/ SFP_HSEC,
175         /*reserved*/ {0, 0, 0}
176 };
177
178 const static struct scsi_format_page format_page_changeable = {
179         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
180         /*page_length*/sizeof(struct scsi_format_page) - 2,
181         /*tracks_per_zone*/ {0, 0},
182         /*alt_sectors_per_zone*/ {0, 0},
183         /*alt_tracks_per_zone*/ {0, 0},
184         /*alt_tracks_per_lun*/ {0, 0},
185         /*sectors_per_track*/ {0, 0},
186         /*bytes_per_sector*/ {0, 0},
187         /*interleave*/ {0, 0},
188         /*track_skew*/ {0, 0},
189         /*cylinder_skew*/ {0, 0},
190         /*flags*/ 0,
191         /*reserved*/ {0, 0, 0}
192 };
193
194 const static struct scsi_rigid_disk_page rigid_disk_page_default = {
195         /*page_code*/SMS_RIGID_DISK_PAGE,
196         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
197         /*cylinders*/ {0, 0, 0},
198         /*heads*/ CTL_DEFAULT_HEADS,
199         /*start_write_precomp*/ {0, 0, 0},
200         /*start_reduced_current*/ {0, 0, 0},
201         /*step_rate*/ {0, 0},
202         /*landing_zone_cylinder*/ {0, 0, 0},
203         /*rpl*/ SRDP_RPL_DISABLED,
204         /*rotational_offset*/ 0,
205         /*reserved1*/ 0,
206         /*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
207                            CTL_DEFAULT_ROTATION_RATE & 0xff},
208         /*reserved2*/ {0, 0}
209 };
210
211 const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
212         /*page_code*/SMS_RIGID_DISK_PAGE,
213         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
214         /*cylinders*/ {0, 0, 0},
215         /*heads*/ 0,
216         /*start_write_precomp*/ {0, 0, 0},
217         /*start_reduced_current*/ {0, 0, 0},
218         /*step_rate*/ {0, 0},
219         /*landing_zone_cylinder*/ {0, 0, 0},
220         /*rpl*/ 0,
221         /*rotational_offset*/ 0,
222         /*reserved1*/ 0,
223         /*rotation_rate*/ {0, 0},
224         /*reserved2*/ {0, 0}
225 };
226
227 const static struct scsi_caching_page caching_page_default = {
228         /*page_code*/SMS_CACHING_PAGE,
229         /*page_length*/sizeof(struct scsi_caching_page) - 2,
230         /*flags1*/ SCP_DISC | SCP_WCE,
231         /*ret_priority*/ 0,
232         /*disable_pf_transfer_len*/ {0xff, 0xff},
233         /*min_prefetch*/ {0, 0},
234         /*max_prefetch*/ {0xff, 0xff},
235         /*max_pf_ceiling*/ {0xff, 0xff},
236         /*flags2*/ 0,
237         /*cache_segments*/ 0,
238         /*cache_seg_size*/ {0, 0},
239         /*reserved*/ 0,
240         /*non_cache_seg_size*/ {0, 0, 0}
241 };
242
243 const static struct scsi_caching_page caching_page_changeable = {
244         /*page_code*/SMS_CACHING_PAGE,
245         /*page_length*/sizeof(struct scsi_caching_page) - 2,
246         /*flags1*/ SCP_WCE | SCP_RCD,
247         /*ret_priority*/ 0,
248         /*disable_pf_transfer_len*/ {0, 0},
249         /*min_prefetch*/ {0, 0},
250         /*max_prefetch*/ {0, 0},
251         /*max_pf_ceiling*/ {0, 0},
252         /*flags2*/ 0,
253         /*cache_segments*/ 0,
254         /*cache_seg_size*/ {0, 0},
255         /*reserved*/ 0,
256         /*non_cache_seg_size*/ {0, 0, 0}
257 };
258
259 const static struct scsi_control_page control_page_default = {
260         /*page_code*/SMS_CONTROL_MODE_PAGE,
261         /*page_length*/sizeof(struct scsi_control_page) - 2,
262         /*rlec*/0,
263         /*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
264         /*eca_and_aen*/0,
265         /*flags4*/SCP_TAS,
266         /*aen_holdoff_period*/{0, 0},
267         /*busy_timeout_period*/{0, 0},
268         /*extended_selftest_completion_time*/{0, 0}
269 };
270
271 const static struct scsi_control_page control_page_changeable = {
272         /*page_code*/SMS_CONTROL_MODE_PAGE,
273         /*page_length*/sizeof(struct scsi_control_page) - 2,
274         /*rlec*/SCP_DSENSE,
275         /*queue_flags*/SCP_QUEUE_ALG_MASK,
276         /*eca_and_aen*/SCP_SWP,
277         /*flags4*/0,
278         /*aen_holdoff_period*/{0, 0},
279         /*busy_timeout_period*/{0, 0},
280         /*extended_selftest_completion_time*/{0, 0}
281 };
282
283 const static struct scsi_info_exceptions_page ie_page_default = {
284         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
285         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
286         /*info_flags*/SIEP_FLAGS_DEXCPT,
287         /*mrie*/0,
288         /*interval_timer*/{0, 0, 0, 0},
289         /*report_count*/{0, 0, 0, 0}
290 };
291
292 const static struct scsi_info_exceptions_page ie_page_changeable = {
293         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
294         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
295         /*info_flags*/0,
296         /*mrie*/0,
297         /*interval_timer*/{0, 0, 0, 0},
298         /*report_count*/{0, 0, 0, 0}
299 };
300
301 #define CTL_LBPM_LEN    (sizeof(struct ctl_logical_block_provisioning_page) - 4)
302
303 const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
304         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
305         /*subpage_code*/0x02,
306         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
307         /*flags*/0,
308         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
309         /*descr*/{}},
310         {{/*flags*/0,
311           /*resource*/0x01,
312           /*reserved*/{0, 0},
313           /*count*/{0, 0, 0, 0}},
314          {/*flags*/0,
315           /*resource*/0x02,
316           /*reserved*/{0, 0},
317           /*count*/{0, 0, 0, 0}},
318          {/*flags*/0,
319           /*resource*/0xf1,
320           /*reserved*/{0, 0},
321           /*count*/{0, 0, 0, 0}},
322          {/*flags*/0,
323           /*resource*/0xf2,
324           /*reserved*/{0, 0},
325           /*count*/{0, 0, 0, 0}}
326         }
327 };
328
329 const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
330         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
331         /*subpage_code*/0x02,
332         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
333         /*flags*/0,
334         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
335         /*descr*/{}},
336         {{/*flags*/0,
337           /*resource*/0,
338           /*reserved*/{0, 0},
339           /*count*/{0, 0, 0, 0}},
340          {/*flags*/0,
341           /*resource*/0,
342           /*reserved*/{0, 0},
343           /*count*/{0, 0, 0, 0}},
344          {/*flags*/0,
345           /*resource*/0,
346           /*reserved*/{0, 0},
347           /*count*/{0, 0, 0, 0}},
348          {/*flags*/0,
349           /*resource*/0,
350           /*reserved*/{0, 0},
351           /*count*/{0, 0, 0, 0}}
352         }
353 };
354
355 /*
356  * XXX KDM move these into the softc.
357  */
358 static int rcv_sync_msg;
359 static uint8_t ctl_pause_rtr;
360
361 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
362 static int worker_threads = -1;
363 TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
364 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
365     &worker_threads, 1, "Number of worker threads");
366 static int ctl_debug = CTL_DEBUG_NONE;
367 TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
368 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
369     &ctl_debug, 0, "Enabled debug flags");
370
371 /*
372  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
373  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
374  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
375  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
376  */
377 #define SCSI_EVPD_NUM_SUPPORTED_PAGES   10
378
379 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
380                                   int param);
381 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
382 static int ctl_init(void);
383 void ctl_shutdown(void);
384 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
385 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
386 static void ctl_ioctl_online(void *arg);
387 static void ctl_ioctl_offline(void *arg);
388 static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
389 static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
390 static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
391 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
392 static int ctl_ioctl_submit_wait(union ctl_io *io);
393 static void ctl_ioctl_datamove(union ctl_io *io);
394 static void ctl_ioctl_done(union ctl_io *io);
395 static void ctl_ioctl_hard_startstop_callback(void *arg,
396                                               struct cfi_metatask *metatask);
397 static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
398 static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
399                               struct ctl_ooa *ooa_hdr,
400                               struct ctl_ooa_entry *kern_entries);
401 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
402                      struct thread *td);
403 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
404                          struct ctl_be_lun *be_lun, struct ctl_id target_id);
405 static int ctl_free_lun(struct ctl_lun *lun);
406 static void ctl_create_lun(struct ctl_be_lun *be_lun);
407 static struct ctl_port * ctl_io_port(struct ctl_io_hdr *io_hdr);
408 /**
409 static void ctl_failover_change_pages(struct ctl_softc *softc,
410                                       struct ctl_scsiio *ctsio, int master);
411 **/
412
413 static int ctl_do_mode_select(union ctl_io *io);
414 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
415                            uint64_t res_key, uint64_t sa_res_key,
416                            uint8_t type, uint32_t residx,
417                            struct ctl_scsiio *ctsio,
418                            struct scsi_per_res_out *cdb,
419                            struct scsi_per_res_out_parms* param);
420 static void ctl_pro_preempt_other(struct ctl_lun *lun,
421                                   union ctl_ha_msg *msg);
422 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
423 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
424 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
425 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
426 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
427 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
428 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
429                                          int alloc_len);
430 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
431                                          int alloc_len);
432 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
433 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
434 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
435 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
436 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
437 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
438     bool seq);
439 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
440 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
441     union ctl_io *pending_io, union ctl_io *ooa_io);
442 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
443                                 union ctl_io *starting_io);
444 static int ctl_check_blocked(struct ctl_lun *lun);
445 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
446                                 const struct ctl_cmd_entry *entry,
447                                 struct ctl_scsiio *ctsio);
448 //static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
449 static void ctl_failover(void);
450 static void ctl_clear_ua(struct ctl_softc *ctl_softc, uint32_t initidx,
451                          ctl_ua_type ua_type);
452 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
453                                struct ctl_scsiio *ctsio);
454 static int ctl_scsiio(struct ctl_scsiio *ctsio);
455
456 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
457 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
458                             ctl_ua_type ua_type);
459 static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
460                          ctl_ua_type ua_type);
461 static int ctl_abort_task(union ctl_io *io);
462 static int ctl_abort_task_set(union ctl_io *io);
463 static int ctl_i_t_nexus_reset(union ctl_io *io);
464 static void ctl_run_task(union ctl_io *io);
465 #ifdef CTL_IO_DELAY
466 static void ctl_datamove_timer_wakeup(void *arg);
467 static void ctl_done_timer_wakeup(void *arg);
468 #endif /* CTL_IO_DELAY */
469
470 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
471 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
472 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
473 static void ctl_datamove_remote_write(union ctl_io *io);
474 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
475 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
476 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
477 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
478                                     ctl_ha_dt_cb callback);
479 static void ctl_datamove_remote_read(union ctl_io *io);
480 static void ctl_datamove_remote(union ctl_io *io);
481 static int ctl_process_done(union ctl_io *io);
482 static void ctl_lun_thread(void *arg);
483 static void ctl_thresh_thread(void *arg);
484 static void ctl_work_thread(void *arg);
485 static void ctl_enqueue_incoming(union ctl_io *io);
486 static void ctl_enqueue_rtr(union ctl_io *io);
487 static void ctl_enqueue_done(union ctl_io *io);
488 static void ctl_enqueue_isc(union ctl_io *io);
489 static const struct ctl_cmd_entry *
490     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
491 static const struct ctl_cmd_entry *
492     ctl_validate_command(struct ctl_scsiio *ctsio);
493 static int ctl_cmd_applicable(uint8_t lun_type,
494     const struct ctl_cmd_entry *entry);
495
496 /*
497  * Load the serialization table.  This isn't very pretty, but is probably
498  * the easiest way to do it.
499  */
500 #include "ctl_ser_table.c"
501
502 /*
503  * We only need to define open, close and ioctl routines for this driver.
504  */
505 static struct cdevsw ctl_cdevsw = {
506         .d_version =    D_VERSION,
507         .d_flags =      0,
508         .d_open =       ctl_open,
509         .d_close =      ctl_close,
510         .d_ioctl =      ctl_ioctl,
511         .d_name =       "ctl",
512 };
513
514
515 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
516 MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
517
518 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
519
520 static moduledata_t ctl_moduledata = {
521         "ctl",
522         ctl_module_event_handler,
523         NULL
524 };
525
526 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
527 MODULE_VERSION(ctl, 1);
528
529 static struct ctl_frontend ioctl_frontend =
530 {
531         .name = "ioctl",
532 };
533
534 static void
535 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
536                             union ctl_ha_msg *msg_info)
537 {
538         struct ctl_scsiio *ctsio;
539
540         if (msg_info->hdr.original_sc == NULL) {
541                 printf("%s: original_sc == NULL!\n", __func__);
542                 /* XXX KDM now what? */
543                 return;
544         }
545
546         ctsio = &msg_info->hdr.original_sc->scsiio;
547         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
548         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
549         ctsio->io_hdr.status = msg_info->hdr.status;
550         ctsio->scsi_status = msg_info->scsi.scsi_status;
551         ctsio->sense_len = msg_info->scsi.sense_len;
552         ctsio->sense_residual = msg_info->scsi.sense_residual;
553         ctsio->residual = msg_info->scsi.residual;
554         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
555                sizeof(ctsio->sense_data));
556         memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
557                &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
558         ctl_enqueue_isc((union ctl_io *)ctsio);
559 }
560
561 static void
562 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
563                                 union ctl_ha_msg *msg_info)
564 {
565         struct ctl_scsiio *ctsio;
566
567         if (msg_info->hdr.serializing_sc == NULL) {
568                 printf("%s: serializing_sc == NULL!\n", __func__);
569                 /* XXX KDM now what? */
570                 return;
571         }
572
573         ctsio = &msg_info->hdr.serializing_sc->scsiio;
574 #if 0
575         /*
576          * Attempt to catch the situation where an I/O has
577          * been freed, and we're using it again.
578          */
579         if (ctsio->io_hdr.io_type == 0xff) {
580                 union ctl_io *tmp_io;
581                 tmp_io = (union ctl_io *)ctsio;
582                 printf("%s: %p use after free!\n", __func__,
583                        ctsio);
584                 printf("%s: type %d msg %d cdb %x iptl: "
585                        "%d:%d:%d:%d tag 0x%04x "
586                        "flag %#x status %x\n",
587                         __func__,
588                         tmp_io->io_hdr.io_type,
589                         tmp_io->io_hdr.msg_type,
590                         tmp_io->scsiio.cdb[0],
591                         tmp_io->io_hdr.nexus.initid.id,
592                         tmp_io->io_hdr.nexus.targ_port,
593                         tmp_io->io_hdr.nexus.targ_target.id,
594                         tmp_io->io_hdr.nexus.targ_lun,
595                         (tmp_io->io_hdr.io_type ==
596                         CTL_IO_TASK) ?
597                         tmp_io->taskio.tag_num :
598                         tmp_io->scsiio.tag_num,
599                         tmp_io->io_hdr.flags,
600                         tmp_io->io_hdr.status);
601         }
602 #endif
603         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
604         ctl_enqueue_isc((union ctl_io *)ctsio);
605 }
606
607 /*
608  * ISC (Inter Shelf Communication) event handler.  Events from the HA
609  * subsystem come in here.
610  */
611 static void
612 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
613 {
614         struct ctl_softc *softc;
615         union ctl_io *io;
616         struct ctl_prio *presio;
617         ctl_ha_status isc_status;
618
619         softc = control_softc;
620         io = NULL;
621
622
623 #if 0
624         printf("CTL: Isc Msg event %d\n", event);
625 #endif
626         if (event == CTL_HA_EVT_MSG_RECV) {
627                 union ctl_ha_msg msg_info;
628
629                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
630                                              sizeof(msg_info), /*wait*/ 0);
631 #if 0
632                 printf("CTL: msg_type %d\n", msg_info.msg_type);
633 #endif
634                 if (isc_status != 0) {
635                         printf("Error receiving message, status = %d\n",
636                                isc_status);
637                         return;
638                 }
639
640                 switch (msg_info.hdr.msg_type) {
641                 case CTL_MSG_SERIALIZE:
642 #if 0
643                         printf("Serialize\n");
644 #endif
645                         io = ctl_alloc_io_nowait(softc->othersc_pool);
646                         if (io == NULL) {
647                                 printf("ctl_isc_event_handler: can't allocate "
648                                        "ctl_io!\n");
649                                 /* Bad Juju */
650                                 /* Need to set busy and send msg back */
651                                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
652                                 msg_info.hdr.status = CTL_SCSI_ERROR;
653                                 msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
654                                 msg_info.scsi.sense_len = 0;
655                                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
656                                     sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
657                                 }
658                                 goto bailout;
659                         }
660                         ctl_zero_io(io);
661                         // populate ctsio from msg_info
662                         io->io_hdr.io_type = CTL_IO_SCSI;
663                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
664                         io->io_hdr.original_sc = msg_info.hdr.original_sc;
665 #if 0
666                         printf("pOrig %x\n", (int)msg_info.original_sc);
667 #endif
668                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
669                                             CTL_FLAG_IO_ACTIVE;
670                         /*
671                          * If we're in serialization-only mode, we don't
672                          * want to go through full done processing.  Thus
673                          * the COPY flag.
674                          *
675                          * XXX KDM add another flag that is more specific.
676                          */
677                         if (softc->ha_mode == CTL_HA_MODE_SER_ONLY)
678                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
679                         io->io_hdr.nexus = msg_info.hdr.nexus;
680 #if 0
681                         printf("targ %d, port %d, iid %d, lun %d\n",
682                                io->io_hdr.nexus.targ_target.id,
683                                io->io_hdr.nexus.targ_port,
684                                io->io_hdr.nexus.initid.id,
685                                io->io_hdr.nexus.targ_lun);
686 #endif
687                         io->scsiio.tag_num = msg_info.scsi.tag_num;
688                         io->scsiio.tag_type = msg_info.scsi.tag_type;
689                         memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
690                                CTL_MAX_CDBLEN);
691                         if (softc->ha_mode == CTL_HA_MODE_XFER) {
692                                 const struct ctl_cmd_entry *entry;
693
694                                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
695                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
696                                 io->io_hdr.flags |=
697                                         entry->flags & CTL_FLAG_DATA_MASK;
698                         }
699                         ctl_enqueue_isc(io);
700                         break;
701
702                 /* Performed on the Originating SC, XFER mode only */
703                 case CTL_MSG_DATAMOVE: {
704                         struct ctl_sg_entry *sgl;
705                         int i, j;
706
707                         io = msg_info.hdr.original_sc;
708                         if (io == NULL) {
709                                 printf("%s: original_sc == NULL!\n", __func__);
710                                 /* XXX KDM do something here */
711                                 break;
712                         }
713                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
714                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
715                         /*
716                          * Keep track of this, we need to send it back over
717                          * when the datamove is complete.
718                          */
719                         io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
720
721                         if (msg_info.dt.sg_sequence == 0) {
722                                 /*
723                                  * XXX KDM we use the preallocated S/G list
724                                  * here, but we'll need to change this to
725                                  * dynamic allocation if we need larger S/G
726                                  * lists.
727                                  */
728                                 if (msg_info.dt.kern_sg_entries >
729                                     sizeof(io->io_hdr.remote_sglist) /
730                                     sizeof(io->io_hdr.remote_sglist[0])) {
731                                         printf("%s: number of S/G entries "
732                                             "needed %u > allocated num %zd\n",
733                                             __func__,
734                                             msg_info.dt.kern_sg_entries,
735                                             sizeof(io->io_hdr.remote_sglist)/
736                                             sizeof(io->io_hdr.remote_sglist[0]));
737                                 
738                                         /*
739                                          * XXX KDM send a message back to
740                                          * the other side to shut down the
741                                          * DMA.  The error will come back
742                                          * through via the normal channel.
743                                          */
744                                         break;
745                                 }
746                                 sgl = io->io_hdr.remote_sglist;
747                                 memset(sgl, 0,
748                                        sizeof(io->io_hdr.remote_sglist));
749
750                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
751
752                                 io->scsiio.kern_sg_entries =
753                                         msg_info.dt.kern_sg_entries;
754                                 io->scsiio.rem_sg_entries =
755                                         msg_info.dt.kern_sg_entries;
756                                 io->scsiio.kern_data_len =
757                                         msg_info.dt.kern_data_len;
758                                 io->scsiio.kern_total_len =
759                                         msg_info.dt.kern_total_len;
760                                 io->scsiio.kern_data_resid =
761                                         msg_info.dt.kern_data_resid;
762                                 io->scsiio.kern_rel_offset =
763                                         msg_info.dt.kern_rel_offset;
764                                 /*
765                                  * Clear out per-DMA flags.
766                                  */
767                                 io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
768                                 /*
769                                  * Add per-DMA flags that are set for this
770                                  * particular DMA request.
771                                  */
772                                 io->io_hdr.flags |= msg_info.dt.flags &
773                                                     CTL_FLAG_RDMA_MASK;
774                         } else
775                                 sgl = (struct ctl_sg_entry *)
776                                         io->scsiio.kern_data_ptr;
777
778                         for (i = msg_info.dt.sent_sg_entries, j = 0;
779                              i < (msg_info.dt.sent_sg_entries +
780                              msg_info.dt.cur_sg_entries); i++, j++) {
781                                 sgl[i].addr = msg_info.dt.sg_list[j].addr;
782                                 sgl[i].len = msg_info.dt.sg_list[j].len;
783
784 #if 0
785                                 printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
786                                        __func__,
787                                        msg_info.dt.sg_list[j].addr,
788                                        msg_info.dt.sg_list[j].len,
789                                        sgl[i].addr, sgl[i].len, j, i);
790 #endif
791                         }
792 #if 0
793                         memcpy(&sgl[msg_info.dt.sent_sg_entries],
794                                msg_info.dt.sg_list,
795                                sizeof(*sgl) * msg_info.dt.cur_sg_entries);
796 #endif
797
798                         /*
799                          * If this is the last piece of the I/O, we've got
800                          * the full S/G list.  Queue processing in the thread.
801                          * Otherwise wait for the next piece.
802                          */
803                         if (msg_info.dt.sg_last != 0)
804                                 ctl_enqueue_isc(io);
805                         break;
806                 }
807                 /* Performed on the Serializing (primary) SC, XFER mode only */
808                 case CTL_MSG_DATAMOVE_DONE: {
809                         if (msg_info.hdr.serializing_sc == NULL) {
810                                 printf("%s: serializing_sc == NULL!\n",
811                                        __func__);
812                                 /* XXX KDM now what? */
813                                 break;
814                         }
815                         /*
816                          * We grab the sense information here in case
817                          * there was a failure, so we can return status
818                          * back to the initiator.
819                          */
820                         io = msg_info.hdr.serializing_sc;
821                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
822                         io->io_hdr.status = msg_info.hdr.status;
823                         io->scsiio.scsi_status = msg_info.scsi.scsi_status;
824                         io->scsiio.sense_len = msg_info.scsi.sense_len;
825                         io->scsiio.sense_residual =msg_info.scsi.sense_residual;
826                         io->io_hdr.port_status = msg_info.scsi.fetd_status;
827                         io->scsiio.residual = msg_info.scsi.residual;
828                         memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
829                                sizeof(io->scsiio.sense_data));
830                         ctl_enqueue_isc(io);
831                         break;
832                 }
833
834                 /* Preformed on Originating SC, SER_ONLY mode */
835                 case CTL_MSG_R2R:
836                         io = msg_info.hdr.original_sc;
837                         if (io == NULL) {
838                                 printf("%s: Major Bummer\n", __func__);
839                                 return;
840                         } else {
841 #if 0
842                                 printf("pOrig %x\n",(int) ctsio);
843 #endif
844                         }
845                         io->io_hdr.msg_type = CTL_MSG_R2R;
846                         io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
847                         ctl_enqueue_isc(io);
848                         break;
849
850                 /*
851                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
852                  * mode.
853                  * Performed on the Originating (i.e. secondary) SC in XFER
854                  * mode
855                  */
856                 case CTL_MSG_FINISH_IO:
857                         if (softc->ha_mode == CTL_HA_MODE_XFER)
858                                 ctl_isc_handler_finish_xfer(softc,
859                                                             &msg_info);
860                         else
861                                 ctl_isc_handler_finish_ser_only(softc,
862                                                                 &msg_info);
863                         break;
864
865                 /* Preformed on Originating SC */
866                 case CTL_MSG_BAD_JUJU:
867                         io = msg_info.hdr.original_sc;
868                         if (io == NULL) {
869                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
870                                        __func__);
871                                 break;
872                         }
873                         ctl_copy_sense_data(&msg_info, io);
874                         /*
875                          * IO should have already been cleaned up on other
876                          * SC so clear this flag so we won't send a message
877                          * back to finish the IO there.
878                          */
879                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
880                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
881
882                         /* io = msg_info.hdr.serializing_sc; */
883                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
884                         ctl_enqueue_isc(io);
885                         break;
886
887                 /* Handle resets sent from the other side */
888                 case CTL_MSG_MANAGE_TASKS: {
889                         struct ctl_taskio *taskio;
890                         taskio = (struct ctl_taskio *)ctl_alloc_io_nowait(
891                             softc->othersc_pool);
892                         if (taskio == NULL) {
893                                 printf("ctl_isc_event_handler: can't allocate "
894                                        "ctl_io!\n");
895                                 /* Bad Juju */
896                                 /* should I just call the proper reset func
897                                    here??? */
898                                 goto bailout;
899                         }
900                         ctl_zero_io((union ctl_io *)taskio);
901                         taskio->io_hdr.io_type = CTL_IO_TASK;
902                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
903                         taskio->io_hdr.nexus = msg_info.hdr.nexus;
904                         taskio->task_action = msg_info.task.task_action;
905                         taskio->tag_num = msg_info.task.tag_num;
906                         taskio->tag_type = msg_info.task.tag_type;
907 #ifdef CTL_TIME_IO
908                         taskio->io_hdr.start_time = time_uptime;
909                         getbintime(&taskio->io_hdr.start_bt);
910 #if 0
911                         cs_prof_gettime(&taskio->io_hdr.start_ticks);
912 #endif
913 #endif /* CTL_TIME_IO */
914                         ctl_run_task((union ctl_io *)taskio);
915                         break;
916                 }
917                 /* Persistent Reserve action which needs attention */
918                 case CTL_MSG_PERS_ACTION:
919                         presio = (struct ctl_prio *)ctl_alloc_io_nowait(
920                             softc->othersc_pool);
921                         if (presio == NULL) {
922                                 printf("ctl_isc_event_handler: can't allocate "
923                                        "ctl_io!\n");
924                                 /* Bad Juju */
925                                 /* Need to set busy and send msg back */
926                                 goto bailout;
927                         }
928                         ctl_zero_io((union ctl_io *)presio);
929                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
930                         presio->pr_msg = msg_info.pr;
931                         ctl_enqueue_isc((union ctl_io *)presio);
932                         break;
933                 case CTL_MSG_SYNC_FE:
934                         rcv_sync_msg = 1;
935                         break;
936                 default:
937                         printf("How did I get here?\n");
938                 }
939         } else if (event == CTL_HA_EVT_MSG_SENT) {
940                 if (param != CTL_HA_STATUS_SUCCESS) {
941                         printf("Bad status from ctl_ha_msg_send status %d\n",
942                                param);
943                 }
944                 return;
945         } else if (event == CTL_HA_EVT_DISCONNECT) {
946                 printf("CTL: Got a disconnect from Isc\n");
947                 return;
948         } else {
949                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
950                 return;
951         }
952
953 bailout:
954         return;
955 }
956
957 static void
958 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
959 {
960         struct scsi_sense_data *sense;
961
962         sense = &dest->scsiio.sense_data;
963         bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
964         dest->scsiio.scsi_status = src->scsi.scsi_status;
965         dest->scsiio.sense_len = src->scsi.sense_len;
966         dest->io_hdr.status = src->hdr.status;
967 }
968
969 static void
970 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
971 {
972         ctl_ua_type *pu;
973
974         mtx_assert(&lun->lun_lock, MA_OWNED);
975         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
976         if (pu == NULL)
977                 return;
978         pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
979 }
980
981 static void
982 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
983 {
984         int i, j;
985
986         mtx_assert(&lun->lun_lock, MA_OWNED);
987         for (i = 0; i < CTL_MAX_PORTS; i++) {
988                 if (lun->pending_ua[i] == NULL)
989                         continue;
990                 for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
991                         if (i * CTL_MAX_INIT_PER_PORT + j == except)
992                                 continue;
993                         lun->pending_ua[i][j] |= ua;
994                 }
995         }
996 }
997
998 static void
999 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1000 {
1001         ctl_ua_type *pu;
1002
1003         mtx_assert(&lun->lun_lock, MA_OWNED);
1004         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1005         if (pu == NULL)
1006                 return;
1007         pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1008 }
1009
1010 static void
1011 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1012 {
1013         int i, j;
1014
1015         mtx_assert(&lun->lun_lock, MA_OWNED);
1016         for (i = 0; i < CTL_MAX_PORTS; i++) {
1017                 if (lun->pending_ua[i] == NULL)
1018                         continue;
1019                 for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1020                         if (i * CTL_MAX_INIT_PER_PORT + j == except)
1021                                 continue;
1022                         lun->pending_ua[i][j] &= ~ua;
1023                 }
1024         }
1025 }
1026
1027 static int
1028 ctl_ha_state_sysctl(SYSCTL_HANDLER_ARGS)
1029 {
1030         struct ctl_softc *softc = (struct ctl_softc *)arg1;
1031         struct ctl_lun *lun;
1032         int error, value;
1033
1034         if (softc->flags & CTL_FLAG_ACTIVE_SHELF)
1035                 value = 0;
1036         else
1037                 value = 1;
1038
1039         error = sysctl_handle_int(oidp, &value, 0, req);
1040         if ((error != 0) || (req->newptr == NULL))
1041                 return (error);
1042
1043         mtx_lock(&softc->ctl_lock);
1044         if (value == 0)
1045                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1046         else
1047                 softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1048         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1049                 mtx_lock(&lun->lun_lock);
1050                 ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1051                 mtx_unlock(&lun->lun_lock);
1052         }
1053         mtx_unlock(&softc->ctl_lock);
1054         return (0);
1055 }
1056
1057 static int
1058 ctl_init(void)
1059 {
1060         struct ctl_softc *softc;
1061         void *other_pool;
1062         struct ctl_port *port;
1063         int i, error, retval;
1064         //int isc_retval;
1065
1066         retval = 0;
1067         ctl_pause_rtr = 0;
1068         rcv_sync_msg = 0;
1069
1070         control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1071                                M_WAITOK | M_ZERO);
1072         softc = control_softc;
1073
1074         softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1075                               "cam/ctl");
1076
1077         softc->dev->si_drv1 = softc;
1078
1079         /*
1080          * By default, return a "bad LUN" peripheral qualifier for unknown
1081          * LUNs.  The user can override this default using the tunable or
1082          * sysctl.  See the comment in ctl_inquiry_std() for more details.
1083          */
1084         softc->inquiry_pq_no_lun = 1;
1085         TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
1086                           &softc->inquiry_pq_no_lun);
1087         sysctl_ctx_init(&softc->sysctl_ctx);
1088         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1089                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1090                 CTLFLAG_RD, 0, "CAM Target Layer");
1091
1092         if (softc->sysctl_tree == NULL) {
1093                 printf("%s: unable to allocate sysctl tree\n", __func__);
1094                 destroy_dev(softc->dev);
1095                 free(control_softc, M_DEVBUF);
1096                 control_softc = NULL;
1097                 return (ENOMEM);
1098         }
1099
1100         SYSCTL_ADD_INT(&softc->sysctl_ctx,
1101                        SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1102                        "inquiry_pq_no_lun", CTLFLAG_RW,
1103                        &softc->inquiry_pq_no_lun, 0,
1104                        "Report no lun possible for invalid LUNs");
1105
1106         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1107         softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1108             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1109         softc->open_count = 0;
1110
1111         /*
1112          * Default to actually sending a SYNCHRONIZE CACHE command down to
1113          * the drive.
1114          */
1115         softc->flags = CTL_FLAG_REAL_SYNC;
1116
1117         /*
1118          * In Copan's HA scheme, the "master" and "slave" roles are
1119          * figured out through the slot the controller is in.  Although it
1120          * is an active/active system, someone has to be in charge.
1121          */
1122         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1123             OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1124             "HA head ID (0 - no HA)");
1125         if (softc->ha_id == 0) {
1126                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1127                 softc->is_single = 1;
1128                 softc->port_offset = 0;
1129         } else
1130                 softc->port_offset = (softc->ha_id - 1) * CTL_MAX_PORTS;
1131         softc->persis_offset = softc->port_offset * CTL_MAX_INIT_PER_PORT;
1132
1133         /*
1134          * XXX KDM need to figure out where we want to get our target ID
1135          * and WWID.  Is it different on each port?
1136          */
1137         softc->target.id = 0;
1138         softc->target.wwid[0] = 0x12345678;
1139         softc->target.wwid[1] = 0x87654321;
1140         STAILQ_INIT(&softc->lun_list);
1141         STAILQ_INIT(&softc->pending_lun_queue);
1142         STAILQ_INIT(&softc->fe_list);
1143         STAILQ_INIT(&softc->port_list);
1144         STAILQ_INIT(&softc->be_list);
1145         ctl_tpc_init(softc);
1146
1147         if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1148                             &other_pool) != 0)
1149         {
1150                 printf("ctl: can't allocate %d entry other SC pool, "
1151                        "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1152                 return (ENOMEM);
1153         }
1154         softc->othersc_pool = other_pool;
1155
1156         if (worker_threads <= 0)
1157                 worker_threads = max(1, mp_ncpus / 4);
1158         if (worker_threads > CTL_MAX_THREADS)
1159                 worker_threads = CTL_MAX_THREADS;
1160
1161         for (i = 0; i < worker_threads; i++) {
1162                 struct ctl_thread *thr = &softc->threads[i];
1163
1164                 mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1165                 thr->ctl_softc = softc;
1166                 STAILQ_INIT(&thr->incoming_queue);
1167                 STAILQ_INIT(&thr->rtr_queue);
1168                 STAILQ_INIT(&thr->done_queue);
1169                 STAILQ_INIT(&thr->isc_queue);
1170
1171                 error = kproc_kthread_add(ctl_work_thread, thr,
1172                     &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1173                 if (error != 0) {
1174                         printf("error creating CTL work thread!\n");
1175                         ctl_pool_free(other_pool);
1176                         return (error);
1177                 }
1178         }
1179         error = kproc_kthread_add(ctl_lun_thread, softc,
1180             &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1181         if (error != 0) {
1182                 printf("error creating CTL lun thread!\n");
1183                 ctl_pool_free(other_pool);
1184                 return (error);
1185         }
1186         error = kproc_kthread_add(ctl_thresh_thread, softc,
1187             &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1188         if (error != 0) {
1189                 printf("error creating CTL threshold thread!\n");
1190                 ctl_pool_free(other_pool);
1191                 return (error);
1192         }
1193         if (bootverbose)
1194                 printf("ctl: CAM Target Layer loaded\n");
1195
1196         /*
1197          * Initialize the ioctl front end.
1198          */
1199         ctl_frontend_register(&ioctl_frontend);
1200         port = &softc->ioctl_info.port;
1201         port->frontend = &ioctl_frontend;
1202         sprintf(softc->ioctl_info.port_name, "ioctl");
1203         port->port_type = CTL_PORT_IOCTL;
1204         port->num_requested_ctl_io = 100;
1205         port->port_name = softc->ioctl_info.port_name;
1206         port->port_online = ctl_ioctl_online;
1207         port->port_offline = ctl_ioctl_offline;
1208         port->onoff_arg = &softc->ioctl_info;
1209         port->lun_enable = ctl_ioctl_lun_enable;
1210         port->lun_disable = ctl_ioctl_lun_disable;
1211         port->targ_lun_arg = &softc->ioctl_info;
1212         port->fe_datamove = ctl_ioctl_datamove;
1213         port->fe_done = ctl_ioctl_done;
1214         port->max_targets = 15;
1215         port->max_target_id = 15;
1216
1217         if (ctl_port_register(&softc->ioctl_info.port) != 0) {
1218                 printf("ctl: ioctl front end registration failed, will "
1219                        "continue anyway\n");
1220         }
1221
1222         SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1223             OID_AUTO, "ha_state", CTLTYPE_INT | CTLFLAG_RWTUN,
1224             softc, 0, ctl_ha_state_sysctl, "I", "HA state for this head");
1225
1226 #ifdef CTL_IO_DELAY
1227         if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1228                 printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1229                        sizeof(struct callout), CTL_TIMER_BYTES);
1230                 return (EINVAL);
1231         }
1232 #endif /* CTL_IO_DELAY */
1233
1234         return (0);
1235 }
1236
1237 void
1238 ctl_shutdown(void)
1239 {
1240         struct ctl_softc *softc;
1241         struct ctl_lun *lun, *next_lun;
1242
1243         softc = (struct ctl_softc *)control_softc;
1244
1245         if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1246                 printf("ctl: ioctl front end deregistration failed\n");
1247
1248         mtx_lock(&softc->ctl_lock);
1249
1250         /*
1251          * Free up each LUN.
1252          */
1253         for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1254                 next_lun = STAILQ_NEXT(lun, links);
1255                 ctl_free_lun(lun);
1256         }
1257
1258         mtx_unlock(&softc->ctl_lock);
1259
1260         ctl_frontend_deregister(&ioctl_frontend);
1261
1262 #if 0
1263         ctl_shutdown_thread(softc->work_thread);
1264         mtx_destroy(&softc->queue_lock);
1265 #endif
1266
1267         ctl_tpc_shutdown(softc);
1268         uma_zdestroy(softc->io_zone);
1269         mtx_destroy(&softc->ctl_lock);
1270
1271         destroy_dev(softc->dev);
1272
1273         sysctl_ctx_free(&softc->sysctl_ctx);
1274
1275         free(control_softc, M_DEVBUF);
1276         control_softc = NULL;
1277
1278         if (bootverbose)
1279                 printf("ctl: CAM Target Layer unloaded\n");
1280 }
1281
1282 static int
1283 ctl_module_event_handler(module_t mod, int what, void *arg)
1284 {
1285
1286         switch (what) {
1287         case MOD_LOAD:
1288                 return (ctl_init());
1289         case MOD_UNLOAD:
1290                 return (EBUSY);
1291         default:
1292                 return (EOPNOTSUPP);
1293         }
1294 }
1295
1296 /*
1297  * XXX KDM should we do some access checks here?  Bump a reference count to
1298  * prevent a CTL module from being unloaded while someone has it open?
1299  */
1300 static int
1301 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1302 {
1303         return (0);
1304 }
1305
1306 static int
1307 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1308 {
1309         return (0);
1310 }
1311
1312 int
1313 ctl_port_enable(ctl_port_type port_type)
1314 {
1315         struct ctl_softc *softc = control_softc;
1316         struct ctl_port *port;
1317
1318         if (softc->is_single == 0) {
1319                 union ctl_ha_msg msg_info;
1320                 int isc_retval;
1321
1322 #if 0
1323                 printf("%s: HA mode, synchronizing frontend enable\n",
1324                         __func__);
1325 #endif
1326                 msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1327                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1328                         sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1329                         printf("Sync msg send error retval %d\n", isc_retval);
1330                 }
1331                 if (!rcv_sync_msg) {
1332                         isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1333                                 sizeof(msg_info), 1);
1334                 }
1335 #if 0
1336                 printf("CTL:Frontend Enable\n");
1337         } else {
1338                 printf("%s: single mode, skipping frontend synchronization\n",
1339                         __func__);
1340 #endif
1341         }
1342
1343         STAILQ_FOREACH(port, &softc->port_list, links) {
1344                 if (port_type & port->port_type)
1345                 {
1346 #if 0
1347                         printf("port %d\n", port->targ_port);
1348 #endif
1349                         ctl_port_online(port);
1350                 }
1351         }
1352
1353         return (0);
1354 }
1355
1356 int
1357 ctl_port_disable(ctl_port_type port_type)
1358 {
1359         struct ctl_softc *softc;
1360         struct ctl_port *port;
1361
1362         softc = control_softc;
1363
1364         STAILQ_FOREACH(port, &softc->port_list, links) {
1365                 if (port_type & port->port_type)
1366                         ctl_port_offline(port);
1367         }
1368
1369         return (0);
1370 }
1371
1372 /*
1373  * Returns 0 for success, 1 for failure.
1374  * Currently the only failure mode is if there aren't enough entries
1375  * allocated.  So, in case of a failure, look at num_entries_dropped,
1376  * reallocate and try again.
1377  */
1378 int
1379 ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1380               int *num_entries_filled, int *num_entries_dropped,
1381               ctl_port_type port_type, int no_virtual)
1382 {
1383         struct ctl_softc *softc;
1384         struct ctl_port *port;
1385         int entries_dropped, entries_filled;
1386         int retval;
1387         int i;
1388
1389         softc = control_softc;
1390
1391         retval = 0;
1392         entries_filled = 0;
1393         entries_dropped = 0;
1394
1395         i = 0;
1396         mtx_lock(&softc->ctl_lock);
1397         STAILQ_FOREACH(port, &softc->port_list, links) {
1398                 struct ctl_port_entry *entry;
1399
1400                 if ((port->port_type & port_type) == 0)
1401                         continue;
1402
1403                 if ((no_virtual != 0)
1404                  && (port->virtual_port != 0))
1405                         continue;
1406
1407                 if (entries_filled >= num_entries_alloced) {
1408                         entries_dropped++;
1409                         continue;
1410                 }
1411                 entry = &entries[i];
1412
1413                 entry->port_type = port->port_type;
1414                 strlcpy(entry->port_name, port->port_name,
1415                         sizeof(entry->port_name));
1416                 entry->physical_port = port->physical_port;
1417                 entry->virtual_port = port->virtual_port;
1418                 entry->wwnn = port->wwnn;
1419                 entry->wwpn = port->wwpn;
1420
1421                 i++;
1422                 entries_filled++;
1423         }
1424
1425         mtx_unlock(&softc->ctl_lock);
1426
1427         if (entries_dropped > 0)
1428                 retval = 1;
1429
1430         *num_entries_dropped = entries_dropped;
1431         *num_entries_filled = entries_filled;
1432
1433         return (retval);
1434 }
1435
1436 static void
1437 ctl_ioctl_online(void *arg)
1438 {
1439         struct ctl_ioctl_info *ioctl_info;
1440
1441         ioctl_info = (struct ctl_ioctl_info *)arg;
1442
1443         ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1444 }
1445
1446 static void
1447 ctl_ioctl_offline(void *arg)
1448 {
1449         struct ctl_ioctl_info *ioctl_info;
1450
1451         ioctl_info = (struct ctl_ioctl_info *)arg;
1452
1453         ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1454 }
1455
1456 /*
1457  * Remove an initiator by port number and initiator ID.
1458  * Returns 0 for success, -1 for failure.
1459  */
1460 int
1461 ctl_remove_initiator(struct ctl_port *port, int iid)
1462 {
1463         struct ctl_softc *softc = control_softc;
1464
1465         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1466
1467         if (iid > CTL_MAX_INIT_PER_PORT) {
1468                 printf("%s: initiator ID %u > maximun %u!\n",
1469                        __func__, iid, CTL_MAX_INIT_PER_PORT);
1470                 return (-1);
1471         }
1472
1473         mtx_lock(&softc->ctl_lock);
1474         port->wwpn_iid[iid].in_use--;
1475         port->wwpn_iid[iid].last_use = time_uptime;
1476         mtx_unlock(&softc->ctl_lock);
1477
1478         return (0);
1479 }
1480
1481 /*
1482  * Add an initiator to the initiator map.
1483  * Returns iid for success, < 0 for failure.
1484  */
1485 int
1486 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1487 {
1488         struct ctl_softc *softc = control_softc;
1489         time_t best_time;
1490         int i, best;
1491
1492         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1493
1494         if (iid >= CTL_MAX_INIT_PER_PORT) {
1495                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1496                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1497                 free(name, M_CTL);
1498                 return (-1);
1499         }
1500
1501         mtx_lock(&softc->ctl_lock);
1502
1503         if (iid < 0 && (wwpn != 0 || name != NULL)) {
1504                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1505                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1506                                 iid = i;
1507                                 break;
1508                         }
1509                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
1510                             strcmp(name, port->wwpn_iid[i].name) == 0) {
1511                                 iid = i;
1512                                 break;
1513                         }
1514                 }
1515         }
1516
1517         if (iid < 0) {
1518                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1519                         if (port->wwpn_iid[i].in_use == 0 &&
1520                             port->wwpn_iid[i].wwpn == 0 &&
1521                             port->wwpn_iid[i].name == NULL) {
1522                                 iid = i;
1523                                 break;
1524                         }
1525                 }
1526         }
1527
1528         if (iid < 0) {
1529                 best = -1;
1530                 best_time = INT32_MAX;
1531                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1532                         if (port->wwpn_iid[i].in_use == 0) {
1533                                 if (port->wwpn_iid[i].last_use < best_time) {
1534                                         best = i;
1535                                         best_time = port->wwpn_iid[i].last_use;
1536                                 }
1537                         }
1538                 }
1539                 iid = best;
1540         }
1541
1542         if (iid < 0) {
1543                 mtx_unlock(&softc->ctl_lock);
1544                 free(name, M_CTL);
1545                 return (-2);
1546         }
1547
1548         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1549                 /*
1550                  * This is not an error yet.
1551                  */
1552                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1553 #if 0
1554                         printf("%s: port %d iid %u WWPN %#jx arrived"
1555                             " again\n", __func__, port->targ_port,
1556                             iid, (uintmax_t)wwpn);
1557 #endif
1558                         goto take;
1559                 }
1560                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1561                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
1562 #if 0
1563                         printf("%s: port %d iid %u name '%s' arrived"
1564                             " again\n", __func__, port->targ_port,
1565                             iid, name);
1566 #endif
1567                         goto take;
1568                 }
1569
1570                 /*
1571                  * This is an error, but what do we do about it?  The
1572                  * driver is telling us we have a new WWPN for this
1573                  * initiator ID, so we pretty much need to use it.
1574                  */
1575                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1576                     " but WWPN %#jx '%s' is still at that address\n",
1577                     __func__, port->targ_port, iid, wwpn, name,
1578                     (uintmax_t)port->wwpn_iid[iid].wwpn,
1579                     port->wwpn_iid[iid].name);
1580
1581                 /*
1582                  * XXX KDM clear have_ca and ua_pending on each LUN for
1583                  * this initiator.
1584                  */
1585         }
1586 take:
1587         free(port->wwpn_iid[iid].name, M_CTL);
1588         port->wwpn_iid[iid].name = name;
1589         port->wwpn_iid[iid].wwpn = wwpn;
1590         port->wwpn_iid[iid].in_use++;
1591         mtx_unlock(&softc->ctl_lock);
1592
1593         return (iid);
1594 }
1595
1596 static int
1597 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1598 {
1599         int len;
1600
1601         switch (port->port_type) {
1602         case CTL_PORT_FC:
1603         {
1604                 struct scsi_transportid_fcp *id =
1605                     (struct scsi_transportid_fcp *)buf;
1606                 if (port->wwpn_iid[iid].wwpn == 0)
1607                         return (0);
1608                 memset(id, 0, sizeof(*id));
1609                 id->format_protocol = SCSI_PROTO_FC;
1610                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1611                 return (sizeof(*id));
1612         }
1613         case CTL_PORT_ISCSI:
1614         {
1615                 struct scsi_transportid_iscsi_port *id =
1616                     (struct scsi_transportid_iscsi_port *)buf;
1617                 if (port->wwpn_iid[iid].name == NULL)
1618                         return (0);
1619                 memset(id, 0, 256);
1620                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1621                     SCSI_PROTO_ISCSI;
1622                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1623                 len = roundup2(min(len, 252), 4);
1624                 scsi_ulto2b(len, id->additional_length);
1625                 return (sizeof(*id) + len);
1626         }
1627         case CTL_PORT_SAS:
1628         {
1629                 struct scsi_transportid_sas *id =
1630                     (struct scsi_transportid_sas *)buf;
1631                 if (port->wwpn_iid[iid].wwpn == 0)
1632                         return (0);
1633                 memset(id, 0, sizeof(*id));
1634                 id->format_protocol = SCSI_PROTO_SAS;
1635                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1636                 return (sizeof(*id));
1637         }
1638         default:
1639         {
1640                 struct scsi_transportid_spi *id =
1641                     (struct scsi_transportid_spi *)buf;
1642                 memset(id, 0, sizeof(*id));
1643                 id->format_protocol = SCSI_PROTO_SPI;
1644                 scsi_ulto2b(iid, id->scsi_addr);
1645                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1646                 return (sizeof(*id));
1647         }
1648         }
1649 }
1650
1651 static int
1652 ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1653 {
1654         return (0);
1655 }
1656
1657 static int
1658 ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1659 {
1660         return (0);
1661 }
1662
1663 /*
1664  * Data movement routine for the CTL ioctl frontend port.
1665  */
1666 static int
1667 ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1668 {
1669         struct ctl_sg_entry *ext_sglist, *kern_sglist;
1670         struct ctl_sg_entry ext_entry, kern_entry;
1671         int ext_sglen, ext_sg_entries, kern_sg_entries;
1672         int ext_sg_start, ext_offset;
1673         int len_to_copy, len_copied;
1674         int kern_watermark, ext_watermark;
1675         int ext_sglist_malloced;
1676         int i, j;
1677
1678         ext_sglist_malloced = 0;
1679         ext_sg_start = 0;
1680         ext_offset = 0;
1681
1682         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1683
1684         /*
1685          * If this flag is set, fake the data transfer.
1686          */
1687         if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1688                 ctsio->ext_data_filled = ctsio->ext_data_len;
1689                 goto bailout;
1690         }
1691
1692         /*
1693          * To simplify things here, if we have a single buffer, stick it in
1694          * a S/G entry and just make it a single entry S/G list.
1695          */
1696         if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1697                 int len_seen;
1698
1699                 ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1700
1701                 ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1702                                                            M_WAITOK);
1703                 ext_sglist_malloced = 1;
1704                 if (copyin(ctsio->ext_data_ptr, ext_sglist,
1705                                    ext_sglen) != 0) {
1706                         ctl_set_internal_failure(ctsio,
1707                                                  /*sks_valid*/ 0,
1708                                                  /*retry_count*/ 0);
1709                         goto bailout;
1710                 }
1711                 ext_sg_entries = ctsio->ext_sg_entries;
1712                 len_seen = 0;
1713                 for (i = 0; i < ext_sg_entries; i++) {
1714                         if ((len_seen + ext_sglist[i].len) >=
1715                              ctsio->ext_data_filled) {
1716                                 ext_sg_start = i;
1717                                 ext_offset = ctsio->ext_data_filled - len_seen;
1718                                 break;
1719                         }
1720                         len_seen += ext_sglist[i].len;
1721                 }
1722         } else {
1723                 ext_sglist = &ext_entry;
1724                 ext_sglist->addr = ctsio->ext_data_ptr;
1725                 ext_sglist->len = ctsio->ext_data_len;
1726                 ext_sg_entries = 1;
1727                 ext_sg_start = 0;
1728                 ext_offset = ctsio->ext_data_filled;
1729         }
1730
1731         if (ctsio->kern_sg_entries > 0) {
1732                 kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1733                 kern_sg_entries = ctsio->kern_sg_entries;
1734         } else {
1735                 kern_sglist = &kern_entry;
1736                 kern_sglist->addr = ctsio->kern_data_ptr;
1737                 kern_sglist->len = ctsio->kern_data_len;
1738                 kern_sg_entries = 1;
1739         }
1740
1741
1742         kern_watermark = 0;
1743         ext_watermark = ext_offset;
1744         len_copied = 0;
1745         for (i = ext_sg_start, j = 0;
1746              i < ext_sg_entries && j < kern_sg_entries;) {
1747                 uint8_t *ext_ptr, *kern_ptr;
1748
1749                 len_to_copy = MIN(ext_sglist[i].len - ext_watermark,
1750                                   kern_sglist[j].len - kern_watermark);
1751
1752                 ext_ptr = (uint8_t *)ext_sglist[i].addr;
1753                 ext_ptr = ext_ptr + ext_watermark;
1754                 if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1755                         /*
1756                          * XXX KDM fix this!
1757                          */
1758                         panic("need to implement bus address support");
1759 #if 0
1760                         kern_ptr = bus_to_virt(kern_sglist[j].addr);
1761 #endif
1762                 } else
1763                         kern_ptr = (uint8_t *)kern_sglist[j].addr;
1764                 kern_ptr = kern_ptr + kern_watermark;
1765
1766                 kern_watermark += len_to_copy;
1767                 ext_watermark += len_to_copy;
1768
1769                 if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1770                      CTL_FLAG_DATA_IN) {
1771                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1772                                          "bytes to user\n", len_to_copy));
1773                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1774                                          "to %p\n", kern_ptr, ext_ptr));
1775                         if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1776                                 ctl_set_internal_failure(ctsio,
1777                                                          /*sks_valid*/ 0,
1778                                                          /*retry_count*/ 0);
1779                                 goto bailout;
1780                         }
1781                 } else {
1782                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1783                                          "bytes from user\n", len_to_copy));
1784                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1785                                          "to %p\n", ext_ptr, kern_ptr));
1786                         if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1787                                 ctl_set_internal_failure(ctsio,
1788                                                          /*sks_valid*/ 0,
1789                                                          /*retry_count*/0);
1790                                 goto bailout;
1791                         }
1792                 }
1793
1794                 len_copied += len_to_copy;
1795
1796                 if (ext_sglist[i].len == ext_watermark) {
1797                         i++;
1798                         ext_watermark = 0;
1799                 }
1800
1801                 if (kern_sglist[j].len == kern_watermark) {
1802                         j++;
1803                         kern_watermark = 0;
1804                 }
1805         }
1806
1807         ctsio->ext_data_filled += len_copied;
1808
1809         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1810                          "kern_sg_entries: %d\n", ext_sg_entries,
1811                          kern_sg_entries));
1812         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1813                          "kern_data_len = %d\n", ctsio->ext_data_len,
1814                          ctsio->kern_data_len));
1815
1816
1817         /* XXX KDM set residual?? */
1818 bailout:
1819
1820         if (ext_sglist_malloced != 0)
1821                 free(ext_sglist, M_CTL);
1822
1823         return (CTL_RETVAL_COMPLETE);
1824 }
1825
1826 /*
1827  * Serialize a command that went down the "wrong" side, and so was sent to
1828  * this controller for execution.  The logic is a little different than the
1829  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1830  * sent back to the other side, but in the success case, we execute the
1831  * command on this side (XFER mode) or tell the other side to execute it
1832  * (SER_ONLY mode).
1833  */
1834 static int
1835 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1836 {
1837         struct ctl_softc *softc;
1838         union ctl_ha_msg msg_info;
1839         struct ctl_lun *lun;
1840         int retval = 0;
1841         uint32_t targ_lun;
1842
1843         softc = control_softc;
1844
1845         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1846         lun = softc->ctl_luns[targ_lun];
1847         if (lun==NULL)
1848         {
1849                 /*
1850                  * Why isn't LUN defined? The other side wouldn't
1851                  * send a cmd if the LUN is undefined.
1852                  */
1853                 printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1854
1855                 /* "Logical unit not supported" */
1856                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1857                                    lun,
1858                                    /*sense_format*/SSD_TYPE_NONE,
1859                                    /*current_error*/ 1,
1860                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1861                                    /*asc*/ 0x25,
1862                                    /*ascq*/ 0x00,
1863                                    SSD_ELEM_NONE);
1864
1865                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1866                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1867                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1868                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1869                 msg_info.hdr.serializing_sc = NULL;
1870                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1871                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1872                                 sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1873                 }
1874                 return(1);
1875
1876         }
1877
1878         mtx_lock(&lun->lun_lock);
1879         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1880
1881         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1882                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1883                  ooa_links))) {
1884         case CTL_ACTION_BLOCK:
1885                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1886                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1887                                   blocked_links);
1888                 break;
1889         case CTL_ACTION_PASS:
1890         case CTL_ACTION_SKIP:
1891                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
1892                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1893                         ctl_enqueue_rtr((union ctl_io *)ctsio);
1894                 } else {
1895
1896                         /* send msg back to other side */
1897                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1898                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1899                         msg_info.hdr.msg_type = CTL_MSG_R2R;
1900 #if 0
1901                         printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1902 #endif
1903                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1904                             sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1905                         }
1906                 }
1907                 break;
1908         case CTL_ACTION_OVERLAP:
1909                 /* OVERLAPPED COMMANDS ATTEMPTED */
1910                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1911                                    lun,
1912                                    /*sense_format*/SSD_TYPE_NONE,
1913                                    /*current_error*/ 1,
1914                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1915                                    /*asc*/ 0x4E,
1916                                    /*ascq*/ 0x00,
1917                                    SSD_ELEM_NONE);
1918
1919                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1920                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1921                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1922                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1923                 msg_info.hdr.serializing_sc = NULL;
1924                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1925 #if 0
1926                 printf("BAD JUJU:Major Bummer Overlap\n");
1927 #endif
1928                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1929                 retval = 1;
1930                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1931                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1932                 }
1933                 break;
1934         case CTL_ACTION_OVERLAP_TAG:
1935                 /* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1936                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1937                                    lun,
1938                                    /*sense_format*/SSD_TYPE_NONE,
1939                                    /*current_error*/ 1,
1940                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1941                                    /*asc*/ 0x4D,
1942                                    /*ascq*/ ctsio->tag_num & 0xff,
1943                                    SSD_ELEM_NONE);
1944
1945                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1946                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1947                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1948                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1949                 msg_info.hdr.serializing_sc = NULL;
1950                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1951 #if 0
1952                 printf("BAD JUJU:Major Bummer Overlap Tag\n");
1953 #endif
1954                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1955                 retval = 1;
1956                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1957                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1958                 }
1959                 break;
1960         case CTL_ACTION_ERROR:
1961         default:
1962                 /* "Internal target failure" */
1963                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1964                                    lun,
1965                                    /*sense_format*/SSD_TYPE_NONE,
1966                                    /*current_error*/ 1,
1967                                    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1968                                    /*asc*/ 0x44,
1969                                    /*ascq*/ 0x00,
1970                                    SSD_ELEM_NONE);
1971
1972                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1973                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1974                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1975                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1976                 msg_info.hdr.serializing_sc = NULL;
1977                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1978 #if 0
1979                 printf("BAD JUJU:Major Bummer HW Error\n");
1980 #endif
1981                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1982                 retval = 1;
1983                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1984                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1985                 }
1986                 break;
1987         }
1988         mtx_unlock(&lun->lun_lock);
1989         return (retval);
1990 }
1991
1992 static int
1993 ctl_ioctl_submit_wait(union ctl_io *io)
1994 {
1995         struct ctl_fe_ioctl_params params;
1996         ctl_fe_ioctl_state last_state;
1997         int done, retval;
1998
1999         retval = 0;
2000
2001         bzero(&params, sizeof(params));
2002
2003         mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
2004         cv_init(&params.sem, "ctlioccv");
2005         params.state = CTL_IOCTL_INPROG;
2006         last_state = params.state;
2007
2008         io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
2009
2010         CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
2011
2012         /* This shouldn't happen */
2013         if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
2014                 return (retval);
2015
2016         done = 0;
2017
2018         do {
2019                 mtx_lock(&params.ioctl_mtx);
2020                 /*
2021                  * Check the state here, and don't sleep if the state has
2022                  * already changed (i.e. wakeup has already occured, but we
2023                  * weren't waiting yet).
2024                  */
2025                 if (params.state == last_state) {
2026                         /* XXX KDM cv_wait_sig instead? */
2027                         cv_wait(&params.sem, &params.ioctl_mtx);
2028                 }
2029                 last_state = params.state;
2030
2031                 switch (params.state) {
2032                 case CTL_IOCTL_INPROG:
2033                         /* Why did we wake up? */
2034                         /* XXX KDM error here? */
2035                         mtx_unlock(&params.ioctl_mtx);
2036                         break;
2037                 case CTL_IOCTL_DATAMOVE:
2038                         CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
2039
2040                         /*
2041                          * change last_state back to INPROG to avoid
2042                          * deadlock on subsequent data moves.
2043                          */
2044                         params.state = last_state = CTL_IOCTL_INPROG;
2045
2046                         mtx_unlock(&params.ioctl_mtx);
2047                         ctl_ioctl_do_datamove(&io->scsiio);
2048                         /*
2049                          * Note that in some cases, most notably writes,
2050                          * this will queue the I/O and call us back later.
2051                          * In other cases, generally reads, this routine
2052                          * will immediately call back and wake us up,
2053                          * probably using our own context.
2054                          */
2055                         io->scsiio.be_move_done(io);
2056                         break;
2057                 case CTL_IOCTL_DONE:
2058                         mtx_unlock(&params.ioctl_mtx);
2059                         CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
2060                         done = 1;
2061                         break;
2062                 default:
2063                         mtx_unlock(&params.ioctl_mtx);
2064                         /* XXX KDM error here? */
2065                         break;
2066                 }
2067         } while (done == 0);
2068
2069         mtx_destroy(&params.ioctl_mtx);
2070         cv_destroy(&params.sem);
2071
2072         return (CTL_RETVAL_COMPLETE);
2073 }
2074
2075 static void
2076 ctl_ioctl_datamove(union ctl_io *io)
2077 {
2078         struct ctl_fe_ioctl_params *params;
2079
2080         params = (struct ctl_fe_ioctl_params *)
2081                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2082
2083         mtx_lock(&params->ioctl_mtx);
2084         params->state = CTL_IOCTL_DATAMOVE;
2085         cv_broadcast(&params->sem);
2086         mtx_unlock(&params->ioctl_mtx);
2087 }
2088
2089 static void
2090 ctl_ioctl_done(union ctl_io *io)
2091 {
2092         struct ctl_fe_ioctl_params *params;
2093
2094         params = (struct ctl_fe_ioctl_params *)
2095                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2096
2097         mtx_lock(&params->ioctl_mtx);
2098         params->state = CTL_IOCTL_DONE;
2099         cv_broadcast(&params->sem);
2100         mtx_unlock(&params->ioctl_mtx);
2101 }
2102
2103 static void
2104 ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2105 {
2106         struct ctl_fe_ioctl_startstop_info *sd_info;
2107
2108         sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2109
2110         sd_info->hs_info.status = metatask->status;
2111         sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2112         sd_info->hs_info.luns_complete =
2113                 metatask->taskinfo.startstop.luns_complete;
2114         sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2115
2116         cv_broadcast(&sd_info->sem);
2117 }
2118
2119 static void
2120 ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2121 {
2122         struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2123
2124         fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2125
2126         mtx_lock(fe_bbr_info->lock);
2127         fe_bbr_info->bbr_info->status = metatask->status;
2128         fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2129         fe_bbr_info->wakeup_done = 1;
2130         mtx_unlock(fe_bbr_info->lock);
2131
2132         cv_broadcast(&fe_bbr_info->sem);
2133 }
2134
2135 /*
2136  * Returns 0 for success, errno for failure.
2137  */
2138 static int
2139 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2140                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2141 {
2142         union ctl_io *io;
2143         int retval;
2144
2145         retval = 0;
2146
2147         mtx_lock(&lun->lun_lock);
2148         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2149              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2150              ooa_links)) {
2151                 struct ctl_ooa_entry *entry;
2152
2153                 /*
2154                  * If we've got more than we can fit, just count the
2155                  * remaining entries.
2156                  */
2157                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2158                         continue;
2159
2160                 entry = &kern_entries[*cur_fill_num];
2161
2162                 entry->tag_num = io->scsiio.tag_num;
2163                 entry->lun_num = lun->lun;
2164 #ifdef CTL_TIME_IO
2165                 entry->start_bt = io->io_hdr.start_bt;
2166 #endif
2167                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2168                 entry->cdb_len = io->scsiio.cdb_len;
2169                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2170                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2171
2172                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2173                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2174
2175                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2176                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2177
2178                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2179                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2180
2181                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2182                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2183         }
2184         mtx_unlock(&lun->lun_lock);
2185
2186         return (retval);
2187 }
2188
2189 static void *
2190 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2191                  size_t error_str_len)
2192 {
2193         void *kptr;
2194
2195         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2196
2197         if (copyin(user_addr, kptr, len) != 0) {
2198                 snprintf(error_str, error_str_len, "Error copying %d bytes "
2199                          "from user address %p to kernel address %p", len,
2200                          user_addr, kptr);
2201                 free(kptr, M_CTL);
2202                 return (NULL);
2203         }
2204
2205         return (kptr);
2206 }
2207
2208 static void
2209 ctl_free_args(int num_args, struct ctl_be_arg *args)
2210 {
2211         int i;
2212
2213         if (args == NULL)
2214                 return;
2215
2216         for (i = 0; i < num_args; i++) {
2217                 free(args[i].kname, M_CTL);
2218                 free(args[i].kvalue, M_CTL);
2219         }
2220
2221         free(args, M_CTL);
2222 }
2223
2224 static struct ctl_be_arg *
2225 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2226                 char *error_str, size_t error_str_len)
2227 {
2228         struct ctl_be_arg *args;
2229         int i;
2230
2231         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2232                                 error_str, error_str_len);
2233
2234         if (args == NULL)
2235                 goto bailout;
2236
2237         for (i = 0; i < num_args; i++) {
2238                 args[i].kname = NULL;
2239                 args[i].kvalue = NULL;
2240         }
2241
2242         for (i = 0; i < num_args; i++) {
2243                 uint8_t *tmpptr;
2244
2245                 args[i].kname = ctl_copyin_alloc(args[i].name,
2246                         args[i].namelen, error_str, error_str_len);
2247                 if (args[i].kname == NULL)
2248                         goto bailout;
2249
2250                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2251                         snprintf(error_str, error_str_len, "Argument %d "
2252                                  "name is not NUL-terminated", i);
2253                         goto bailout;
2254                 }
2255
2256                 if (args[i].flags & CTL_BEARG_RD) {
2257                         tmpptr = ctl_copyin_alloc(args[i].value,
2258                                 args[i].vallen, error_str, error_str_len);
2259                         if (tmpptr == NULL)
2260                                 goto bailout;
2261                         if ((args[i].flags & CTL_BEARG_ASCII)
2262                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2263                                 snprintf(error_str, error_str_len, "Argument "
2264                                     "%d value is not NUL-terminated", i);
2265                                 goto bailout;
2266                         }
2267                         args[i].kvalue = tmpptr;
2268                 } else {
2269                         args[i].kvalue = malloc(args[i].vallen,
2270                             M_CTL, M_WAITOK | M_ZERO);
2271                 }
2272         }
2273
2274         return (args);
2275 bailout:
2276
2277         ctl_free_args(num_args, args);
2278
2279         return (NULL);
2280 }
2281
2282 static void
2283 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2284 {
2285         int i;
2286
2287         for (i = 0; i < num_args; i++) {
2288                 if (args[i].flags & CTL_BEARG_WR)
2289                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2290         }
2291 }
2292
2293 /*
2294  * Escape characters that are illegal or not recommended in XML.
2295  */
2296 int
2297 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2298 {
2299         char *end = str + size;
2300         int retval;
2301
2302         retval = 0;
2303
2304         for (; *str && str < end; str++) {
2305                 switch (*str) {
2306                 case '&':
2307                         retval = sbuf_printf(sb, "&amp;");
2308                         break;
2309                 case '>':
2310                         retval = sbuf_printf(sb, "&gt;");
2311                         break;
2312                 case '<':
2313                         retval = sbuf_printf(sb, "&lt;");
2314                         break;
2315                 default:
2316                         retval = sbuf_putc(sb, *str);
2317                         break;
2318                 }
2319
2320                 if (retval != 0)
2321                         break;
2322
2323         }
2324
2325         return (retval);
2326 }
2327
2328 static void
2329 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2330 {
2331         struct scsi_vpd_id_descriptor *desc;
2332         int i;
2333
2334         if (id == NULL || id->len < 4)
2335                 return;
2336         desc = (struct scsi_vpd_id_descriptor *)id->data;
2337         switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2338         case SVPD_ID_TYPE_T10:
2339                 sbuf_printf(sb, "t10.");
2340                 break;
2341         case SVPD_ID_TYPE_EUI64:
2342                 sbuf_printf(sb, "eui.");
2343                 break;
2344         case SVPD_ID_TYPE_NAA:
2345                 sbuf_printf(sb, "naa.");
2346                 break;
2347         case SVPD_ID_TYPE_SCSI_NAME:
2348                 break;
2349         }
2350         switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2351         case SVPD_ID_CODESET_BINARY:
2352                 for (i = 0; i < desc->length; i++)
2353                         sbuf_printf(sb, "%02x", desc->identifier[i]);
2354                 break;
2355         case SVPD_ID_CODESET_ASCII:
2356                 sbuf_printf(sb, "%.*s", (int)desc->length,
2357                     (char *)desc->identifier);
2358                 break;
2359         case SVPD_ID_CODESET_UTF8:
2360                 sbuf_printf(sb, "%s", (char *)desc->identifier);
2361                 break;
2362         }
2363 }
2364
2365 static int
2366 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2367           struct thread *td)
2368 {
2369         struct ctl_softc *softc;
2370         int retval;
2371
2372         softc = control_softc;
2373
2374         retval = 0;
2375
2376         switch (cmd) {
2377         case CTL_IO: {
2378                 union ctl_io *io;
2379                 void *pool_tmp;
2380
2381                 /*
2382                  * If we haven't been "enabled", don't allow any SCSI I/O
2383                  * to this FETD.
2384                  */
2385                 if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2386                         retval = EPERM;
2387                         break;
2388                 }
2389
2390                 io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2391
2392                 /*
2393                  * Need to save the pool reference so it doesn't get
2394                  * spammed by the user's ctl_io.
2395                  */
2396                 pool_tmp = io->io_hdr.pool;
2397                 memcpy(io, (void *)addr, sizeof(*io));
2398                 io->io_hdr.pool = pool_tmp;
2399
2400                 /*
2401                  * No status yet, so make sure the status is set properly.
2402                  */
2403                 io->io_hdr.status = CTL_STATUS_NONE;
2404
2405                 /*
2406                  * The user sets the initiator ID, target and LUN IDs.
2407                  */
2408                 io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2409                 io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2410                 if ((io->io_hdr.io_type == CTL_IO_SCSI)
2411                  && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2412                         io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2413
2414                 retval = ctl_ioctl_submit_wait(io);
2415
2416                 if (retval != 0) {
2417                         ctl_free_io(io);
2418                         break;
2419                 }
2420
2421                 memcpy((void *)addr, io, sizeof(*io));
2422
2423                 /* return this to our pool */
2424                 ctl_free_io(io);
2425
2426                 break;
2427         }
2428         case CTL_ENABLE_PORT:
2429         case CTL_DISABLE_PORT:
2430         case CTL_SET_PORT_WWNS: {
2431                 struct ctl_port *port;
2432                 struct ctl_port_entry *entry;
2433
2434                 entry = (struct ctl_port_entry *)addr;
2435                 
2436                 mtx_lock(&softc->ctl_lock);
2437                 STAILQ_FOREACH(port, &softc->port_list, links) {
2438                         int action, done;
2439
2440                         action = 0;
2441                         done = 0;
2442
2443                         if ((entry->port_type == CTL_PORT_NONE)
2444                          && (entry->targ_port == port->targ_port)) {
2445                                 /*
2446                                  * If the user only wants to enable or
2447                                  * disable or set WWNs on a specific port,
2448                                  * do the operation and we're done.
2449                                  */
2450                                 action = 1;
2451                                 done = 1;
2452                         } else if (entry->port_type & port->port_type) {
2453                                 /*
2454                                  * Compare the user's type mask with the
2455                                  * particular frontend type to see if we
2456                                  * have a match.
2457                                  */
2458                                 action = 1;
2459                                 done = 0;
2460
2461                                 /*
2462                                  * Make sure the user isn't trying to set
2463                                  * WWNs on multiple ports at the same time.
2464                                  */
2465                                 if (cmd == CTL_SET_PORT_WWNS) {
2466                                         printf("%s: Can't set WWNs on "
2467                                                "multiple ports\n", __func__);
2468                                         retval = EINVAL;
2469                                         break;
2470                                 }
2471                         }
2472                         if (action != 0) {
2473                                 /*
2474                                  * XXX KDM we have to drop the lock here,
2475                                  * because the online/offline operations
2476                                  * can potentially block.  We need to
2477                                  * reference count the frontends so they
2478                                  * can't go away,
2479                                  */
2480                                 mtx_unlock(&softc->ctl_lock);
2481
2482                                 if (cmd == CTL_ENABLE_PORT) {
2483                                         struct ctl_lun *lun;
2484
2485                                         STAILQ_FOREACH(lun, &softc->lun_list,
2486                                                        links) {
2487                                                 port->lun_enable(port->targ_lun_arg,
2488                                                     lun->target,
2489                                                     lun->lun);
2490                                         }
2491
2492                                         ctl_port_online(port);
2493                                 } else if (cmd == CTL_DISABLE_PORT) {
2494                                         struct ctl_lun *lun;
2495
2496                                         ctl_port_offline(port);
2497
2498                                         STAILQ_FOREACH(lun, &softc->lun_list,
2499                                                        links) {
2500                                                 port->lun_disable(
2501                                                     port->targ_lun_arg,
2502                                                     lun->target,
2503                                                     lun->lun);
2504                                         }
2505                                 }
2506
2507                                 mtx_lock(&softc->ctl_lock);
2508
2509                                 if (cmd == CTL_SET_PORT_WWNS)
2510                                         ctl_port_set_wwns(port,
2511                                             (entry->flags & CTL_PORT_WWNN_VALID) ?
2512                                             1 : 0, entry->wwnn,
2513                                             (entry->flags & CTL_PORT_WWPN_VALID) ?
2514                                             1 : 0, entry->wwpn);
2515                         }
2516                         if (done != 0)
2517                                 break;
2518                 }
2519                 mtx_unlock(&softc->ctl_lock);
2520                 break;
2521         }
2522         case CTL_GET_PORT_LIST: {
2523                 struct ctl_port *port;
2524                 struct ctl_port_list *list;
2525                 int i;
2526
2527                 list = (struct ctl_port_list *)addr;
2528
2529                 if (list->alloc_len != (list->alloc_num *
2530                     sizeof(struct ctl_port_entry))) {
2531                         printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2532                                "alloc_num %u * sizeof(struct ctl_port_entry) "
2533                                "%zu\n", __func__, list->alloc_len,
2534                                list->alloc_num, sizeof(struct ctl_port_entry));
2535                         retval = EINVAL;
2536                         break;
2537                 }
2538                 list->fill_len = 0;
2539                 list->fill_num = 0;
2540                 list->dropped_num = 0;
2541                 i = 0;
2542                 mtx_lock(&softc->ctl_lock);
2543                 STAILQ_FOREACH(port, &softc->port_list, links) {
2544                         struct ctl_port_entry entry, *list_entry;
2545
2546                         if (list->fill_num >= list->alloc_num) {
2547                                 list->dropped_num++;
2548                                 continue;
2549                         }
2550
2551                         entry.port_type = port->port_type;
2552                         strlcpy(entry.port_name, port->port_name,
2553                                 sizeof(entry.port_name));
2554                         entry.targ_port = port->targ_port;
2555                         entry.physical_port = port->physical_port;
2556                         entry.virtual_port = port->virtual_port;
2557                         entry.wwnn = port->wwnn;
2558                         entry.wwpn = port->wwpn;
2559                         if (port->status & CTL_PORT_STATUS_ONLINE)
2560                                 entry.online = 1;
2561                         else
2562                                 entry.online = 0;
2563
2564                         list_entry = &list->entries[i];
2565
2566                         retval = copyout(&entry, list_entry, sizeof(entry));
2567                         if (retval != 0) {
2568                                 printf("%s: CTL_GET_PORT_LIST: copyout "
2569                                        "returned %d\n", __func__, retval);
2570                                 break;
2571                         }
2572                         i++;
2573                         list->fill_num++;
2574                         list->fill_len += sizeof(entry);
2575                 }
2576                 mtx_unlock(&softc->ctl_lock);
2577
2578                 /*
2579                  * If this is non-zero, we had a copyout fault, so there's
2580                  * probably no point in attempting to set the status inside
2581                  * the structure.
2582                  */
2583                 if (retval != 0)
2584                         break;
2585
2586                 if (list->dropped_num > 0)
2587                         list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2588                 else
2589                         list->status = CTL_PORT_LIST_OK;
2590                 break;
2591         }
2592         case CTL_DUMP_OOA: {
2593                 struct ctl_lun *lun;
2594                 union ctl_io *io;
2595                 char printbuf[128];
2596                 struct sbuf sb;
2597
2598                 mtx_lock(&softc->ctl_lock);
2599                 printf("Dumping OOA queues:\n");
2600                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2601                         mtx_lock(&lun->lun_lock);
2602                         for (io = (union ctl_io *)TAILQ_FIRST(
2603                              &lun->ooa_queue); io != NULL;
2604                              io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2605                              ooa_links)) {
2606                                 sbuf_new(&sb, printbuf, sizeof(printbuf),
2607                                          SBUF_FIXEDLEN);
2608                                 sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2609                                             (intmax_t)lun->lun,
2610                                             io->scsiio.tag_num,
2611                                             (io->io_hdr.flags &
2612                                             CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2613                                             (io->io_hdr.flags &
2614                                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2615                                             (io->io_hdr.flags &
2616                                             CTL_FLAG_ABORT) ? " ABORT" : "",
2617                                             (io->io_hdr.flags &
2618                                         CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2619                                 ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2620                                 sbuf_finish(&sb);
2621                                 printf("%s\n", sbuf_data(&sb));
2622                         }
2623                         mtx_unlock(&lun->lun_lock);
2624                 }
2625                 printf("OOA queues dump done\n");
2626                 mtx_unlock(&softc->ctl_lock);
2627                 break;
2628         }
2629         case CTL_GET_OOA: {
2630                 struct ctl_lun *lun;
2631                 struct ctl_ooa *ooa_hdr;
2632                 struct ctl_ooa_entry *entries;
2633                 uint32_t cur_fill_num;
2634
2635                 ooa_hdr = (struct ctl_ooa *)addr;
2636
2637                 if ((ooa_hdr->alloc_len == 0)
2638                  || (ooa_hdr->alloc_num == 0)) {
2639                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2640                                "must be non-zero\n", __func__,
2641                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2642                         retval = EINVAL;
2643                         break;
2644                 }
2645
2646                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2647                     sizeof(struct ctl_ooa_entry))) {
2648                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2649                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2650                                __func__, ooa_hdr->alloc_len,
2651                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2652                         retval = EINVAL;
2653                         break;
2654                 }
2655
2656                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2657                 if (entries == NULL) {
2658                         printf("%s: could not allocate %d bytes for OOA "
2659                                "dump\n", __func__, ooa_hdr->alloc_len);
2660                         retval = ENOMEM;
2661                         break;
2662                 }
2663
2664                 mtx_lock(&softc->ctl_lock);
2665                 if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2666                  && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2667                   || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2668                         mtx_unlock(&softc->ctl_lock);
2669                         free(entries, M_CTL);
2670                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2671                                __func__, (uintmax_t)ooa_hdr->lun_num);
2672                         retval = EINVAL;
2673                         break;
2674                 }
2675
2676                 cur_fill_num = 0;
2677
2678                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2679                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2680                                 retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2681                                         ooa_hdr, entries);
2682                                 if (retval != 0)
2683                                         break;
2684                         }
2685                         if (retval != 0) {
2686                                 mtx_unlock(&softc->ctl_lock);
2687                                 free(entries, M_CTL);
2688                                 break;
2689                         }
2690                 } else {
2691                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2692
2693                         retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2694                                                     entries);
2695                 }
2696                 mtx_unlock(&softc->ctl_lock);
2697
2698                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2699                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2700                         sizeof(struct ctl_ooa_entry);
2701                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2702                 if (retval != 0) {
2703                         printf("%s: error copying out %d bytes for OOA dump\n", 
2704                                __func__, ooa_hdr->fill_len);
2705                 }
2706
2707                 getbintime(&ooa_hdr->cur_bt);
2708
2709                 if (cur_fill_num > ooa_hdr->alloc_num) {
2710                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2711                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2712                 } else {
2713                         ooa_hdr->dropped_num = 0;
2714                         ooa_hdr->status = CTL_OOA_OK;
2715                 }
2716
2717                 free(entries, M_CTL);
2718                 break;
2719         }
2720         case CTL_CHECK_OOA: {
2721                 union ctl_io *io;
2722                 struct ctl_lun *lun;
2723                 struct ctl_ooa_info *ooa_info;
2724
2725
2726                 ooa_info = (struct ctl_ooa_info *)addr;
2727
2728                 if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2729                         ooa_info->status = CTL_OOA_INVALID_LUN;
2730                         break;
2731                 }
2732                 mtx_lock(&softc->ctl_lock);
2733                 lun = softc->ctl_luns[ooa_info->lun_id];
2734                 if (lun == NULL) {
2735                         mtx_unlock(&softc->ctl_lock);
2736                         ooa_info->status = CTL_OOA_INVALID_LUN;
2737                         break;
2738                 }
2739                 mtx_lock(&lun->lun_lock);
2740                 mtx_unlock(&softc->ctl_lock);
2741                 ooa_info->num_entries = 0;
2742                 for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2743                      io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2744                      &io->io_hdr, ooa_links)) {
2745                         ooa_info->num_entries++;
2746                 }
2747                 mtx_unlock(&lun->lun_lock);
2748
2749                 ooa_info->status = CTL_OOA_SUCCESS;
2750
2751                 break;
2752         }
2753         case CTL_HARD_START:
2754         case CTL_HARD_STOP: {
2755                 struct ctl_fe_ioctl_startstop_info ss_info;
2756                 struct cfi_metatask *metatask;
2757                 struct mtx hs_mtx;
2758
2759                 mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2760
2761                 cv_init(&ss_info.sem, "hard start/stop cv" );
2762
2763                 metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2764                 if (metatask == NULL) {
2765                         retval = ENOMEM;
2766                         mtx_destroy(&hs_mtx);
2767                         break;
2768                 }
2769
2770                 if (cmd == CTL_HARD_START)
2771                         metatask->tasktype = CFI_TASK_STARTUP;
2772                 else
2773                         metatask->tasktype = CFI_TASK_SHUTDOWN;
2774
2775                 metatask->callback = ctl_ioctl_hard_startstop_callback;
2776                 metatask->callback_arg = &ss_info;
2777
2778                 cfi_action(metatask);
2779
2780                 /* Wait for the callback */
2781                 mtx_lock(&hs_mtx);
2782                 cv_wait_sig(&ss_info.sem, &hs_mtx);
2783                 mtx_unlock(&hs_mtx);
2784
2785                 /*
2786                  * All information has been copied from the metatask by the
2787                  * time cv_broadcast() is called, so we free the metatask here.
2788                  */
2789                 cfi_free_metatask(metatask);
2790
2791                 memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2792
2793                 mtx_destroy(&hs_mtx);
2794                 break;
2795         }
2796         case CTL_BBRREAD: {
2797                 struct ctl_bbrread_info *bbr_info;
2798                 struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2799                 struct mtx bbr_mtx;
2800                 struct cfi_metatask *metatask;
2801
2802                 bbr_info = (struct ctl_bbrread_info *)addr;
2803
2804                 bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2805
2806                 bzero(&bbr_mtx, sizeof(bbr_mtx));
2807                 mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2808
2809                 fe_bbr_info.bbr_info = bbr_info;
2810                 fe_bbr_info.lock = &bbr_mtx;
2811
2812                 cv_init(&fe_bbr_info.sem, "BBR read cv");
2813                 metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2814
2815                 if (metatask == NULL) {
2816                         mtx_destroy(&bbr_mtx);
2817                         cv_destroy(&fe_bbr_info.sem);
2818                         retval = ENOMEM;
2819                         break;
2820                 }
2821                 metatask->tasktype = CFI_TASK_BBRREAD;
2822                 metatask->callback = ctl_ioctl_bbrread_callback;
2823                 metatask->callback_arg = &fe_bbr_info;
2824                 metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2825                 metatask->taskinfo.bbrread.lba = bbr_info->lba;
2826                 metatask->taskinfo.bbrread.len = bbr_info->len;
2827
2828                 cfi_action(metatask);
2829
2830                 mtx_lock(&bbr_mtx);
2831                 while (fe_bbr_info.wakeup_done == 0)
2832                         cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2833                 mtx_unlock(&bbr_mtx);
2834
2835                 bbr_info->status = metatask->status;
2836                 bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2837                 bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2838                 memcpy(&bbr_info->sense_data,
2839                        &metatask->taskinfo.bbrread.sense_data,
2840                        MIN(sizeof(bbr_info->sense_data),
2841                            sizeof(metatask->taskinfo.bbrread.sense_data)));
2842
2843                 cfi_free_metatask(metatask);
2844
2845                 mtx_destroy(&bbr_mtx);
2846                 cv_destroy(&fe_bbr_info.sem);
2847
2848                 break;
2849         }
2850         case CTL_DELAY_IO: {
2851                 struct ctl_io_delay_info *delay_info;
2852 #ifdef CTL_IO_DELAY
2853                 struct ctl_lun *lun;
2854 #endif /* CTL_IO_DELAY */
2855
2856                 delay_info = (struct ctl_io_delay_info *)addr;
2857
2858 #ifdef CTL_IO_DELAY
2859                 mtx_lock(&softc->ctl_lock);
2860
2861                 if ((delay_info->lun_id >= CTL_MAX_LUNS)
2862                  || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2863                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2864                 } else {
2865                         lun = softc->ctl_luns[delay_info->lun_id];
2866                         mtx_lock(&lun->lun_lock);
2867
2868                         delay_info->status = CTL_DELAY_STATUS_OK;
2869
2870                         switch (delay_info->delay_type) {
2871                         case CTL_DELAY_TYPE_CONT:
2872                                 break;
2873                         case CTL_DELAY_TYPE_ONESHOT:
2874                                 break;
2875                         default:
2876                                 delay_info->status =
2877                                         CTL_DELAY_STATUS_INVALID_TYPE;
2878                                 break;
2879                         }
2880
2881                         switch (delay_info->delay_loc) {
2882                         case CTL_DELAY_LOC_DATAMOVE:
2883                                 lun->delay_info.datamove_type =
2884                                         delay_info->delay_type;
2885                                 lun->delay_info.datamove_delay =
2886                                         delay_info->delay_secs;
2887                                 break;
2888                         case CTL_DELAY_LOC_DONE:
2889                                 lun->delay_info.done_type =
2890                                         delay_info->delay_type;
2891                                 lun->delay_info.done_delay =
2892                                         delay_info->delay_secs;
2893                                 break;
2894                         default:
2895                                 delay_info->status =
2896                                         CTL_DELAY_STATUS_INVALID_LOC;
2897                                 break;
2898                         }
2899                         mtx_unlock(&lun->lun_lock);
2900                 }
2901
2902                 mtx_unlock(&softc->ctl_lock);
2903 #else
2904                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2905 #endif /* CTL_IO_DELAY */
2906                 break;
2907         }
2908         case CTL_REALSYNC_SET: {
2909                 int *syncstate;
2910
2911                 syncstate = (int *)addr;
2912
2913                 mtx_lock(&softc->ctl_lock);
2914                 switch (*syncstate) {
2915                 case 0:
2916                         softc->flags &= ~CTL_FLAG_REAL_SYNC;
2917                         break;
2918                 case 1:
2919                         softc->flags |= CTL_FLAG_REAL_SYNC;
2920                         break;
2921                 default:
2922                         retval = EINVAL;
2923                         break;
2924                 }
2925                 mtx_unlock(&softc->ctl_lock);
2926                 break;
2927         }
2928         case CTL_REALSYNC_GET: {
2929                 int *syncstate;
2930
2931                 syncstate = (int*)addr;
2932
2933                 mtx_lock(&softc->ctl_lock);
2934                 if (softc->flags & CTL_FLAG_REAL_SYNC)
2935                         *syncstate = 1;
2936                 else
2937                         *syncstate = 0;
2938                 mtx_unlock(&softc->ctl_lock);
2939
2940                 break;
2941         }
2942         case CTL_SETSYNC:
2943         case CTL_GETSYNC: {
2944                 struct ctl_sync_info *sync_info;
2945                 struct ctl_lun *lun;
2946
2947                 sync_info = (struct ctl_sync_info *)addr;
2948
2949                 mtx_lock(&softc->ctl_lock);
2950                 lun = softc->ctl_luns[sync_info->lun_id];
2951                 if (lun == NULL) {
2952                         mtx_unlock(&softc->ctl_lock);
2953                         sync_info->status = CTL_GS_SYNC_NO_LUN;
2954                 }
2955                 /*
2956                  * Get or set the sync interval.  We're not bounds checking
2957                  * in the set case, hopefully the user won't do something
2958                  * silly.
2959                  */
2960                 mtx_lock(&lun->lun_lock);
2961                 mtx_unlock(&softc->ctl_lock);
2962                 if (cmd == CTL_GETSYNC)
2963                         sync_info->sync_interval = lun->sync_interval;
2964                 else
2965                         lun->sync_interval = sync_info->sync_interval;
2966                 mtx_unlock(&lun->lun_lock);
2967
2968                 sync_info->status = CTL_GS_SYNC_OK;
2969
2970                 break;
2971         }
2972         case CTL_GETSTATS: {
2973                 struct ctl_stats *stats;
2974                 struct ctl_lun *lun;
2975                 int i;
2976
2977                 stats = (struct ctl_stats *)addr;
2978
2979                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2980                      stats->alloc_len) {
2981                         stats->status = CTL_SS_NEED_MORE_SPACE;
2982                         stats->num_luns = softc->num_luns;
2983                         break;
2984                 }
2985                 /*
2986                  * XXX KDM no locking here.  If the LUN list changes,
2987                  * things can blow up.
2988                  */
2989                 for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2990                      i++, lun = STAILQ_NEXT(lun, links)) {
2991                         retval = copyout(&lun->stats, &stats->lun_stats[i],
2992                                          sizeof(lun->stats));
2993                         if (retval != 0)
2994                                 break;
2995                 }
2996                 stats->num_luns = softc->num_luns;
2997                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2998                                  softc->num_luns;
2999                 stats->status = CTL_SS_OK;
3000 #ifdef CTL_TIME_IO
3001                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
3002 #else
3003                 stats->flags = CTL_STATS_FLAG_NONE;
3004 #endif
3005                 getnanouptime(&stats->timestamp);
3006                 break;
3007         }
3008         case CTL_ERROR_INJECT: {
3009                 struct ctl_error_desc *err_desc, *new_err_desc;
3010                 struct ctl_lun *lun;
3011
3012                 err_desc = (struct ctl_error_desc *)addr;
3013
3014                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
3015                                       M_WAITOK | M_ZERO);
3016                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
3017
3018                 mtx_lock(&softc->ctl_lock);
3019                 lun = softc->ctl_luns[err_desc->lun_id];
3020                 if (lun == NULL) {
3021                         mtx_unlock(&softc->ctl_lock);
3022                         free(new_err_desc, M_CTL);
3023                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
3024                                __func__, (uintmax_t)err_desc->lun_id);
3025                         retval = EINVAL;
3026                         break;
3027                 }
3028                 mtx_lock(&lun->lun_lock);
3029                 mtx_unlock(&softc->ctl_lock);
3030
3031                 /*
3032                  * We could do some checking here to verify the validity
3033                  * of the request, but given the complexity of error
3034                  * injection requests, the checking logic would be fairly
3035                  * complex.
3036                  *
3037                  * For now, if the request is invalid, it just won't get
3038                  * executed and might get deleted.
3039                  */
3040                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
3041
3042                 /*
3043                  * XXX KDM check to make sure the serial number is unique,
3044                  * in case we somehow manage to wrap.  That shouldn't
3045                  * happen for a very long time, but it's the right thing to
3046                  * do.
3047                  */
3048                 new_err_desc->serial = lun->error_serial;
3049                 err_desc->serial = lun->error_serial;
3050                 lun->error_serial++;
3051
3052                 mtx_unlock(&lun->lun_lock);
3053                 break;
3054         }
3055         case CTL_ERROR_INJECT_DELETE: {
3056                 struct ctl_error_desc *delete_desc, *desc, *desc2;
3057                 struct ctl_lun *lun;
3058                 int delete_done;
3059
3060                 delete_desc = (struct ctl_error_desc *)addr;
3061                 delete_done = 0;
3062
3063                 mtx_lock(&softc->ctl_lock);
3064                 lun = softc->ctl_luns[delete_desc->lun_id];
3065                 if (lun == NULL) {
3066                         mtx_unlock(&softc->ctl_lock);
3067                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
3068                                __func__, (uintmax_t)delete_desc->lun_id);
3069                         retval = EINVAL;
3070                         break;
3071                 }
3072                 mtx_lock(&lun->lun_lock);
3073                 mtx_unlock(&softc->ctl_lock);
3074                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
3075                         if (desc->serial != delete_desc->serial)
3076                                 continue;
3077
3078                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
3079                                       links);
3080                         free(desc, M_CTL);
3081                         delete_done = 1;
3082                 }
3083                 mtx_unlock(&lun->lun_lock);
3084                 if (delete_done == 0) {
3085                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
3086                                "error serial %ju on LUN %u\n", __func__, 
3087                                delete_desc->serial, delete_desc->lun_id);
3088                         retval = EINVAL;
3089                         break;
3090                 }
3091                 break;
3092         }
3093         case CTL_DUMP_STRUCTS: {
3094                 int i, j, k;
3095                 struct ctl_port *port;
3096                 struct ctl_frontend *fe;
3097
3098                 mtx_lock(&softc->ctl_lock);
3099                 printf("CTL Persistent Reservation information start:\n");
3100                 for (i = 0; i < CTL_MAX_LUNS; i++) {
3101                         struct ctl_lun *lun;
3102
3103                         lun = softc->ctl_luns[i];
3104
3105                         if ((lun == NULL)
3106                          || ((lun->flags & CTL_LUN_DISABLED) != 0))
3107                                 continue;
3108
3109                         for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
3110                                 if (lun->pr_keys[j] == NULL)
3111                                         continue;
3112                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3113                                         if (lun->pr_keys[j][k] == 0)
3114                                                 continue;
3115                                         printf("  LUN %d port %d iid %d key "
3116                                                "%#jx\n", i, j, k,
3117                                                (uintmax_t)lun->pr_keys[j][k]);
3118                                 }
3119                         }
3120                 }
3121                 printf("CTL Persistent Reservation information end\n");
3122                 printf("CTL Ports:\n");
3123                 STAILQ_FOREACH(port, &softc->port_list, links) {
3124                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3125                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3126                                port->frontend->name, port->port_type,
3127                                port->physical_port, port->virtual_port,
3128                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3129                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3130                                 if (port->wwpn_iid[j].in_use == 0 &&
3131                                     port->wwpn_iid[j].wwpn == 0 &&
3132                                     port->wwpn_iid[j].name == NULL)
3133                                         continue;
3134
3135                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
3136                                     j, port->wwpn_iid[j].in_use,
3137                                     (uintmax_t)port->wwpn_iid[j].wwpn,
3138                                     port->wwpn_iid[j].name);
3139                         }
3140                 }
3141                 printf("CTL Port information end\n");
3142                 mtx_unlock(&softc->ctl_lock);
3143                 /*
3144                  * XXX KDM calling this without a lock.  We'd likely want
3145                  * to drop the lock before calling the frontend's dump
3146                  * routine anyway.
3147                  */
3148                 printf("CTL Frontends:\n");
3149                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
3150                         printf("  Frontend '%s'\n", fe->name);
3151                         if (fe->fe_dump != NULL)
3152                                 fe->fe_dump();
3153                 }
3154                 printf("CTL Frontend information end\n");
3155                 break;
3156         }
3157         case CTL_LUN_REQ: {
3158                 struct ctl_lun_req *lun_req;
3159                 struct ctl_backend_driver *backend;
3160
3161                 lun_req = (struct ctl_lun_req *)addr;
3162
3163                 backend = ctl_backend_find(lun_req->backend);
3164                 if (backend == NULL) {
3165                         lun_req->status = CTL_LUN_ERROR;
3166                         snprintf(lun_req->error_str,
3167                                  sizeof(lun_req->error_str),
3168                                  "Backend \"%s\" not found.",
3169                                  lun_req->backend);
3170                         break;
3171                 }
3172                 if (lun_req->num_be_args > 0) {
3173                         lun_req->kern_be_args = ctl_copyin_args(
3174                                 lun_req->num_be_args,
3175                                 lun_req->be_args,
3176                                 lun_req->error_str,
3177                                 sizeof(lun_req->error_str));
3178                         if (lun_req->kern_be_args == NULL) {
3179                                 lun_req->status = CTL_LUN_ERROR;
3180                                 break;
3181                         }
3182                 }
3183
3184                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3185
3186                 if (lun_req->num_be_args > 0) {
3187                         ctl_copyout_args(lun_req->num_be_args,
3188                                       lun_req->kern_be_args);
3189                         ctl_free_args(lun_req->num_be_args,
3190                                       lun_req->kern_be_args);
3191                 }
3192                 break;
3193         }
3194         case CTL_LUN_LIST: {
3195                 struct sbuf *sb;
3196                 struct ctl_lun *lun;
3197                 struct ctl_lun_list *list;
3198                 struct ctl_option *opt;
3199
3200                 list = (struct ctl_lun_list *)addr;
3201
3202                 /*
3203                  * Allocate a fixed length sbuf here, based on the length
3204                  * of the user's buffer.  We could allocate an auto-extending
3205                  * buffer, and then tell the user how much larger our
3206                  * amount of data is than his buffer, but that presents
3207                  * some problems:
3208                  *
3209                  * 1.  The sbuf(9) routines use a blocking malloc, and so
3210                  *     we can't hold a lock while calling them with an
3211                  *     auto-extending buffer.
3212                  *
3213                  * 2.  There is not currently a LUN reference counting
3214                  *     mechanism, outside of outstanding transactions on
3215                  *     the LUN's OOA queue.  So a LUN could go away on us
3216                  *     while we're getting the LUN number, backend-specific
3217                  *     information, etc.  Thus, given the way things
3218                  *     currently work, we need to hold the CTL lock while
3219                  *     grabbing LUN information.
3220                  *
3221                  * So, from the user's standpoint, the best thing to do is
3222                  * allocate what he thinks is a reasonable buffer length,
3223                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3224                  * double the buffer length and try again.  (And repeat
3225                  * that until he succeeds.)
3226                  */
3227                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3228                 if (sb == NULL) {
3229                         list->status = CTL_LUN_LIST_ERROR;
3230                         snprintf(list->error_str, sizeof(list->error_str),
3231                                  "Unable to allocate %d bytes for LUN list",
3232                                  list->alloc_len);
3233                         break;
3234                 }
3235
3236                 sbuf_printf(sb, "<ctllunlist>\n");
3237
3238                 mtx_lock(&softc->ctl_lock);
3239                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3240                         mtx_lock(&lun->lun_lock);
3241                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3242                                              (uintmax_t)lun->lun);
3243
3244                         /*
3245                          * Bail out as soon as we see that we've overfilled
3246                          * the buffer.
3247                          */
3248                         if (retval != 0)
3249                                 break;
3250
3251                         retval = sbuf_printf(sb, "\t<backend_type>%s"
3252                                              "</backend_type>\n",
3253                                              (lun->backend == NULL) ?  "none" :
3254                                              lun->backend->name);
3255
3256                         if (retval != 0)
3257                                 break;
3258
3259                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3260                                              lun->be_lun->lun_type);
3261
3262                         if (retval != 0)
3263                                 break;
3264
3265                         if (lun->backend == NULL) {
3266                                 retval = sbuf_printf(sb, "</lun>\n");
3267                                 if (retval != 0)
3268                                         break;
3269                                 continue;
3270                         }
3271
3272                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3273                                              (lun->be_lun->maxlba > 0) ?
3274                                              lun->be_lun->maxlba + 1 : 0);
3275
3276                         if (retval != 0)
3277                                 break;
3278
3279                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3280                                              lun->be_lun->blocksize);
3281
3282                         if (retval != 0)
3283                                 break;
3284
3285                         retval = sbuf_printf(sb, "\t<serial_number>");
3286
3287                         if (retval != 0)
3288                                 break;
3289
3290                         retval = ctl_sbuf_printf_esc(sb,
3291                             lun->be_lun->serial_num,
3292                             sizeof(lun->be_lun->serial_num));
3293
3294                         if (retval != 0)
3295                                 break;
3296
3297                         retval = sbuf_printf(sb, "</serial_number>\n");
3298                 
3299                         if (retval != 0)
3300                                 break;
3301
3302                         retval = sbuf_printf(sb, "\t<device_id>");
3303
3304                         if (retval != 0)
3305                                 break;
3306
3307                         retval = ctl_sbuf_printf_esc(sb,
3308                             lun->be_lun->device_id,
3309                             sizeof(lun->be_lun->device_id));
3310
3311                         if (retval != 0)
3312                                 break;
3313
3314                         retval = sbuf_printf(sb, "</device_id>\n");
3315
3316                         if (retval != 0)
3317                                 break;
3318
3319                         if (lun->backend->lun_info != NULL) {
3320                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3321                                 if (retval != 0)
3322                                         break;
3323                         }
3324                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3325                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3326                                     opt->name, opt->value, opt->name);
3327                                 if (retval != 0)
3328                                         break;
3329                         }
3330
3331                         retval = sbuf_printf(sb, "</lun>\n");
3332
3333                         if (retval != 0)
3334                                 break;
3335                         mtx_unlock(&lun->lun_lock);
3336                 }
3337                 if (lun != NULL)
3338                         mtx_unlock(&lun->lun_lock);
3339                 mtx_unlock(&softc->ctl_lock);
3340
3341                 if ((retval != 0)
3342                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3343                         retval = 0;
3344                         sbuf_delete(sb);
3345                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3346                         snprintf(list->error_str, sizeof(list->error_str),
3347                                  "Out of space, %d bytes is too small",
3348                                  list->alloc_len);
3349                         break;
3350                 }
3351
3352                 sbuf_finish(sb);
3353
3354                 retval = copyout(sbuf_data(sb), list->lun_xml,
3355                                  sbuf_len(sb) + 1);
3356
3357                 list->fill_len = sbuf_len(sb) + 1;
3358                 list->status = CTL_LUN_LIST_OK;
3359                 sbuf_delete(sb);
3360                 break;
3361         }
3362         case CTL_ISCSI: {
3363                 struct ctl_iscsi *ci;
3364                 struct ctl_frontend *fe;
3365
3366                 ci = (struct ctl_iscsi *)addr;
3367
3368                 fe = ctl_frontend_find("iscsi");
3369                 if (fe == NULL) {
3370                         ci->status = CTL_ISCSI_ERROR;
3371                         snprintf(ci->error_str, sizeof(ci->error_str),
3372                             "Frontend \"iscsi\" not found.");
3373                         break;
3374                 }
3375
3376                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3377                 break;
3378         }
3379         case CTL_PORT_REQ: {
3380                 struct ctl_req *req;
3381                 struct ctl_frontend *fe;
3382
3383                 req = (struct ctl_req *)addr;
3384
3385                 fe = ctl_frontend_find(req->driver);
3386                 if (fe == NULL) {
3387                         req->status = CTL_LUN_ERROR;
3388                         snprintf(req->error_str, sizeof(req->error_str),
3389                             "Frontend \"%s\" not found.", req->driver);
3390                         break;
3391                 }
3392                 if (req->num_args > 0) {
3393                         req->kern_args = ctl_copyin_args(req->num_args,
3394                             req->args, req->error_str, sizeof(req->error_str));
3395                         if (req->kern_args == NULL) {
3396                                 req->status = CTL_LUN_ERROR;
3397                                 break;
3398                         }
3399                 }
3400
3401                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3402
3403                 if (req->num_args > 0) {
3404                         ctl_copyout_args(req->num_args, req->kern_args);
3405                         ctl_free_args(req->num_args, req->kern_args);
3406                 }
3407                 break;
3408         }
3409         case CTL_PORT_LIST: {
3410                 struct sbuf *sb;
3411                 struct ctl_port *port;
3412                 struct ctl_lun_list *list;
3413                 struct ctl_option *opt;
3414                 int j;
3415                 uint32_t plun;
3416
3417                 list = (struct ctl_lun_list *)addr;
3418
3419                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3420                 if (sb == NULL) {
3421                         list->status = CTL_LUN_LIST_ERROR;
3422                         snprintf(list->error_str, sizeof(list->error_str),
3423                                  "Unable to allocate %d bytes for LUN list",
3424                                  list->alloc_len);
3425                         break;
3426                 }
3427
3428                 sbuf_printf(sb, "<ctlportlist>\n");
3429
3430                 mtx_lock(&softc->ctl_lock);
3431                 STAILQ_FOREACH(port, &softc->port_list, links) {
3432                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3433                                              (uintmax_t)port->targ_port);
3434
3435                         /*
3436                          * Bail out as soon as we see that we've overfilled
3437                          * the buffer.
3438                          */
3439                         if (retval != 0)
3440                                 break;
3441
3442                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3443                             "</frontend_type>\n", port->frontend->name);
3444                         if (retval != 0)
3445                                 break;
3446
3447                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3448                                              port->port_type);
3449                         if (retval != 0)
3450                                 break;
3451
3452                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3453                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3454                         if (retval != 0)
3455                                 break;
3456
3457                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3458                             port->port_name);
3459                         if (retval != 0)
3460                                 break;
3461
3462                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3463                             port->physical_port);
3464                         if (retval != 0)
3465                                 break;
3466
3467                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3468                             port->virtual_port);
3469                         if (retval != 0)
3470                                 break;
3471
3472                         if (port->target_devid != NULL) {
3473                                 sbuf_printf(sb, "\t<target>");
3474                                 ctl_id_sbuf(port->target_devid, sb);
3475                                 sbuf_printf(sb, "</target>\n");
3476                         }
3477
3478                         if (port->port_devid != NULL) {
3479                                 sbuf_printf(sb, "\t<port>");
3480                                 ctl_id_sbuf(port->port_devid, sb);
3481                                 sbuf_printf(sb, "</port>\n");
3482                         }
3483
3484                         if (port->port_info != NULL) {
3485                                 retval = port->port_info(port->onoff_arg, sb);
3486                                 if (retval != 0)
3487                                         break;
3488                         }
3489                         STAILQ_FOREACH(opt, &port->options, links) {
3490                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3491                                     opt->name, opt->value, opt->name);
3492                                 if (retval != 0)
3493                                         break;
3494                         }
3495
3496                         if (port->lun_map != NULL) {
3497                                 sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3498                                 for (j = 0; j < CTL_MAX_LUNS; j++) {
3499                                         plun = ctl_lun_map_from_port(port, j);
3500                                         if (plun >= CTL_MAX_LUNS)
3501                                                 continue;
3502                                         sbuf_printf(sb,
3503                                             "\t<lun id=\"%u\">%u</lun>\n",
3504                                             j, plun);
3505                                 }
3506                         }
3507
3508                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3509                                 if (port->wwpn_iid[j].in_use == 0 ||
3510                                     (port->wwpn_iid[j].wwpn == 0 &&
3511                                      port->wwpn_iid[j].name == NULL))
3512                                         continue;
3513
3514                                 if (port->wwpn_iid[j].name != NULL)
3515                                         retval = sbuf_printf(sb,
3516                                             "\t<initiator id=\"%u\">%s</initiator>\n",
3517                                             j, port->wwpn_iid[j].name);
3518                                 else
3519                                         retval = sbuf_printf(sb,
3520                                             "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3521                                             j, port->wwpn_iid[j].wwpn);
3522                                 if (retval != 0)
3523                                         break;
3524                         }
3525                         if (retval != 0)
3526                                 break;
3527
3528                         retval = sbuf_printf(sb, "</targ_port>\n");
3529                         if (retval != 0)
3530                                 break;
3531                 }
3532                 mtx_unlock(&softc->ctl_lock);
3533
3534                 if ((retval != 0)
3535                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3536                         retval = 0;
3537                         sbuf_delete(sb);
3538                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3539                         snprintf(list->error_str, sizeof(list->error_str),
3540                                  "Out of space, %d bytes is too small",
3541                                  list->alloc_len);
3542                         break;
3543                 }
3544
3545                 sbuf_finish(sb);
3546
3547                 retval = copyout(sbuf_data(sb), list->lun_xml,
3548                                  sbuf_len(sb) + 1);
3549
3550                 list->fill_len = sbuf_len(sb) + 1;
3551                 list->status = CTL_LUN_LIST_OK;
3552                 sbuf_delete(sb);
3553                 break;
3554         }
3555         case CTL_LUN_MAP: {
3556                 struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3557                 struct ctl_port *port;
3558
3559                 mtx_lock(&softc->ctl_lock);
3560                 if (lm->port >= CTL_MAX_PORTS ||
3561                     (port = softc->ctl_ports[lm->port]) == NULL) {
3562                         mtx_unlock(&softc->ctl_lock);
3563                         return (ENXIO);
3564                 }
3565                 if (lm->plun < CTL_MAX_LUNS) {
3566                         if (lm->lun == UINT32_MAX)
3567                                 retval = ctl_lun_map_unset(port, lm->plun);
3568                         else if (lm->lun < CTL_MAX_LUNS &&
3569                             softc->ctl_luns[lm->lun] != NULL)
3570                                 retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3571                         else {
3572                                 mtx_unlock(&softc->ctl_lock);
3573                                 return (ENXIO);
3574                         }
3575                 } else if (lm->plun == UINT32_MAX) {
3576                         if (lm->lun == UINT32_MAX)
3577                                 retval = ctl_lun_map_deinit(port);
3578                         else
3579                                 retval = ctl_lun_map_init(port);
3580                 } else {
3581                         mtx_unlock(&softc->ctl_lock);
3582                         return (ENXIO);
3583                 }
3584                 mtx_unlock(&softc->ctl_lock);
3585                 break;
3586         }
3587         default: {
3588                 /* XXX KDM should we fix this? */
3589 #if 0
3590                 struct ctl_backend_driver *backend;
3591                 unsigned int type;
3592                 int found;
3593
3594                 found = 0;
3595
3596                 /*
3597                  * We encode the backend type as the ioctl type for backend
3598                  * ioctls.  So parse it out here, and then search for a
3599                  * backend of this type.
3600                  */
3601                 type = _IOC_TYPE(cmd);
3602
3603                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3604                         if (backend->type == type) {
3605                                 found = 1;
3606                                 break;
3607                         }
3608                 }
3609                 if (found == 0) {
3610                         printf("ctl: unknown ioctl command %#lx or backend "
3611                                "%d\n", cmd, type);
3612                         retval = EINVAL;
3613                         break;
3614                 }
3615                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3616 #endif
3617                 retval = ENOTTY;
3618                 break;
3619         }
3620         }
3621         return (retval);
3622 }
3623
3624 uint32_t
3625 ctl_get_initindex(struct ctl_nexus *nexus)
3626 {
3627         if (nexus->targ_port < CTL_MAX_PORTS)
3628                 return (nexus->initid.id +
3629                         (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3630         else
3631                 return (nexus->initid.id +
3632                        ((nexus->targ_port - CTL_MAX_PORTS) *
3633                         CTL_MAX_INIT_PER_PORT));
3634 }
3635
3636 uint32_t
3637 ctl_get_resindex(struct ctl_nexus *nexus)
3638 {
3639         return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3640 }
3641
3642 uint32_t
3643 ctl_port_idx(int port_num)
3644 {
3645         if (port_num < CTL_MAX_PORTS)
3646                 return(port_num);
3647         else
3648                 return(port_num - CTL_MAX_PORTS);
3649 }
3650
3651 int
3652 ctl_lun_map_init(struct ctl_port *port)
3653 {
3654         uint32_t i;
3655
3656         if (port->lun_map == NULL)
3657                 port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3658                     M_CTL, M_NOWAIT);
3659         if (port->lun_map == NULL)
3660                 return (ENOMEM);
3661         for (i = 0; i < CTL_MAX_LUNS; i++)
3662                 port->lun_map[i] = UINT32_MAX;
3663         return (0);
3664 }
3665
3666 int
3667 ctl_lun_map_deinit(struct ctl_port *port)
3668 {
3669
3670         if (port->lun_map == NULL)
3671                 return (0);
3672         free(port->lun_map, M_CTL);
3673         port->lun_map = NULL;
3674         return (0);
3675 }
3676
3677 int
3678 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3679 {
3680         int status;
3681
3682         if (port->lun_map == NULL) {
3683                 status = ctl_lun_map_init(port);
3684                 if (status != 0)
3685                         return (status);
3686         }
3687         port->lun_map[plun] = glun;
3688         return (0);
3689 }
3690
3691 int
3692 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3693 {
3694
3695         if (port->lun_map == NULL)
3696                 return (0);
3697         port->lun_map[plun] = UINT32_MAX;
3698         return (0);
3699 }
3700
3701 int
3702 ctl_lun_map_unsetg(struct ctl_port *port, uint32_t glun)
3703 {
3704         int i;
3705
3706         if (port->lun_map == NULL)
3707                 return (0);
3708         for (i = 0; i < CTL_MAX_LUNS; i++) {
3709                 if (port->lun_map[i] == glun)
3710                         port->lun_map[i] = UINT32_MAX;
3711         }
3712         return (0);
3713 }
3714
3715 uint32_t
3716 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3717 {
3718
3719         if (port == NULL)
3720                 return (UINT32_MAX);
3721         if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3722                 return (lun_id);
3723         return (port->lun_map[lun_id]);
3724 }
3725
3726 uint32_t
3727 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3728 {
3729         uint32_t i;
3730
3731         if (port == NULL)
3732                 return (UINT32_MAX);
3733         if (port->lun_map == NULL)
3734                 return (lun_id);
3735         for (i = 0; i < CTL_MAX_LUNS; i++) {
3736                 if (port->lun_map[i] == lun_id)
3737                         return (i);
3738         }
3739         return (UINT32_MAX);
3740 }
3741
3742 static struct ctl_port *
3743 ctl_io_port(struct ctl_io_hdr *io_hdr)
3744 {
3745         int port_num;
3746
3747         port_num = io_hdr->nexus.targ_port;
3748         return (control_softc->ctl_ports[ctl_port_idx(port_num)]);
3749 }
3750
3751 /*
3752  * Note:  This only works for bitmask sizes that are at least 32 bits, and
3753  * that are a power of 2.
3754  */
3755 int
3756 ctl_ffz(uint32_t *mask, uint32_t size)
3757 {
3758         uint32_t num_chunks, num_pieces;
3759         int i, j;
3760
3761         num_chunks = (size >> 5);
3762         if (num_chunks == 0)
3763                 num_chunks++;
3764         num_pieces = MIN((sizeof(uint32_t) * 8), size);
3765
3766         for (i = 0; i < num_chunks; i++) {
3767                 for (j = 0; j < num_pieces; j++) {
3768                         if ((mask[i] & (1 << j)) == 0)
3769                                 return ((i << 5) + j);
3770                 }
3771         }
3772
3773         return (-1);
3774 }
3775
3776 int
3777 ctl_set_mask(uint32_t *mask, uint32_t bit)
3778 {
3779         uint32_t chunk, piece;
3780
3781         chunk = bit >> 5;
3782         piece = bit % (sizeof(uint32_t) * 8);
3783
3784         if ((mask[chunk] & (1 << piece)) != 0)
3785                 return (-1);
3786         else
3787                 mask[chunk] |= (1 << piece);
3788
3789         return (0);
3790 }
3791
3792 int
3793 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3794 {
3795         uint32_t chunk, piece;
3796
3797         chunk = bit >> 5;
3798         piece = bit % (sizeof(uint32_t) * 8);
3799
3800         if ((mask[chunk] & (1 << piece)) == 0)
3801                 return (-1);
3802         else
3803                 mask[chunk] &= ~(1 << piece);
3804
3805         return (0);
3806 }
3807
3808 int
3809 ctl_is_set(uint32_t *mask, uint32_t bit)
3810 {
3811         uint32_t chunk, piece;
3812
3813         chunk = bit >> 5;
3814         piece = bit % (sizeof(uint32_t) * 8);
3815
3816         if ((mask[chunk] & (1 << piece)) == 0)
3817                 return (0);
3818         else
3819                 return (1);
3820 }
3821
3822 static uint64_t
3823 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3824 {
3825         uint64_t *t;
3826
3827         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3828         if (t == NULL)
3829                 return (0);
3830         return (t[residx % CTL_MAX_INIT_PER_PORT]);
3831 }
3832
3833 static void
3834 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3835 {
3836         uint64_t *t;
3837
3838         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3839         if (t == NULL)
3840                 return;
3841         t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3842 }
3843
3844 static void
3845 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3846 {
3847         uint64_t *p;
3848         u_int i;
3849
3850         i = residx/CTL_MAX_INIT_PER_PORT;
3851         if (lun->pr_keys[i] != NULL)
3852                 return;
3853         mtx_unlock(&lun->lun_lock);
3854         p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3855             M_WAITOK | M_ZERO);
3856         mtx_lock(&lun->lun_lock);
3857         if (lun->pr_keys[i] == NULL)
3858                 lun->pr_keys[i] = p;
3859         else
3860                 free(p, M_CTL);
3861 }
3862
3863 static void
3864 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3865 {
3866         uint64_t *t;
3867
3868         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3869         KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3870         t[residx % CTL_MAX_INIT_PER_PORT] = key;
3871 }
3872
3873 /*
3874  * ctl_softc, pool_name, total_ctl_io are passed in.
3875  * npool is passed out.
3876  */
3877 int
3878 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3879                 uint32_t total_ctl_io, void **npool)
3880 {
3881 #ifdef IO_POOLS
3882         struct ctl_io_pool *pool;
3883
3884         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3885                                             M_NOWAIT | M_ZERO);
3886         if (pool == NULL)
3887                 return (ENOMEM);
3888
3889         snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3890         pool->ctl_softc = ctl_softc;
3891         pool->zone = uma_zsecond_create(pool->name, NULL,
3892             NULL, NULL, NULL, ctl_softc->io_zone);
3893         /* uma_prealloc(pool->zone, total_ctl_io); */
3894
3895         *npool = pool;
3896 #else
3897         *npool = ctl_softc->io_zone;
3898 #endif
3899         return (0);
3900 }
3901
3902 void
3903 ctl_pool_free(struct ctl_io_pool *pool)
3904 {
3905
3906         if (pool == NULL)
3907                 return;
3908
3909 #ifdef IO_POOLS
3910         uma_zdestroy(pool->zone);
3911         free(pool, M_CTL);
3912 #endif
3913 }
3914
3915 union ctl_io *
3916 ctl_alloc_io(void *pool_ref)
3917 {
3918         union ctl_io *io;
3919 #ifdef IO_POOLS
3920         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3921
3922         io = uma_zalloc(pool->zone, M_WAITOK);
3923 #else
3924         io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3925 #endif
3926         if (io != NULL)
3927                 io->io_hdr.pool = pool_ref;
3928         return (io);
3929 }
3930
3931 union ctl_io *
3932 ctl_alloc_io_nowait(void *pool_ref)
3933 {
3934         union ctl_io *io;
3935 #ifdef IO_POOLS
3936         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3937
3938         io = uma_zalloc(pool->zone, M_NOWAIT);
3939 #else
3940         io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3941 #endif
3942         if (io != NULL)
3943                 io->io_hdr.pool = pool_ref;
3944         return (io);
3945 }
3946
3947 void
3948 ctl_free_io(union ctl_io *io)
3949 {
3950 #ifdef IO_POOLS
3951         struct ctl_io_pool *pool;
3952 #endif
3953
3954         if (io == NULL)
3955                 return;
3956
3957 #ifdef IO_POOLS
3958         pool = (struct ctl_io_pool *)io->io_hdr.pool;
3959         uma_zfree(pool->zone, io);
3960 #else
3961         uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3962 #endif
3963 }
3964
3965 void
3966 ctl_zero_io(union ctl_io *io)
3967 {
3968         void *pool_ref;
3969
3970         if (io == NULL)
3971                 return;
3972
3973         /*
3974          * May need to preserve linked list pointers at some point too.
3975          */
3976         pool_ref = io->io_hdr.pool;
3977         memset(io, 0, sizeof(*io));
3978         io->io_hdr.pool = pool_ref;
3979 }
3980
3981 /*
3982  * This routine is currently used for internal copies of ctl_ios that need
3983  * to persist for some reason after we've already returned status to the
3984  * FETD.  (Thus the flag set.)
3985  *
3986  * XXX XXX
3987  * Note that this makes a blind copy of all fields in the ctl_io, except
3988  * for the pool reference.  This includes any memory that has been
3989  * allocated!  That memory will no longer be valid after done has been
3990  * called, so this would be VERY DANGEROUS for command that actually does
3991  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3992  * start and stop commands, which don't transfer any data, so this is not a
3993  * problem.  If it is used for anything else, the caller would also need to
3994  * allocate data buffer space and this routine would need to be modified to
3995  * copy the data buffer(s) as well.
3996  */
3997 void
3998 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3999 {
4000         void *pool_ref;
4001
4002         if ((src == NULL)
4003          || (dest == NULL))
4004                 return;
4005
4006         /*
4007          * May need to preserve linked list pointers at some point too.
4008          */
4009         pool_ref = dest->io_hdr.pool;
4010
4011         memcpy(dest, src, MIN(sizeof(*src), sizeof(*dest)));
4012
4013         dest->io_hdr.pool = pool_ref;
4014         /*
4015          * We need to know that this is an internal copy, and doesn't need
4016          * to get passed back to the FETD that allocated it.
4017          */
4018         dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
4019 }
4020
4021 int
4022 ctl_expand_number(const char *buf, uint64_t *num)
4023 {
4024         char *endptr;
4025         uint64_t number;
4026         unsigned shift;
4027
4028         number = strtoq(buf, &endptr, 0);
4029
4030         switch (tolower((unsigned char)*endptr)) {
4031         case 'e':
4032                 shift = 60;
4033                 break;
4034         case 'p':
4035                 shift = 50;
4036                 break;
4037         case 't':
4038                 shift = 40;
4039                 break;
4040         case 'g':
4041                 shift = 30;
4042                 break;
4043         case 'm':
4044                 shift = 20;
4045                 break;
4046         case 'k':
4047                 shift = 10;
4048                 break;
4049         case 'b':
4050         case '\0': /* No unit. */
4051                 *num = number;
4052                 return (0);
4053         default:
4054                 /* Unrecognized unit. */
4055                 return (-1);
4056         }
4057
4058         if ((number << shift) >> shift != number) {
4059                 /* Overflow */
4060                 return (-1);
4061         }
4062         *num = number << shift;
4063         return (0);
4064 }
4065
4066
4067 /*
4068  * This routine could be used in the future to load default and/or saved
4069  * mode page parameters for a particuar lun.
4070  */
4071 static int
4072 ctl_init_page_index(struct ctl_lun *lun)
4073 {
4074         int i;
4075         struct ctl_page_index *page_index;
4076         const char *value;
4077         uint64_t ival;
4078
4079         memcpy(&lun->mode_pages.index, page_index_template,
4080                sizeof(page_index_template));
4081
4082         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4083
4084                 page_index = &lun->mode_pages.index[i];
4085                 /*
4086                  * If this is a disk-only mode page, there's no point in
4087                  * setting it up.  For some pages, we have to have some
4088                  * basic information about the disk in order to calculate the
4089                  * mode page data.
4090                  */
4091                 if ((lun->be_lun->lun_type != T_DIRECT)
4092                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4093                         continue;
4094
4095                 switch (page_index->page_code & SMPH_PC_MASK) {
4096                 case SMS_RW_ERROR_RECOVERY_PAGE: {
4097                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4098                                 panic("subpage is incorrect!");
4099                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4100                                &rw_er_page_default,
4101                                sizeof(rw_er_page_default));
4102                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4103                                &rw_er_page_changeable,
4104                                sizeof(rw_er_page_changeable));
4105                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4106                                &rw_er_page_default,
4107                                sizeof(rw_er_page_default));
4108                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4109                                &rw_er_page_default,
4110                                sizeof(rw_er_page_default));
4111                         page_index->page_data =
4112                                 (uint8_t *)lun->mode_pages.rw_er_page;
4113                         break;
4114                 }
4115                 case SMS_FORMAT_DEVICE_PAGE: {
4116                         struct scsi_format_page *format_page;
4117
4118                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4119                                 panic("subpage is incorrect!");
4120
4121                         /*
4122                          * Sectors per track are set above.  Bytes per
4123                          * sector need to be set here on a per-LUN basis.
4124                          */
4125                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4126                                &format_page_default,
4127                                sizeof(format_page_default));
4128                         memcpy(&lun->mode_pages.format_page[
4129                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
4130                                sizeof(format_page_changeable));
4131                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4132                                &format_page_default,
4133                                sizeof(format_page_default));
4134                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4135                                &format_page_default,
4136                                sizeof(format_page_default));
4137
4138                         format_page = &lun->mode_pages.format_page[
4139                                 CTL_PAGE_CURRENT];
4140                         scsi_ulto2b(lun->be_lun->blocksize,
4141                                     format_page->bytes_per_sector);
4142
4143                         format_page = &lun->mode_pages.format_page[
4144                                 CTL_PAGE_DEFAULT];
4145                         scsi_ulto2b(lun->be_lun->blocksize,
4146                                     format_page->bytes_per_sector);
4147
4148                         format_page = &lun->mode_pages.format_page[
4149                                 CTL_PAGE_SAVED];
4150                         scsi_ulto2b(lun->be_lun->blocksize,
4151                                     format_page->bytes_per_sector);
4152
4153                         page_index->page_data =
4154                                 (uint8_t *)lun->mode_pages.format_page;
4155                         break;
4156                 }
4157                 case SMS_RIGID_DISK_PAGE: {
4158                         struct scsi_rigid_disk_page *rigid_disk_page;
4159                         uint32_t sectors_per_cylinder;
4160                         uint64_t cylinders;
4161 #ifndef __XSCALE__
4162                         int shift;
4163 #endif /* !__XSCALE__ */
4164
4165                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4166                                 panic("invalid subpage value %d",
4167                                       page_index->subpage);
4168
4169                         /*
4170                          * Rotation rate and sectors per track are set
4171                          * above.  We calculate the cylinders here based on
4172                          * capacity.  Due to the number of heads and
4173                          * sectors per track we're using, smaller arrays
4174                          * may turn out to have 0 cylinders.  Linux and
4175                          * FreeBSD don't pay attention to these mode pages
4176                          * to figure out capacity, but Solaris does.  It
4177                          * seems to deal with 0 cylinders just fine, and
4178                          * works out a fake geometry based on the capacity.
4179                          */
4180                         memcpy(&lun->mode_pages.rigid_disk_page[
4181                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4182                                sizeof(rigid_disk_page_default));
4183                         memcpy(&lun->mode_pages.rigid_disk_page[
4184                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4185                                sizeof(rigid_disk_page_changeable));
4186
4187                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4188                                 CTL_DEFAULT_HEADS;
4189
4190                         /*
4191                          * The divide method here will be more accurate,
4192                          * probably, but results in floating point being
4193                          * used in the kernel on i386 (__udivdi3()).  On the
4194                          * XScale, though, __udivdi3() is implemented in
4195                          * software.
4196                          *
4197                          * The shift method for cylinder calculation is
4198                          * accurate if sectors_per_cylinder is a power of
4199                          * 2.  Otherwise it might be slightly off -- you
4200                          * might have a bit of a truncation problem.
4201                          */
4202 #ifdef  __XSCALE__
4203                         cylinders = (lun->be_lun->maxlba + 1) /
4204                                 sectors_per_cylinder;
4205 #else
4206                         for (shift = 31; shift > 0; shift--) {
4207                                 if (sectors_per_cylinder & (1 << shift))
4208                                         break;
4209                         }
4210                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
4211 #endif
4212
4213                         /*
4214                          * We've basically got 3 bytes, or 24 bits for the
4215                          * cylinder size in the mode page.  If we're over,
4216                          * just round down to 2^24.
4217                          */
4218                         if (cylinders > 0xffffff)
4219                                 cylinders = 0xffffff;
4220
4221                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4222                                 CTL_PAGE_DEFAULT];
4223                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4224
4225                         if ((value = ctl_get_opt(&lun->be_lun->options,
4226                             "rpm")) != NULL) {
4227                                 scsi_ulto2b(strtol(value, NULL, 0),
4228                                      rigid_disk_page->rotation_rate);
4229                         }
4230
4231                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4232                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4233                                sizeof(rigid_disk_page_default));
4234                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4235                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4236                                sizeof(rigid_disk_page_default));
4237
4238                         page_index->page_data =
4239                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
4240                         break;
4241                 }
4242                 case SMS_CACHING_PAGE: {
4243                         struct scsi_caching_page *caching_page;
4244
4245                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4246                                 panic("invalid subpage value %d",
4247                                       page_index->subpage);
4248                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4249                                &caching_page_default,
4250                                sizeof(caching_page_default));
4251                         memcpy(&lun->mode_pages.caching_page[
4252                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4253                                sizeof(caching_page_changeable));
4254                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4255                                &caching_page_default,
4256                                sizeof(caching_page_default));
4257                         caching_page = &lun->mode_pages.caching_page[
4258                             CTL_PAGE_SAVED];
4259                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
4260                         if (value != NULL && strcmp(value, "off") == 0)
4261                                 caching_page->flags1 &= ~SCP_WCE;
4262                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
4263                         if (value != NULL && strcmp(value, "off") == 0)
4264                                 caching_page->flags1 |= SCP_RCD;
4265                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4266                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4267                                sizeof(caching_page_default));
4268                         page_index->page_data =
4269                                 (uint8_t *)lun->mode_pages.caching_page;
4270                         break;
4271                 }
4272                 case SMS_CONTROL_MODE_PAGE: {
4273                         struct scsi_control_page *control_page;
4274
4275                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4276                                 panic("invalid subpage value %d",
4277                                       page_index->subpage);
4278
4279                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4280                                &control_page_default,
4281                                sizeof(control_page_default));
4282                         memcpy(&lun->mode_pages.control_page[
4283                                CTL_PAGE_CHANGEABLE], &control_page_changeable,
4284                                sizeof(control_page_changeable));
4285                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4286                                &control_page_default,
4287                                sizeof(control_page_default));
4288                         control_page = &lun->mode_pages.control_page[
4289                             CTL_PAGE_SAVED];
4290                         value = ctl_get_opt(&lun->be_lun->options, "reordering");
4291                         if (value != NULL && strcmp(value, "unrestricted") == 0) {
4292                                 control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4293                                 control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4294                         }
4295                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4296                                &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4297                                sizeof(control_page_default));
4298                         page_index->page_data =
4299                                 (uint8_t *)lun->mode_pages.control_page;
4300                         break;
4301
4302                 }
4303                 case SMS_INFO_EXCEPTIONS_PAGE: {
4304                         switch (page_index->subpage) {
4305                         case SMS_SUBPAGE_PAGE_0:
4306                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4307                                        &ie_page_default,
4308                                        sizeof(ie_page_default));
4309                                 memcpy(&lun->mode_pages.ie_page[
4310                                        CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4311                                        sizeof(ie_page_changeable));
4312                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4313                                        &ie_page_default,
4314                                        sizeof(ie_page_default));
4315                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4316                                        &ie_page_default,
4317                                        sizeof(ie_page_default));
4318                                 page_index->page_data =
4319                                         (uint8_t *)lun->mode_pages.ie_page;
4320                                 break;
4321                         case 0x02: {
4322                                 struct ctl_logical_block_provisioning_page *page;
4323
4324                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4325                                        &lbp_page_default,
4326                                        sizeof(lbp_page_default));
4327                                 memcpy(&lun->mode_pages.lbp_page[
4328                                        CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4329                                        sizeof(lbp_page_changeable));
4330                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4331                                        &lbp_page_default,
4332                                        sizeof(lbp_page_default));
4333                                 page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4334                                 value = ctl_get_opt(&lun->be_lun->options,
4335                                     "avail-threshold");
4336                                 if (value != NULL &&
4337                                     ctl_expand_number(value, &ival) == 0) {
4338                                         page->descr[0].flags |= SLBPPD_ENABLED |
4339                                             SLBPPD_ARMING_DEC;
4340                                         if (lun->be_lun->blocksize)
4341                                                 ival /= lun->be_lun->blocksize;
4342                                         else
4343                                                 ival /= 512;
4344                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4345                                             page->descr[0].count);
4346                                 }
4347                                 value = ctl_get_opt(&lun->be_lun->options,
4348                                     "used-threshold");
4349                                 if (value != NULL &&
4350                                     ctl_expand_number(value, &ival) == 0) {
4351                                         page->descr[1].flags |= SLBPPD_ENABLED |
4352                                             SLBPPD_ARMING_INC;
4353                                         if (lun->be_lun->blocksize)
4354                                                 ival /= lun->be_lun->blocksize;
4355                                         else
4356                                                 ival /= 512;
4357                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4358                                             page->descr[1].count);
4359                                 }
4360                                 value = ctl_get_opt(&lun->be_lun->options,
4361                                     "pool-avail-threshold");
4362                                 if (value != NULL &&
4363                                     ctl_expand_number(value, &ival) == 0) {
4364                                         page->descr[2].flags |= SLBPPD_ENABLED |
4365                                             SLBPPD_ARMING_DEC;
4366                                         if (lun->be_lun->blocksize)
4367                                                 ival /= lun->be_lun->blocksize;
4368                                         else
4369                                                 ival /= 512;
4370                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4371                                             page->descr[2].count);
4372                                 }
4373                                 value = ctl_get_opt(&lun->be_lun->options,
4374                                     "pool-used-threshold");
4375                                 if (value != NULL &&
4376                                     ctl_expand_number(value, &ival) == 0) {
4377                                         page->descr[3].flags |= SLBPPD_ENABLED |
4378                                             SLBPPD_ARMING_INC;
4379                                         if (lun->be_lun->blocksize)
4380                                                 ival /= lun->be_lun->blocksize;
4381                                         else
4382                                                 ival /= 512;
4383                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4384                                             page->descr[3].count);
4385                                 }
4386                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4387                                        &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4388                                        sizeof(lbp_page_default));
4389                                 page_index->page_data =
4390                                         (uint8_t *)lun->mode_pages.lbp_page;
4391                         }}
4392                         break;
4393                 }
4394                 case SMS_VENDOR_SPECIFIC_PAGE:{
4395                         switch (page_index->subpage) {
4396                         case DBGCNF_SUBPAGE_CODE: {
4397                                 struct copan_debugconf_subpage *current_page,
4398                                                                *saved_page;
4399
4400                                 memcpy(&lun->mode_pages.debugconf_subpage[
4401                                        CTL_PAGE_CURRENT],
4402                                        &debugconf_page_default,
4403                                        sizeof(debugconf_page_default));
4404                                 memcpy(&lun->mode_pages.debugconf_subpage[
4405                                        CTL_PAGE_CHANGEABLE],
4406                                        &debugconf_page_changeable,
4407                                        sizeof(debugconf_page_changeable));
4408                                 memcpy(&lun->mode_pages.debugconf_subpage[
4409                                        CTL_PAGE_DEFAULT],
4410                                        &debugconf_page_default,
4411                                        sizeof(debugconf_page_default));
4412                                 memcpy(&lun->mode_pages.debugconf_subpage[
4413                                        CTL_PAGE_SAVED],
4414                                        &debugconf_page_default,
4415                                        sizeof(debugconf_page_default));
4416                                 page_index->page_data =
4417                                         (uint8_t *)lun->mode_pages.debugconf_subpage;
4418
4419                                 current_page = (struct copan_debugconf_subpage *)
4420                                         (page_index->page_data +
4421                                          (page_index->page_len *
4422                                           CTL_PAGE_CURRENT));
4423                                 saved_page = (struct copan_debugconf_subpage *)
4424                                         (page_index->page_data +
4425                                          (page_index->page_len *
4426                                           CTL_PAGE_SAVED));
4427                                 break;
4428                         }
4429                         default:
4430                                 panic("invalid subpage value %d",
4431                                       page_index->subpage);
4432                                 break;
4433                         }
4434                         break;
4435                 }
4436                 default:
4437                         panic("invalid page value %d",
4438                               page_index->page_code & SMPH_PC_MASK);
4439                         break;
4440         }
4441         }
4442
4443         return (CTL_RETVAL_COMPLETE);
4444 }
4445
4446 static int
4447 ctl_init_log_page_index(struct ctl_lun *lun)
4448 {
4449         struct ctl_page_index *page_index;
4450         int i, j, k, prev;
4451
4452         memcpy(&lun->log_pages.index, log_page_index_template,
4453                sizeof(log_page_index_template));
4454
4455         prev = -1;
4456         for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4457
4458                 page_index = &lun->log_pages.index[i];
4459                 /*
4460                  * If this is a disk-only mode page, there's no point in
4461                  * setting it up.  For some pages, we have to have some
4462                  * basic information about the disk in order to calculate the
4463                  * mode page data.
4464                  */
4465                 if ((lun->be_lun->lun_type != T_DIRECT)
4466                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4467                         continue;
4468
4469                 if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4470                      lun->backend->lun_attr == NULL)
4471                         continue;
4472
4473                 if (page_index->page_code != prev) {
4474                         lun->log_pages.pages_page[j] = page_index->page_code;
4475                         prev = page_index->page_code;
4476                         j++;
4477                 }
4478                 lun->log_pages.subpages_page[k*2] = page_index->page_code;
4479                 lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4480                 k++;
4481         }
4482         lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4483         lun->log_pages.index[0].page_len = j;
4484         lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4485         lun->log_pages.index[1].page_len = k * 2;
4486         lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4487         lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4488         lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4489         lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4490
4491         return (CTL_RETVAL_COMPLETE);
4492 }
4493
4494 static int
4495 hex2bin(const char *str, uint8_t *buf, int buf_size)
4496 {
4497         int i;
4498         u_char c;
4499
4500         memset(buf, 0, buf_size);
4501         while (isspace(str[0]))
4502                 str++;
4503         if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4504                 str += 2;
4505         buf_size *= 2;
4506         for (i = 0; str[i] != 0 && i < buf_size; i++) {
4507                 c = str[i];
4508                 if (isdigit(c))
4509                         c -= '0';
4510                 else if (isalpha(c))
4511                         c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4512                 else
4513                         break;
4514                 if (c >= 16)
4515                         break;
4516                 if ((i & 1) == 0)
4517                         buf[i / 2] |= (c << 4);
4518                 else
4519                         buf[i / 2] |= c;
4520         }
4521         return ((i + 1) / 2);
4522 }
4523
4524 /*
4525  * LUN allocation.
4526  *
4527  * Requirements:
4528  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4529  *   wants us to allocate the LUN and he can block.
4530  * - ctl_softc is always set
4531  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4532  *
4533  * Returns 0 for success, non-zero (errno) for failure.
4534  */
4535 static int
4536 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4537               struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4538 {
4539         struct ctl_lun *nlun, *lun;
4540         struct ctl_port *port;
4541         struct scsi_vpd_id_descriptor *desc;
4542         struct scsi_vpd_id_t10 *t10id;
4543         const char *eui, *naa, *scsiname, *vendor, *value;
4544         int lun_number, i, lun_malloced;
4545         int devidlen, idlen1, idlen2 = 0, len;
4546
4547         if (be_lun == NULL)
4548                 return (EINVAL);
4549
4550         /*
4551          * We currently only support Direct Access or Processor LUN types.
4552          */
4553         switch (be_lun->lun_type) {
4554         case T_DIRECT:
4555                 break;
4556         case T_PROCESSOR:
4557                 break;
4558         case T_SEQUENTIAL:
4559         case T_CHANGER:
4560         default:
4561                 be_lun->lun_config_status(be_lun->be_lun,
4562                                           CTL_LUN_CONFIG_FAILURE);
4563                 break;
4564         }
4565         if (ctl_lun == NULL) {
4566                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4567                 lun_malloced = 1;
4568         } else {
4569                 lun_malloced = 0;
4570                 lun = ctl_lun;
4571         }
4572
4573         memset(lun, 0, sizeof(*lun));
4574         if (lun_malloced)
4575                 lun->flags = CTL_LUN_MALLOCED;
4576
4577         /* Generate LUN ID. */
4578         devidlen = max(CTL_DEVID_MIN_LEN,
4579             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4580         idlen1 = sizeof(*t10id) + devidlen;
4581         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4582         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4583         if (scsiname != NULL) {
4584                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4585                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4586         }
4587         eui = ctl_get_opt(&be_lun->options, "eui");
4588         if (eui != NULL) {
4589                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4590         }
4591         naa = ctl_get_opt(&be_lun->options, "naa");
4592         if (naa != NULL) {
4593                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4594         }
4595         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4596             M_CTL, M_WAITOK | M_ZERO);
4597         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4598         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4599         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4600         desc->length = idlen1;
4601         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4602         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4603         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4604                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4605         } else {
4606                 strncpy(t10id->vendor, vendor,
4607                     min(sizeof(t10id->vendor), strlen(vendor)));
4608         }
4609         strncpy((char *)t10id->vendor_spec_id,
4610             (char *)be_lun->device_id, devidlen);
4611         if (scsiname != NULL) {
4612                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4613                     desc->length);
4614                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4615                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4616                     SVPD_ID_TYPE_SCSI_NAME;
4617                 desc->length = idlen2;
4618                 strlcpy(desc->identifier, scsiname, idlen2);
4619         }
4620         if (eui != NULL) {
4621                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4622                     desc->length);
4623                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4624                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4625                     SVPD_ID_TYPE_EUI64;
4626                 desc->length = hex2bin(eui, desc->identifier, 16);
4627                 desc->length = desc->length > 12 ? 16 :
4628                     (desc->length > 8 ? 12 : 8);
4629                 len -= 16 - desc->length;
4630         }
4631         if (naa != NULL) {
4632                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4633                     desc->length);
4634                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4635                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4636                     SVPD_ID_TYPE_NAA;
4637                 desc->length = hex2bin(naa, desc->identifier, 16);
4638                 desc->length = desc->length > 8 ? 16 : 8;
4639                 len -= 16 - desc->length;
4640         }
4641         lun->lun_devid->len = len;
4642
4643         mtx_lock(&ctl_softc->ctl_lock);
4644         /*
4645          * See if the caller requested a particular LUN number.  If so, see
4646          * if it is available.  Otherwise, allocate the first available LUN.
4647          */
4648         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4649                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4650                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4651                         mtx_unlock(&ctl_softc->ctl_lock);
4652                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4653                                 printf("ctl: requested LUN ID %d is higher "
4654                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4655                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4656                         } else {
4657                                 /*
4658                                  * XXX KDM return an error, or just assign
4659                                  * another LUN ID in this case??
4660                                  */
4661                                 printf("ctl: requested LUN ID %d is already "
4662                                        "in use\n", be_lun->req_lun_id);
4663                         }
4664                         if (lun->flags & CTL_LUN_MALLOCED)
4665                                 free(lun, M_CTL);
4666                         be_lun->lun_config_status(be_lun->be_lun,
4667                                                   CTL_LUN_CONFIG_FAILURE);
4668                         return (ENOSPC);
4669                 }
4670                 lun_number = be_lun->req_lun_id;
4671         } else {
4672                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4673                 if (lun_number == -1) {
4674                         mtx_unlock(&ctl_softc->ctl_lock);
4675                         printf("ctl: can't allocate LUN on target %ju, out of "
4676                                "LUNs\n", (uintmax_t)target_id.id);
4677                         if (lun->flags & CTL_LUN_MALLOCED)
4678                                 free(lun, M_CTL);
4679                         be_lun->lun_config_status(be_lun->be_lun,
4680                                                   CTL_LUN_CONFIG_FAILURE);
4681                         return (ENOSPC);
4682                 }
4683         }
4684         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4685
4686         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4687         lun->target = target_id;
4688         lun->lun = lun_number;
4689         lun->be_lun = be_lun;
4690         /*
4691          * The processor LUN is always enabled.  Disk LUNs come on line
4692          * disabled, and must be enabled by the backend.
4693          */
4694         lun->flags |= CTL_LUN_DISABLED;
4695         lun->backend = be_lun->be;
4696         be_lun->ctl_lun = lun;
4697         be_lun->lun_id = lun_number;
4698         atomic_add_int(&be_lun->be->num_luns, 1);
4699         if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4700                 lun->flags |= CTL_LUN_OFFLINE;
4701
4702         if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4703                 lun->flags |= CTL_LUN_STOPPED;
4704
4705         if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4706                 lun->flags |= CTL_LUN_INOPERABLE;
4707
4708         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4709                 lun->flags |= CTL_LUN_PRIMARY_SC;
4710
4711         value = ctl_get_opt(&be_lun->options, "readonly");
4712         if (value != NULL && strcmp(value, "on") == 0)
4713                 lun->flags |= CTL_LUN_READONLY;
4714
4715         lun->serseq = CTL_LUN_SERSEQ_OFF;
4716         if (be_lun->flags & CTL_LUN_FLAG_SERSEQ_READ)
4717                 lun->serseq = CTL_LUN_SERSEQ_READ;
4718         value = ctl_get_opt(&be_lun->options, "serseq");
4719         if (value != NULL && strcmp(value, "on") == 0)
4720                 lun->serseq = CTL_LUN_SERSEQ_ON;
4721         else if (value != NULL && strcmp(value, "read") == 0)
4722                 lun->serseq = CTL_LUN_SERSEQ_READ;
4723         else if (value != NULL && strcmp(value, "off") == 0)
4724                 lun->serseq = CTL_LUN_SERSEQ_OFF;
4725
4726         lun->ctl_softc = ctl_softc;
4727 #ifdef CTL_TIME_IO
4728         lun->last_busy = getsbinuptime();
4729 #endif
4730         TAILQ_INIT(&lun->ooa_queue);
4731         TAILQ_INIT(&lun->blocked_queue);
4732         STAILQ_INIT(&lun->error_list);
4733         ctl_tpc_lun_init(lun);
4734
4735         /*
4736          * Initialize the mode and log page index.
4737          */
4738         ctl_init_page_index(lun);
4739         ctl_init_log_page_index(lun);
4740
4741         /*
4742          * Now, before we insert this lun on the lun list, set the lun
4743          * inventory changed UA for all other luns.
4744          */
4745         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4746                 mtx_lock(&nlun->lun_lock);
4747                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4748                 mtx_unlock(&nlun->lun_lock);
4749         }
4750
4751         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4752
4753         ctl_softc->ctl_luns[lun_number] = lun;
4754
4755         ctl_softc->num_luns++;
4756
4757         /* Setup statistics gathering */
4758         lun->stats.device_type = be_lun->lun_type;
4759         lun->stats.lun_number = lun_number;
4760         if (lun->stats.device_type == T_DIRECT)
4761                 lun->stats.blocksize = be_lun->blocksize;
4762         else
4763                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4764         for (i = 0;i < CTL_MAX_PORTS;i++)
4765                 lun->stats.ports[i].targ_port = i;
4766
4767         mtx_unlock(&ctl_softc->ctl_lock);
4768
4769         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4770
4771         /*
4772          * Run through each registered FETD and bring it online if it isn't
4773          * already.  Enable the target ID if it hasn't been enabled, and
4774          * enable this particular LUN.
4775          */
4776         STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4777                 int retval;
4778
4779                 retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4780                 if (retval != 0) {
4781                         printf("ctl_alloc_lun: FETD %s port %d returned error "
4782                                "%d for lun_enable on target %ju lun %d\n",
4783                                port->port_name, port->targ_port, retval,
4784                                (uintmax_t)target_id.id, lun_number);
4785                 } else
4786                         port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4787         }
4788         return (0);
4789 }
4790
4791 /*
4792  * Delete a LUN.
4793  * Assumptions:
4794  * - LUN has already been marked invalid and any pending I/O has been taken
4795  *   care of.
4796  */
4797 static int
4798 ctl_free_lun(struct ctl_lun *lun)
4799 {
4800         struct ctl_softc *softc;
4801         struct ctl_port *port;
4802         struct ctl_lun *nlun;
4803         int i;
4804
4805         softc = lun->ctl_softc;
4806
4807         mtx_assert(&softc->ctl_lock, MA_OWNED);
4808
4809         STAILQ_FOREACH(port, &softc->port_list, links)
4810                 ctl_lun_map_unsetg(port, lun->lun);
4811
4812         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4813
4814         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4815
4816         softc->ctl_luns[lun->lun] = NULL;
4817
4818         if (!TAILQ_EMPTY(&lun->ooa_queue))
4819                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4820
4821         softc->num_luns--;
4822
4823         /*
4824          * XXX KDM this scheme only works for a single target/multiple LUN
4825          * setup.  It needs to be revamped for a multiple target scheme.
4826          *
4827          * XXX KDM this results in port->lun_disable() getting called twice,
4828          * once when ctl_disable_lun() is called, and a second time here.
4829          * We really need to re-think the LUN disable semantics.  There
4830          * should probably be several steps/levels to LUN removal:
4831          *  - disable
4832          *  - invalidate
4833          *  - free
4834          *
4835          * Right now we only have a disable method when communicating to
4836          * the front end ports, at least for individual LUNs.
4837          */
4838 #if 0
4839         STAILQ_FOREACH(port, &softc->port_list, links) {
4840                 int retval;
4841
4842                 retval = port->lun_disable(port->targ_lun_arg, lun->target,
4843                                          lun->lun);
4844                 if (retval != 0) {
4845                         printf("ctl_free_lun: FETD %s port %d returned error "
4846                                "%d for lun_disable on target %ju lun %jd\n",
4847                                port->port_name, port->targ_port, retval,
4848                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4849                 }
4850
4851                 if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4852                         port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4853
4854                         retval = port->targ_disable(port->targ_lun_arg,lun->target);
4855                         if (retval != 0) {
4856                                 printf("ctl_free_lun: FETD %s port %d "
4857                                        "returned error %d for targ_disable on "
4858                                        "target %ju\n", port->port_name,
4859                                        port->targ_port, retval,
4860                                        (uintmax_t)lun->target.id);
4861                         } else
4862                                 port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4863
4864                         if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4865                                 continue;
4866
4867 #if 0
4868                         port->port_offline(port->onoff_arg);
4869                         port->status &= ~CTL_PORT_STATUS_ONLINE;
4870 #endif
4871                 }
4872         }
4873 #endif
4874
4875         /*
4876          * Tell the backend to free resources, if this LUN has a backend.
4877          */
4878         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4879         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4880
4881         ctl_tpc_lun_shutdown(lun);
4882         mtx_destroy(&lun->lun_lock);
4883         free(lun->lun_devid, M_CTL);
4884         for (i = 0; i < CTL_MAX_PORTS; i++)
4885                 free(lun->pending_ua[i], M_CTL);
4886         for (i = 0; i < 2 * CTL_MAX_PORTS; i++)
4887                 free(lun->pr_keys[i], M_CTL);
4888         free(lun->write_buffer, M_CTL);
4889         if (lun->flags & CTL_LUN_MALLOCED)
4890                 free(lun, M_CTL);
4891
4892         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4893                 mtx_lock(&nlun->lun_lock);
4894                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4895                 mtx_unlock(&nlun->lun_lock);
4896         }
4897
4898         return (0);
4899 }
4900
4901 static void
4902 ctl_create_lun(struct ctl_be_lun *be_lun)
4903 {
4904         struct ctl_softc *softc;
4905
4906         softc = control_softc;
4907
4908         /*
4909          * ctl_alloc_lun() should handle all potential failure cases.
4910          */
4911         ctl_alloc_lun(softc, NULL, be_lun, softc->target);
4912 }
4913
4914 int
4915 ctl_add_lun(struct ctl_be_lun *be_lun)
4916 {
4917         struct ctl_softc *softc = control_softc;
4918
4919         mtx_lock(&softc->ctl_lock);
4920         STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4921         mtx_unlock(&softc->ctl_lock);
4922         wakeup(&softc->pending_lun_queue);
4923
4924         return (0);
4925 }
4926
4927 int
4928 ctl_enable_lun(struct ctl_be_lun *be_lun)
4929 {
4930         struct ctl_softc *softc;
4931         struct ctl_port *port, *nport;
4932         struct ctl_lun *lun;
4933         int retval;
4934
4935         lun = (struct ctl_lun *)be_lun->ctl_lun;
4936         softc = lun->ctl_softc;
4937
4938         mtx_lock(&softc->ctl_lock);
4939         mtx_lock(&lun->lun_lock);
4940         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4941                 /*
4942                  * eh?  Why did we get called if the LUN is already
4943                  * enabled?
4944                  */
4945                 mtx_unlock(&lun->lun_lock);
4946                 mtx_unlock(&softc->ctl_lock);
4947                 return (0);
4948         }
4949         lun->flags &= ~CTL_LUN_DISABLED;
4950         mtx_unlock(&lun->lun_lock);
4951
4952         for (port = STAILQ_FIRST(&softc->port_list); port != NULL; port = nport) {
4953                 nport = STAILQ_NEXT(port, links);
4954
4955                 /*
4956                  * Drop the lock while we call the FETD's enable routine.
4957                  * This can lead to a callback into CTL (at least in the
4958                  * case of the internal initiator frontend.
4959                  */
4960                 mtx_unlock(&softc->ctl_lock);
4961                 retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4962                 mtx_lock(&softc->ctl_lock);
4963                 if (retval != 0) {
4964                         printf("%s: FETD %s port %d returned error "
4965                                "%d for lun_enable on target %ju lun %jd\n",
4966                                __func__, port->port_name, port->targ_port, retval,
4967                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4968                 }
4969 #if 0
4970                  else {
4971             /* NOTE:  TODO:  why does lun enable affect port status? */
4972                         port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4973                 }
4974 #endif
4975         }
4976
4977         mtx_unlock(&softc->ctl_lock);
4978
4979         return (0);
4980 }
4981
4982 int
4983 ctl_disable_lun(struct ctl_be_lun *be_lun)
4984 {
4985         struct ctl_softc *softc;
4986         struct ctl_port *port;
4987         struct ctl_lun *lun;
4988         int retval;
4989
4990         lun = (struct ctl_lun *)be_lun->ctl_lun;
4991         softc = lun->ctl_softc;
4992
4993         mtx_lock(&softc->ctl_lock);
4994         mtx_lock(&lun->lun_lock);
4995         if (lun->flags & CTL_LUN_DISABLED) {
4996                 mtx_unlock(&lun->lun_lock);
4997                 mtx_unlock(&softc->ctl_lock);
4998                 return (0);
4999         }
5000         lun->flags |= CTL_LUN_DISABLED;
5001         mtx_unlock(&lun->lun_lock);
5002
5003         STAILQ_FOREACH(port, &softc->port_list, links) {
5004                 mtx_unlock(&softc->ctl_lock);
5005                 /*
5006                  * Drop the lock before we call the frontend's disable
5007                  * routine, to avoid lock order reversals.
5008                  *
5009                  * XXX KDM what happens if the frontend list changes while
5010                  * we're traversing it?  It's unlikely, but should be handled.
5011                  */
5012                 retval = port->lun_disable(port->targ_lun_arg, lun->target,
5013                                          lun->lun);
5014                 mtx_lock(&softc->ctl_lock);
5015                 if (retval != 0) {
5016                         printf("%s: FETD %s port %d returned error "
5017                                "%d for lun_disable on target %ju lun %jd\n",
5018                                __func__, port->port_name, port->targ_port, retval,
5019                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
5020                 }
5021         }
5022
5023         mtx_unlock(&softc->ctl_lock);
5024
5025         return (0);
5026 }
5027
5028 int
5029 ctl_start_lun(struct ctl_be_lun *be_lun)
5030 {
5031         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5032
5033         mtx_lock(&lun->lun_lock);
5034         lun->flags &= ~CTL_LUN_STOPPED;
5035         mtx_unlock(&lun->lun_lock);
5036         return (0);
5037 }
5038
5039 int
5040 ctl_stop_lun(struct ctl_be_lun *be_lun)
5041 {
5042         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5043
5044         mtx_lock(&lun->lun_lock);
5045         lun->flags |= CTL_LUN_STOPPED;
5046         mtx_unlock(&lun->lun_lock);
5047         return (0);
5048 }
5049
5050 int
5051 ctl_lun_offline(struct ctl_be_lun *be_lun)
5052 {
5053         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5054
5055         mtx_lock(&lun->lun_lock);
5056         lun->flags |= CTL_LUN_OFFLINE;
5057         mtx_unlock(&lun->lun_lock);
5058         return (0);
5059 }
5060
5061 int
5062 ctl_lun_online(struct ctl_be_lun *be_lun)
5063 {
5064         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5065
5066         mtx_lock(&lun->lun_lock);
5067         lun->flags &= ~CTL_LUN_OFFLINE;
5068         mtx_unlock(&lun->lun_lock);
5069         return (0);
5070 }
5071
5072 int
5073 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
5074 {
5075         struct ctl_softc *softc;
5076         struct ctl_lun *lun;
5077
5078         lun = (struct ctl_lun *)be_lun->ctl_lun;
5079         softc = lun->ctl_softc;
5080
5081         mtx_lock(&lun->lun_lock);
5082
5083         /*
5084          * The LUN needs to be disabled before it can be marked invalid.
5085          */
5086         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
5087                 mtx_unlock(&lun->lun_lock);
5088                 return (-1);
5089         }
5090         /*
5091          * Mark the LUN invalid.
5092          */
5093         lun->flags |= CTL_LUN_INVALID;
5094
5095         /*
5096          * If there is nothing in the OOA queue, go ahead and free the LUN.
5097          * If we have something in the OOA queue, we'll free it when the
5098          * last I/O completes.
5099          */
5100         if (TAILQ_EMPTY(&lun->ooa_queue)) {
5101                 mtx_unlock(&lun->lun_lock);
5102                 mtx_lock(&softc->ctl_lock);
5103                 ctl_free_lun(lun);
5104                 mtx_unlock(&softc->ctl_lock);
5105         } else
5106                 mtx_unlock(&lun->lun_lock);
5107
5108         return (0);
5109 }
5110
5111 int
5112 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5113 {
5114         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5115
5116         mtx_lock(&lun->lun_lock);
5117         lun->flags |= CTL_LUN_INOPERABLE;
5118         mtx_unlock(&lun->lun_lock);
5119         return (0);
5120 }
5121
5122 int
5123 ctl_lun_operable(struct ctl_be_lun *be_lun)
5124 {
5125         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5126
5127         mtx_lock(&lun->lun_lock);
5128         lun->flags &= ~CTL_LUN_INOPERABLE;
5129         mtx_unlock(&lun->lun_lock);
5130         return (0);
5131 }
5132
5133 void
5134 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5135 {
5136         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5137
5138         mtx_lock(&lun->lun_lock);
5139         ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGED);
5140         mtx_unlock(&lun->lun_lock);
5141 }
5142
5143 /*
5144  * Backend "memory move is complete" callback for requests that never
5145  * make it down to say RAIDCore's configuration code.
5146  */
5147 int
5148 ctl_config_move_done(union ctl_io *io)
5149 {
5150         int retval;
5151
5152         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5153         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5154             ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5155
5156         if ((io->io_hdr.port_status != 0) &&
5157             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5158              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5159                 /*
5160                  * For hardware error sense keys, the sense key
5161                  * specific value is defined to be a retry count,
5162                  * but we use it to pass back an internal FETD
5163                  * error code.  XXX KDM  Hopefully the FETD is only
5164                  * using 16 bits for an error code, since that's
5165                  * all the space we have in the sks field.
5166                  */
5167                 ctl_set_internal_failure(&io->scsiio,
5168                                          /*sks_valid*/ 1,
5169                                          /*retry_count*/
5170                                          io->io_hdr.port_status);
5171         }
5172
5173         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5174             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5175              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5176             ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5177                 /*
5178                  * XXX KDM just assuming a single pointer here, and not a
5179                  * S/G list.  If we start using S/G lists for config data,
5180                  * we'll need to know how to clean them up here as well.
5181                  */
5182                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5183                         free(io->scsiio.kern_data_ptr, M_CTL);
5184                 ctl_done(io);
5185                 retval = CTL_RETVAL_COMPLETE;
5186         } else {
5187                 /*
5188                  * XXX KDM now we need to continue data movement.  Some
5189                  * options:
5190                  * - call ctl_scsiio() again?  We don't do this for data
5191                  *   writes, because for those at least we know ahead of
5192                  *   time where the write will go and how long it is.  For
5193                  *   config writes, though, that information is largely
5194                  *   contained within the write itself, thus we need to
5195                  *   parse out the data again.
5196                  *
5197                  * - Call some other function once the data is in?
5198                  */
5199                 if (ctl_debug & CTL_DEBUG_CDB_DATA)
5200                         ctl_data_print(io);
5201
5202                 /*
5203                  * XXX KDM call ctl_scsiio() again for now, and check flag
5204                  * bits to see whether we're allocated or not.
5205                  */
5206                 retval = ctl_scsiio(&io->scsiio);
5207         }
5208         return (retval);
5209 }
5210
5211 /*
5212  * This gets called by a backend driver when it is done with a
5213  * data_submit method.
5214  */
5215 void
5216 ctl_data_submit_done(union ctl_io *io)
5217 {
5218         /*
5219          * If the IO_CONT flag is set, we need to call the supplied
5220          * function to continue processing the I/O, instead of completing
5221          * the I/O just yet.
5222          *
5223          * If there is an error, though, we don't want to keep processing.
5224          * Instead, just send status back to the initiator.
5225          */
5226         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5227             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5228             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5229              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5230                 io->scsiio.io_cont(io);
5231                 return;
5232         }
5233         ctl_done(io);
5234 }
5235
5236 /*
5237  * This gets called by a backend driver when it is done with a
5238  * configuration write.
5239  */
5240 void
5241 ctl_config_write_done(union ctl_io *io)
5242 {
5243         uint8_t *buf;
5244
5245         /*
5246          * If the IO_CONT flag is set, we need to call the supplied
5247          * function to continue processing the I/O, instead of completing
5248          * the I/O just yet.
5249          *
5250          * If there is an error, though, we don't want to keep processing.
5251          * Instead, just send status back to the initiator.
5252          */
5253         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5254             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5255             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5256              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5257                 io->scsiio.io_cont(io);
5258                 return;
5259         }
5260         /*
5261          * Since a configuration write can be done for commands that actually
5262          * have data allocated, like write buffer, and commands that have
5263          * no data, like start/stop unit, we need to check here.
5264          */
5265         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5266                 buf = io->scsiio.kern_data_ptr;
5267         else
5268                 buf = NULL;
5269         ctl_done(io);
5270         if (buf)
5271                 free(buf, M_CTL);
5272 }
5273
5274 void
5275 ctl_config_read_done(union ctl_io *io)
5276 {
5277         uint8_t *buf;
5278
5279         /*
5280          * If there is some error -- we are done, skip data transfer.
5281          */
5282         if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5283             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5284              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5285                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5286                         buf = io->scsiio.kern_data_ptr;
5287                 else
5288                         buf = NULL;
5289                 ctl_done(io);
5290                 if (buf)
5291                         free(buf, M_CTL);
5292                 return;
5293         }
5294
5295         /*
5296          * If the IO_CONT flag is set, we need to call the supplied
5297          * function to continue processing the I/O, instead of completing
5298          * the I/O just yet.
5299          */
5300         if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5301                 io->scsiio.io_cont(io);
5302                 return;
5303         }
5304
5305         ctl_datamove(io);
5306 }
5307
5308 /*
5309  * SCSI release command.
5310  */
5311 int
5312 ctl_scsi_release(struct ctl_scsiio *ctsio)
5313 {
5314         int length, longid, thirdparty_id, resv_id;
5315         struct ctl_lun *lun;
5316         uint32_t residx;
5317
5318         length = 0;
5319         resv_id = 0;
5320
5321         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5322
5323         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5324         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5325
5326         switch (ctsio->cdb[0]) {
5327         case RELEASE_10: {
5328                 struct scsi_release_10 *cdb;
5329
5330                 cdb = (struct scsi_release_10 *)ctsio->cdb;
5331
5332                 if (cdb->byte2 & SR10_LONGID)
5333                         longid = 1;
5334                 else
5335                         thirdparty_id = cdb->thirdparty_id;
5336
5337                 resv_id = cdb->resv_id;
5338                 length = scsi_2btoul(cdb->length);
5339                 break;
5340         }
5341         }
5342
5343
5344         /*
5345          * XXX KDM right now, we only support LUN reservation.  We don't
5346          * support 3rd party reservations, or extent reservations, which
5347          * might actually need the parameter list.  If we've gotten this
5348          * far, we've got a LUN reservation.  Anything else got kicked out
5349          * above.  So, according to SPC, ignore the length.
5350          */
5351         length = 0;
5352
5353         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5354          && (length > 0)) {
5355                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5356                 ctsio->kern_data_len = length;
5357                 ctsio->kern_total_len = length;
5358                 ctsio->kern_data_resid = 0;
5359                 ctsio->kern_rel_offset = 0;
5360                 ctsio->kern_sg_entries = 0;
5361                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5362                 ctsio->be_move_done = ctl_config_move_done;
5363                 ctl_datamove((union ctl_io *)ctsio);
5364
5365                 return (CTL_RETVAL_COMPLETE);
5366         }
5367
5368         if (length > 0)
5369                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5370
5371         mtx_lock(&lun->lun_lock);
5372
5373         /*
5374          * According to SPC, it is not an error for an intiator to attempt
5375          * to release a reservation on a LUN that isn't reserved, or that
5376          * is reserved by another initiator.  The reservation can only be
5377          * released, though, by the initiator who made it or by one of
5378          * several reset type events.
5379          */
5380         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5381                         lun->flags &= ~CTL_LUN_RESERVED;
5382
5383         mtx_unlock(&lun->lun_lock);
5384
5385         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5386                 free(ctsio->kern_data_ptr, M_CTL);
5387                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5388         }
5389
5390         ctl_set_success(ctsio);
5391         ctl_done((union ctl_io *)ctsio);
5392         return (CTL_RETVAL_COMPLETE);
5393 }
5394
5395 int
5396 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5397 {
5398         int extent, thirdparty, longid;
5399         int resv_id, length;
5400         uint64_t thirdparty_id;
5401         struct ctl_lun *lun;
5402         uint32_t residx;
5403
5404         extent = 0;
5405         thirdparty = 0;
5406         longid = 0;
5407         resv_id = 0;
5408         length = 0;
5409         thirdparty_id = 0;
5410
5411         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5412
5413         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5414         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5415
5416         switch (ctsio->cdb[0]) {
5417         case RESERVE_10: {
5418                 struct scsi_reserve_10 *cdb;
5419
5420                 cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5421
5422                 if (cdb->byte2 & SR10_LONGID)
5423                         longid = 1;
5424                 else
5425                         thirdparty_id = cdb->thirdparty_id;
5426
5427                 resv_id = cdb->resv_id;
5428                 length = scsi_2btoul(cdb->length);
5429                 break;
5430         }
5431         }
5432
5433         /*
5434          * XXX KDM right now, we only support LUN reservation.  We don't
5435          * support 3rd party reservations, or extent reservations, which
5436          * might actually need the parameter list.  If we've gotten this
5437          * far, we've got a LUN reservation.  Anything else got kicked out
5438          * above.  So, according to SPC, ignore the length.
5439          */
5440         length = 0;
5441
5442         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5443          && (length > 0)) {
5444                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5445                 ctsio->kern_data_len = length;
5446                 ctsio->kern_total_len = length;
5447                 ctsio->kern_data_resid = 0;
5448                 ctsio->kern_rel_offset = 0;
5449                 ctsio->kern_sg_entries = 0;
5450                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5451                 ctsio->be_move_done = ctl_config_move_done;
5452                 ctl_datamove((union ctl_io *)ctsio);
5453
5454                 return (CTL_RETVAL_COMPLETE);
5455         }
5456
5457         if (length > 0)
5458                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5459
5460         mtx_lock(&lun->lun_lock);
5461         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5462                 ctl_set_reservation_conflict(ctsio);
5463                 goto bailout;
5464         }
5465
5466         lun->flags |= CTL_LUN_RESERVED;
5467         lun->res_idx = residx;
5468
5469         ctl_set_success(ctsio);
5470
5471 bailout:
5472         mtx_unlock(&lun->lun_lock);
5473
5474         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5475                 free(ctsio->kern_data_ptr, M_CTL);
5476                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5477         }
5478
5479         ctl_done((union ctl_io *)ctsio);
5480         return (CTL_RETVAL_COMPLETE);
5481 }
5482
5483 int
5484 ctl_start_stop(struct ctl_scsiio *ctsio)
5485 {
5486         struct scsi_start_stop_unit *cdb;
5487         struct ctl_lun *lun;
5488         int retval;
5489
5490         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5491
5492         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5493         retval = 0;
5494
5495         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5496
5497         /*
5498          * XXX KDM
5499          * We don't support the immediate bit on a stop unit.  In order to
5500          * do that, we would need to code up a way to know that a stop is
5501          * pending, and hold off any new commands until it completes, one
5502          * way or another.  Then we could accept or reject those commands
5503          * depending on its status.  We would almost need to do the reverse
5504          * of what we do below for an immediate start -- return the copy of
5505          * the ctl_io to the FETD with status to send to the host (and to
5506          * free the copy!) and then free the original I/O once the stop
5507          * actually completes.  That way, the OOA queue mechanism can work
5508          * to block commands that shouldn't proceed.  Another alternative
5509          * would be to put the copy in the queue in place of the original,
5510          * and return the original back to the caller.  That could be
5511          * slightly safer..
5512          */
5513         if ((cdb->byte2 & SSS_IMMED)
5514          && ((cdb->how & SSS_START) == 0)) {
5515                 ctl_set_invalid_field(ctsio,
5516                                       /*sks_valid*/ 1,
5517                                       /*command*/ 1,
5518                                       /*field*/ 1,
5519                                       /*bit_valid*/ 1,
5520                                       /*bit*/ 0);
5521                 ctl_done((union ctl_io *)ctsio);
5522                 return (CTL_RETVAL_COMPLETE);
5523         }
5524
5525         if ((lun->flags & CTL_LUN_PR_RESERVED)
5526          && ((cdb->how & SSS_START)==0)) {
5527                 uint32_t residx;
5528
5529                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5530                 if (ctl_get_prkey(lun, residx) == 0
5531                  || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5532
5533                         ctl_set_reservation_conflict(ctsio);
5534                         ctl_done((union ctl_io *)ctsio);
5535                         return (CTL_RETVAL_COMPLETE);
5536                 }
5537         }
5538
5539         /*
5540          * If there is no backend on this device, we can't start or stop
5541          * it.  In theory we shouldn't get any start/stop commands in the
5542          * first place at this level if the LUN doesn't have a backend.
5543          * That should get stopped by the command decode code.
5544          */
5545         if (lun->backend == NULL) {
5546                 ctl_set_invalid_opcode(ctsio);
5547                 ctl_done((union ctl_io *)ctsio);
5548                 return (CTL_RETVAL_COMPLETE);
5549         }
5550
5551         /*
5552          * XXX KDM Copan-specific offline behavior.
5553          * Figure out a reasonable way to port this?
5554          */
5555 #ifdef NEEDTOPORT
5556         mtx_lock(&lun->lun_lock);
5557
5558         if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5559          && (lun->flags & CTL_LUN_OFFLINE)) {
5560                 /*
5561                  * If the LUN is offline, and the on/offline bit isn't set,
5562                  * reject the start or stop.  Otherwise, let it through.
5563                  */
5564                 mtx_unlock(&lun->lun_lock);
5565                 ctl_set_lun_not_ready(ctsio);
5566                 ctl_done((union ctl_io *)ctsio);
5567         } else {
5568                 mtx_unlock(&lun->lun_lock);
5569 #endif /* NEEDTOPORT */
5570                 /*
5571                  * This could be a start or a stop when we're online,
5572                  * or a stop/offline or start/online.  A start or stop when
5573                  * we're offline is covered in the case above.
5574                  */
5575                 /*
5576                  * In the non-immediate case, we send the request to
5577                  * the backend and return status to the user when
5578                  * it is done.
5579                  *
5580                  * In the immediate case, we allocate a new ctl_io
5581                  * to hold a copy of the request, and send that to
5582                  * the backend.  We then set good status on the
5583                  * user's request and return it immediately.
5584                  */
5585                 if (cdb->byte2 & SSS_IMMED) {
5586                         union ctl_io *new_io;
5587
5588                         new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5589                         ctl_copy_io((union ctl_io *)ctsio, new_io);
5590                         retval = lun->backend->config_write(new_io);
5591                         ctl_set_success(ctsio);
5592                         ctl_done((union ctl_io *)ctsio);
5593                 } else {
5594                         retval = lun->backend->config_write(
5595                                 (union ctl_io *)ctsio);
5596                 }
5597 #ifdef NEEDTOPORT
5598         }
5599 #endif
5600         return (retval);
5601 }
5602
5603 /*
5604  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5605  * we don't really do anything with the LBA and length fields if the user
5606  * passes them in.  Instead we'll just flush out the cache for the entire
5607  * LUN.
5608  */
5609 int
5610 ctl_sync_cache(struct ctl_scsiio *ctsio)
5611 {
5612         struct ctl_lun *lun;
5613         struct ctl_softc *softc;
5614         uint64_t starting_lba;
5615         uint32_t block_count;
5616         int retval;
5617
5618         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5619
5620         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5621         softc = lun->ctl_softc;
5622         retval = 0;
5623
5624         switch (ctsio->cdb[0]) {
5625         case SYNCHRONIZE_CACHE: {
5626                 struct scsi_sync_cache *cdb;
5627                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5628
5629                 starting_lba = scsi_4btoul(cdb->begin_lba);
5630                 block_count = scsi_2btoul(cdb->lb_count);
5631                 break;
5632         }
5633         case SYNCHRONIZE_CACHE_16: {
5634                 struct scsi_sync_cache_16 *cdb;
5635                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5636
5637                 starting_lba = scsi_8btou64(cdb->begin_lba);
5638                 block_count = scsi_4btoul(cdb->lb_count);
5639                 break;
5640         }
5641         default:
5642                 ctl_set_invalid_opcode(ctsio);
5643                 ctl_done((union ctl_io *)ctsio);
5644                 goto bailout;
5645                 break; /* NOTREACHED */
5646         }
5647
5648         /*
5649          * We check the LBA and length, but don't do anything with them.
5650          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5651          * get flushed.  This check will just help satisfy anyone who wants
5652          * to see an error for an out of range LBA.
5653          */
5654         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5655                 ctl_set_lba_out_of_range(ctsio);
5656                 ctl_done((union ctl_io *)ctsio);
5657                 goto bailout;
5658         }
5659
5660         /*
5661          * If this LUN has no backend, we can't flush the cache anyway.
5662          */
5663         if (lun->backend == NULL) {
5664                 ctl_set_invalid_opcode(ctsio);
5665                 ctl_done((union ctl_io *)ctsio);
5666                 goto bailout;
5667         }
5668
5669         /*
5670          * Check to see whether we're configured to send the SYNCHRONIZE
5671          * CACHE command directly to the back end.
5672          */
5673         mtx_lock(&lun->lun_lock);
5674         if ((softc->flags & CTL_FLAG_REAL_SYNC)
5675          && (++(lun->sync_count) >= lun->sync_interval)) {
5676                 lun->sync_count = 0;
5677                 mtx_unlock(&lun->lun_lock);
5678                 retval = lun->backend->config_write((union ctl_io *)ctsio);
5679         } else {
5680                 mtx_unlock(&lun->lun_lock);
5681                 ctl_set_success(ctsio);
5682                 ctl_done((union ctl_io *)ctsio);
5683         }
5684
5685 bailout:
5686
5687         return (retval);
5688 }
5689
5690 int
5691 ctl_format(struct ctl_scsiio *ctsio)
5692 {
5693         struct scsi_format *cdb;
5694         struct ctl_lun *lun;
5695         int length, defect_list_len;
5696
5697         CTL_DEBUG_PRINT(("ctl_format\n"));
5698
5699         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5700
5701         cdb = (struct scsi_format *)ctsio->cdb;
5702
5703         length = 0;
5704         if (cdb->byte2 & SF_FMTDATA) {
5705                 if (cdb->byte2 & SF_LONGLIST)
5706                         length = sizeof(struct scsi_format_header_long);
5707                 else
5708                         length = sizeof(struct scsi_format_header_short);
5709         }
5710
5711         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5712          && (length > 0)) {
5713                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5714                 ctsio->kern_data_len = length;
5715                 ctsio->kern_total_len = length;
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         defect_list_len = 0;
5727
5728         if (cdb->byte2 & SF_FMTDATA) {
5729                 if (cdb->byte2 & SF_LONGLIST) {
5730                         struct scsi_format_header_long *header;
5731
5732                         header = (struct scsi_format_header_long *)
5733                                 ctsio->kern_data_ptr;
5734
5735                         defect_list_len = scsi_4btoul(header->defect_list_len);
5736                         if (defect_list_len != 0) {
5737                                 ctl_set_invalid_field(ctsio,
5738                                                       /*sks_valid*/ 1,
5739                                                       /*command*/ 0,
5740                                                       /*field*/ 2,
5741                                                       /*bit_valid*/ 0,
5742                                                       /*bit*/ 0);
5743                                 goto bailout;
5744                         }
5745                 } else {
5746                         struct scsi_format_header_short *header;
5747
5748                         header = (struct scsi_format_header_short *)
5749                                 ctsio->kern_data_ptr;
5750
5751                         defect_list_len = scsi_2btoul(header->defect_list_len);
5752                         if (defect_list_len != 0) {
5753                                 ctl_set_invalid_field(ctsio,
5754                                                       /*sks_valid*/ 1,
5755                                                       /*command*/ 0,
5756                                                       /*field*/ 2,
5757                                                       /*bit_valid*/ 0,
5758                                                       /*bit*/ 0);
5759                                 goto bailout;
5760                         }
5761                 }
5762         }
5763
5764         /*
5765          * The format command will clear out the "Medium format corrupted"
5766          * status if set by the configuration code.  That status is really
5767          * just a way to notify the host that we have lost the media, and
5768          * get them to issue a command that will basically make them think
5769          * they're blowing away the media.
5770          */
5771         mtx_lock(&lun->lun_lock);
5772         lun->flags &= ~CTL_LUN_INOPERABLE;
5773         mtx_unlock(&lun->lun_lock);
5774
5775         ctl_set_success(ctsio);
5776 bailout:
5777
5778         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5779                 free(ctsio->kern_data_ptr, M_CTL);
5780                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5781         }
5782
5783         ctl_done((union ctl_io *)ctsio);
5784         return (CTL_RETVAL_COMPLETE);
5785 }
5786
5787 int
5788 ctl_read_buffer(struct ctl_scsiio *ctsio)
5789 {
5790         struct scsi_read_buffer *cdb;
5791         struct ctl_lun *lun;
5792         int buffer_offset, len;
5793         static uint8_t descr[4];
5794         static uint8_t echo_descr[4] = { 0 };
5795
5796         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5797
5798         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5799         cdb = (struct scsi_read_buffer *)ctsio->cdb;
5800
5801         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5802             (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5803             (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5804                 ctl_set_invalid_field(ctsio,
5805                                       /*sks_valid*/ 1,
5806                                       /*command*/ 1,
5807                                       /*field*/ 1,
5808                                       /*bit_valid*/ 1,
5809                                       /*bit*/ 4);
5810                 ctl_done((union ctl_io *)ctsio);
5811                 return (CTL_RETVAL_COMPLETE);
5812         }
5813
5814         len = scsi_3btoul(cdb->length);
5815         buffer_offset = scsi_3btoul(cdb->offset);
5816
5817         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5818                 ctl_set_invalid_field(ctsio,
5819                                       /*sks_valid*/ 1,
5820                                       /*command*/ 1,
5821                                       /*field*/ 6,
5822                                       /*bit_valid*/ 0,
5823                                       /*bit*/ 0);
5824                 ctl_done((union ctl_io *)ctsio);
5825                 return (CTL_RETVAL_COMPLETE);
5826         }
5827
5828         if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5829                 descr[0] = 0;
5830                 scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5831                 ctsio->kern_data_ptr = descr;
5832                 len = min(len, sizeof(descr));
5833         } else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5834                 ctsio->kern_data_ptr = echo_descr;
5835                 len = min(len, sizeof(echo_descr));
5836         } else {
5837                 if (lun->write_buffer == NULL) {
5838                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5839                             M_CTL, M_WAITOK);
5840                 }
5841                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5842         }
5843         ctsio->kern_data_len = len;
5844         ctsio->kern_total_len = len;
5845         ctsio->kern_data_resid = 0;
5846         ctsio->kern_rel_offset = 0;
5847         ctsio->kern_sg_entries = 0;
5848         ctl_set_success(ctsio);
5849         ctsio->be_move_done = ctl_config_move_done;
5850         ctl_datamove((union ctl_io *)ctsio);
5851         return (CTL_RETVAL_COMPLETE);
5852 }
5853
5854 int
5855 ctl_write_buffer(struct ctl_scsiio *ctsio)
5856 {
5857         struct scsi_write_buffer *cdb;
5858         struct ctl_lun *lun;
5859         int buffer_offset, len;
5860
5861         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5862
5863         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5864         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5865
5866         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5867                 ctl_set_invalid_field(ctsio,
5868                                       /*sks_valid*/ 1,
5869                                       /*command*/ 1,
5870                                       /*field*/ 1,
5871                                       /*bit_valid*/ 1,
5872                                       /*bit*/ 4);
5873                 ctl_done((union ctl_io *)ctsio);
5874                 return (CTL_RETVAL_COMPLETE);
5875         }
5876
5877         len = scsi_3btoul(cdb->length);
5878         buffer_offset = scsi_3btoul(cdb->offset);
5879
5880         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5881                 ctl_set_invalid_field(ctsio,
5882                                       /*sks_valid*/ 1,
5883                                       /*command*/ 1,
5884                                       /*field*/ 6,
5885                                       /*bit_valid*/ 0,
5886                                       /*bit*/ 0);
5887                 ctl_done((union ctl_io *)ctsio);
5888                 return (CTL_RETVAL_COMPLETE);
5889         }
5890
5891         /*
5892          * If we've got a kernel request that hasn't been malloced yet,
5893          * malloc it and tell the caller the data buffer is here.
5894          */
5895         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5896                 if (lun->write_buffer == NULL) {
5897                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5898                             M_CTL, M_WAITOK);
5899                 }
5900                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5901                 ctsio->kern_data_len = len;
5902                 ctsio->kern_total_len = len;
5903                 ctsio->kern_data_resid = 0;
5904                 ctsio->kern_rel_offset = 0;
5905                 ctsio->kern_sg_entries = 0;
5906                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5907                 ctsio->be_move_done = ctl_config_move_done;
5908                 ctl_datamove((union ctl_io *)ctsio);
5909
5910                 return (CTL_RETVAL_COMPLETE);
5911         }
5912
5913         ctl_set_success(ctsio);
5914         ctl_done((union ctl_io *)ctsio);
5915         return (CTL_RETVAL_COMPLETE);
5916 }
5917
5918 int
5919 ctl_write_same(struct ctl_scsiio *ctsio)
5920 {
5921         struct ctl_lun *lun;
5922         struct ctl_lba_len_flags *lbalen;
5923         uint64_t lba;
5924         uint32_t num_blocks;
5925         int len, retval;
5926         uint8_t byte2;
5927
5928         retval = CTL_RETVAL_COMPLETE;
5929
5930         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5931
5932         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5933
5934         switch (ctsio->cdb[0]) {
5935         case WRITE_SAME_10: {
5936                 struct scsi_write_same_10 *cdb;
5937
5938                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5939
5940                 lba = scsi_4btoul(cdb->addr);
5941                 num_blocks = scsi_2btoul(cdb->length);
5942                 byte2 = cdb->byte2;
5943                 break;
5944         }
5945         case WRITE_SAME_16: {
5946                 struct scsi_write_same_16 *cdb;
5947
5948                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5949
5950                 lba = scsi_8btou64(cdb->addr);
5951                 num_blocks = scsi_4btoul(cdb->length);
5952                 byte2 = cdb->byte2;
5953                 break;
5954         }
5955         default:
5956                 /*
5957                  * We got a command we don't support.  This shouldn't
5958                  * happen, commands should be filtered out above us.
5959                  */
5960                 ctl_set_invalid_opcode(ctsio);
5961                 ctl_done((union ctl_io *)ctsio);
5962
5963                 return (CTL_RETVAL_COMPLETE);
5964                 break; /* NOTREACHED */
5965         }
5966
5967         /* NDOB and ANCHOR flags can be used only together with UNMAP */
5968         if ((byte2 & SWS_UNMAP) == 0 &&
5969             (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5970                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5971                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5972                 ctl_done((union ctl_io *)ctsio);
5973                 return (CTL_RETVAL_COMPLETE);
5974         }
5975
5976         /*
5977          * The first check is to make sure we're in bounds, the second
5978          * check is to catch wrap-around problems.  If the lba + num blocks
5979          * is less than the lba, then we've wrapped around and the block
5980          * range is invalid anyway.
5981          */
5982         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5983          || ((lba + num_blocks) < lba)) {
5984                 ctl_set_lba_out_of_range(ctsio);
5985                 ctl_done((union ctl_io *)ctsio);
5986                 return (CTL_RETVAL_COMPLETE);
5987         }
5988
5989         /* Zero number of blocks means "to the last logical block" */
5990         if (num_blocks == 0) {
5991                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5992                         ctl_set_invalid_field(ctsio,
5993                                               /*sks_valid*/ 0,
5994                                               /*command*/ 1,
5995                                               /*field*/ 0,
5996                                               /*bit_valid*/ 0,
5997                                               /*bit*/ 0);
5998                         ctl_done((union ctl_io *)ctsio);
5999                         return (CTL_RETVAL_COMPLETE);
6000                 }
6001                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
6002         }
6003
6004         len = lun->be_lun->blocksize;
6005
6006         /*
6007          * If we've got a kernel request that hasn't been malloced yet,
6008          * malloc it and tell the caller the data buffer is here.
6009          */
6010         if ((byte2 & SWS_NDOB) == 0 &&
6011             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6012                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6013                 ctsio->kern_data_len = len;
6014                 ctsio->kern_total_len = len;
6015                 ctsio->kern_data_resid = 0;
6016                 ctsio->kern_rel_offset = 0;
6017                 ctsio->kern_sg_entries = 0;
6018                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6019                 ctsio->be_move_done = ctl_config_move_done;
6020                 ctl_datamove((union ctl_io *)ctsio);
6021
6022                 return (CTL_RETVAL_COMPLETE);
6023         }
6024
6025         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6026         lbalen->lba = lba;
6027         lbalen->len = num_blocks;
6028         lbalen->flags = byte2;
6029         retval = lun->backend->config_write((union ctl_io *)ctsio);
6030
6031         return (retval);
6032 }
6033
6034 int
6035 ctl_unmap(struct ctl_scsiio *ctsio)
6036 {
6037         struct ctl_lun *lun;
6038         struct scsi_unmap *cdb;
6039         struct ctl_ptr_len_flags *ptrlen;
6040         struct scsi_unmap_header *hdr;
6041         struct scsi_unmap_desc *buf, *end, *endnz, *range;
6042         uint64_t lba;
6043         uint32_t num_blocks;
6044         int len, retval;
6045         uint8_t byte2;
6046
6047         retval = CTL_RETVAL_COMPLETE;
6048
6049         CTL_DEBUG_PRINT(("ctl_unmap\n"));
6050
6051         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6052         cdb = (struct scsi_unmap *)ctsio->cdb;
6053
6054         len = scsi_2btoul(cdb->length);
6055         byte2 = cdb->byte2;
6056
6057         /*
6058          * If we've got a kernel request that hasn't been malloced yet,
6059          * malloc it and tell the caller the data buffer is here.
6060          */
6061         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6062                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6063                 ctsio->kern_data_len = len;
6064                 ctsio->kern_total_len = len;
6065                 ctsio->kern_data_resid = 0;
6066                 ctsio->kern_rel_offset = 0;
6067                 ctsio->kern_sg_entries = 0;
6068                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6069                 ctsio->be_move_done = ctl_config_move_done;
6070                 ctl_datamove((union ctl_io *)ctsio);
6071
6072                 return (CTL_RETVAL_COMPLETE);
6073         }
6074
6075         len = ctsio->kern_total_len - ctsio->kern_data_resid;
6076         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
6077         if (len < sizeof (*hdr) ||
6078             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
6079             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
6080             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
6081                 ctl_set_invalid_field(ctsio,
6082                                       /*sks_valid*/ 0,
6083                                       /*command*/ 0,
6084                                       /*field*/ 0,
6085                                       /*bit_valid*/ 0,
6086                                       /*bit*/ 0);
6087                 goto done;
6088         }
6089         len = scsi_2btoul(hdr->desc_length);
6090         buf = (struct scsi_unmap_desc *)(hdr + 1);
6091         end = buf + len / sizeof(*buf);
6092
6093         endnz = buf;
6094         for (range = buf; range < end; range++) {
6095                 lba = scsi_8btou64(range->lba);
6096                 num_blocks = scsi_4btoul(range->length);
6097                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6098                  || ((lba + num_blocks) < lba)) {
6099                         ctl_set_lba_out_of_range(ctsio);
6100                         ctl_done((union ctl_io *)ctsio);
6101                         return (CTL_RETVAL_COMPLETE);
6102                 }
6103                 if (num_blocks != 0)
6104                         endnz = range + 1;
6105         }
6106
6107         /*
6108          * Block backend can not handle zero last range.
6109          * Filter it out and return if there is nothing left.
6110          */
6111         len = (uint8_t *)endnz - (uint8_t *)buf;
6112         if (len == 0) {
6113                 ctl_set_success(ctsio);
6114                 goto done;
6115         }
6116
6117         mtx_lock(&lun->lun_lock);
6118         ptrlen = (struct ctl_ptr_len_flags *)
6119             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6120         ptrlen->ptr = (void *)buf;
6121         ptrlen->len = len;
6122         ptrlen->flags = byte2;
6123         ctl_check_blocked(lun);
6124         mtx_unlock(&lun->lun_lock);
6125
6126         retval = lun->backend->config_write((union ctl_io *)ctsio);
6127         return (retval);
6128
6129 done:
6130         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
6131                 free(ctsio->kern_data_ptr, M_CTL);
6132                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
6133         }
6134         ctl_done((union ctl_io *)ctsio);
6135         return (CTL_RETVAL_COMPLETE);
6136 }
6137
6138 /*
6139  * Note that this function currently doesn't actually do anything inside
6140  * CTL to enforce things if the DQue bit is turned on.
6141  *
6142  * Also note that this function can't be used in the default case, because
6143  * the DQue bit isn't set in the changeable mask for the control mode page
6144  * anyway.  This is just here as an example for how to implement a page
6145  * handler, and a placeholder in case we want to allow the user to turn
6146  * tagged queueing on and off.
6147  *
6148  * The D_SENSE bit handling is functional, however, and will turn
6149  * descriptor sense on and off for a given LUN.
6150  */
6151 int
6152 ctl_control_page_handler(struct ctl_scsiio *ctsio,
6153                          struct ctl_page_index *page_index, uint8_t *page_ptr)
6154 {
6155         struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6156         struct ctl_lun *lun;
6157         int set_ua;
6158         uint32_t initidx;
6159
6160         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6161         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6162         set_ua = 0;
6163
6164         user_cp = (struct scsi_control_page *)page_ptr;
6165         current_cp = (struct scsi_control_page *)
6166                 (page_index->page_data + (page_index->page_len *
6167                 CTL_PAGE_CURRENT));
6168         saved_cp = (struct scsi_control_page *)
6169                 (page_index->page_data + (page_index->page_len *
6170                 CTL_PAGE_SAVED));
6171
6172         mtx_lock(&lun->lun_lock);
6173         if (((current_cp->rlec & SCP_DSENSE) == 0)
6174          && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6175                 /*
6176                  * Descriptor sense is currently turned off and the user
6177                  * wants to turn it on.
6178                  */
6179                 current_cp->rlec |= SCP_DSENSE;
6180                 saved_cp->rlec |= SCP_DSENSE;
6181                 lun->flags |= CTL_LUN_SENSE_DESC;
6182                 set_ua = 1;
6183         } else if (((current_cp->rlec & SCP_DSENSE) != 0)
6184                 && ((user_cp->rlec & SCP_DSENSE) == 0)) {
6185                 /*
6186                  * Descriptor sense is currently turned on, and the user
6187                  * wants to turn it off.
6188                  */
6189                 current_cp->rlec &= ~SCP_DSENSE;
6190                 saved_cp->rlec &= ~SCP_DSENSE;
6191                 lun->flags &= ~CTL_LUN_SENSE_DESC;
6192                 set_ua = 1;
6193         }
6194         if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6195             (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6196                 current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6197                 current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6198                 saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6199                 saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6200                 set_ua = 1;
6201         }
6202         if ((current_cp->eca_and_aen & SCP_SWP) !=
6203             (user_cp->eca_and_aen & SCP_SWP)) {
6204                 current_cp->eca_and_aen &= ~SCP_SWP;
6205                 current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6206                 saved_cp->eca_and_aen &= ~SCP_SWP;
6207                 saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6208                 set_ua = 1;
6209         }
6210         if (set_ua != 0)
6211                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6212         mtx_unlock(&lun->lun_lock);
6213
6214         return (0);
6215 }
6216
6217 int
6218 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6219                      struct ctl_page_index *page_index, uint8_t *page_ptr)
6220 {
6221         struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6222         struct ctl_lun *lun;
6223         int set_ua;
6224         uint32_t initidx;
6225
6226         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6227         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6228         set_ua = 0;
6229
6230         user_cp = (struct scsi_caching_page *)page_ptr;
6231         current_cp = (struct scsi_caching_page *)
6232                 (page_index->page_data + (page_index->page_len *
6233                 CTL_PAGE_CURRENT));
6234         saved_cp = (struct scsi_caching_page *)
6235                 (page_index->page_data + (page_index->page_len *
6236                 CTL_PAGE_SAVED));
6237
6238         mtx_lock(&lun->lun_lock);
6239         if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6240             (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6241                 current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6242                 current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6243                 saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6244                 saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6245                 set_ua = 1;
6246         }
6247         if (set_ua != 0)
6248                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6249         mtx_unlock(&lun->lun_lock);
6250
6251         return (0);
6252 }
6253
6254 int
6255 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6256                                 struct ctl_page_index *page_index,
6257                                 uint8_t *page_ptr)
6258 {
6259         uint8_t *c;
6260         int i;
6261
6262         c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6263         ctl_time_io_secs =
6264                 (c[0] << 8) |
6265                 (c[1] << 0) |
6266                 0;
6267         CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6268         printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6269         printf("page data:");
6270         for (i=0; i<8; i++)
6271                 printf(" %.2x",page_ptr[i]);
6272         printf("\n");
6273         return (0);
6274 }
6275
6276 int
6277 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6278                                struct ctl_page_index *page_index,
6279                                int pc)
6280 {
6281         struct copan_debugconf_subpage *page;
6282
6283         page = (struct copan_debugconf_subpage *)page_index->page_data +
6284                 (page_index->page_len * pc);
6285
6286         switch (pc) {
6287         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6288         case SMS_PAGE_CTRL_DEFAULT >> 6:
6289         case SMS_PAGE_CTRL_SAVED >> 6:
6290                 /*
6291                  * We don't update the changable or default bits for this page.
6292                  */
6293                 break;
6294         case SMS_PAGE_CTRL_CURRENT >> 6:
6295                 page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6296                 page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6297                 break;
6298         default:
6299 #ifdef NEEDTOPORT
6300                 EPRINT(0, "Invalid PC %d!!", pc);
6301 #endif /* NEEDTOPORT */
6302                 break;
6303         }
6304         return (0);
6305 }
6306
6307
6308 static int
6309 ctl_do_mode_select(union ctl_io *io)
6310 {
6311         struct scsi_mode_page_header *page_header;
6312         struct ctl_page_index *page_index;
6313         struct ctl_scsiio *ctsio;
6314         int control_dev, page_len;
6315         int page_len_offset, page_len_size;
6316         union ctl_modepage_info *modepage_info;
6317         struct ctl_lun *lun;
6318         int *len_left, *len_used;
6319         int retval, i;
6320
6321         ctsio = &io->scsiio;
6322         page_index = NULL;
6323         page_len = 0;
6324         retval = CTL_RETVAL_COMPLETE;
6325
6326         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6327
6328         if (lun->be_lun->lun_type != T_DIRECT)
6329                 control_dev = 1;
6330         else
6331                 control_dev = 0;
6332
6333         modepage_info = (union ctl_modepage_info *)
6334                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6335         len_left = &modepage_info->header.len_left;
6336         len_used = &modepage_info->header.len_used;
6337
6338 do_next_page:
6339
6340         page_header = (struct scsi_mode_page_header *)
6341                 (ctsio->kern_data_ptr + *len_used);
6342
6343         if (*len_left == 0) {
6344                 free(ctsio->kern_data_ptr, M_CTL);
6345                 ctl_set_success(ctsio);
6346                 ctl_done((union ctl_io *)ctsio);
6347                 return (CTL_RETVAL_COMPLETE);
6348         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6349
6350                 free(ctsio->kern_data_ptr, M_CTL);
6351                 ctl_set_param_len_error(ctsio);
6352                 ctl_done((union ctl_io *)ctsio);
6353                 return (CTL_RETVAL_COMPLETE);
6354
6355         } else if ((page_header->page_code & SMPH_SPF)
6356                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6357
6358                 free(ctsio->kern_data_ptr, M_CTL);
6359                 ctl_set_param_len_error(ctsio);
6360                 ctl_done((union ctl_io *)ctsio);
6361                 return (CTL_RETVAL_COMPLETE);
6362         }
6363
6364
6365         /*
6366          * XXX KDM should we do something with the block descriptor?
6367          */
6368         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6369
6370                 if ((control_dev != 0)
6371                  && (lun->mode_pages.index[i].page_flags &
6372                      CTL_PAGE_FLAG_DISK_ONLY))
6373                         continue;
6374
6375                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6376                     (page_header->page_code & SMPH_PC_MASK))
6377                         continue;
6378
6379                 /*
6380                  * If neither page has a subpage code, then we've got a
6381                  * match.
6382                  */
6383                 if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6384                  && ((page_header->page_code & SMPH_SPF) == 0)) {
6385                         page_index = &lun->mode_pages.index[i];
6386                         page_len = page_header->page_length;
6387                         break;
6388                 }
6389
6390                 /*
6391                  * If both pages have subpages, then the subpage numbers
6392                  * have to match.
6393                  */
6394                 if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6395                   && (page_header->page_code & SMPH_SPF)) {
6396                         struct scsi_mode_page_header_sp *sph;
6397
6398                         sph = (struct scsi_mode_page_header_sp *)page_header;
6399
6400                         if (lun->mode_pages.index[i].subpage ==
6401                             sph->subpage) {
6402                                 page_index = &lun->mode_pages.index[i];
6403                                 page_len = scsi_2btoul(sph->page_length);
6404                                 break;
6405                         }
6406                 }
6407         }
6408
6409         /*
6410          * If we couldn't find the page, or if we don't have a mode select
6411          * handler for it, send back an error to the user.
6412          */
6413         if ((page_index == NULL)
6414          || (page_index->select_handler == NULL)) {
6415                 ctl_set_invalid_field(ctsio,
6416                                       /*sks_valid*/ 1,
6417                                       /*command*/ 0,
6418                                       /*field*/ *len_used,
6419                                       /*bit_valid*/ 0,
6420                                       /*bit*/ 0);
6421                 free(ctsio->kern_data_ptr, M_CTL);
6422                 ctl_done((union ctl_io *)ctsio);
6423                 return (CTL_RETVAL_COMPLETE);
6424         }
6425
6426         if (page_index->page_code & SMPH_SPF) {
6427                 page_len_offset = 2;
6428                 page_len_size = 2;
6429         } else {
6430                 page_len_size = 1;
6431                 page_len_offset = 1;
6432         }
6433
6434         /*
6435          * If the length the initiator gives us isn't the one we specify in
6436          * the mode page header, or if they didn't specify enough data in
6437          * the CDB to avoid truncating this page, kick out the request.
6438          */
6439         if ((page_len != (page_index->page_len - page_len_offset -
6440                           page_len_size))
6441          || (*len_left < page_index->page_len)) {
6442
6443
6444                 ctl_set_invalid_field(ctsio,
6445                                       /*sks_valid*/ 1,
6446                                       /*command*/ 0,
6447                                       /*field*/ *len_used + page_len_offset,
6448                                       /*bit_valid*/ 0,
6449                                       /*bit*/ 0);
6450                 free(ctsio->kern_data_ptr, M_CTL);
6451                 ctl_done((union ctl_io *)ctsio);
6452                 return (CTL_RETVAL_COMPLETE);
6453         }
6454
6455         /*
6456          * Run through the mode page, checking to make sure that the bits
6457          * the user changed are actually legal for him to change.
6458          */
6459         for (i = 0; i < page_index->page_len; i++) {
6460                 uint8_t *user_byte, *change_mask, *current_byte;
6461                 int bad_bit;
6462                 int j;
6463
6464                 user_byte = (uint8_t *)page_header + i;
6465                 change_mask = page_index->page_data +
6466                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6467                 current_byte = page_index->page_data +
6468                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6469
6470                 /*
6471                  * Check to see whether the user set any bits in this byte
6472                  * that he is not allowed to set.
6473                  */
6474                 if ((*user_byte & ~(*change_mask)) ==
6475                     (*current_byte & ~(*change_mask)))
6476                         continue;
6477
6478                 /*
6479                  * Go through bit by bit to determine which one is illegal.
6480                  */
6481                 bad_bit = 0;
6482                 for (j = 7; j >= 0; j--) {
6483                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6484                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6485                                 bad_bit = i;
6486                                 break;
6487                         }
6488                 }
6489                 ctl_set_invalid_field(ctsio,
6490                                       /*sks_valid*/ 1,
6491                                       /*command*/ 0,
6492                                       /*field*/ *len_used + i,
6493                                       /*bit_valid*/ 1,
6494                                       /*bit*/ bad_bit);
6495                 free(ctsio->kern_data_ptr, M_CTL);
6496                 ctl_done((union ctl_io *)ctsio);
6497                 return (CTL_RETVAL_COMPLETE);
6498         }
6499
6500         /*
6501          * Decrement these before we call the page handler, since we may
6502          * end up getting called back one way or another before the handler
6503          * returns to this context.
6504          */
6505         *len_left -= page_index->page_len;
6506         *len_used += page_index->page_len;
6507
6508         retval = page_index->select_handler(ctsio, page_index,
6509                                             (uint8_t *)page_header);
6510
6511         /*
6512          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6513          * wait until this queued command completes to finish processing
6514          * the mode page.  If it returns anything other than
6515          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6516          * already set the sense information, freed the data pointer, and
6517          * completed the io for us.
6518          */
6519         if (retval != CTL_RETVAL_COMPLETE)
6520                 goto bailout_no_done;
6521
6522         /*
6523          * If the initiator sent us more than one page, parse the next one.
6524          */
6525         if (*len_left > 0)
6526                 goto do_next_page;
6527
6528         ctl_set_success(ctsio);
6529         free(ctsio->kern_data_ptr, M_CTL);
6530         ctl_done((union ctl_io *)ctsio);
6531
6532 bailout_no_done:
6533
6534         return (CTL_RETVAL_COMPLETE);
6535
6536 }
6537
6538 int
6539 ctl_mode_select(struct ctl_scsiio *ctsio)
6540 {
6541         int param_len, pf, sp;
6542         int header_size, bd_len;
6543         int len_left, len_used;
6544         struct ctl_page_index *page_index;
6545         struct ctl_lun *lun;
6546         int control_dev, page_len;
6547         union ctl_modepage_info *modepage_info;
6548         int retval;
6549
6550         pf = 0;
6551         sp = 0;
6552         page_len = 0;
6553         len_used = 0;
6554         len_left = 0;
6555         retval = 0;
6556         bd_len = 0;
6557         page_index = NULL;
6558
6559         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6560
6561         if (lun->be_lun->lun_type != T_DIRECT)
6562                 control_dev = 1;
6563         else
6564                 control_dev = 0;
6565
6566         switch (ctsio->cdb[0]) {
6567         case MODE_SELECT_6: {
6568                 struct scsi_mode_select_6 *cdb;
6569
6570                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6571
6572                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6573                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6574
6575                 param_len = cdb->length;
6576                 header_size = sizeof(struct scsi_mode_header_6);
6577                 break;
6578         }
6579         case MODE_SELECT_10: {
6580                 struct scsi_mode_select_10 *cdb;
6581
6582                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6583
6584                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6585                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6586
6587                 param_len = scsi_2btoul(cdb->length);
6588                 header_size = sizeof(struct scsi_mode_header_10);
6589                 break;
6590         }
6591         default:
6592                 ctl_set_invalid_opcode(ctsio);
6593                 ctl_done((union ctl_io *)ctsio);
6594                 return (CTL_RETVAL_COMPLETE);
6595                 break; /* NOTREACHED */
6596         }
6597
6598         /*
6599          * From SPC-3:
6600          * "A parameter list length of zero indicates that the Data-Out Buffer
6601          * shall be empty. This condition shall not be considered as an error."
6602          */
6603         if (param_len == 0) {
6604                 ctl_set_success(ctsio);
6605                 ctl_done((union ctl_io *)ctsio);
6606                 return (CTL_RETVAL_COMPLETE);
6607         }
6608
6609         /*
6610          * Since we'll hit this the first time through, prior to
6611          * allocation, we don't need to free a data buffer here.
6612          */
6613         if (param_len < header_size) {
6614                 ctl_set_param_len_error(ctsio);
6615                 ctl_done((union ctl_io *)ctsio);
6616                 return (CTL_RETVAL_COMPLETE);
6617         }
6618
6619         /*
6620          * Allocate the data buffer and grab the user's data.  In theory,
6621          * we shouldn't have to sanity check the parameter list length here
6622          * because the maximum size is 64K.  We should be able to malloc
6623          * that much without too many problems.
6624          */
6625         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6626                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6627                 ctsio->kern_data_len = param_len;
6628                 ctsio->kern_total_len = param_len;
6629                 ctsio->kern_data_resid = 0;
6630                 ctsio->kern_rel_offset = 0;
6631                 ctsio->kern_sg_entries = 0;
6632                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6633                 ctsio->be_move_done = ctl_config_move_done;
6634                 ctl_datamove((union ctl_io *)ctsio);
6635
6636                 return (CTL_RETVAL_COMPLETE);
6637         }
6638
6639         switch (ctsio->cdb[0]) {
6640         case MODE_SELECT_6: {
6641                 struct scsi_mode_header_6 *mh6;
6642
6643                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6644                 bd_len = mh6->blk_desc_len;
6645                 break;
6646         }
6647         case MODE_SELECT_10: {
6648                 struct scsi_mode_header_10 *mh10;
6649
6650                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6651                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6652                 break;
6653         }
6654         default:
6655                 panic("Invalid CDB type %#x", ctsio->cdb[0]);
6656                 break;
6657         }
6658
6659         if (param_len < (header_size + bd_len)) {
6660                 free(ctsio->kern_data_ptr, M_CTL);
6661                 ctl_set_param_len_error(ctsio);
6662                 ctl_done((union ctl_io *)ctsio);
6663                 return (CTL_RETVAL_COMPLETE);
6664         }
6665
6666         /*
6667          * Set the IO_CONT flag, so that if this I/O gets passed to
6668          * ctl_config_write_done(), it'll get passed back to
6669          * ctl_do_mode_select() for further processing, or completion if
6670          * we're all done.
6671          */
6672         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6673         ctsio->io_cont = ctl_do_mode_select;
6674
6675         modepage_info = (union ctl_modepage_info *)
6676                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6677
6678         memset(modepage_info, 0, sizeof(*modepage_info));
6679
6680         len_left = param_len - header_size - bd_len;
6681         len_used = header_size + bd_len;
6682
6683         modepage_info->header.len_left = len_left;
6684         modepage_info->header.len_used = len_used;
6685
6686         return (ctl_do_mode_select((union ctl_io *)ctsio));
6687 }
6688
6689 int
6690 ctl_mode_sense(struct ctl_scsiio *ctsio)
6691 {
6692         struct ctl_lun *lun;
6693         int pc, page_code, dbd, llba, subpage;
6694         int alloc_len, page_len, header_len, total_len;
6695         struct scsi_mode_block_descr *block_desc;
6696         struct ctl_page_index *page_index;
6697         int control_dev;
6698
6699         dbd = 0;
6700         llba = 0;
6701         block_desc = NULL;
6702         page_index = NULL;
6703
6704         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6705
6706         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6707
6708         if (lun->be_lun->lun_type != T_DIRECT)
6709                 control_dev = 1;
6710         else
6711                 control_dev = 0;
6712
6713         switch (ctsio->cdb[0]) {
6714         case MODE_SENSE_6: {
6715                 struct scsi_mode_sense_6 *cdb;
6716
6717                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6718
6719                 header_len = sizeof(struct scsi_mode_hdr_6);
6720                 if (cdb->byte2 & SMS_DBD)
6721                         dbd = 1;
6722                 else
6723                         header_len += sizeof(struct scsi_mode_block_descr);
6724
6725                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6726                 page_code = cdb->page & SMS_PAGE_CODE;
6727                 subpage = cdb->subpage;
6728                 alloc_len = cdb->length;
6729                 break;
6730         }
6731         case MODE_SENSE_10: {
6732                 struct scsi_mode_sense_10 *cdb;
6733
6734                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6735
6736                 header_len = sizeof(struct scsi_mode_hdr_10);
6737
6738                 if (cdb->byte2 & SMS_DBD)
6739                         dbd = 1;
6740                 else
6741                         header_len += sizeof(struct scsi_mode_block_descr);
6742                 if (cdb->byte2 & SMS10_LLBAA)
6743                         llba = 1;
6744                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6745                 page_code = cdb->page & SMS_PAGE_CODE;
6746                 subpage = cdb->subpage;
6747                 alloc_len = scsi_2btoul(cdb->length);
6748                 break;
6749         }
6750         default:
6751                 ctl_set_invalid_opcode(ctsio);
6752                 ctl_done((union ctl_io *)ctsio);
6753                 return (CTL_RETVAL_COMPLETE);
6754                 break; /* NOTREACHED */
6755         }
6756
6757         /*
6758          * We have to make a first pass through to calculate the size of
6759          * the pages that match the user's query.  Then we allocate enough
6760          * memory to hold it, and actually copy the data into the buffer.
6761          */
6762         switch (page_code) {
6763         case SMS_ALL_PAGES_PAGE: {
6764                 int i;
6765
6766                 page_len = 0;
6767
6768                 /*
6769                  * At the moment, values other than 0 and 0xff here are
6770                  * reserved according to SPC-3.
6771                  */
6772                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6773                  && (subpage != SMS_SUBPAGE_ALL)) {
6774                         ctl_set_invalid_field(ctsio,
6775                                               /*sks_valid*/ 1,
6776                                               /*command*/ 1,
6777                                               /*field*/ 3,
6778                                               /*bit_valid*/ 0,
6779                                               /*bit*/ 0);
6780                         ctl_done((union ctl_io *)ctsio);
6781                         return (CTL_RETVAL_COMPLETE);
6782                 }
6783
6784                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6785                         if ((control_dev != 0)
6786                          && (lun->mode_pages.index[i].page_flags &
6787                              CTL_PAGE_FLAG_DISK_ONLY))
6788                                 continue;
6789
6790                         /*
6791                          * We don't use this subpage if the user didn't
6792                          * request all subpages.
6793                          */
6794                         if ((lun->mode_pages.index[i].subpage != 0)
6795                          && (subpage == SMS_SUBPAGE_PAGE_0))
6796                                 continue;
6797
6798 #if 0
6799                         printf("found page %#x len %d\n",
6800                                lun->mode_pages.index[i].page_code &
6801                                SMPH_PC_MASK,
6802                                lun->mode_pages.index[i].page_len);
6803 #endif
6804                         page_len += lun->mode_pages.index[i].page_len;
6805                 }
6806                 break;
6807         }
6808         default: {
6809                 int i;
6810
6811                 page_len = 0;
6812
6813                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6814                         /* Look for the right page code */
6815                         if ((lun->mode_pages.index[i].page_code &
6816                              SMPH_PC_MASK) != page_code)
6817                                 continue;
6818
6819                         /* Look for the right subpage or the subpage wildcard*/
6820                         if ((lun->mode_pages.index[i].subpage != subpage)
6821                          && (subpage != SMS_SUBPAGE_ALL))
6822                                 continue;
6823
6824                         /* Make sure the page is supported for this dev type */
6825                         if ((control_dev != 0)
6826                          && (lun->mode_pages.index[i].page_flags &
6827                              CTL_PAGE_FLAG_DISK_ONLY))
6828                                 continue;
6829
6830 #if 0
6831                         printf("found page %#x len %d\n",
6832                                lun->mode_pages.index[i].page_code &
6833                                SMPH_PC_MASK,
6834                                lun->mode_pages.index[i].page_len);
6835 #endif
6836
6837                         page_len += lun->mode_pages.index[i].page_len;
6838                 }
6839
6840                 if (page_len == 0) {
6841                         ctl_set_invalid_field(ctsio,
6842                                               /*sks_valid*/ 1,
6843                                               /*command*/ 1,
6844                                               /*field*/ 2,
6845                                               /*bit_valid*/ 1,
6846                                               /*bit*/ 5);
6847                         ctl_done((union ctl_io *)ctsio);
6848                         return (CTL_RETVAL_COMPLETE);
6849                 }
6850                 break;
6851         }
6852         }
6853
6854         total_len = header_len + page_len;
6855 #if 0
6856         printf("header_len = %d, page_len = %d, total_len = %d\n",
6857                header_len, page_len, total_len);
6858 #endif
6859
6860         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6861         ctsio->kern_sg_entries = 0;
6862         ctsio->kern_data_resid = 0;
6863         ctsio->kern_rel_offset = 0;
6864         if (total_len < alloc_len) {
6865                 ctsio->residual = alloc_len - total_len;
6866                 ctsio->kern_data_len = total_len;
6867                 ctsio->kern_total_len = total_len;
6868         } else {
6869                 ctsio->residual = 0;
6870                 ctsio->kern_data_len = alloc_len;
6871                 ctsio->kern_total_len = alloc_len;
6872         }
6873
6874         switch (ctsio->cdb[0]) {
6875         case MODE_SENSE_6: {
6876                 struct scsi_mode_hdr_6 *header;
6877
6878                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6879
6880                 header->datalen = MIN(total_len - 1, 254);
6881                 if (control_dev == 0) {
6882                         header->dev_specific = 0x10; /* DPOFUA */
6883                         if ((lun->flags & CTL_LUN_READONLY) ||
6884                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6885                             .eca_and_aen & SCP_SWP) != 0)
6886                                     header->dev_specific |= 0x80; /* WP */
6887                 }
6888                 if (dbd)
6889                         header->block_descr_len = 0;
6890                 else
6891                         header->block_descr_len =
6892                                 sizeof(struct scsi_mode_block_descr);
6893                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6894                 break;
6895         }
6896         case MODE_SENSE_10: {
6897                 struct scsi_mode_hdr_10 *header;
6898                 int datalen;
6899
6900                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6901
6902                 datalen = MIN(total_len - 2, 65533);
6903                 scsi_ulto2b(datalen, header->datalen);
6904                 if (control_dev == 0) {
6905                         header->dev_specific = 0x10; /* DPOFUA */
6906                         if ((lun->flags & CTL_LUN_READONLY) ||
6907                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6908                             .eca_and_aen & SCP_SWP) != 0)
6909                                     header->dev_specific |= 0x80; /* WP */
6910                 }
6911                 if (dbd)
6912                         scsi_ulto2b(0, header->block_descr_len);
6913                 else
6914                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6915                                     header->block_descr_len);
6916                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6917                 break;
6918         }
6919         default:
6920                 panic("invalid CDB type %#x", ctsio->cdb[0]);
6921                 break; /* NOTREACHED */
6922         }
6923
6924         /*
6925          * If we've got a disk, use its blocksize in the block
6926          * descriptor.  Otherwise, just set it to 0.
6927          */
6928         if (dbd == 0) {
6929                 if (control_dev == 0)
6930                         scsi_ulto3b(lun->be_lun->blocksize,
6931                                     block_desc->block_len);
6932                 else
6933                         scsi_ulto3b(0, block_desc->block_len);
6934         }
6935
6936         switch (page_code) {
6937         case SMS_ALL_PAGES_PAGE: {
6938                 int i, data_used;
6939
6940                 data_used = header_len;
6941                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6942                         struct ctl_page_index *page_index;
6943
6944                         page_index = &lun->mode_pages.index[i];
6945
6946                         if ((control_dev != 0)
6947                          && (page_index->page_flags &
6948                             CTL_PAGE_FLAG_DISK_ONLY))
6949                                 continue;
6950
6951                         /*
6952                          * We don't use this subpage if the user didn't
6953                          * request all subpages.  We already checked (above)
6954                          * to make sure the user only specified a subpage
6955                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6956                          */
6957                         if ((page_index->subpage != 0)
6958                          && (subpage == SMS_SUBPAGE_PAGE_0))
6959                                 continue;
6960
6961                         /*
6962                          * Call the handler, if it exists, to update the
6963                          * page to the latest values.
6964                          */
6965                         if (page_index->sense_handler != NULL)
6966                                 page_index->sense_handler(ctsio, page_index,pc);
6967
6968                         memcpy(ctsio->kern_data_ptr + data_used,
6969                                page_index->page_data +
6970                                (page_index->page_len * pc),
6971                                page_index->page_len);
6972                         data_used += page_index->page_len;
6973                 }
6974                 break;
6975         }
6976         default: {
6977                 int i, data_used;
6978
6979                 data_used = header_len;
6980
6981                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6982                         struct ctl_page_index *page_index;
6983
6984                         page_index = &lun->mode_pages.index[i];
6985
6986                         /* Look for the right page code */
6987                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6988                                 continue;
6989
6990                         /* Look for the right subpage or the subpage wildcard*/
6991                         if ((page_index->subpage != subpage)
6992                          && (subpage != SMS_SUBPAGE_ALL))
6993                                 continue;
6994
6995                         /* Make sure the page is supported for this dev type */
6996                         if ((control_dev != 0)
6997                          && (page_index->page_flags &
6998                              CTL_PAGE_FLAG_DISK_ONLY))
6999                                 continue;
7000
7001                         /*
7002                          * Call the handler, if it exists, to update the
7003                          * page to the latest values.
7004                          */
7005                         if (page_index->sense_handler != NULL)
7006                                 page_index->sense_handler(ctsio, page_index,pc);
7007
7008                         memcpy(ctsio->kern_data_ptr + data_used,
7009                                page_index->page_data +
7010                                (page_index->page_len * pc),
7011                                page_index->page_len);
7012                         data_used += page_index->page_len;
7013                 }
7014                 break;
7015         }
7016         }
7017
7018         ctl_set_success(ctsio);
7019         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7020         ctsio->be_move_done = ctl_config_move_done;
7021         ctl_datamove((union ctl_io *)ctsio);
7022         return (CTL_RETVAL_COMPLETE);
7023 }
7024
7025 int
7026 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
7027                                struct ctl_page_index *page_index,
7028                                int pc)
7029 {
7030         struct ctl_lun *lun;
7031         struct scsi_log_param_header *phdr;
7032         uint8_t *data;
7033         uint64_t val;
7034
7035         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7036         data = page_index->page_data;
7037
7038         if (lun->backend->lun_attr != NULL &&
7039             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
7040              != UINT64_MAX) {
7041                 phdr = (struct scsi_log_param_header *)data;
7042                 scsi_ulto2b(0x0001, phdr->param_code);
7043                 phdr->param_control = SLP_LBIN | SLP_LP;
7044                 phdr->param_len = 8;
7045                 data = (uint8_t *)(phdr + 1);
7046                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7047                 data[4] = 0x02; /* per-pool */
7048                 data += phdr->param_len;
7049         }
7050
7051         if (lun->backend->lun_attr != NULL &&
7052             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
7053              != UINT64_MAX) {
7054                 phdr = (struct scsi_log_param_header *)data;
7055                 scsi_ulto2b(0x0002, phdr->param_code);
7056                 phdr->param_control = SLP_LBIN | SLP_LP;
7057                 phdr->param_len = 8;
7058                 data = (uint8_t *)(phdr + 1);
7059                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7060                 data[4] = 0x01; /* per-LUN */
7061                 data += phdr->param_len;
7062         }
7063
7064         if (lun->backend->lun_attr != NULL &&
7065             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
7066              != UINT64_MAX) {
7067                 phdr = (struct scsi_log_param_header *)data;
7068                 scsi_ulto2b(0x00f1, phdr->param_code);
7069                 phdr->param_control = SLP_LBIN | SLP_LP;
7070                 phdr->param_len = 8;
7071                 data = (uint8_t *)(phdr + 1);
7072                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7073                 data[4] = 0x02; /* per-pool */
7074                 data += phdr->param_len;
7075         }
7076
7077         if (lun->backend->lun_attr != NULL &&
7078             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
7079              != UINT64_MAX) {
7080                 phdr = (struct scsi_log_param_header *)data;
7081                 scsi_ulto2b(0x00f2, phdr->param_code);
7082                 phdr->param_control = SLP_LBIN | SLP_LP;
7083                 phdr->param_len = 8;
7084                 data = (uint8_t *)(phdr + 1);
7085                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7086                 data[4] = 0x02; /* per-pool */
7087                 data += phdr->param_len;
7088         }
7089
7090         page_index->page_len = data - page_index->page_data;
7091         return (0);
7092 }
7093
7094 int
7095 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
7096                                struct ctl_page_index *page_index,
7097                                int pc)
7098 {
7099         struct ctl_lun *lun;
7100         struct stat_page *data;
7101         uint64_t rn, wn, rb, wb;
7102         struct bintime rt, wt;
7103         int i;
7104
7105         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7106         data = (struct stat_page *)page_index->page_data;
7107
7108         scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
7109         data->sap.hdr.param_control = SLP_LBIN;
7110         data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
7111             sizeof(struct scsi_log_param_header);
7112         rn = wn = rb = wb = 0;
7113         bintime_clear(&rt);
7114         bintime_clear(&wt);
7115         for (i = 0; i < CTL_MAX_PORTS; i++) {
7116                 rn += lun->stats.ports[i].operations[CTL_STATS_READ];
7117                 wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
7118                 rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
7119                 wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
7120                 bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
7121                 bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
7122         }
7123         scsi_u64to8b(rn, data->sap.read_num);
7124         scsi_u64to8b(wn, data->sap.write_num);
7125         if (lun->stats.blocksize > 0) {
7126                 scsi_u64to8b(wb / lun->stats.blocksize,
7127                     data->sap.recvieved_lba);
7128                 scsi_u64to8b(rb / lun->stats.blocksize,
7129                     data->sap.transmitted_lba);
7130         }
7131         scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
7132             data->sap.read_int);
7133         scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
7134             data->sap.write_int);
7135         scsi_u64to8b(0, data->sap.weighted_num);
7136         scsi_u64to8b(0, data->sap.weighted_int);
7137         scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
7138         data->it.hdr.param_control = SLP_LBIN;
7139         data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
7140             sizeof(struct scsi_log_param_header);
7141 #ifdef CTL_TIME_IO
7142         scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
7143 #endif
7144         scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
7145         data->it.hdr.param_control = SLP_LBIN;
7146         data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
7147             sizeof(struct scsi_log_param_header);
7148         scsi_ulto4b(3, data->ti.exponent);
7149         scsi_ulto4b(1, data->ti.integer);
7150
7151         page_index->page_len = sizeof(*data);
7152         return (0);
7153 }
7154
7155 int
7156 ctl_log_sense(struct ctl_scsiio *ctsio)
7157 {
7158         struct ctl_lun *lun;
7159         int i, pc, page_code, subpage;
7160         int alloc_len, total_len;
7161         struct ctl_page_index *page_index;
7162         struct scsi_log_sense *cdb;
7163         struct scsi_log_header *header;
7164
7165         CTL_DEBUG_PRINT(("ctl_log_sense\n"));
7166
7167         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7168         cdb = (struct scsi_log_sense *)ctsio->cdb;
7169         pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
7170         page_code = cdb->page & SLS_PAGE_CODE;
7171         subpage = cdb->subpage;
7172         alloc_len = scsi_2btoul(cdb->length);
7173
7174         page_index = NULL;
7175         for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
7176                 page_index = &lun->log_pages.index[i];
7177
7178                 /* Look for the right page code */
7179                 if ((page_index->page_code & SL_PAGE_CODE) != page_code)
7180                         continue;
7181
7182                 /* Look for the right subpage or the subpage wildcard*/
7183                 if (page_index->subpage != subpage)
7184                         continue;
7185
7186                 break;
7187         }
7188         if (i >= CTL_NUM_LOG_PAGES) {
7189                 ctl_set_invalid_field(ctsio,
7190                                       /*sks_valid*/ 1,
7191                                       /*command*/ 1,
7192                                       /*field*/ 2,
7193                                       /*bit_valid*/ 0,
7194                                       /*bit*/ 0);
7195                 ctl_done((union ctl_io *)ctsio);
7196                 return (CTL_RETVAL_COMPLETE);
7197         }
7198
7199         total_len = sizeof(struct scsi_log_header) + page_index->page_len;
7200
7201         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7202         ctsio->kern_sg_entries = 0;
7203         ctsio->kern_data_resid = 0;
7204         ctsio->kern_rel_offset = 0;
7205         if (total_len < alloc_len) {
7206                 ctsio->residual = alloc_len - total_len;
7207                 ctsio->kern_data_len = total_len;
7208                 ctsio->kern_total_len = total_len;
7209         } else {
7210                 ctsio->residual = 0;
7211                 ctsio->kern_data_len = alloc_len;
7212                 ctsio->kern_total_len = alloc_len;
7213         }
7214
7215         header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7216         header->page = page_index->page_code;
7217         if (page_index->subpage) {
7218                 header->page |= SL_SPF;
7219                 header->subpage = page_index->subpage;
7220         }
7221         scsi_ulto2b(page_index->page_len, header->datalen);
7222
7223         /*
7224          * Call the handler, if it exists, to update the
7225          * page to the latest values.
7226          */
7227         if (page_index->sense_handler != NULL)
7228                 page_index->sense_handler(ctsio, page_index, pc);
7229
7230         memcpy(header + 1, page_index->page_data, page_index->page_len);
7231
7232         ctl_set_success(ctsio);
7233         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7234         ctsio->be_move_done = ctl_config_move_done;
7235         ctl_datamove((union ctl_io *)ctsio);
7236         return (CTL_RETVAL_COMPLETE);
7237 }
7238
7239 int
7240 ctl_read_capacity(struct ctl_scsiio *ctsio)
7241 {
7242         struct scsi_read_capacity *cdb;
7243         struct scsi_read_capacity_data *data;
7244         struct ctl_lun *lun;
7245         uint32_t lba;
7246
7247         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7248
7249         cdb = (struct scsi_read_capacity *)ctsio->cdb;
7250
7251         lba = scsi_4btoul(cdb->addr);
7252         if (((cdb->pmi & SRC_PMI) == 0)
7253          && (lba != 0)) {
7254                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7255                                       /*sks_valid*/ 1,
7256                                       /*command*/ 1,
7257                                       /*field*/ 2,
7258                                       /*bit_valid*/ 0,
7259                                       /*bit*/ 0);
7260                 ctl_done((union ctl_io *)ctsio);
7261                 return (CTL_RETVAL_COMPLETE);
7262         }
7263
7264         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7265
7266         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7267         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7268         ctsio->residual = 0;
7269         ctsio->kern_data_len = sizeof(*data);
7270         ctsio->kern_total_len = sizeof(*data);
7271         ctsio->kern_data_resid = 0;
7272         ctsio->kern_rel_offset = 0;
7273         ctsio->kern_sg_entries = 0;
7274
7275         /*
7276          * If the maximum LBA is greater than 0xfffffffe, the user must
7277          * issue a SERVICE ACTION IN (16) command, with the read capacity
7278          * serivce action set.
7279          */
7280         if (lun->be_lun->maxlba > 0xfffffffe)
7281                 scsi_ulto4b(0xffffffff, data->addr);
7282         else
7283                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7284
7285         /*
7286          * XXX KDM this may not be 512 bytes...
7287          */
7288         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7289
7290         ctl_set_success(ctsio);
7291         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7292         ctsio->be_move_done = ctl_config_move_done;
7293         ctl_datamove((union ctl_io *)ctsio);
7294         return (CTL_RETVAL_COMPLETE);
7295 }
7296
7297 int
7298 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7299 {
7300         struct scsi_read_capacity_16 *cdb;
7301         struct scsi_read_capacity_data_long *data;
7302         struct ctl_lun *lun;
7303         uint64_t lba;
7304         uint32_t alloc_len;
7305
7306         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7307
7308         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7309
7310         alloc_len = scsi_4btoul(cdb->alloc_len);
7311         lba = scsi_8btou64(cdb->addr);
7312
7313         if ((cdb->reladr & SRC16_PMI)
7314          && (lba != 0)) {
7315                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7316                                       /*sks_valid*/ 1,
7317                                       /*command*/ 1,
7318                                       /*field*/ 2,
7319                                       /*bit_valid*/ 0,
7320                                       /*bit*/ 0);
7321                 ctl_done((union ctl_io *)ctsio);
7322                 return (CTL_RETVAL_COMPLETE);
7323         }
7324
7325         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7326
7327         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7328         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7329
7330         if (sizeof(*data) < alloc_len) {
7331                 ctsio->residual = alloc_len - sizeof(*data);
7332                 ctsio->kern_data_len = sizeof(*data);
7333                 ctsio->kern_total_len = sizeof(*data);
7334         } else {
7335                 ctsio->residual = 0;
7336                 ctsio->kern_data_len = alloc_len;
7337                 ctsio->kern_total_len = alloc_len;
7338         }
7339         ctsio->kern_data_resid = 0;
7340         ctsio->kern_rel_offset = 0;
7341         ctsio->kern_sg_entries = 0;
7342
7343         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7344         /* XXX KDM this may not be 512 bytes... */
7345         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7346         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7347         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7348         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7349                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7350
7351         ctl_set_success(ctsio);
7352         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7353         ctsio->be_move_done = ctl_config_move_done;
7354         ctl_datamove((union ctl_io *)ctsio);
7355         return (CTL_RETVAL_COMPLETE);
7356 }
7357
7358 int
7359 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7360 {
7361         struct scsi_get_lba_status *cdb;
7362         struct scsi_get_lba_status_data *data;
7363         struct ctl_lun *lun;
7364         struct ctl_lba_len_flags *lbalen;
7365         uint64_t lba;
7366         uint32_t alloc_len, total_len;
7367         int retval;
7368
7369         CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7370
7371         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7372         cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7373         lba = scsi_8btou64(cdb->addr);
7374         alloc_len = scsi_4btoul(cdb->alloc_len);
7375
7376         if (lba > lun->be_lun->maxlba) {
7377                 ctl_set_lba_out_of_range(ctsio);
7378                 ctl_done((union ctl_io *)ctsio);
7379                 return (CTL_RETVAL_COMPLETE);
7380         }
7381
7382         total_len = sizeof(*data) + sizeof(data->descr[0]);
7383         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7384         data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7385
7386         if (total_len < alloc_len) {
7387                 ctsio->residual = alloc_len - total_len;
7388                 ctsio->kern_data_len = total_len;
7389                 ctsio->kern_total_len = total_len;
7390         } else {
7391                 ctsio->residual = 0;
7392                 ctsio->kern_data_len = alloc_len;
7393                 ctsio->kern_total_len = alloc_len;
7394         }
7395         ctsio->kern_data_resid = 0;
7396         ctsio->kern_rel_offset = 0;
7397         ctsio->kern_sg_entries = 0;
7398
7399         /* Fill dummy data in case backend can't tell anything. */
7400         scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7401         scsi_u64to8b(lba, data->descr[0].addr);
7402         scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7403             data->descr[0].length);
7404         data->descr[0].status = 0; /* Mapped or unknown. */
7405
7406         ctl_set_success(ctsio);
7407         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7408         ctsio->be_move_done = ctl_config_move_done;
7409
7410         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7411         lbalen->lba = lba;
7412         lbalen->len = total_len;
7413         lbalen->flags = 0;
7414         retval = lun->backend->config_read((union ctl_io *)ctsio);
7415         return (CTL_RETVAL_COMPLETE);
7416 }
7417
7418 int
7419 ctl_read_defect(struct ctl_scsiio *ctsio)
7420 {
7421         struct scsi_read_defect_data_10 *ccb10;
7422         struct scsi_read_defect_data_12 *ccb12;
7423         struct scsi_read_defect_data_hdr_10 *data10;
7424         struct scsi_read_defect_data_hdr_12 *data12;
7425         uint32_t alloc_len, data_len;
7426         uint8_t format;
7427
7428         CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7429
7430         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7431                 ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7432                 format = ccb10->format;
7433                 alloc_len = scsi_2btoul(ccb10->alloc_length);
7434                 data_len = sizeof(*data10);
7435         } else {
7436                 ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7437                 format = ccb12->format;
7438                 alloc_len = scsi_4btoul(ccb12->alloc_length);
7439                 data_len = sizeof(*data12);
7440         }
7441         if (alloc_len == 0) {
7442                 ctl_set_success(ctsio);
7443                 ctl_done((union ctl_io *)ctsio);
7444                 return (CTL_RETVAL_COMPLETE);
7445         }
7446
7447         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7448         if (data_len < alloc_len) {
7449                 ctsio->residual = alloc_len - data_len;
7450                 ctsio->kern_data_len = data_len;
7451                 ctsio->kern_total_len = data_len;
7452         } else {
7453                 ctsio->residual = 0;
7454                 ctsio->kern_data_len = alloc_len;
7455                 ctsio->kern_total_len = alloc_len;
7456         }
7457         ctsio->kern_data_resid = 0;
7458         ctsio->kern_rel_offset = 0;
7459         ctsio->kern_sg_entries = 0;
7460
7461         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7462                 data10 = (struct scsi_read_defect_data_hdr_10 *)
7463                     ctsio->kern_data_ptr;
7464                 data10->format = format;
7465                 scsi_ulto2b(0, data10->length);
7466         } else {
7467                 data12 = (struct scsi_read_defect_data_hdr_12 *)
7468                     ctsio->kern_data_ptr;
7469                 data12->format = format;
7470                 scsi_ulto2b(0, data12->generation);
7471                 scsi_ulto4b(0, data12->length);
7472         }
7473
7474         ctl_set_success(ctsio);
7475         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7476         ctsio->be_move_done = ctl_config_move_done;
7477         ctl_datamove((union ctl_io *)ctsio);
7478         return (CTL_RETVAL_COMPLETE);
7479 }
7480
7481 int
7482 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7483 {
7484         struct scsi_maintenance_in *cdb;
7485         int retval;
7486         int alloc_len, ext, total_len = 0, g, p, pc, pg, gs, os;
7487         int num_target_port_groups, num_target_ports;
7488         struct ctl_lun *lun;
7489         struct ctl_softc *softc;
7490         struct ctl_port *port;
7491         struct scsi_target_group_data *rtg_ptr;
7492         struct scsi_target_group_data_extended *rtg_ext_ptr;
7493         struct scsi_target_port_group_descriptor *tpg_desc;
7494
7495         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7496
7497         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7498         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7499         softc = lun->ctl_softc;
7500
7501         retval = CTL_RETVAL_COMPLETE;
7502
7503         switch (cdb->byte2 & STG_PDF_MASK) {
7504         case STG_PDF_LENGTH:
7505                 ext = 0;
7506                 break;
7507         case STG_PDF_EXTENDED:
7508                 ext = 1;
7509                 break;
7510         default:
7511                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7512                                       /*sks_valid*/ 1,
7513                                       /*command*/ 1,
7514                                       /*field*/ 2,
7515                                       /*bit_valid*/ 1,
7516                                       /*bit*/ 5);
7517                 ctl_done((union ctl_io *)ctsio);
7518                 return(retval);
7519         }
7520
7521         if (softc->is_single)
7522                 num_target_port_groups = 1;
7523         else
7524                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7525         num_target_ports = 0;
7526         mtx_lock(&softc->ctl_lock);
7527         STAILQ_FOREACH(port, &softc->port_list, links) {
7528                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7529                         continue;
7530                 if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7531                         continue;
7532                 num_target_ports++;
7533         }
7534         mtx_unlock(&softc->ctl_lock);
7535
7536         if (ext)
7537                 total_len = sizeof(struct scsi_target_group_data_extended);
7538         else
7539                 total_len = sizeof(struct scsi_target_group_data);
7540         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7541                 num_target_port_groups +
7542             sizeof(struct scsi_target_port_descriptor) *
7543                 num_target_ports * num_target_port_groups;
7544
7545         alloc_len = scsi_4btoul(cdb->length);
7546
7547         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7548
7549         ctsio->kern_sg_entries = 0;
7550
7551         if (total_len < alloc_len) {
7552                 ctsio->residual = alloc_len - total_len;
7553                 ctsio->kern_data_len = total_len;
7554                 ctsio->kern_total_len = total_len;
7555         } else {
7556                 ctsio->residual = 0;
7557                 ctsio->kern_data_len = alloc_len;
7558                 ctsio->kern_total_len = alloc_len;
7559         }
7560         ctsio->kern_data_resid = 0;
7561         ctsio->kern_rel_offset = 0;
7562
7563         if (ext) {
7564                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7565                     ctsio->kern_data_ptr;
7566                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7567                 rtg_ext_ptr->format_type = 0x10;
7568                 rtg_ext_ptr->implicit_transition_time = 0;
7569                 tpg_desc = &rtg_ext_ptr->groups[0];
7570         } else {
7571                 rtg_ptr = (struct scsi_target_group_data *)
7572                     ctsio->kern_data_ptr;
7573                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7574                 tpg_desc = &rtg_ptr->groups[0];
7575         }
7576
7577         mtx_lock(&softc->ctl_lock);
7578         pg = softc->port_offset / CTL_MAX_PORTS;
7579         if (softc->flags & CTL_FLAG_ACTIVE_SHELF) {
7580                 if (softc->ha_mode == CTL_HA_MODE_ACT_STBY) {
7581                         gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7582                         os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7583                 } else if (lun->flags & CTL_LUN_PRIMARY_SC) {
7584                         gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7585                         os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7586                 } else {
7587                         gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7588                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7589                 }
7590         } else {
7591                 gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7592                 os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7593         }
7594         for (g = 0; g < num_target_port_groups; g++) {
7595                 tpg_desc->pref_state = (g == pg) ? gs : os;
7596                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP;
7597                 scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7598                 tpg_desc->status = TPG_IMPLICIT;
7599                 pc = 0;
7600                 STAILQ_FOREACH(port, &softc->port_list, links) {
7601                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7602                                 continue;
7603                         if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7604                                 continue;
7605                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7606                         scsi_ulto2b(p, tpg_desc->descriptors[pc].
7607                             relative_target_port_identifier);
7608                         pc++;
7609                 }
7610                 tpg_desc->target_port_count = pc;
7611                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7612                     &tpg_desc->descriptors[pc];
7613         }
7614         mtx_unlock(&softc->ctl_lock);
7615
7616         ctl_set_success(ctsio);
7617         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7618         ctsio->be_move_done = ctl_config_move_done;
7619         ctl_datamove((union ctl_io *)ctsio);
7620         return(retval);
7621 }
7622
7623 int
7624 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7625 {
7626         struct ctl_lun *lun;
7627         struct scsi_report_supported_opcodes *cdb;
7628         const struct ctl_cmd_entry *entry, *sentry;
7629         struct scsi_report_supported_opcodes_all *all;
7630         struct scsi_report_supported_opcodes_descr *descr;
7631         struct scsi_report_supported_opcodes_one *one;
7632         int retval;
7633         int alloc_len, total_len;
7634         int opcode, service_action, i, j, num;
7635
7636         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7637
7638         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7639         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7640
7641         retval = CTL_RETVAL_COMPLETE;
7642
7643         opcode = cdb->requested_opcode;
7644         service_action = scsi_2btoul(cdb->requested_service_action);
7645         switch (cdb->options & RSO_OPTIONS_MASK) {
7646         case RSO_OPTIONS_ALL:
7647                 num = 0;
7648                 for (i = 0; i < 256; i++) {
7649                         entry = &ctl_cmd_table[i];
7650                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7651                                 for (j = 0; j < 32; j++) {
7652                                         sentry = &((const struct ctl_cmd_entry *)
7653                                             entry->execute)[j];
7654                                         if (ctl_cmd_applicable(
7655                                             lun->be_lun->lun_type, sentry))
7656                                                 num++;
7657                                 }
7658                         } else {
7659                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7660                                     entry))
7661                                         num++;
7662                         }
7663                 }
7664                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7665                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7666                 break;
7667         case RSO_OPTIONS_OC:
7668                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7669                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7670                                               /*sks_valid*/ 1,
7671                                               /*command*/ 1,
7672                                               /*field*/ 2,
7673                                               /*bit_valid*/ 1,
7674                                               /*bit*/ 2);
7675                         ctl_done((union ctl_io *)ctsio);
7676                         return (CTL_RETVAL_COMPLETE);
7677                 }
7678                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7679                 break;
7680         case RSO_OPTIONS_OC_SA:
7681                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7682                     service_action >= 32) {
7683                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7684                                               /*sks_valid*/ 1,
7685                                               /*command*/ 1,
7686                                               /*field*/ 2,
7687                                               /*bit_valid*/ 1,
7688                                               /*bit*/ 2);
7689                         ctl_done((union ctl_io *)ctsio);
7690                         return (CTL_RETVAL_COMPLETE);
7691                 }
7692                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7693                 break;
7694         default:
7695                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7696                                       /*sks_valid*/ 1,
7697                                       /*command*/ 1,
7698                                       /*field*/ 2,
7699                                       /*bit_valid*/ 1,
7700                                       /*bit*/ 2);
7701                 ctl_done((union ctl_io *)ctsio);
7702                 return (CTL_RETVAL_COMPLETE);
7703         }
7704
7705         alloc_len = scsi_4btoul(cdb->length);
7706
7707         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7708
7709         ctsio->kern_sg_entries = 0;
7710
7711         if (total_len < alloc_len) {
7712                 ctsio->residual = alloc_len - total_len;
7713                 ctsio->kern_data_len = total_len;
7714                 ctsio->kern_total_len = total_len;
7715         } else {
7716                 ctsio->residual = 0;
7717                 ctsio->kern_data_len = alloc_len;
7718                 ctsio->kern_total_len = alloc_len;
7719         }
7720         ctsio->kern_data_resid = 0;
7721         ctsio->kern_rel_offset = 0;
7722
7723         switch (cdb->options & RSO_OPTIONS_MASK) {
7724         case RSO_OPTIONS_ALL:
7725                 all = (struct scsi_report_supported_opcodes_all *)
7726                     ctsio->kern_data_ptr;
7727                 num = 0;
7728                 for (i = 0; i < 256; i++) {
7729                         entry = &ctl_cmd_table[i];
7730                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7731                                 for (j = 0; j < 32; j++) {
7732                                         sentry = &((const struct ctl_cmd_entry *)
7733                                             entry->execute)[j];
7734                                         if (!ctl_cmd_applicable(
7735                                             lun->be_lun->lun_type, sentry))
7736                                                 continue;
7737                                         descr = &all->descr[num++];
7738                                         descr->opcode = i;
7739                                         scsi_ulto2b(j, descr->service_action);
7740                                         descr->flags = RSO_SERVACTV;
7741                                         scsi_ulto2b(sentry->length,
7742                                             descr->cdb_length);
7743                                 }
7744                         } else {
7745                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7746                                     entry))
7747                                         continue;
7748                                 descr = &all->descr[num++];
7749                                 descr->opcode = i;
7750                                 scsi_ulto2b(0, descr->service_action);
7751                                 descr->flags = 0;
7752                                 scsi_ulto2b(entry->length, descr->cdb_length);
7753                         }
7754                 }
7755                 scsi_ulto4b(
7756                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7757                     all->length);
7758                 break;
7759         case RSO_OPTIONS_OC:
7760                 one = (struct scsi_report_supported_opcodes_one *)
7761                     ctsio->kern_data_ptr;
7762                 entry = &ctl_cmd_table[opcode];
7763                 goto fill_one;
7764         case RSO_OPTIONS_OC_SA:
7765                 one = (struct scsi_report_supported_opcodes_one *)
7766                     ctsio->kern_data_ptr;
7767                 entry = &ctl_cmd_table[opcode];
7768                 entry = &((const struct ctl_cmd_entry *)
7769                     entry->execute)[service_action];
7770 fill_one:
7771                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7772                         one->support = 3;
7773                         scsi_ulto2b(entry->length, one->cdb_length);
7774                         one->cdb_usage[0] = opcode;
7775                         memcpy(&one->cdb_usage[1], entry->usage,
7776                             entry->length - 1);
7777                 } else
7778                         one->support = 1;
7779                 break;
7780         }
7781
7782         ctl_set_success(ctsio);
7783         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7784         ctsio->be_move_done = ctl_config_move_done;
7785         ctl_datamove((union ctl_io *)ctsio);
7786         return(retval);
7787 }
7788
7789 int
7790 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7791 {
7792         struct scsi_report_supported_tmf *cdb;
7793         struct scsi_report_supported_tmf_data *data;
7794         int retval;
7795         int alloc_len, total_len;
7796
7797         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7798
7799         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7800
7801         retval = CTL_RETVAL_COMPLETE;
7802
7803         total_len = sizeof(struct scsi_report_supported_tmf_data);
7804         alloc_len = scsi_4btoul(cdb->length);
7805
7806         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7807
7808         ctsio->kern_sg_entries = 0;
7809
7810         if (total_len < alloc_len) {
7811                 ctsio->residual = alloc_len - total_len;
7812                 ctsio->kern_data_len = total_len;
7813                 ctsio->kern_total_len = total_len;
7814         } else {
7815                 ctsio->residual = 0;
7816                 ctsio->kern_data_len = alloc_len;
7817                 ctsio->kern_total_len = alloc_len;
7818         }
7819         ctsio->kern_data_resid = 0;
7820         ctsio->kern_rel_offset = 0;
7821
7822         data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7823         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7824         data->byte2 |= RST_ITNRS;
7825
7826         ctl_set_success(ctsio);
7827         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7828         ctsio->be_move_done = ctl_config_move_done;
7829         ctl_datamove((union ctl_io *)ctsio);
7830         return (retval);
7831 }
7832
7833 int
7834 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7835 {
7836         struct scsi_report_timestamp *cdb;
7837         struct scsi_report_timestamp_data *data;
7838         struct timeval tv;
7839         int64_t timestamp;
7840         int retval;
7841         int alloc_len, total_len;
7842
7843         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7844
7845         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7846
7847         retval = CTL_RETVAL_COMPLETE;
7848
7849         total_len = sizeof(struct scsi_report_timestamp_data);
7850         alloc_len = scsi_4btoul(cdb->length);
7851
7852         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7853
7854         ctsio->kern_sg_entries = 0;
7855
7856         if (total_len < alloc_len) {
7857                 ctsio->residual = alloc_len - total_len;
7858                 ctsio->kern_data_len = total_len;
7859                 ctsio->kern_total_len = total_len;
7860         } else {
7861                 ctsio->residual = 0;
7862                 ctsio->kern_data_len = alloc_len;
7863                 ctsio->kern_total_len = alloc_len;
7864         }
7865         ctsio->kern_data_resid = 0;
7866         ctsio->kern_rel_offset = 0;
7867
7868         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7869         scsi_ulto2b(sizeof(*data) - 2, data->length);
7870         data->origin = RTS_ORIG_OUTSIDE;
7871         getmicrotime(&tv);
7872         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7873         scsi_ulto4b(timestamp >> 16, data->timestamp);
7874         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7875
7876         ctl_set_success(ctsio);
7877         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7878         ctsio->be_move_done = ctl_config_move_done;
7879         ctl_datamove((union ctl_io *)ctsio);
7880         return (retval);
7881 }
7882
7883 int
7884 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7885 {
7886         struct scsi_per_res_in *cdb;
7887         int alloc_len, total_len = 0;
7888         /* struct scsi_per_res_in_rsrv in_data; */
7889         struct ctl_lun *lun;
7890         struct ctl_softc *softc;
7891         uint64_t key;
7892
7893         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7894
7895         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7896
7897         alloc_len = scsi_2btoul(cdb->length);
7898
7899         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7900         softc = lun->ctl_softc;
7901
7902 retry:
7903         mtx_lock(&lun->lun_lock);
7904         switch (cdb->action) {
7905         case SPRI_RK: /* read keys */
7906                 total_len = sizeof(struct scsi_per_res_in_keys) +
7907                         lun->pr_key_count *
7908                         sizeof(struct scsi_per_res_key);
7909                 break;
7910         case SPRI_RR: /* read reservation */
7911                 if (lun->flags & CTL_LUN_PR_RESERVED)
7912                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7913                 else
7914                         total_len = sizeof(struct scsi_per_res_in_header);
7915                 break;
7916         case SPRI_RC: /* report capabilities */
7917                 total_len = sizeof(struct scsi_per_res_cap);
7918                 break;
7919         case SPRI_RS: /* read full status */
7920                 total_len = sizeof(struct scsi_per_res_in_header) +
7921                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7922                     lun->pr_key_count;
7923                 break;
7924         default:
7925                 panic("Invalid PR type %x", cdb->action);
7926         }
7927         mtx_unlock(&lun->lun_lock);
7928
7929         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7930
7931         if (total_len < alloc_len) {
7932                 ctsio->residual = alloc_len - total_len;
7933                 ctsio->kern_data_len = total_len;
7934                 ctsio->kern_total_len = total_len;
7935         } else {
7936                 ctsio->residual = 0;
7937                 ctsio->kern_data_len = alloc_len;
7938                 ctsio->kern_total_len = alloc_len;
7939         }
7940
7941         ctsio->kern_data_resid = 0;
7942         ctsio->kern_rel_offset = 0;
7943         ctsio->kern_sg_entries = 0;
7944
7945         mtx_lock(&lun->lun_lock);
7946         switch (cdb->action) {
7947         case SPRI_RK: { // read keys
7948         struct scsi_per_res_in_keys *res_keys;
7949                 int i, key_count;
7950
7951                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7952
7953                 /*
7954                  * We had to drop the lock to allocate our buffer, which
7955                  * leaves time for someone to come in with another
7956                  * persistent reservation.  (That is unlikely, though,
7957                  * since this should be the only persistent reservation
7958                  * command active right now.)
7959                  */
7960                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7961                     (lun->pr_key_count *
7962                      sizeof(struct scsi_per_res_key)))){
7963                         mtx_unlock(&lun->lun_lock);
7964                         free(ctsio->kern_data_ptr, M_CTL);
7965                         printf("%s: reservation length changed, retrying\n",
7966                                __func__);
7967                         goto retry;
7968                 }
7969
7970                 scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7971
7972                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7973                              lun->pr_key_count, res_keys->header.length);
7974
7975                 for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7976                         if ((key = ctl_get_prkey(lun, i)) == 0)
7977                                 continue;
7978
7979                         /*
7980                          * We used lun->pr_key_count to calculate the
7981                          * size to allocate.  If it turns out the number of
7982                          * initiators with the registered flag set is
7983                          * larger than that (i.e. they haven't been kept in
7984                          * sync), we've got a problem.
7985                          */
7986                         if (key_count >= lun->pr_key_count) {
7987 #ifdef NEEDTOPORT
7988                                 csevent_log(CSC_CTL | CSC_SHELF_SW |
7989                                             CTL_PR_ERROR,
7990                                             csevent_LogType_Fault,
7991                                             csevent_AlertLevel_Yellow,
7992                                             csevent_FRU_ShelfController,
7993                                             csevent_FRU_Firmware,
7994                                         csevent_FRU_Unknown,
7995                                             "registered keys %d >= key "
7996                                             "count %d", key_count,
7997                                             lun->pr_key_count);
7998 #endif
7999                                 key_count++;
8000                                 continue;
8001                         }
8002                         scsi_u64to8b(key, res_keys->keys[key_count].key);
8003                         key_count++;
8004                 }
8005                 break;
8006         }
8007         case SPRI_RR: { // read reservation
8008                 struct scsi_per_res_in_rsrv *res;
8009                 int tmp_len, header_only;
8010
8011                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
8012
8013                 scsi_ulto4b(lun->PRGeneration, res->header.generation);
8014
8015                 if (lun->flags & CTL_LUN_PR_RESERVED)
8016                 {
8017                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
8018                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
8019                                     res->header.length);
8020                         header_only = 0;
8021                 } else {
8022                         tmp_len = sizeof(struct scsi_per_res_in_header);
8023                         scsi_ulto4b(0, res->header.length);
8024                         header_only = 1;
8025                 }
8026
8027                 /*
8028                  * We had to drop the lock to allocate our buffer, which
8029                  * leaves time for someone to come in with another
8030                  * persistent reservation.  (That is unlikely, though,
8031                  * since this should be the only persistent reservation
8032                  * command active right now.)
8033                  */
8034                 if (tmp_len != total_len) {
8035                         mtx_unlock(&lun->lun_lock);
8036                         free(ctsio->kern_data_ptr, M_CTL);
8037                         printf("%s: reservation status changed, retrying\n",
8038                                __func__);
8039                         goto retry;
8040                 }
8041
8042                 /*
8043                  * No reservation held, so we're done.
8044                  */
8045                 if (header_only != 0)
8046                         break;
8047
8048                 /*
8049                  * If the registration is an All Registrants type, the key
8050                  * is 0, since it doesn't really matter.
8051                  */
8052                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8053                         scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
8054                             res->data.reservation);
8055                 }
8056                 res->data.scopetype = lun->res_type;
8057                 break;
8058         }
8059         case SPRI_RC:     //report capabilities
8060         {
8061                 struct scsi_per_res_cap *res_cap;
8062                 uint16_t type_mask;
8063
8064                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
8065                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
8066                 res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
8067                 type_mask = SPRI_TM_WR_EX_AR |
8068                             SPRI_TM_EX_AC_RO |
8069                             SPRI_TM_WR_EX_RO |
8070                             SPRI_TM_EX_AC |
8071                             SPRI_TM_WR_EX |
8072                             SPRI_TM_EX_AC_AR;
8073                 scsi_ulto2b(type_mask, res_cap->type_mask);
8074                 break;
8075         }
8076         case SPRI_RS: { // read full status
8077                 struct scsi_per_res_in_full *res_status;
8078                 struct scsi_per_res_in_full_desc *res_desc;
8079                 struct ctl_port *port;
8080                 int i, len;
8081
8082                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
8083
8084                 /*
8085                  * We had to drop the lock to allocate our buffer, which
8086                  * leaves time for someone to come in with another
8087                  * persistent reservation.  (That is unlikely, though,
8088                  * since this should be the only persistent reservation
8089                  * command active right now.)
8090                  */
8091                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
8092                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
8093                      lun->pr_key_count)){
8094                         mtx_unlock(&lun->lun_lock);
8095                         free(ctsio->kern_data_ptr, M_CTL);
8096                         printf("%s: reservation length changed, retrying\n",
8097                                __func__);
8098                         goto retry;
8099                 }
8100
8101                 scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
8102
8103                 res_desc = &res_status->desc[0];
8104                 for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
8105                         if ((key = ctl_get_prkey(lun, i)) == 0)
8106                                 continue;
8107
8108                         scsi_u64to8b(key, res_desc->res_key.key);
8109                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
8110                             (lun->pr_res_idx == i ||
8111                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
8112                                 res_desc->flags = SPRI_FULL_R_HOLDER;
8113                                 res_desc->scopetype = lun->res_type;
8114                         }
8115                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
8116                             res_desc->rel_trgt_port_id);
8117                         len = 0;
8118                         port = softc->ctl_ports[
8119                             ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
8120                         if (port != NULL)
8121                                 len = ctl_create_iid(port,
8122                                     i % CTL_MAX_INIT_PER_PORT,
8123                                     res_desc->transport_id);
8124                         scsi_ulto4b(len, res_desc->additional_length);
8125                         res_desc = (struct scsi_per_res_in_full_desc *)
8126                             &res_desc->transport_id[len];
8127                 }
8128                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
8129                     res_status->header.length);
8130                 break;
8131         }
8132         default:
8133                 /*
8134                  * This is a bug, because we just checked for this above,
8135                  * and should have returned an error.
8136                  */
8137                 panic("Invalid PR type %x", cdb->action);
8138                 break; /* NOTREACHED */
8139         }
8140         mtx_unlock(&lun->lun_lock);
8141
8142         ctl_set_success(ctsio);
8143         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8144         ctsio->be_move_done = ctl_config_move_done;
8145         ctl_datamove((union ctl_io *)ctsio);
8146         return (CTL_RETVAL_COMPLETE);
8147 }
8148
8149 static void
8150 ctl_est_res_ua(struct ctl_lun *lun, uint32_t residx, ctl_ua_type ua)
8151 {
8152         int off = lun->ctl_softc->persis_offset;
8153
8154         if (residx >= off && residx < off + CTL_MAX_INITIATORS)
8155                 ctl_est_ua(lun, residx - off, ua);
8156 }
8157
8158 /*
8159  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
8160  * it should return.
8161  */
8162 static int
8163 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
8164                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
8165                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
8166                 struct scsi_per_res_out_parms* param)
8167 {
8168         union ctl_ha_msg persis_io;
8169         int retval, i;
8170         int isc_retval;
8171
8172         retval = 0;
8173
8174         mtx_lock(&lun->lun_lock);
8175         if (sa_res_key == 0) {
8176                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8177                         /* validate scope and type */
8178                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8179                              SPR_LU_SCOPE) {
8180                                 mtx_unlock(&lun->lun_lock);
8181                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8182                                                       /*sks_valid*/ 1,
8183                                                       /*command*/ 1,
8184                                                       /*field*/ 2,
8185                                                       /*bit_valid*/ 1,
8186                                                       /*bit*/ 4);
8187                                 ctl_done((union ctl_io *)ctsio);
8188                                 return (1);
8189                         }
8190
8191                         if (type>8 || type==2 || type==4 || type==0) {
8192                                 mtx_unlock(&lun->lun_lock);
8193                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8194                                                       /*sks_valid*/ 1,
8195                                                       /*command*/ 1,
8196                                                       /*field*/ 2,
8197                                                       /*bit_valid*/ 1,
8198                                                       /*bit*/ 0);
8199                                 ctl_done((union ctl_io *)ctsio);
8200                                 return (1);
8201                         }
8202
8203                         /*
8204                          * Unregister everybody else and build UA for
8205                          * them
8206                          */
8207                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8208                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8209                                         continue;
8210
8211                                 ctl_clr_prkey(lun, i);
8212                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8213                         }
8214                         lun->pr_key_count = 1;
8215                         lun->res_type = type;
8216                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8217                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8218                                 lun->pr_res_idx = residx;
8219
8220                         /* send msg to other side */
8221                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8222                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8223                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8224                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8225                         persis_io.pr.pr_info.res_type = type;
8226                         memcpy(persis_io.pr.pr_info.sa_res_key,
8227                                param->serv_act_res_key,
8228                                sizeof(param->serv_act_res_key));
8229                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8230                              &persis_io, sizeof(persis_io), 0)) >
8231                              CTL_HA_STATUS_SUCCESS) {
8232                                 printf("CTL:Persis Out error returned "
8233                                        "from ctl_ha_msg_send %d\n",
8234                                        isc_retval);
8235                         }
8236                 } else {
8237                         /* not all registrants */
8238                         mtx_unlock(&lun->lun_lock);
8239                         free(ctsio->kern_data_ptr, M_CTL);
8240                         ctl_set_invalid_field(ctsio,
8241                                               /*sks_valid*/ 1,
8242                                               /*command*/ 0,
8243                                               /*field*/ 8,
8244                                               /*bit_valid*/ 0,
8245                                               /*bit*/ 0);
8246                         ctl_done((union ctl_io *)ctsio);
8247                         return (1);
8248                 }
8249         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8250                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
8251                 int found = 0;
8252
8253                 if (res_key == sa_res_key) {
8254                         /* special case */
8255                         /*
8256                          * The spec implies this is not good but doesn't
8257                          * say what to do. There are two choices either
8258                          * generate a res conflict or check condition
8259                          * with illegal field in parameter data. Since
8260                          * that is what is done when the sa_res_key is
8261                          * zero I'll take that approach since this has
8262                          * to do with the sa_res_key.
8263                          */
8264                         mtx_unlock(&lun->lun_lock);
8265                         free(ctsio->kern_data_ptr, M_CTL);
8266                         ctl_set_invalid_field(ctsio,
8267                                               /*sks_valid*/ 1,
8268                                               /*command*/ 0,
8269                                               /*field*/ 8,
8270                                               /*bit_valid*/ 0,
8271                                               /*bit*/ 0);
8272                         ctl_done((union ctl_io *)ctsio);
8273                         return (1);
8274                 }
8275
8276                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8277                         if (ctl_get_prkey(lun, i) != sa_res_key)
8278                                 continue;
8279
8280                         found = 1;
8281                         ctl_clr_prkey(lun, i);
8282                         lun->pr_key_count--;
8283                         ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8284                 }
8285                 if (!found) {
8286                         mtx_unlock(&lun->lun_lock);
8287                         free(ctsio->kern_data_ptr, M_CTL);
8288                         ctl_set_reservation_conflict(ctsio);
8289                         ctl_done((union ctl_io *)ctsio);
8290                         return (CTL_RETVAL_COMPLETE);
8291                 }
8292                 /* send msg to other side */
8293                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8294                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8295                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8296                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
8297                 persis_io.pr.pr_info.res_type = type;
8298                 memcpy(persis_io.pr.pr_info.sa_res_key,
8299                        param->serv_act_res_key,
8300                        sizeof(param->serv_act_res_key));
8301                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8302                      &persis_io, sizeof(persis_io), 0)) >
8303                      CTL_HA_STATUS_SUCCESS) {
8304                         printf("CTL:Persis Out error returned from "
8305                                "ctl_ha_msg_send %d\n", isc_retval);
8306                 }
8307         } else {
8308                 /* Reserved but not all registrants */
8309                 /* sa_res_key is res holder */
8310                 if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8311                         /* validate scope and type */
8312                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8313                              SPR_LU_SCOPE) {
8314                                 mtx_unlock(&lun->lun_lock);
8315                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8316                                                       /*sks_valid*/ 1,
8317                                                       /*command*/ 1,
8318                                                       /*field*/ 2,
8319                                                       /*bit_valid*/ 1,
8320                                                       /*bit*/ 4);
8321                                 ctl_done((union ctl_io *)ctsio);
8322                                 return (1);
8323                         }
8324
8325                         if (type>8 || type==2 || type==4 || type==0) {
8326                                 mtx_unlock(&lun->lun_lock);
8327                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8328                                                       /*sks_valid*/ 1,
8329                                                       /*command*/ 1,
8330                                                       /*field*/ 2,
8331                                                       /*bit_valid*/ 1,
8332                                                       /*bit*/ 0);
8333                                 ctl_done((union ctl_io *)ctsio);
8334                                 return (1);
8335                         }
8336
8337                         /*
8338                          * Do the following:
8339                          * if sa_res_key != res_key remove all
8340                          * registrants w/sa_res_key and generate UA
8341                          * for these registrants(Registrations
8342                          * Preempted) if it wasn't an exclusive
8343                          * reservation generate UA(Reservations
8344                          * Preempted) for all other registered nexuses
8345                          * if the type has changed. Establish the new
8346                          * reservation and holder. If res_key and
8347                          * sa_res_key are the same do the above
8348                          * except don't unregister the res holder.
8349                          */
8350
8351                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8352                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8353                                         continue;
8354
8355                                 if (sa_res_key == ctl_get_prkey(lun, i)) {
8356                                         ctl_clr_prkey(lun, i);
8357                                         lun->pr_key_count--;
8358                                         ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8359                                 } else if (type != lun->res_type
8360                                         && (lun->res_type == SPR_TYPE_WR_EX_RO
8361                                          || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8362                                         ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
8363                                 }
8364                         }
8365                         lun->res_type = type;
8366                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8367                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8368                                 lun->pr_res_idx = residx;
8369                         else
8370                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8371
8372                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8373                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8374                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8375                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8376                         persis_io.pr.pr_info.res_type = type;
8377                         memcpy(persis_io.pr.pr_info.sa_res_key,
8378                                param->serv_act_res_key,
8379                                sizeof(param->serv_act_res_key));
8380                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8381                              &persis_io, sizeof(persis_io), 0)) >
8382                              CTL_HA_STATUS_SUCCESS) {
8383                                 printf("CTL:Persis Out error returned "
8384                                        "from ctl_ha_msg_send %d\n",
8385                                        isc_retval);
8386                         }
8387                 } else {
8388                         /*
8389                          * sa_res_key is not the res holder just
8390                          * remove registrants
8391                          */
8392                         int found=0;
8393
8394                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8395                                 if (sa_res_key != ctl_get_prkey(lun, i))
8396                                         continue;
8397
8398                                 found = 1;
8399                                 ctl_clr_prkey(lun, i);
8400                                 lun->pr_key_count--;
8401                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8402                         }
8403
8404                         if (!found) {
8405                                 mtx_unlock(&lun->lun_lock);
8406                                 free(ctsio->kern_data_ptr, M_CTL);
8407                                 ctl_set_reservation_conflict(ctsio);
8408                                 ctl_done((union ctl_io *)ctsio);
8409                                 return (1);
8410                         }
8411                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8412                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8413                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8414                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8415                         persis_io.pr.pr_info.res_type = type;
8416                         memcpy(persis_io.pr.pr_info.sa_res_key,
8417                                param->serv_act_res_key,
8418                                sizeof(param->serv_act_res_key));
8419                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8420                              &persis_io, sizeof(persis_io), 0)) >
8421                              CTL_HA_STATUS_SUCCESS) {
8422                                 printf("CTL:Persis Out error returned "
8423                                        "from ctl_ha_msg_send %d\n",
8424                                 isc_retval);
8425                         }
8426                 }
8427         }
8428
8429         lun->PRGeneration++;
8430         mtx_unlock(&lun->lun_lock);
8431
8432         return (retval);
8433 }
8434
8435 static void
8436 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8437 {
8438         uint64_t sa_res_key;
8439         int i;
8440
8441         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8442
8443         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8444          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8445          || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8446                 if (sa_res_key == 0) {
8447                         /*
8448                          * Unregister everybody else and build UA for
8449                          * them
8450                          */
8451                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8452                                 if (i == msg->pr.pr_info.residx ||
8453                                     ctl_get_prkey(lun, i) == 0)
8454                                         continue;
8455
8456                                 ctl_clr_prkey(lun, i);
8457                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8458                         }
8459
8460                         lun->pr_key_count = 1;
8461                         lun->res_type = msg->pr.pr_info.res_type;
8462                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8463                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8464                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8465                 } else {
8466                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8467                                 if (sa_res_key == ctl_get_prkey(lun, i))
8468                                         continue;
8469
8470                                 ctl_clr_prkey(lun, i);
8471                                 lun->pr_key_count--;
8472                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8473                         }
8474                 }
8475         } else {
8476                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8477                         if (i == msg->pr.pr_info.residx ||
8478                             ctl_get_prkey(lun, i) == 0)
8479                                 continue;
8480
8481                         if (sa_res_key == ctl_get_prkey(lun, i)) {
8482                                 ctl_clr_prkey(lun, i);
8483                                 lun->pr_key_count--;
8484                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8485                         } else if (msg->pr.pr_info.res_type != lun->res_type
8486                                 && (lun->res_type == SPR_TYPE_WR_EX_RO
8487                                  || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8488                                 ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
8489                         }
8490                 }
8491                 lun->res_type = msg->pr.pr_info.res_type;
8492                 if (lun->res_type != SPR_TYPE_WR_EX_AR
8493                  && lun->res_type != SPR_TYPE_EX_AC_AR)
8494                         lun->pr_res_idx = msg->pr.pr_info.residx;
8495                 else
8496                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8497         }
8498         lun->PRGeneration++;
8499
8500 }
8501
8502
8503 int
8504 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8505 {
8506         int retval;
8507         int isc_retval;
8508         u_int32_t param_len;
8509         struct scsi_per_res_out *cdb;
8510         struct ctl_lun *lun;
8511         struct scsi_per_res_out_parms* param;
8512         struct ctl_softc *softc;
8513         uint32_t residx;
8514         uint64_t res_key, sa_res_key, key;
8515         uint8_t type;
8516         union ctl_ha_msg persis_io;
8517         int    i;
8518
8519         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8520
8521         retval = CTL_RETVAL_COMPLETE;
8522
8523         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8524         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8525         softc = lun->ctl_softc;
8526
8527         /*
8528          * We only support whole-LUN scope.  The scope & type are ignored for
8529          * register, register and ignore existing key and clear.
8530          * We sometimes ignore scope and type on preempts too!!
8531          * Verify reservation type here as well.
8532          */
8533         type = cdb->scope_type & SPR_TYPE_MASK;
8534         if ((cdb->action == SPRO_RESERVE)
8535          || (cdb->action == SPRO_RELEASE)) {
8536                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8537                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8538                                               /*sks_valid*/ 1,
8539                                               /*command*/ 1,
8540                                               /*field*/ 2,
8541                                               /*bit_valid*/ 1,
8542                                               /*bit*/ 4);
8543                         ctl_done((union ctl_io *)ctsio);
8544                         return (CTL_RETVAL_COMPLETE);
8545                 }
8546
8547                 if (type>8 || type==2 || type==4 || type==0) {
8548                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8549                                               /*sks_valid*/ 1,
8550                                               /*command*/ 1,
8551                                               /*field*/ 2,
8552                                               /*bit_valid*/ 1,
8553                                               /*bit*/ 0);
8554                         ctl_done((union ctl_io *)ctsio);
8555                         return (CTL_RETVAL_COMPLETE);
8556                 }
8557         }
8558
8559         param_len = scsi_4btoul(cdb->length);
8560
8561         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8562                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8563                 ctsio->kern_data_len = param_len;
8564                 ctsio->kern_total_len = param_len;
8565                 ctsio->kern_data_resid = 0;
8566                 ctsio->kern_rel_offset = 0;
8567                 ctsio->kern_sg_entries = 0;
8568                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8569                 ctsio->be_move_done = ctl_config_move_done;
8570                 ctl_datamove((union ctl_io *)ctsio);
8571
8572                 return (CTL_RETVAL_COMPLETE);
8573         }
8574
8575         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8576
8577         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8578         res_key = scsi_8btou64(param->res_key.key);
8579         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8580
8581         /*
8582          * Validate the reservation key here except for SPRO_REG_IGNO
8583          * This must be done for all other service actions
8584          */
8585         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8586                 mtx_lock(&lun->lun_lock);
8587                 if ((key = ctl_get_prkey(lun, residx)) != 0) {
8588                         if (res_key != key) {
8589                                 /*
8590                                  * The current key passed in doesn't match
8591                                  * the one the initiator previously
8592                                  * registered.
8593                                  */
8594                                 mtx_unlock(&lun->lun_lock);
8595                                 free(ctsio->kern_data_ptr, M_CTL);
8596                                 ctl_set_reservation_conflict(ctsio);
8597                                 ctl_done((union ctl_io *)ctsio);
8598                                 return (CTL_RETVAL_COMPLETE);
8599                         }
8600                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8601                         /*
8602                          * We are not registered
8603                          */
8604                         mtx_unlock(&lun->lun_lock);
8605                         free(ctsio->kern_data_ptr, M_CTL);
8606                         ctl_set_reservation_conflict(ctsio);
8607                         ctl_done((union ctl_io *)ctsio);
8608                         return (CTL_RETVAL_COMPLETE);
8609                 } else if (res_key != 0) {
8610                         /*
8611                          * We are not registered and trying to register but
8612                          * the register key isn't zero.
8613                          */
8614                         mtx_unlock(&lun->lun_lock);
8615                         free(ctsio->kern_data_ptr, M_CTL);
8616                         ctl_set_reservation_conflict(ctsio);
8617                         ctl_done((union ctl_io *)ctsio);
8618                         return (CTL_RETVAL_COMPLETE);
8619                 }
8620                 mtx_unlock(&lun->lun_lock);
8621         }
8622
8623         switch (cdb->action & SPRO_ACTION_MASK) {
8624         case SPRO_REGISTER:
8625         case SPRO_REG_IGNO: {
8626
8627 #if 0
8628                 printf("Registration received\n");
8629 #endif
8630
8631                 /*
8632                  * We don't support any of these options, as we report in
8633                  * the read capabilities request (see
8634                  * ctl_persistent_reserve_in(), above).
8635                  */
8636                 if ((param->flags & SPR_SPEC_I_PT)
8637                  || (param->flags & SPR_ALL_TG_PT)
8638                  || (param->flags & SPR_APTPL)) {
8639                         int bit_ptr;
8640
8641                         if (param->flags & SPR_APTPL)
8642                                 bit_ptr = 0;
8643                         else if (param->flags & SPR_ALL_TG_PT)
8644                                 bit_ptr = 2;
8645                         else /* SPR_SPEC_I_PT */
8646                                 bit_ptr = 3;
8647
8648                         free(ctsio->kern_data_ptr, M_CTL);
8649                         ctl_set_invalid_field(ctsio,
8650                                               /*sks_valid*/ 1,
8651                                               /*command*/ 0,
8652                                               /*field*/ 20,
8653                                               /*bit_valid*/ 1,
8654                                               /*bit*/ bit_ptr);
8655                         ctl_done((union ctl_io *)ctsio);
8656                         return (CTL_RETVAL_COMPLETE);
8657                 }
8658
8659                 mtx_lock(&lun->lun_lock);
8660
8661                 /*
8662                  * The initiator wants to clear the
8663                  * key/unregister.
8664                  */
8665                 if (sa_res_key == 0) {
8666                         if ((res_key == 0
8667                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8668                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8669                           && ctl_get_prkey(lun, residx) == 0)) {
8670                                 mtx_unlock(&lun->lun_lock);
8671                                 goto done;
8672                         }
8673
8674                         ctl_clr_prkey(lun, residx);
8675                         lun->pr_key_count--;
8676
8677                         if (residx == lun->pr_res_idx) {
8678                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8679                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8680
8681                                 if ((lun->res_type == SPR_TYPE_WR_EX_RO
8682                                   || lun->res_type == SPR_TYPE_EX_AC_RO)
8683                                  && lun->pr_key_count) {
8684                                         /*
8685                                          * If the reservation is a registrants
8686                                          * only type we need to generate a UA
8687                                          * for other registered inits.  The
8688                                          * sense code should be RESERVATIONS
8689                                          * RELEASED
8690                                          */
8691
8692                                         for (i = 0; i < CTL_MAX_INITIATORS;i++){
8693                                                 if (ctl_get_prkey(lun, i +
8694                                                     softc->persis_offset) == 0)
8695                                                         continue;
8696                                                 ctl_est_ua(lun, i,
8697                                                     CTL_UA_RES_RELEASE);
8698                                         }
8699                                 }
8700                                 lun->res_type = 0;
8701                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8702                                 if (lun->pr_key_count==0) {
8703                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8704                                         lun->res_type = 0;
8705                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8706                                 }
8707                         }
8708                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8709                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8710                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8711                         persis_io.pr.pr_info.residx = residx;
8712                         if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8713                              &persis_io, sizeof(persis_io), 0 )) >
8714                              CTL_HA_STATUS_SUCCESS) {
8715                                 printf("CTL:Persis Out error returned from "
8716                                        "ctl_ha_msg_send %d\n", isc_retval);
8717                         }
8718                 } else /* sa_res_key != 0 */ {
8719
8720                         /*
8721                          * If we aren't registered currently then increment
8722                          * the key count and set the registered flag.
8723                          */
8724                         ctl_alloc_prkey(lun, residx);
8725                         if (ctl_get_prkey(lun, residx) == 0)
8726                                 lun->pr_key_count++;
8727                         ctl_set_prkey(lun, residx, sa_res_key);
8728
8729                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8730                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8731                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8732                         persis_io.pr.pr_info.residx = residx;
8733                         memcpy(persis_io.pr.pr_info.sa_res_key,
8734                                param->serv_act_res_key,
8735                                sizeof(param->serv_act_res_key));
8736                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8737                              &persis_io, sizeof(persis_io), 0)) >
8738                              CTL_HA_STATUS_SUCCESS) {
8739                                 printf("CTL:Persis Out error returned from "
8740                                        "ctl_ha_msg_send %d\n", isc_retval);
8741                         }
8742                 }
8743                 lun->PRGeneration++;
8744                 mtx_unlock(&lun->lun_lock);
8745
8746                 break;
8747         }
8748         case SPRO_RESERVE:
8749 #if 0
8750                 printf("Reserve executed type %d\n", type);
8751 #endif
8752                 mtx_lock(&lun->lun_lock);
8753                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8754                         /*
8755                          * if this isn't the reservation holder and it's
8756                          * not a "all registrants" type or if the type is
8757                          * different then we have a conflict
8758                          */
8759                         if ((lun->pr_res_idx != residx
8760                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8761                          || lun->res_type != type) {
8762                                 mtx_unlock(&lun->lun_lock);
8763                                 free(ctsio->kern_data_ptr, M_CTL);
8764                                 ctl_set_reservation_conflict(ctsio);
8765                                 ctl_done((union ctl_io *)ctsio);
8766                                 return (CTL_RETVAL_COMPLETE);
8767                         }
8768                         mtx_unlock(&lun->lun_lock);
8769                 } else /* create a reservation */ {
8770                         /*
8771                          * If it's not an "all registrants" type record
8772                          * reservation holder
8773                          */
8774                         if (type != SPR_TYPE_WR_EX_AR
8775                          && type != SPR_TYPE_EX_AC_AR)
8776                                 lun->pr_res_idx = residx; /* Res holder */
8777                         else
8778                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8779
8780                         lun->flags |= CTL_LUN_PR_RESERVED;
8781                         lun->res_type = type;
8782
8783                         mtx_unlock(&lun->lun_lock);
8784
8785                         /* send msg to other side */
8786                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8787                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8788                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8789                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8790                         persis_io.pr.pr_info.res_type = type;
8791                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8792                              &persis_io, sizeof(persis_io), 0)) >
8793                              CTL_HA_STATUS_SUCCESS) {
8794                                 printf("CTL:Persis Out error returned from "
8795                                        "ctl_ha_msg_send %d\n", isc_retval);
8796                         }
8797                 }
8798                 break;
8799
8800         case SPRO_RELEASE:
8801                 mtx_lock(&lun->lun_lock);
8802                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8803                         /* No reservation exists return good status */
8804                         mtx_unlock(&lun->lun_lock);
8805                         goto done;
8806                 }
8807                 /*
8808                  * Is this nexus a reservation holder?
8809                  */
8810                 if (lun->pr_res_idx != residx
8811                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8812                         /*
8813                          * not a res holder return good status but
8814                          * do nothing
8815                          */
8816                         mtx_unlock(&lun->lun_lock);
8817                         goto done;
8818                 }
8819
8820                 if (lun->res_type != type) {
8821                         mtx_unlock(&lun->lun_lock);
8822                         free(ctsio->kern_data_ptr, M_CTL);
8823                         ctl_set_illegal_pr_release(ctsio);
8824                         ctl_done((union ctl_io *)ctsio);
8825                         return (CTL_RETVAL_COMPLETE);
8826                 }
8827
8828                 /* okay to release */
8829                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8830                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8831                 lun->res_type = 0;
8832
8833                 /*
8834                  * if this isn't an exclusive access
8835                  * res generate UA for all other
8836                  * registrants.
8837                  */
8838                 if (type != SPR_TYPE_EX_AC
8839                  && type != SPR_TYPE_WR_EX) {
8840                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8841                                 if (i == residx ||
8842                                     ctl_get_prkey(lun,
8843                                      i + softc->persis_offset) == 0)
8844                                         continue;
8845                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8846                         }
8847                 }
8848                 mtx_unlock(&lun->lun_lock);
8849                 /* Send msg to other side */
8850                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8851                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8852                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8853                 if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8854                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8855                         printf("CTL:Persis Out error returned from "
8856                                "ctl_ha_msg_send %d\n", isc_retval);
8857                 }
8858                 break;
8859
8860         case SPRO_CLEAR:
8861                 /* send msg to other side */
8862
8863                 mtx_lock(&lun->lun_lock);
8864                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8865                 lun->res_type = 0;
8866                 lun->pr_key_count = 0;
8867                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8868
8869                 ctl_clr_prkey(lun, residx);
8870                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8871                         if (ctl_get_prkey(lun, i) != 0) {
8872                                 ctl_clr_prkey(lun, i);
8873                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8874                         }
8875                 lun->PRGeneration++;
8876                 mtx_unlock(&lun->lun_lock);
8877                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8878                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8879                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8880                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8881                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8882                         printf("CTL:Persis Out error returned from "
8883                                "ctl_ha_msg_send %d\n", isc_retval);
8884                 }
8885                 break;
8886
8887         case SPRO_PREEMPT:
8888         case SPRO_PRE_ABO: {
8889                 int nretval;
8890
8891                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8892                                           residx, ctsio, cdb, param);
8893                 if (nretval != 0)
8894                         return (CTL_RETVAL_COMPLETE);
8895                 break;
8896         }
8897         default:
8898                 panic("Invalid PR type %x", cdb->action);
8899         }
8900
8901 done:
8902         free(ctsio->kern_data_ptr, M_CTL);
8903         ctl_set_success(ctsio);
8904         ctl_done((union ctl_io *)ctsio);
8905
8906         return (retval);
8907 }
8908
8909 /*
8910  * This routine is for handling a message from the other SC pertaining to
8911  * persistent reserve out. All the error checking will have been done
8912  * so only perorming the action need be done here to keep the two
8913  * in sync.
8914  */
8915 static void
8916 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8917 {
8918         struct ctl_lun *lun;
8919         struct ctl_softc *softc;
8920         int i;
8921         uint32_t targ_lun;
8922
8923         softc = control_softc;
8924
8925         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8926         lun = softc->ctl_luns[targ_lun];
8927         mtx_lock(&lun->lun_lock);
8928         switch(msg->pr.pr_info.action) {
8929         case CTL_PR_REG_KEY:
8930                 ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8931                 if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8932                         lun->pr_key_count++;
8933                 ctl_set_prkey(lun, msg->pr.pr_info.residx,
8934                     scsi_8btou64(msg->pr.pr_info.sa_res_key));
8935                 lun->PRGeneration++;
8936                 break;
8937
8938         case CTL_PR_UNREG_KEY:
8939                 ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8940                 lun->pr_key_count--;
8941
8942                 /* XXX Need to see if the reservation has been released */
8943                 /* if so do we need to generate UA? */
8944                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8945                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8946                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8947
8948                         if ((lun->res_type == SPR_TYPE_WR_EX_RO
8949                           || lun->res_type == SPR_TYPE_EX_AC_RO)
8950                          && lun->pr_key_count) {
8951                                 /*
8952                                  * If the reservation is a registrants
8953                                  * only type we need to generate a UA
8954                                  * for other registered inits.  The
8955                                  * sense code should be RESERVATIONS
8956                                  * RELEASED
8957                                  */
8958
8959                                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8960                                         if (ctl_get_prkey(lun, i +
8961                                             softc->persis_offset) == 0)
8962                                                 continue;
8963
8964                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8965                                 }
8966                         }
8967                         lun->res_type = 0;
8968                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8969                         if (lun->pr_key_count==0) {
8970                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8971                                 lun->res_type = 0;
8972                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8973                         }
8974                 }
8975                 lun->PRGeneration++;
8976                 break;
8977
8978         case CTL_PR_RESERVE:
8979                 lun->flags |= CTL_LUN_PR_RESERVED;
8980                 lun->res_type = msg->pr.pr_info.res_type;
8981                 lun->pr_res_idx = msg->pr.pr_info.residx;
8982
8983                 break;
8984
8985         case CTL_PR_RELEASE:
8986                 /*
8987                  * if this isn't an exclusive access res generate UA for all
8988                  * other registrants.
8989                  */
8990                 if (lun->res_type != SPR_TYPE_EX_AC
8991                  && lun->res_type != SPR_TYPE_WR_EX) {
8992                         for (i = 0; i < CTL_MAX_INITIATORS; i++)
8993                                 if (ctl_get_prkey(lun, i + softc->persis_offset) != 0)
8994                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8995                 }
8996
8997                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8998                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8999                 lun->res_type = 0;
9000                 break;
9001
9002         case CTL_PR_PREEMPT:
9003                 ctl_pro_preempt_other(lun, msg);
9004                 break;
9005         case CTL_PR_CLEAR:
9006                 lun->flags &= ~CTL_LUN_PR_RESERVED;
9007                 lun->res_type = 0;
9008                 lun->pr_key_count = 0;
9009                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
9010
9011                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
9012                         if (ctl_get_prkey(lun, i) == 0)
9013                                 continue;
9014                         ctl_clr_prkey(lun, i);
9015                         ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
9016                 }
9017                 lun->PRGeneration++;
9018                 break;
9019         }
9020
9021         mtx_unlock(&lun->lun_lock);
9022 }
9023
9024 int
9025 ctl_read_write(struct ctl_scsiio *ctsio)
9026 {
9027         struct ctl_lun *lun;
9028         struct ctl_lba_len_flags *lbalen;
9029         uint64_t lba;
9030         uint32_t num_blocks;
9031         int flags, retval;
9032         int isread;
9033
9034         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9035
9036         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
9037
9038         flags = 0;
9039         retval = CTL_RETVAL_COMPLETE;
9040
9041         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
9042               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
9043         switch (ctsio->cdb[0]) {
9044         case READ_6:
9045         case WRITE_6: {
9046                 struct scsi_rw_6 *cdb;
9047
9048                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
9049
9050                 lba = scsi_3btoul(cdb->addr);
9051                 /* only 5 bits are valid in the most significant address byte */
9052                 lba &= 0x1fffff;
9053                 num_blocks = cdb->length;
9054                 /*
9055                  * This is correct according to SBC-2.
9056                  */
9057                 if (num_blocks == 0)
9058                         num_blocks = 256;
9059                 break;
9060         }
9061         case READ_10:
9062         case WRITE_10: {
9063                 struct scsi_rw_10 *cdb;
9064
9065                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
9066                 if (cdb->byte2 & SRW10_FUA)
9067                         flags |= CTL_LLF_FUA;
9068                 if (cdb->byte2 & SRW10_DPO)
9069                         flags |= CTL_LLF_DPO;
9070                 lba = scsi_4btoul(cdb->addr);
9071                 num_blocks = scsi_2btoul(cdb->length);
9072                 break;
9073         }
9074         case WRITE_VERIFY_10: {
9075                 struct scsi_write_verify_10 *cdb;
9076
9077                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
9078                 flags |= CTL_LLF_FUA;
9079                 if (cdb->byte2 & SWV_DPO)
9080                         flags |= CTL_LLF_DPO;
9081                 lba = scsi_4btoul(cdb->addr);
9082                 num_blocks = scsi_2btoul(cdb->length);
9083                 break;
9084         }
9085         case READ_12:
9086         case WRITE_12: {
9087                 struct scsi_rw_12 *cdb;
9088
9089                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
9090                 if (cdb->byte2 & SRW12_FUA)
9091                         flags |= CTL_LLF_FUA;
9092                 if (cdb->byte2 & SRW12_DPO)
9093                         flags |= CTL_LLF_DPO;
9094                 lba = scsi_4btoul(cdb->addr);
9095                 num_blocks = scsi_4btoul(cdb->length);
9096                 break;
9097         }
9098         case WRITE_VERIFY_12: {
9099                 struct scsi_write_verify_12 *cdb;
9100
9101                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
9102                 flags |= CTL_LLF_FUA;
9103                 if (cdb->byte2 & SWV_DPO)
9104                         flags |= CTL_LLF_DPO;
9105                 lba = scsi_4btoul(cdb->addr);
9106                 num_blocks = scsi_4btoul(cdb->length);
9107                 break;
9108         }
9109         case READ_16:
9110         case WRITE_16: {
9111                 struct scsi_rw_16 *cdb;
9112
9113                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9114                 if (cdb->byte2 & SRW12_FUA)
9115                         flags |= CTL_LLF_FUA;
9116                 if (cdb->byte2 & SRW12_DPO)
9117                         flags |= CTL_LLF_DPO;
9118                 lba = scsi_8btou64(cdb->addr);
9119                 num_blocks = scsi_4btoul(cdb->length);
9120                 break;
9121         }
9122         case WRITE_ATOMIC_16: {
9123                 struct scsi_rw_16 *cdb;
9124
9125                 if (lun->be_lun->atomicblock == 0) {
9126                         ctl_set_invalid_opcode(ctsio);
9127                         ctl_done((union ctl_io *)ctsio);
9128                         return (CTL_RETVAL_COMPLETE);
9129                 }
9130
9131                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9132                 if (cdb->byte2 & SRW12_FUA)
9133                         flags |= CTL_LLF_FUA;
9134                 if (cdb->byte2 & SRW12_DPO)
9135                         flags |= CTL_LLF_DPO;
9136                 lba = scsi_8btou64(cdb->addr);
9137                 num_blocks = scsi_4btoul(cdb->length);
9138                 if (num_blocks > lun->be_lun->atomicblock) {
9139                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
9140                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
9141                             /*bit*/ 0);
9142                         ctl_done((union ctl_io *)ctsio);
9143                         return (CTL_RETVAL_COMPLETE);
9144                 }
9145                 break;
9146         }
9147         case WRITE_VERIFY_16: {
9148                 struct scsi_write_verify_16 *cdb;
9149
9150                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9151                 flags |= CTL_LLF_FUA;
9152                 if (cdb->byte2 & SWV_DPO)
9153                         flags |= CTL_LLF_DPO;
9154                 lba = scsi_8btou64(cdb->addr);
9155                 num_blocks = scsi_4btoul(cdb->length);
9156                 break;
9157         }
9158         default:
9159                 /*
9160                  * We got a command we don't support.  This shouldn't
9161                  * happen, commands should be filtered out above us.
9162                  */
9163                 ctl_set_invalid_opcode(ctsio);
9164                 ctl_done((union ctl_io *)ctsio);
9165
9166                 return (CTL_RETVAL_COMPLETE);
9167                 break; /* NOTREACHED */
9168         }
9169
9170         /*
9171          * The first check is to make sure we're in bounds, the second
9172          * check is to catch wrap-around problems.  If the lba + num blocks
9173          * is less than the lba, then we've wrapped around and the block
9174          * range is invalid anyway.
9175          */
9176         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9177          || ((lba + num_blocks) < lba)) {
9178                 ctl_set_lba_out_of_range(ctsio);
9179                 ctl_done((union ctl_io *)ctsio);
9180                 return (CTL_RETVAL_COMPLETE);
9181         }
9182
9183         /*
9184          * According to SBC-3, a transfer length of 0 is not an error.
9185          * Note that this cannot happen with WRITE(6) or READ(6), since 0
9186          * translates to 256 blocks for those commands.
9187          */
9188         if (num_blocks == 0) {
9189                 ctl_set_success(ctsio);
9190                 ctl_done((union ctl_io *)ctsio);
9191                 return (CTL_RETVAL_COMPLETE);
9192         }
9193
9194         /* Set FUA and/or DPO if caches are disabled. */
9195         if (isread) {
9196                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9197                     SCP_RCD) != 0)
9198                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9199         } else {
9200                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9201                     SCP_WCE) == 0)
9202                         flags |= CTL_LLF_FUA;
9203         }
9204
9205         lbalen = (struct ctl_lba_len_flags *)
9206             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9207         lbalen->lba = lba;
9208         lbalen->len = num_blocks;
9209         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9210
9211         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9212         ctsio->kern_rel_offset = 0;
9213
9214         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9215
9216         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9217
9218         return (retval);
9219 }
9220
9221 static int
9222 ctl_cnw_cont(union ctl_io *io)
9223 {
9224         struct ctl_scsiio *ctsio;
9225         struct ctl_lun *lun;
9226         struct ctl_lba_len_flags *lbalen;
9227         int retval;
9228
9229         ctsio = &io->scsiio;
9230         ctsio->io_hdr.status = CTL_STATUS_NONE;
9231         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9232         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9233         lbalen = (struct ctl_lba_len_flags *)
9234             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9235         lbalen->flags &= ~CTL_LLF_COMPARE;
9236         lbalen->flags |= CTL_LLF_WRITE;
9237
9238         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9239         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9240         return (retval);
9241 }
9242
9243 int
9244 ctl_cnw(struct ctl_scsiio *ctsio)
9245 {
9246         struct ctl_lun *lun;
9247         struct ctl_lba_len_flags *lbalen;
9248         uint64_t lba;
9249         uint32_t num_blocks;
9250         int flags, retval;
9251
9252         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9253
9254         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9255
9256         flags = 0;
9257         retval = CTL_RETVAL_COMPLETE;
9258
9259         switch (ctsio->cdb[0]) {
9260         case COMPARE_AND_WRITE: {
9261                 struct scsi_compare_and_write *cdb;
9262
9263                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9264                 if (cdb->byte2 & SRW10_FUA)
9265                         flags |= CTL_LLF_FUA;
9266                 if (cdb->byte2 & SRW10_DPO)
9267                         flags |= CTL_LLF_DPO;
9268                 lba = scsi_8btou64(cdb->addr);
9269                 num_blocks = cdb->length;
9270                 break;
9271         }
9272         default:
9273                 /*
9274                  * We got a command we don't support.  This shouldn't
9275                  * happen, commands should be filtered out above us.
9276                  */
9277                 ctl_set_invalid_opcode(ctsio);
9278                 ctl_done((union ctl_io *)ctsio);
9279
9280                 return (CTL_RETVAL_COMPLETE);
9281                 break; /* NOTREACHED */
9282         }
9283
9284         /*
9285          * The first check is to make sure we're in bounds, the second
9286          * check is to catch wrap-around problems.  If the lba + num blocks
9287          * is less than the lba, then we've wrapped around and the block
9288          * range is invalid anyway.
9289          */
9290         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9291          || ((lba + num_blocks) < lba)) {
9292                 ctl_set_lba_out_of_range(ctsio);
9293                 ctl_done((union ctl_io *)ctsio);
9294                 return (CTL_RETVAL_COMPLETE);
9295         }
9296
9297         /*
9298          * According to SBC-3, a transfer length of 0 is not an error.
9299          */
9300         if (num_blocks == 0) {
9301                 ctl_set_success(ctsio);
9302                 ctl_done((union ctl_io *)ctsio);
9303                 return (CTL_RETVAL_COMPLETE);
9304         }
9305
9306         /* Set FUA if write cache is disabled. */
9307         if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9308             SCP_WCE) == 0)
9309                 flags |= CTL_LLF_FUA;
9310
9311         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9312         ctsio->kern_rel_offset = 0;
9313
9314         /*
9315          * Set the IO_CONT flag, so that if this I/O gets passed to
9316          * ctl_data_submit_done(), it'll get passed back to
9317          * ctl_ctl_cnw_cont() for further processing.
9318          */
9319         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9320         ctsio->io_cont = ctl_cnw_cont;
9321
9322         lbalen = (struct ctl_lba_len_flags *)
9323             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9324         lbalen->lba = lba;
9325         lbalen->len = num_blocks;
9326         lbalen->flags = CTL_LLF_COMPARE | flags;
9327
9328         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9329         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9330         return (retval);
9331 }
9332
9333 int
9334 ctl_verify(struct ctl_scsiio *ctsio)
9335 {
9336         struct ctl_lun *lun;
9337         struct ctl_lba_len_flags *lbalen;
9338         uint64_t lba;
9339         uint32_t num_blocks;
9340         int bytchk, flags;
9341         int retval;
9342
9343         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9344
9345         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9346
9347         bytchk = 0;
9348         flags = CTL_LLF_FUA;
9349         retval = CTL_RETVAL_COMPLETE;
9350
9351         switch (ctsio->cdb[0]) {
9352         case VERIFY_10: {
9353                 struct scsi_verify_10 *cdb;
9354
9355                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
9356                 if (cdb->byte2 & SVFY_BYTCHK)
9357                         bytchk = 1;
9358                 if (cdb->byte2 & SVFY_DPO)
9359                         flags |= CTL_LLF_DPO;
9360                 lba = scsi_4btoul(cdb->addr);
9361                 num_blocks = scsi_2btoul(cdb->length);
9362                 break;
9363         }
9364         case VERIFY_12: {
9365                 struct scsi_verify_12 *cdb;
9366
9367                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
9368                 if (cdb->byte2 & SVFY_BYTCHK)
9369                         bytchk = 1;
9370                 if (cdb->byte2 & SVFY_DPO)
9371                         flags |= CTL_LLF_DPO;
9372                 lba = scsi_4btoul(cdb->addr);
9373                 num_blocks = scsi_4btoul(cdb->length);
9374                 break;
9375         }
9376         case VERIFY_16: {
9377                 struct scsi_rw_16 *cdb;
9378
9379                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9380                 if (cdb->byte2 & SVFY_BYTCHK)
9381                         bytchk = 1;
9382                 if (cdb->byte2 & SVFY_DPO)
9383                         flags |= CTL_LLF_DPO;
9384                 lba = scsi_8btou64(cdb->addr);
9385                 num_blocks = scsi_4btoul(cdb->length);
9386                 break;
9387         }
9388         default:
9389                 /*
9390                  * We got a command we don't support.  This shouldn't
9391                  * happen, commands should be filtered out above us.
9392                  */
9393                 ctl_set_invalid_opcode(ctsio);
9394                 ctl_done((union ctl_io *)ctsio);
9395                 return (CTL_RETVAL_COMPLETE);
9396         }
9397
9398         /*
9399          * The first check is to make sure we're in bounds, the second
9400          * check is to catch wrap-around problems.  If the lba + num blocks
9401          * is less than the lba, then we've wrapped around and the block
9402          * range is invalid anyway.
9403          */
9404         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9405          || ((lba + num_blocks) < lba)) {
9406                 ctl_set_lba_out_of_range(ctsio);
9407                 ctl_done((union ctl_io *)ctsio);
9408                 return (CTL_RETVAL_COMPLETE);
9409         }
9410
9411         /*
9412          * According to SBC-3, a transfer length of 0 is not an error.
9413          */
9414         if (num_blocks == 0) {
9415                 ctl_set_success(ctsio);
9416                 ctl_done((union ctl_io *)ctsio);
9417                 return (CTL_RETVAL_COMPLETE);
9418         }
9419
9420         lbalen = (struct ctl_lba_len_flags *)
9421             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9422         lbalen->lba = lba;
9423         lbalen->len = num_blocks;
9424         if (bytchk) {
9425                 lbalen->flags = CTL_LLF_COMPARE | flags;
9426                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9427         } else {
9428                 lbalen->flags = CTL_LLF_VERIFY | flags;
9429                 ctsio->kern_total_len = 0;
9430         }
9431         ctsio->kern_rel_offset = 0;
9432
9433         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9434         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9435         return (retval);
9436 }
9437
9438 int
9439 ctl_report_luns(struct ctl_scsiio *ctsio)
9440 {
9441         struct ctl_softc *softc = control_softc;
9442         struct scsi_report_luns *cdb;
9443         struct scsi_report_luns_data *lun_data;
9444         struct ctl_lun *lun, *request_lun;
9445         struct ctl_port *port;
9446         int num_luns, retval;
9447         uint32_t alloc_len, lun_datalen;
9448         int num_filled, well_known;
9449         uint32_t initidx, targ_lun_id, lun_id;
9450
9451         retval = CTL_RETVAL_COMPLETE;
9452         well_known = 0;
9453
9454         cdb = (struct scsi_report_luns *)ctsio->cdb;
9455         port = ctl_io_port(&ctsio->io_hdr);
9456
9457         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9458
9459         mtx_lock(&softc->ctl_lock);
9460         num_luns = 0;
9461         for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
9462                 if (ctl_lun_map_from_port(port, targ_lun_id) < CTL_MAX_LUNS)
9463                         num_luns++;
9464         }
9465         mtx_unlock(&softc->ctl_lock);
9466
9467         switch (cdb->select_report) {
9468         case RPL_REPORT_DEFAULT:
9469         case RPL_REPORT_ALL:
9470                 break;
9471         case RPL_REPORT_WELLKNOWN:
9472                 well_known = 1;
9473                 num_luns = 0;
9474                 break;
9475         default:
9476                 ctl_set_invalid_field(ctsio,
9477                                       /*sks_valid*/ 1,
9478                                       /*command*/ 1,
9479                                       /*field*/ 2,
9480                                       /*bit_valid*/ 0,
9481                                       /*bit*/ 0);
9482                 ctl_done((union ctl_io *)ctsio);
9483                 return (retval);
9484                 break; /* NOTREACHED */
9485         }
9486
9487         alloc_len = scsi_4btoul(cdb->length);
9488         /*
9489          * The initiator has to allocate at least 16 bytes for this request,
9490          * so he can at least get the header and the first LUN.  Otherwise
9491          * we reject the request (per SPC-3 rev 14, section 6.21).
9492          */
9493         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9494             sizeof(struct scsi_report_luns_lundata))) {
9495                 ctl_set_invalid_field(ctsio,
9496                                       /*sks_valid*/ 1,
9497                                       /*command*/ 1,
9498                                       /*field*/ 6,
9499                                       /*bit_valid*/ 0,
9500                                       /*bit*/ 0);
9501                 ctl_done((union ctl_io *)ctsio);
9502                 return (retval);
9503         }
9504
9505         request_lun = (struct ctl_lun *)
9506                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9507
9508         lun_datalen = sizeof(*lun_data) +
9509                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9510
9511         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9512         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9513         ctsio->kern_sg_entries = 0;
9514
9515         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9516
9517         mtx_lock(&softc->ctl_lock);
9518         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9519                 lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9520                 if (lun_id >= CTL_MAX_LUNS)
9521                         continue;
9522                 lun = softc->ctl_luns[lun_id];
9523                 if (lun == NULL)
9524                         continue;
9525
9526                 if (targ_lun_id <= 0xff) {
9527                         /*
9528                          * Peripheral addressing method, bus number 0.
9529                          */
9530                         lun_data->luns[num_filled].lundata[0] =
9531                                 RPL_LUNDATA_ATYP_PERIPH;
9532                         lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9533                         num_filled++;
9534                 } else if (targ_lun_id <= 0x3fff) {
9535                         /*
9536                          * Flat addressing method.
9537                          */
9538                         lun_data->luns[num_filled].lundata[0] =
9539                                 RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9540                         lun_data->luns[num_filled].lundata[1] =
9541                                 (targ_lun_id & 0xff);
9542                         num_filled++;
9543                 } else if (targ_lun_id <= 0xffffff) {
9544                         /*
9545                          * Extended flat addressing method.
9546                          */
9547                         lun_data->luns[num_filled].lundata[0] =
9548                             RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9549                         scsi_ulto3b(targ_lun_id,
9550                             &lun_data->luns[num_filled].lundata[1]);
9551                         num_filled++;
9552                 } else {
9553                         printf("ctl_report_luns: bogus LUN number %jd, "
9554                                "skipping\n", (intmax_t)targ_lun_id);
9555                 }
9556                 /*
9557                  * According to SPC-3, rev 14 section 6.21:
9558                  *
9559                  * "The execution of a REPORT LUNS command to any valid and
9560                  * installed logical unit shall clear the REPORTED LUNS DATA
9561                  * HAS CHANGED unit attention condition for all logical
9562                  * units of that target with respect to the requesting
9563                  * initiator. A valid and installed logical unit is one
9564                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9565                  * INQUIRY data (see 6.4.2)."
9566                  *
9567                  * If request_lun is NULL, the LUN this report luns command
9568                  * was issued to is either disabled or doesn't exist. In that
9569                  * case, we shouldn't clear any pending lun change unit
9570                  * attention.
9571                  */
9572                 if (request_lun != NULL) {
9573                         mtx_lock(&lun->lun_lock);
9574                         ctl_clr_ua(lun, initidx, CTL_UA_RES_RELEASE);
9575                         mtx_unlock(&lun->lun_lock);
9576                 }
9577         }
9578         mtx_unlock(&softc->ctl_lock);
9579
9580         /*
9581          * It's quite possible that we've returned fewer LUNs than we allocated
9582          * space for.  Trim it.
9583          */
9584         lun_datalen = sizeof(*lun_data) +
9585                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9586
9587         if (lun_datalen < alloc_len) {
9588                 ctsio->residual = alloc_len - lun_datalen;
9589                 ctsio->kern_data_len = lun_datalen;
9590                 ctsio->kern_total_len = lun_datalen;
9591         } else {
9592                 ctsio->residual = 0;
9593                 ctsio->kern_data_len = alloc_len;
9594                 ctsio->kern_total_len = alloc_len;
9595         }
9596         ctsio->kern_data_resid = 0;
9597         ctsio->kern_rel_offset = 0;
9598         ctsio->kern_sg_entries = 0;
9599
9600         /*
9601          * We set this to the actual data length, regardless of how much
9602          * space we actually have to return results.  If the user looks at
9603          * this value, he'll know whether or not he allocated enough space
9604          * and reissue the command if necessary.  We don't support well
9605          * known logical units, so if the user asks for that, return none.
9606          */
9607         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9608
9609         /*
9610          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9611          * this request.
9612          */
9613         ctl_set_success(ctsio);
9614         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9615         ctsio->be_move_done = ctl_config_move_done;
9616         ctl_datamove((union ctl_io *)ctsio);
9617         return (retval);
9618 }
9619
9620 int
9621 ctl_request_sense(struct ctl_scsiio *ctsio)
9622 {
9623         struct scsi_request_sense *cdb;
9624         struct scsi_sense_data *sense_ptr;
9625         struct ctl_softc *ctl_softc;
9626         struct ctl_lun *lun;
9627         uint32_t initidx;
9628         int have_error;
9629         scsi_sense_data_type sense_format;
9630         ctl_ua_type ua_type;
9631
9632         cdb = (struct scsi_request_sense *)ctsio->cdb;
9633
9634         ctl_softc = control_softc;
9635         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9636
9637         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9638
9639         /*
9640          * Determine which sense format the user wants.
9641          */
9642         if (cdb->byte2 & SRS_DESC)
9643                 sense_format = SSD_TYPE_DESC;
9644         else
9645                 sense_format = SSD_TYPE_FIXED;
9646
9647         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9648         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9649         ctsio->kern_sg_entries = 0;
9650
9651         /*
9652          * struct scsi_sense_data, which is currently set to 256 bytes, is
9653          * larger than the largest allowed value for the length field in the
9654          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9655          */
9656         ctsio->residual = 0;
9657         ctsio->kern_data_len = cdb->length;
9658         ctsio->kern_total_len = cdb->length;
9659
9660         ctsio->kern_data_resid = 0;
9661         ctsio->kern_rel_offset = 0;
9662         ctsio->kern_sg_entries = 0;
9663
9664         /*
9665          * If we don't have a LUN, we don't have any pending sense.
9666          */
9667         if (lun == NULL)
9668                 goto no_sense;
9669
9670         have_error = 0;
9671         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9672         /*
9673          * Check for pending sense, and then for pending unit attentions.
9674          * Pending sense gets returned first, then pending unit attentions.
9675          */
9676         mtx_lock(&lun->lun_lock);
9677 #ifdef CTL_WITH_CA
9678         if (ctl_is_set(lun->have_ca, initidx)) {
9679                 scsi_sense_data_type stored_format;
9680
9681                 /*
9682                  * Check to see which sense format was used for the stored
9683                  * sense data.
9684                  */
9685                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9686
9687                 /*
9688                  * If the user requested a different sense format than the
9689                  * one we stored, then we need to convert it to the other
9690                  * format.  If we're going from descriptor to fixed format
9691                  * sense data, we may lose things in translation, depending
9692                  * on what options were used.
9693                  *
9694                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9695                  * for some reason we'll just copy it out as-is.
9696                  */
9697                 if ((stored_format == SSD_TYPE_FIXED)
9698                  && (sense_format == SSD_TYPE_DESC))
9699                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9700                             &lun->pending_sense[initidx],
9701                             (struct scsi_sense_data_desc *)sense_ptr);
9702                 else if ((stored_format == SSD_TYPE_DESC)
9703                       && (sense_format == SSD_TYPE_FIXED))
9704                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9705                             &lun->pending_sense[initidx],
9706                             (struct scsi_sense_data_fixed *)sense_ptr);
9707                 else
9708                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9709                                MIN(sizeof(*sense_ptr),
9710                                sizeof(lun->pending_sense[initidx])));
9711
9712                 ctl_clear_mask(lun->have_ca, initidx);
9713                 have_error = 1;
9714         } else
9715 #endif
9716         {
9717                 ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9718                 if (ua_type != CTL_UA_NONE)
9719                         have_error = 1;
9720                 if (ua_type == CTL_UA_LUN_CHANGE) {
9721                         mtx_unlock(&lun->lun_lock);
9722                         mtx_lock(&ctl_softc->ctl_lock);
9723                         ctl_clear_ua(ctl_softc, initidx, ua_type);
9724                         mtx_unlock(&ctl_softc->ctl_lock);
9725                         mtx_lock(&lun->lun_lock);
9726                 }
9727
9728         }
9729         mtx_unlock(&lun->lun_lock);
9730
9731         /*
9732          * We already have a pending error, return it.
9733          */
9734         if (have_error != 0) {
9735                 /*
9736                  * We report the SCSI status as OK, since the status of the
9737                  * request sense command itself is OK.
9738                  * We report 0 for the sense length, because we aren't doing
9739                  * autosense in this case.  We're reporting sense as
9740                  * parameter data.
9741                  */
9742                 ctl_set_success(ctsio);
9743                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9744                 ctsio->be_move_done = ctl_config_move_done;
9745                 ctl_datamove((union ctl_io *)ctsio);
9746                 return (CTL_RETVAL_COMPLETE);
9747         }
9748
9749 no_sense:
9750
9751         /*
9752          * No sense information to report, so we report that everything is
9753          * okay.
9754          */
9755         ctl_set_sense_data(sense_ptr,
9756                            lun,
9757                            sense_format,
9758                            /*current_error*/ 1,
9759                            /*sense_key*/ SSD_KEY_NO_SENSE,
9760                            /*asc*/ 0x00,
9761                            /*ascq*/ 0x00,
9762                            SSD_ELEM_NONE);
9763
9764         /*
9765          * We report 0 for the sense length, because we aren't doing
9766          * autosense in this case.  We're reporting sense as parameter data.
9767          */
9768         ctl_set_success(ctsio);
9769         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9770         ctsio->be_move_done = ctl_config_move_done;
9771         ctl_datamove((union ctl_io *)ctsio);
9772         return (CTL_RETVAL_COMPLETE);
9773 }
9774
9775 int
9776 ctl_tur(struct ctl_scsiio *ctsio)
9777 {
9778
9779         CTL_DEBUG_PRINT(("ctl_tur\n"));
9780
9781         ctl_set_success(ctsio);
9782         ctl_done((union ctl_io *)ctsio);
9783
9784         return (CTL_RETVAL_COMPLETE);
9785 }
9786
9787 #ifdef notyet
9788 static int
9789 ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9790 {
9791
9792 }
9793 #endif
9794
9795 /*
9796  * SCSI VPD page 0x00, the Supported VPD Pages page.
9797  */
9798 static int
9799 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9800 {
9801         struct scsi_vpd_supported_pages *pages;
9802         int sup_page_size;
9803         struct ctl_lun *lun;
9804         int p;
9805
9806         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9807
9808         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9809             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9810         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9811         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9812         ctsio->kern_sg_entries = 0;
9813
9814         if (sup_page_size < alloc_len) {
9815                 ctsio->residual = alloc_len - sup_page_size;
9816                 ctsio->kern_data_len = sup_page_size;
9817                 ctsio->kern_total_len = sup_page_size;
9818         } else {
9819                 ctsio->residual = 0;
9820                 ctsio->kern_data_len = alloc_len;
9821                 ctsio->kern_total_len = alloc_len;
9822         }
9823         ctsio->kern_data_resid = 0;
9824         ctsio->kern_rel_offset = 0;
9825         ctsio->kern_sg_entries = 0;
9826
9827         /*
9828          * The control device is always connected.  The disk device, on the
9829          * other hand, may not be online all the time.  Need to change this
9830          * to figure out whether the disk device is actually online or not.
9831          */
9832         if (lun != NULL)
9833                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9834                                 lun->be_lun->lun_type;
9835         else
9836                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9837
9838         p = 0;
9839         /* Supported VPD pages */
9840         pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9841         /* Serial Number */
9842         pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9843         /* Device Identification */
9844         pages->page_list[p++] = SVPD_DEVICE_ID;
9845         /* Extended INQUIRY Data */
9846         pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9847         /* Mode Page Policy */
9848         pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9849         /* SCSI Ports */
9850         pages->page_list[p++] = SVPD_SCSI_PORTS;
9851         /* Third-party Copy */
9852         pages->page_list[p++] = SVPD_SCSI_TPC;
9853         if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9854                 /* Block limits */
9855                 pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9856                 /* Block Device Characteristics */
9857                 pages->page_list[p++] = SVPD_BDC;
9858                 /* Logical Block Provisioning */
9859                 pages->page_list[p++] = SVPD_LBP;
9860         }
9861         pages->length = p;
9862
9863         ctl_set_success(ctsio);
9864         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9865         ctsio->be_move_done = ctl_config_move_done;
9866         ctl_datamove((union ctl_io *)ctsio);
9867         return (CTL_RETVAL_COMPLETE);
9868 }
9869
9870 /*
9871  * SCSI VPD page 0x80, the Unit Serial Number page.
9872  */
9873 static int
9874 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9875 {
9876         struct scsi_vpd_unit_serial_number *sn_ptr;
9877         struct ctl_lun *lun;
9878         int data_len;
9879
9880         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9881
9882         data_len = 4 + CTL_SN_LEN;
9883         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9884         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9885         if (data_len < alloc_len) {
9886                 ctsio->residual = alloc_len - data_len;
9887                 ctsio->kern_data_len = data_len;
9888                 ctsio->kern_total_len = data_len;
9889         } else {
9890                 ctsio->residual = 0;
9891                 ctsio->kern_data_len = alloc_len;
9892                 ctsio->kern_total_len = alloc_len;
9893         }
9894         ctsio->kern_data_resid = 0;
9895         ctsio->kern_rel_offset = 0;
9896         ctsio->kern_sg_entries = 0;
9897
9898         /*
9899          * The control device is always connected.  The disk device, on the
9900          * other hand, may not be online all the time.  Need to change this
9901          * to figure out whether the disk device is actually online or not.
9902          */
9903         if (lun != NULL)
9904                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9905                                   lun->be_lun->lun_type;
9906         else
9907                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9908
9909         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9910         sn_ptr->length = CTL_SN_LEN;
9911         /*
9912          * If we don't have a LUN, we just leave the serial number as
9913          * all spaces.
9914          */
9915         if (lun != NULL) {
9916                 strncpy((char *)sn_ptr->serial_num,
9917                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9918         } else
9919                 memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9920
9921         ctl_set_success(ctsio);
9922         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9923         ctsio->be_move_done = ctl_config_move_done;
9924         ctl_datamove((union ctl_io *)ctsio);
9925         return (CTL_RETVAL_COMPLETE);
9926 }
9927
9928
9929 /*
9930  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9931  */
9932 static int
9933 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9934 {
9935         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9936         struct ctl_lun *lun;
9937         int data_len;
9938
9939         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9940
9941         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9942         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9943         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9944         ctsio->kern_sg_entries = 0;
9945
9946         if (data_len < alloc_len) {
9947                 ctsio->residual = alloc_len - data_len;
9948                 ctsio->kern_data_len = data_len;
9949                 ctsio->kern_total_len = data_len;
9950         } else {
9951                 ctsio->residual = 0;
9952                 ctsio->kern_data_len = alloc_len;
9953                 ctsio->kern_total_len = alloc_len;
9954         }
9955         ctsio->kern_data_resid = 0;
9956         ctsio->kern_rel_offset = 0;
9957         ctsio->kern_sg_entries = 0;
9958
9959         /*
9960          * The control device is always connected.  The disk device, on the
9961          * other hand, may not be online all the time.
9962          */
9963         if (lun != NULL)
9964                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9965                                      lun->be_lun->lun_type;
9966         else
9967                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9968         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9969         scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9970         /*
9971          * We support head of queue, ordered and simple tags.
9972          */
9973         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9974         /*
9975          * Volatile cache supported.
9976          */
9977         eid_ptr->flags3 = SVPD_EID_V_SUP;
9978
9979         /*
9980          * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9981          * attention for a particular IT nexus on all LUNs once we report
9982          * it to that nexus once.  This bit is required as of SPC-4.
9983          */
9984         eid_ptr->flags4 = SVPD_EID_LUICLT;
9985
9986         /*
9987          * XXX KDM in order to correctly answer this, we would need
9988          * information from the SIM to determine how much sense data it
9989          * can send.  So this would really be a path inquiry field, most
9990          * likely.  This can be set to a maximum of 252 according to SPC-4,
9991          * but the hardware may or may not be able to support that much.
9992          * 0 just means that the maximum sense data length is not reported.
9993          */
9994         eid_ptr->max_sense_length = 0;
9995
9996         ctl_set_success(ctsio);
9997         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9998         ctsio->be_move_done = ctl_config_move_done;
9999         ctl_datamove((union ctl_io *)ctsio);
10000         return (CTL_RETVAL_COMPLETE);
10001 }
10002
10003 static int
10004 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
10005 {
10006         struct scsi_vpd_mode_page_policy *mpp_ptr;
10007         struct ctl_lun *lun;
10008         int data_len;
10009
10010         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10011
10012         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
10013             sizeof(struct scsi_vpd_mode_page_policy_descr);
10014
10015         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10016         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
10017         ctsio->kern_sg_entries = 0;
10018
10019         if (data_len < alloc_len) {
10020                 ctsio->residual = alloc_len - data_len;
10021                 ctsio->kern_data_len = data_len;
10022                 ctsio->kern_total_len = data_len;
10023         } else {
10024                 ctsio->residual = 0;
10025                 ctsio->kern_data_len = alloc_len;
10026                 ctsio->kern_total_len = alloc_len;
10027         }
10028         ctsio->kern_data_resid = 0;
10029         ctsio->kern_rel_offset = 0;
10030         ctsio->kern_sg_entries = 0;
10031
10032         /*
10033          * The control device is always connected.  The disk device, on the
10034          * other hand, may not be online all the time.
10035          */
10036         if (lun != NULL)
10037                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10038                                      lun->be_lun->lun_type;
10039         else
10040                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10041         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
10042         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
10043         mpp_ptr->descr[0].page_code = 0x3f;
10044         mpp_ptr->descr[0].subpage_code = 0xff;
10045         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
10046
10047         ctl_set_success(ctsio);
10048         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10049         ctsio->be_move_done = ctl_config_move_done;
10050         ctl_datamove((union ctl_io *)ctsio);
10051         return (CTL_RETVAL_COMPLETE);
10052 }
10053
10054 /*
10055  * SCSI VPD page 0x83, the Device Identification page.
10056  */
10057 static int
10058 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
10059 {
10060         struct scsi_vpd_device_id *devid_ptr;
10061         struct scsi_vpd_id_descriptor *desc;
10062         struct ctl_softc *softc;
10063         struct ctl_lun *lun;
10064         struct ctl_port *port;
10065         int data_len;
10066         uint8_t proto;
10067
10068         softc = control_softc;
10069
10070         port = softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
10071         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10072
10073         data_len = sizeof(struct scsi_vpd_device_id) +
10074             sizeof(struct scsi_vpd_id_descriptor) +
10075                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
10076             sizeof(struct scsi_vpd_id_descriptor) +
10077                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
10078         if (lun && lun->lun_devid)
10079                 data_len += lun->lun_devid->len;
10080         if (port->port_devid)
10081                 data_len += port->port_devid->len;
10082         if (port->target_devid)
10083                 data_len += port->target_devid->len;
10084
10085         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10086         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
10087         ctsio->kern_sg_entries = 0;
10088
10089         if (data_len < alloc_len) {
10090                 ctsio->residual = alloc_len - data_len;
10091                 ctsio->kern_data_len = data_len;
10092                 ctsio->kern_total_len = data_len;
10093         } else {
10094                 ctsio->residual = 0;
10095                 ctsio->kern_data_len = alloc_len;
10096                 ctsio->kern_total_len = alloc_len;
10097         }
10098         ctsio->kern_data_resid = 0;
10099         ctsio->kern_rel_offset = 0;
10100         ctsio->kern_sg_entries = 0;
10101
10102         /*
10103          * The control device is always connected.  The disk device, on the
10104          * other hand, may not be online all the time.
10105          */
10106         if (lun != NULL)
10107                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10108                                      lun->be_lun->lun_type;
10109         else
10110                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10111         devid_ptr->page_code = SVPD_DEVICE_ID;
10112         scsi_ulto2b(data_len - 4, devid_ptr->length);
10113
10114         if (port->port_type == CTL_PORT_FC)
10115                 proto = SCSI_PROTO_FC << 4;
10116         else if (port->port_type == CTL_PORT_ISCSI)
10117                 proto = SCSI_PROTO_ISCSI << 4;
10118         else
10119                 proto = SCSI_PROTO_SPI << 4;
10120         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
10121
10122         /*
10123          * We're using a LUN association here.  i.e., this device ID is a
10124          * per-LUN identifier.
10125          */
10126         if (lun && lun->lun_devid) {
10127                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
10128                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10129                     lun->lun_devid->len);
10130         }
10131
10132         /*
10133          * This is for the WWPN which is a port association.
10134          */
10135         if (port->port_devid) {
10136                 memcpy(desc, port->port_devid->data, port->port_devid->len);
10137                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10138                     port->port_devid->len);
10139         }
10140
10141         /*
10142          * This is for the Relative Target Port(type 4h) identifier
10143          */
10144         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10145         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10146             SVPD_ID_TYPE_RELTARG;
10147         desc->length = 4;
10148         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
10149         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10150             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
10151
10152         /*
10153          * This is for the Target Port Group(type 5h) identifier
10154          */
10155         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10156         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10157             SVPD_ID_TYPE_TPORTGRP;
10158         desc->length = 4;
10159         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
10160             &desc->identifier[2]);
10161         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10162             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
10163
10164         /*
10165          * This is for the Target identifier
10166          */
10167         if (port->target_devid) {
10168                 memcpy(desc, port->target_devid->data, port->target_devid->len);
10169         }
10170
10171         ctl_set_success(ctsio);
10172         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10173         ctsio->be_move_done = ctl_config_move_done;
10174         ctl_datamove((union ctl_io *)ctsio);
10175         return (CTL_RETVAL_COMPLETE);
10176 }
10177
10178 static int
10179 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
10180 {
10181         struct ctl_softc *softc = control_softc;
10182         struct scsi_vpd_scsi_ports *sp;
10183         struct scsi_vpd_port_designation *pd;
10184         struct scsi_vpd_port_designation_cont *pdc;
10185         struct ctl_lun *lun;
10186         struct ctl_port *port;
10187         int data_len, num_target_ports, iid_len, id_len, g, pg, p;
10188         int num_target_port_groups;
10189
10190         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10191
10192         if (softc->is_single)
10193                 num_target_port_groups = 1;
10194         else
10195                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10196         num_target_ports = 0;
10197         iid_len = 0;
10198         id_len = 0;
10199         mtx_lock(&softc->ctl_lock);
10200         STAILQ_FOREACH(port, &softc->port_list, links) {
10201                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10202                         continue;
10203                 if (lun != NULL &&
10204                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
10205                         continue;
10206                 num_target_ports++;
10207                 if (port->init_devid)
10208                         iid_len += port->init_devid->len;
10209                 if (port->port_devid)
10210                         id_len += port->port_devid->len;
10211         }
10212         mtx_unlock(&softc->ctl_lock);
10213
10214         data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10215             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10216              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10217         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10218         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10219         ctsio->kern_sg_entries = 0;
10220
10221         if (data_len < alloc_len) {
10222                 ctsio->residual = alloc_len - data_len;
10223                 ctsio->kern_data_len = data_len;
10224                 ctsio->kern_total_len = data_len;
10225         } else {
10226                 ctsio->residual = 0;
10227                 ctsio->kern_data_len = alloc_len;
10228                 ctsio->kern_total_len = alloc_len;
10229         }
10230         ctsio->kern_data_resid = 0;
10231         ctsio->kern_rel_offset = 0;
10232         ctsio->kern_sg_entries = 0;
10233
10234         /*
10235          * The control device is always connected.  The disk device, on the
10236          * other hand, may not be online all the time.  Need to change this
10237          * to figure out whether the disk device is actually online or not.
10238          */
10239         if (lun != NULL)
10240                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10241                                   lun->be_lun->lun_type;
10242         else
10243                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10244
10245         sp->page_code = SVPD_SCSI_PORTS;
10246         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10247             sp->page_length);
10248         pd = &sp->design[0];
10249
10250         mtx_lock(&softc->ctl_lock);
10251         pg = softc->port_offset / CTL_MAX_PORTS;
10252         for (g = 0; g < num_target_port_groups; g++) {
10253                 STAILQ_FOREACH(port, &softc->port_list, links) {
10254                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10255                                 continue;
10256                         if (lun != NULL &&
10257                             ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
10258                                 continue;
10259                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10260                         scsi_ulto2b(p, pd->relative_port_id);
10261                         if (port->init_devid && g == pg) {
10262                                 iid_len = port->init_devid->len;
10263                                 memcpy(pd->initiator_transportid,
10264                                     port->init_devid->data, port->init_devid->len);
10265                         } else
10266                                 iid_len = 0;
10267                         scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10268                         pdc = (struct scsi_vpd_port_designation_cont *)
10269                             (&pd->initiator_transportid[iid_len]);
10270                         if (port->port_devid && g == pg) {
10271                                 id_len = port->port_devid->len;
10272                                 memcpy(pdc->target_port_descriptors,
10273                                     port->port_devid->data, port->port_devid->len);
10274                         } else
10275                                 id_len = 0;
10276                         scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10277                         pd = (struct scsi_vpd_port_designation *)
10278                             ((uint8_t *)pdc->target_port_descriptors + id_len);
10279                 }
10280         }
10281         mtx_unlock(&softc->ctl_lock);
10282
10283         ctl_set_success(ctsio);
10284         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10285         ctsio->be_move_done = ctl_config_move_done;
10286         ctl_datamove((union ctl_io *)ctsio);
10287         return (CTL_RETVAL_COMPLETE);
10288 }
10289
10290 static int
10291 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10292 {
10293         struct scsi_vpd_block_limits *bl_ptr;
10294         struct ctl_lun *lun;
10295         int bs;
10296
10297         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10298
10299         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10300         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10301         ctsio->kern_sg_entries = 0;
10302
10303         if (sizeof(*bl_ptr) < alloc_len) {
10304                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
10305                 ctsio->kern_data_len = sizeof(*bl_ptr);
10306                 ctsio->kern_total_len = sizeof(*bl_ptr);
10307         } else {
10308                 ctsio->residual = 0;
10309                 ctsio->kern_data_len = alloc_len;
10310                 ctsio->kern_total_len = alloc_len;
10311         }
10312         ctsio->kern_data_resid = 0;
10313         ctsio->kern_rel_offset = 0;
10314         ctsio->kern_sg_entries = 0;
10315
10316         /*
10317          * The control device is always connected.  The disk device, on the
10318          * other hand, may not be online all the time.  Need to change this
10319          * to figure out whether the disk device is actually online or not.
10320          */
10321         if (lun != NULL)
10322                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10323                                   lun->be_lun->lun_type;
10324         else
10325                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10326
10327         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10328         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10329         bl_ptr->max_cmp_write_len = 0xff;
10330         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10331         if (lun != NULL) {
10332                 bs = lun->be_lun->blocksize;
10333                 scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
10334                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10335                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10336                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10337                         if (lun->be_lun->ublockexp != 0) {
10338                                 scsi_ulto4b((1 << lun->be_lun->ublockexp),
10339                                     bl_ptr->opt_unmap_grain);
10340                                 scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
10341                                     bl_ptr->unmap_grain_align);
10342                         }
10343                 }
10344                 scsi_ulto4b(lun->be_lun->atomicblock,
10345                     bl_ptr->max_atomic_transfer_length);
10346                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
10347                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10348         }
10349         scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10350
10351         ctl_set_success(ctsio);
10352         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10353         ctsio->be_move_done = ctl_config_move_done;
10354         ctl_datamove((union ctl_io *)ctsio);
10355         return (CTL_RETVAL_COMPLETE);
10356 }
10357
10358 static int
10359 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10360 {
10361         struct scsi_vpd_block_device_characteristics *bdc_ptr;
10362         struct ctl_lun *lun;
10363         const char *value;
10364         u_int i;
10365
10366         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10367
10368         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10369         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10370         ctsio->kern_sg_entries = 0;
10371
10372         if (sizeof(*bdc_ptr) < alloc_len) {
10373                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10374                 ctsio->kern_data_len = sizeof(*bdc_ptr);
10375                 ctsio->kern_total_len = sizeof(*bdc_ptr);
10376         } else {
10377                 ctsio->residual = 0;
10378                 ctsio->kern_data_len = alloc_len;
10379                 ctsio->kern_total_len = alloc_len;
10380         }
10381         ctsio->kern_data_resid = 0;
10382         ctsio->kern_rel_offset = 0;
10383         ctsio->kern_sg_entries = 0;
10384
10385         /*
10386          * The control device is always connected.  The disk device, on the
10387          * other hand, may not be online all the time.  Need to change this
10388          * to figure out whether the disk device is actually online or not.
10389          */
10390         if (lun != NULL)
10391                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10392                                   lun->be_lun->lun_type;
10393         else
10394                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10395         bdc_ptr->page_code = SVPD_BDC;
10396         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10397         if (lun != NULL &&
10398             (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10399                 i = strtol(value, NULL, 0);
10400         else
10401                 i = CTL_DEFAULT_ROTATION_RATE;
10402         scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10403         if (lun != NULL &&
10404             (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10405                 i = strtol(value, NULL, 0);
10406         else
10407                 i = 0;
10408         bdc_ptr->wab_wac_ff = (i & 0x0f);
10409         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10410
10411         ctl_set_success(ctsio);
10412         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10413         ctsio->be_move_done = ctl_config_move_done;
10414         ctl_datamove((union ctl_io *)ctsio);
10415         return (CTL_RETVAL_COMPLETE);
10416 }
10417
10418 static int
10419 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10420 {
10421         struct scsi_vpd_logical_block_prov *lbp_ptr;
10422         struct ctl_lun *lun;
10423
10424         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10425
10426         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10427         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10428         ctsio->kern_sg_entries = 0;
10429
10430         if (sizeof(*lbp_ptr) < alloc_len) {
10431                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10432                 ctsio->kern_data_len = sizeof(*lbp_ptr);
10433                 ctsio->kern_total_len = sizeof(*lbp_ptr);
10434         } else {
10435                 ctsio->residual = 0;
10436                 ctsio->kern_data_len = alloc_len;
10437                 ctsio->kern_total_len = alloc_len;
10438         }
10439         ctsio->kern_data_resid = 0;
10440         ctsio->kern_rel_offset = 0;
10441         ctsio->kern_sg_entries = 0;
10442
10443         /*
10444          * The control device is always connected.  The disk device, on the
10445          * other hand, may not be online all the time.  Need to change this
10446          * to figure out whether the disk device is actually online or not.
10447          */
10448         if (lun != NULL)
10449                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10450                                   lun->be_lun->lun_type;
10451         else
10452                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10453
10454         lbp_ptr->page_code = SVPD_LBP;
10455         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10456         lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10457         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10458                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10459                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10460                 lbp_ptr->prov_type = SVPD_LBP_THIN;
10461         }
10462
10463         ctl_set_success(ctsio);
10464         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10465         ctsio->be_move_done = ctl_config_move_done;
10466         ctl_datamove((union ctl_io *)ctsio);
10467         return (CTL_RETVAL_COMPLETE);
10468 }
10469
10470 /*
10471  * INQUIRY with the EVPD bit set.
10472  */
10473 static int
10474 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10475 {
10476         struct ctl_lun *lun;
10477         struct scsi_inquiry *cdb;
10478         int alloc_len, retval;
10479
10480         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10481         cdb = (struct scsi_inquiry *)ctsio->cdb;
10482         alloc_len = scsi_2btoul(cdb->length);
10483
10484         switch (cdb->page_code) {
10485         case SVPD_SUPPORTED_PAGES:
10486                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10487                 break;
10488         case SVPD_UNIT_SERIAL_NUMBER:
10489                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10490                 break;
10491         case SVPD_DEVICE_ID:
10492                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10493                 break;
10494         case SVPD_EXTENDED_INQUIRY_DATA:
10495                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10496                 break;
10497         case SVPD_MODE_PAGE_POLICY:
10498                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10499                 break;
10500         case SVPD_SCSI_PORTS:
10501                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10502                 break;
10503         case SVPD_SCSI_TPC:
10504                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10505                 break;
10506         case SVPD_BLOCK_LIMITS:
10507                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10508                         goto err;
10509                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10510                 break;
10511         case SVPD_BDC:
10512                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10513                         goto err;
10514                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10515                 break;
10516         case SVPD_LBP:
10517                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10518                         goto err;
10519                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10520                 break;
10521         default:
10522 err:
10523                 ctl_set_invalid_field(ctsio,
10524                                       /*sks_valid*/ 1,
10525                                       /*command*/ 1,
10526                                       /*field*/ 2,
10527                                       /*bit_valid*/ 0,
10528                                       /*bit*/ 0);
10529                 ctl_done((union ctl_io *)ctsio);
10530                 retval = CTL_RETVAL_COMPLETE;
10531                 break;
10532         }
10533
10534         return (retval);
10535 }
10536
10537 /*
10538  * Standard INQUIRY data.
10539  */
10540 static int
10541 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10542 {
10543         struct scsi_inquiry_data *inq_ptr;
10544         struct scsi_inquiry *cdb;
10545         struct ctl_softc *softc;
10546         struct ctl_lun *lun;
10547         char *val;
10548         uint32_t alloc_len, data_len;
10549         ctl_port_type port_type;
10550
10551         softc = control_softc;
10552
10553         /*
10554          * Figure out whether we're talking to a Fibre Channel port or not.
10555          * We treat the ioctl front end, and any SCSI adapters, as packetized
10556          * SCSI front ends.
10557          */
10558         port_type = softc->ctl_ports[
10559             ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10560         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10561                 port_type = CTL_PORT_SCSI;
10562
10563         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10564         cdb = (struct scsi_inquiry *)ctsio->cdb;
10565         alloc_len = scsi_2btoul(cdb->length);
10566
10567         /*
10568          * We malloc the full inquiry data size here and fill it
10569          * in.  If the user only asks for less, we'll give him
10570          * that much.
10571          */
10572         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10573         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10574         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10575         ctsio->kern_sg_entries = 0;
10576         ctsio->kern_data_resid = 0;
10577         ctsio->kern_rel_offset = 0;
10578
10579         if (data_len < alloc_len) {
10580                 ctsio->residual = alloc_len - data_len;
10581                 ctsio->kern_data_len = data_len;
10582                 ctsio->kern_total_len = data_len;
10583         } else {
10584                 ctsio->residual = 0;
10585                 ctsio->kern_data_len = alloc_len;
10586                 ctsio->kern_total_len = alloc_len;
10587         }
10588
10589         /*
10590          * If we have a LUN configured, report it as connected.  Otherwise,
10591          * report that it is offline or no device is supported, depending 
10592          * on the value of inquiry_pq_no_lun.
10593          *
10594          * According to the spec (SPC-4 r34), the peripheral qualifier
10595          * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10596          *
10597          * "A peripheral device having the specified peripheral device type 
10598          * is not connected to this logical unit. However, the device
10599          * server is capable of supporting the specified peripheral device
10600          * type on this logical unit."
10601          *
10602          * According to the same spec, the peripheral qualifier
10603          * SID_QUAL_BAD_LU (011b) is used in this scenario:
10604          *
10605          * "The device server is not capable of supporting a peripheral
10606          * device on this logical unit. For this peripheral qualifier the
10607          * peripheral device type shall be set to 1Fh. All other peripheral
10608          * device type values are reserved for this peripheral qualifier."
10609          *
10610          * Given the text, it would seem that we probably want to report that
10611          * the LUN is offline here.  There is no LUN connected, but we can
10612          * support a LUN at the given LUN number.
10613          *
10614          * In the real world, though, it sounds like things are a little
10615          * different:
10616          *
10617          * - Linux, when presented with a LUN with the offline peripheral
10618          *   qualifier, will create an sg driver instance for it.  So when
10619          *   you attach it to CTL, you wind up with a ton of sg driver
10620          *   instances.  (One for every LUN that Linux bothered to probe.)
10621          *   Linux does this despite the fact that it issues a REPORT LUNs
10622          *   to LUN 0 to get the inventory of supported LUNs.
10623          *
10624          * - There is other anecdotal evidence (from Emulex folks) about
10625          *   arrays that use the offline peripheral qualifier for LUNs that
10626          *   are on the "passive" path in an active/passive array.
10627          *
10628          * So the solution is provide a hopefully reasonable default
10629          * (return bad/no LUN) and allow the user to change the behavior
10630          * with a tunable/sysctl variable.
10631          */
10632         if (lun != NULL)
10633                 inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10634                                   lun->be_lun->lun_type;
10635         else if (softc->inquiry_pq_no_lun == 0)
10636                 inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10637         else
10638                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10639
10640         /* RMB in byte 2 is 0 */
10641         inq_ptr->version = SCSI_REV_SPC4;
10642
10643         /*
10644          * According to SAM-3, even if a device only supports a single
10645          * level of LUN addressing, it should still set the HISUP bit:
10646          *
10647          * 4.9.1 Logical unit numbers overview
10648          *
10649          * All logical unit number formats described in this standard are
10650          * hierarchical in structure even when only a single level in that
10651          * hierarchy is used. The HISUP bit shall be set to one in the
10652          * standard INQUIRY data (see SPC-2) when any logical unit number
10653          * format described in this standard is used.  Non-hierarchical
10654          * formats are outside the scope of this standard.
10655          *
10656          * Therefore we set the HiSup bit here.
10657          *
10658          * The reponse format is 2, per SPC-3.
10659          */
10660         inq_ptr->response_format = SID_HiSup | 2;
10661
10662         inq_ptr->additional_length = data_len -
10663             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10664         CTL_DEBUG_PRINT(("additional_length = %d\n",
10665                          inq_ptr->additional_length));
10666
10667         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10668         /* 16 bit addressing */
10669         if (port_type == CTL_PORT_SCSI)
10670                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10671         /* XXX set the SID_MultiP bit here if we're actually going to
10672            respond on multiple ports */
10673         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10674
10675         /* 16 bit data bus, synchronous transfers */
10676         if (port_type == CTL_PORT_SCSI)
10677                 inq_ptr->flags = SID_WBus16 | SID_Sync;
10678         /*
10679          * XXX KDM do we want to support tagged queueing on the control
10680          * device at all?
10681          */
10682         if ((lun == NULL)
10683          || (lun->be_lun->lun_type != T_PROCESSOR))
10684                 inq_ptr->flags |= SID_CmdQue;
10685         /*
10686          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10687          * We have 8 bytes for the vendor name, and 16 bytes for the device
10688          * name and 4 bytes for the revision.
10689          */
10690         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10691             "vendor")) == NULL) {
10692                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10693         } else {
10694                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10695                 strncpy(inq_ptr->vendor, val,
10696                     min(sizeof(inq_ptr->vendor), strlen(val)));
10697         }
10698         if (lun == NULL) {
10699                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10700                     sizeof(inq_ptr->product));
10701         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10702                 switch (lun->be_lun->lun_type) {
10703                 case T_DIRECT:
10704                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10705                             sizeof(inq_ptr->product));
10706                         break;
10707                 case T_PROCESSOR:
10708                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10709                             sizeof(inq_ptr->product));
10710                         break;
10711                 default:
10712                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10713                             sizeof(inq_ptr->product));
10714                         break;
10715                 }
10716         } else {
10717                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10718                 strncpy(inq_ptr->product, val,
10719                     min(sizeof(inq_ptr->product), strlen(val)));
10720         }
10721
10722         /*
10723          * XXX make this a macro somewhere so it automatically gets
10724          * incremented when we make changes.
10725          */
10726         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10727             "revision")) == NULL) {
10728                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10729         } else {
10730                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10731                 strncpy(inq_ptr->revision, val,
10732                     min(sizeof(inq_ptr->revision), strlen(val)));
10733         }
10734
10735         /*
10736          * For parallel SCSI, we support double transition and single
10737          * transition clocking.  We also support QAS (Quick Arbitration
10738          * and Selection) and Information Unit transfers on both the
10739          * control and array devices.
10740          */
10741         if (port_type == CTL_PORT_SCSI)
10742                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10743                                     SID_SPI_IUS;
10744
10745         /* SAM-5 (no version claimed) */
10746         scsi_ulto2b(0x00A0, inq_ptr->version1);
10747         /* SPC-4 (no version claimed) */
10748         scsi_ulto2b(0x0460, inq_ptr->version2);
10749         if (port_type == CTL_PORT_FC) {
10750                 /* FCP-2 ANSI INCITS.350:2003 */
10751                 scsi_ulto2b(0x0917, inq_ptr->version3);
10752         } else if (port_type == CTL_PORT_SCSI) {
10753                 /* SPI-4 ANSI INCITS.362:200x */
10754                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10755         } else if (port_type == CTL_PORT_ISCSI) {
10756                 /* iSCSI (no version claimed) */
10757                 scsi_ulto2b(0x0960, inq_ptr->version3);
10758         } else if (port_type == CTL_PORT_SAS) {
10759                 /* SAS (no version claimed) */
10760                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10761         }
10762
10763         if (lun == NULL) {
10764                 /* SBC-4 (no version claimed) */
10765                 scsi_ulto2b(0x0600, inq_ptr->version4);
10766         } else {
10767                 switch (lun->be_lun->lun_type) {
10768                 case T_DIRECT:
10769                         /* SBC-4 (no version claimed) */
10770                         scsi_ulto2b(0x0600, inq_ptr->version4);
10771                         break;
10772                 case T_PROCESSOR:
10773                 default:
10774                         break;
10775                 }
10776         }
10777
10778         ctl_set_success(ctsio);
10779         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10780         ctsio->be_move_done = ctl_config_move_done;
10781         ctl_datamove((union ctl_io *)ctsio);
10782         return (CTL_RETVAL_COMPLETE);
10783 }
10784
10785 int
10786 ctl_inquiry(struct ctl_scsiio *ctsio)
10787 {
10788         struct scsi_inquiry *cdb;
10789         int retval;
10790
10791         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10792
10793         cdb = (struct scsi_inquiry *)ctsio->cdb;
10794         if (cdb->byte2 & SI_EVPD)
10795                 retval = ctl_inquiry_evpd(ctsio);
10796         else if (cdb->page_code == 0)
10797                 retval = ctl_inquiry_std(ctsio);
10798         else {
10799                 ctl_set_invalid_field(ctsio,
10800                                       /*sks_valid*/ 1,
10801                                       /*command*/ 1,
10802                                       /*field*/ 2,
10803                                       /*bit_valid*/ 0,
10804                                       /*bit*/ 0);
10805                 ctl_done((union ctl_io *)ctsio);
10806                 return (CTL_RETVAL_COMPLETE);
10807         }
10808
10809         return (retval);
10810 }
10811
10812 /*
10813  * For known CDB types, parse the LBA and length.
10814  */
10815 static int
10816 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10817 {
10818         if (io->io_hdr.io_type != CTL_IO_SCSI)
10819                 return (1);
10820
10821         switch (io->scsiio.cdb[0]) {
10822         case COMPARE_AND_WRITE: {
10823                 struct scsi_compare_and_write *cdb;
10824
10825                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10826
10827                 *lba = scsi_8btou64(cdb->addr);
10828                 *len = cdb->length;
10829                 break;
10830         }
10831         case READ_6:
10832         case WRITE_6: {
10833                 struct scsi_rw_6 *cdb;
10834
10835                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10836
10837                 *lba = scsi_3btoul(cdb->addr);
10838                 /* only 5 bits are valid in the most significant address byte */
10839                 *lba &= 0x1fffff;
10840                 *len = cdb->length;
10841                 break;
10842         }
10843         case READ_10:
10844         case WRITE_10: {
10845                 struct scsi_rw_10 *cdb;
10846
10847                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10848
10849                 *lba = scsi_4btoul(cdb->addr);
10850                 *len = scsi_2btoul(cdb->length);
10851                 break;
10852         }
10853         case WRITE_VERIFY_10: {
10854                 struct scsi_write_verify_10 *cdb;
10855
10856                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10857
10858                 *lba = scsi_4btoul(cdb->addr);
10859                 *len = scsi_2btoul(cdb->length);
10860                 break;
10861         }
10862         case READ_12:
10863         case WRITE_12: {
10864                 struct scsi_rw_12 *cdb;
10865
10866                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10867
10868                 *lba = scsi_4btoul(cdb->addr);
10869                 *len = scsi_4btoul(cdb->length);
10870                 break;
10871         }
10872         case WRITE_VERIFY_12: {
10873                 struct scsi_write_verify_12 *cdb;
10874
10875                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10876
10877                 *lba = scsi_4btoul(cdb->addr);
10878                 *len = scsi_4btoul(cdb->length);
10879                 break;
10880         }
10881         case READ_16:
10882         case WRITE_16:
10883         case WRITE_ATOMIC_16: {
10884                 struct scsi_rw_16 *cdb;
10885
10886                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10887
10888                 *lba = scsi_8btou64(cdb->addr);
10889                 *len = scsi_4btoul(cdb->length);
10890                 break;
10891         }
10892         case WRITE_VERIFY_16: {
10893                 struct scsi_write_verify_16 *cdb;
10894
10895                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10896
10897                 *lba = scsi_8btou64(cdb->addr);
10898                 *len = scsi_4btoul(cdb->length);
10899                 break;
10900         }
10901         case WRITE_SAME_10: {
10902                 struct scsi_write_same_10 *cdb;
10903
10904                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10905
10906                 *lba = scsi_4btoul(cdb->addr);
10907                 *len = scsi_2btoul(cdb->length);
10908                 break;
10909         }
10910         case WRITE_SAME_16: {
10911                 struct scsi_write_same_16 *cdb;
10912
10913                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10914
10915                 *lba = scsi_8btou64(cdb->addr);
10916                 *len = scsi_4btoul(cdb->length);
10917                 break;
10918         }
10919         case VERIFY_10: {
10920                 struct scsi_verify_10 *cdb;
10921
10922                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10923
10924                 *lba = scsi_4btoul(cdb->addr);
10925                 *len = scsi_2btoul(cdb->length);
10926                 break;
10927         }
10928         case VERIFY_12: {
10929                 struct scsi_verify_12 *cdb;
10930
10931                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10932
10933                 *lba = scsi_4btoul(cdb->addr);
10934                 *len = scsi_4btoul(cdb->length);
10935                 break;
10936         }
10937         case VERIFY_16: {
10938                 struct scsi_verify_16 *cdb;
10939
10940                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10941
10942                 *lba = scsi_8btou64(cdb->addr);
10943                 *len = scsi_4btoul(cdb->length);
10944                 break;
10945         }
10946         case UNMAP: {
10947                 *lba = 0;
10948                 *len = UINT64_MAX;
10949                 break;
10950         }
10951         case SERVICE_ACTION_IN: {       /* GET LBA STATUS */
10952                 struct scsi_get_lba_status *cdb;
10953
10954                 cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10955                 *lba = scsi_8btou64(cdb->addr);
10956                 *len = UINT32_MAX;
10957                 break;
10958         }
10959         default:
10960                 return (1);
10961                 break; /* NOTREACHED */
10962         }
10963
10964         return (0);
10965 }
10966
10967 static ctl_action
10968 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10969     bool seq)
10970 {
10971         uint64_t endlba1, endlba2;
10972
10973         endlba1 = lba1 + len1 - (seq ? 0 : 1);
10974         endlba2 = lba2 + len2 - 1;
10975
10976         if ((endlba1 < lba2) || (endlba2 < lba1))
10977                 return (CTL_ACTION_PASS);
10978         else
10979                 return (CTL_ACTION_BLOCK);
10980 }
10981
10982 static int
10983 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10984 {
10985         struct ctl_ptr_len_flags *ptrlen;
10986         struct scsi_unmap_desc *buf, *end, *range;
10987         uint64_t lba;
10988         uint32_t len;
10989
10990         /* If not UNMAP -- go other way. */
10991         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10992             io->scsiio.cdb[0] != UNMAP)
10993                 return (CTL_ACTION_ERROR);
10994
10995         /* If UNMAP without data -- block and wait for data. */
10996         ptrlen = (struct ctl_ptr_len_flags *)
10997             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10998         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10999             ptrlen->ptr == NULL)
11000                 return (CTL_ACTION_BLOCK);
11001
11002         /* UNMAP with data -- check for collision. */
11003         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
11004         end = buf + ptrlen->len / sizeof(*buf);
11005         for (range = buf; range < end; range++) {
11006                 lba = scsi_8btou64(range->lba);
11007                 len = scsi_4btoul(range->length);
11008                 if ((lba < lba2 + len2) && (lba + len > lba2))
11009                         return (CTL_ACTION_BLOCK);
11010         }
11011         return (CTL_ACTION_PASS);
11012 }
11013
11014 static ctl_action
11015 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
11016 {
11017         uint64_t lba1, lba2;
11018         uint64_t len1, len2;
11019         int retval;
11020
11021         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
11022                 return (CTL_ACTION_ERROR);
11023
11024         retval = ctl_extent_check_unmap(io1, lba2, len2);
11025         if (retval != CTL_ACTION_ERROR)
11026                 return (retval);
11027
11028         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
11029                 return (CTL_ACTION_ERROR);
11030
11031         return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
11032 }
11033
11034 static ctl_action
11035 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
11036 {
11037         uint64_t lba1, lba2;
11038         uint64_t len1, len2;
11039
11040         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
11041                 return (CTL_ACTION_ERROR);
11042         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
11043                 return (CTL_ACTION_ERROR);
11044
11045         if (lba1 + len1 == lba2)
11046                 return (CTL_ACTION_BLOCK);
11047         return (CTL_ACTION_PASS);
11048 }
11049
11050 static ctl_action
11051 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
11052     union ctl_io *ooa_io)
11053 {
11054         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
11055         ctl_serialize_action *serialize_row;
11056
11057         /*
11058          * The initiator attempted multiple untagged commands at the same
11059          * time.  Can't do that.
11060          */
11061         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11062          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11063          && ((pending_io->io_hdr.nexus.targ_port ==
11064               ooa_io->io_hdr.nexus.targ_port)
11065           && (pending_io->io_hdr.nexus.initid.id ==
11066               ooa_io->io_hdr.nexus.initid.id))
11067          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11068               CTL_FLAG_STATUS_SENT)) == 0))
11069                 return (CTL_ACTION_OVERLAP);
11070
11071         /*
11072          * The initiator attempted to send multiple tagged commands with
11073          * the same ID.  (It's fine if different initiators have the same
11074          * tag ID.)
11075          *
11076          * Even if all of those conditions are true, we don't kill the I/O
11077          * if the command ahead of us has been aborted.  We won't end up
11078          * sending it to the FETD, and it's perfectly legal to resend a
11079          * command with the same tag number as long as the previous
11080          * instance of this tag number has been aborted somehow.
11081          */
11082         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11083          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11084          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11085          && ((pending_io->io_hdr.nexus.targ_port ==
11086               ooa_io->io_hdr.nexus.targ_port)
11087           && (pending_io->io_hdr.nexus.initid.id ==
11088               ooa_io->io_hdr.nexus.initid.id))
11089          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11090               CTL_FLAG_STATUS_SENT)) == 0))
11091                 return (CTL_ACTION_OVERLAP_TAG);
11092
11093         /*
11094          * If we get a head of queue tag, SAM-3 says that we should
11095          * immediately execute it.
11096          *
11097          * What happens if this command would normally block for some other
11098          * reason?  e.g. a request sense with a head of queue tag
11099          * immediately after a write.  Normally that would block, but this
11100          * will result in its getting executed immediately...
11101          *
11102          * We currently return "pass" instead of "skip", so we'll end up
11103          * going through the rest of the queue to check for overlapped tags.
11104          *
11105          * XXX KDM check for other types of blockage first??
11106          */
11107         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11108                 return (CTL_ACTION_PASS);
11109
11110         /*
11111          * Ordered tags have to block until all items ahead of them
11112          * have completed.  If we get called with an ordered tag, we always
11113          * block, if something else is ahead of us in the queue.
11114          */
11115         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11116                 return (CTL_ACTION_BLOCK);
11117
11118         /*
11119          * Simple tags get blocked until all head of queue and ordered tags
11120          * ahead of them have completed.  I'm lumping untagged commands in
11121          * with simple tags here.  XXX KDM is that the right thing to do?
11122          */
11123         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11124           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11125          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11126           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11127                 return (CTL_ACTION_BLOCK);
11128
11129         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11130         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11131
11132         serialize_row = ctl_serialize_table[ooa_entry->seridx];
11133
11134         switch (serialize_row[pending_entry->seridx]) {
11135         case CTL_SER_BLOCK:
11136                 return (CTL_ACTION_BLOCK);
11137         case CTL_SER_EXTENT:
11138                 return (ctl_extent_check(ooa_io, pending_io,
11139                     (lun->serseq == CTL_LUN_SERSEQ_ON)));
11140         case CTL_SER_EXTENTOPT:
11141                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11142                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11143                         return (ctl_extent_check(ooa_io, pending_io,
11144                             (lun->serseq == CTL_LUN_SERSEQ_ON)));
11145                 return (CTL_ACTION_PASS);
11146         case CTL_SER_EXTENTSEQ:
11147                 if (lun->serseq != CTL_LUN_SERSEQ_OFF)
11148                         return (ctl_extent_check_seq(ooa_io, pending_io));
11149                 return (CTL_ACTION_PASS);
11150         case CTL_SER_PASS:
11151                 return (CTL_ACTION_PASS);
11152         case CTL_SER_BLOCKOPT:
11153                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11154                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11155                         return (CTL_ACTION_BLOCK);
11156                 return (CTL_ACTION_PASS);
11157         case CTL_SER_SKIP:
11158                 return (CTL_ACTION_SKIP);
11159         default:
11160                 panic("invalid serialization value %d",
11161                       serialize_row[pending_entry->seridx]);
11162         }
11163
11164         return (CTL_ACTION_ERROR);
11165 }
11166
11167 /*
11168  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11169  * Assumptions:
11170  * - pending_io is generally either incoming, or on the blocked queue
11171  * - starting I/O is the I/O we want to start the check with.
11172  */
11173 static ctl_action
11174 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11175               union ctl_io *starting_io)
11176 {
11177         union ctl_io *ooa_io;
11178         ctl_action action;
11179
11180         mtx_assert(&lun->lun_lock, MA_OWNED);
11181
11182         /*
11183          * Run back along the OOA queue, starting with the current
11184          * blocked I/O and going through every I/O before it on the
11185          * queue.  If starting_io is NULL, we'll just end up returning
11186          * CTL_ACTION_PASS.
11187          */
11188         for (ooa_io = starting_io; ooa_io != NULL;
11189              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11190              ooa_links)){
11191
11192                 /*
11193                  * This routine just checks to see whether
11194                  * cur_blocked is blocked by ooa_io, which is ahead
11195                  * of it in the queue.  It doesn't queue/dequeue
11196                  * cur_blocked.
11197                  */
11198                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11199                 switch (action) {
11200                 case CTL_ACTION_BLOCK:
11201                 case CTL_ACTION_OVERLAP:
11202                 case CTL_ACTION_OVERLAP_TAG:
11203                 case CTL_ACTION_SKIP:
11204                 case CTL_ACTION_ERROR:
11205                         return (action);
11206                         break; /* NOTREACHED */
11207                 case CTL_ACTION_PASS:
11208                         break;
11209                 default:
11210                         panic("invalid action %d", action);
11211                         break;  /* NOTREACHED */
11212                 }
11213         }
11214
11215         return (CTL_ACTION_PASS);
11216 }
11217
11218 /*
11219  * Assumptions:
11220  * - An I/O has just completed, and has been removed from the per-LUN OOA
11221  *   queue, so some items on the blocked queue may now be unblocked.
11222  */
11223 static int
11224 ctl_check_blocked(struct ctl_lun *lun)
11225 {
11226         union ctl_io *cur_blocked, *next_blocked;
11227
11228         mtx_assert(&lun->lun_lock, MA_OWNED);
11229
11230         /*
11231          * Run forward from the head of the blocked queue, checking each
11232          * entry against the I/Os prior to it on the OOA queue to see if
11233          * there is still any blockage.
11234          *
11235          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11236          * with our removing a variable on it while it is traversing the
11237          * list.
11238          */
11239         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11240              cur_blocked != NULL; cur_blocked = next_blocked) {
11241                 union ctl_io *prev_ooa;
11242                 ctl_action action;
11243
11244                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11245                                                           blocked_links);
11246
11247                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11248                                                       ctl_ooaq, ooa_links);
11249
11250                 /*
11251                  * If cur_blocked happens to be the first item in the OOA
11252                  * queue now, prev_ooa will be NULL, and the action
11253                  * returned will just be CTL_ACTION_PASS.
11254                  */
11255                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11256
11257                 switch (action) {
11258                 case CTL_ACTION_BLOCK:
11259                         /* Nothing to do here, still blocked */
11260                         break;
11261                 case CTL_ACTION_OVERLAP:
11262                 case CTL_ACTION_OVERLAP_TAG:
11263                         /*
11264                          * This shouldn't happen!  In theory we've already
11265                          * checked this command for overlap...
11266                          */
11267                         break;
11268                 case CTL_ACTION_PASS:
11269                 case CTL_ACTION_SKIP: {
11270                         const struct ctl_cmd_entry *entry;
11271                         int isc_retval;
11272
11273                         /*
11274                          * The skip case shouldn't happen, this transaction
11275                          * should have never made it onto the blocked queue.
11276                          */
11277                         /*
11278                          * This I/O is no longer blocked, we can remove it
11279                          * from the blocked queue.  Since this is a TAILQ
11280                          * (doubly linked list), we can do O(1) removals
11281                          * from any place on the list.
11282                          */
11283                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11284                                      blocked_links);
11285                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11286
11287                         if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11288                                 /*
11289                                  * Need to send IO back to original side to
11290                                  * run
11291                                  */
11292                                 union ctl_ha_msg msg_info;
11293
11294                                 msg_info.hdr.original_sc =
11295                                         cur_blocked->io_hdr.original_sc;
11296                                 msg_info.hdr.serializing_sc = cur_blocked;
11297                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
11298                                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11299                                      &msg_info, sizeof(msg_info), 0)) >
11300                                      CTL_HA_STATUS_SUCCESS) {
11301                                         printf("CTL:Check Blocked error from "
11302                                                "ctl_ha_msg_send %d\n",
11303                                                isc_retval);
11304                                 }
11305                                 break;
11306                         }
11307                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11308
11309                         /*
11310                          * Check this I/O for LUN state changes that may
11311                          * have happened while this command was blocked.
11312                          * The LUN state may have been changed by a command
11313                          * ahead of us in the queue, so we need to re-check
11314                          * for any states that can be caused by SCSI
11315                          * commands.
11316                          */
11317                         if (ctl_scsiio_lun_check(lun, entry,
11318                                                  &cur_blocked->scsiio) == 0) {
11319                                 cur_blocked->io_hdr.flags |=
11320                                                       CTL_FLAG_IS_WAS_ON_RTR;
11321                                 ctl_enqueue_rtr(cur_blocked);
11322                         } else
11323                                 ctl_done(cur_blocked);
11324                         break;
11325                 }
11326                 default:
11327                         /*
11328                          * This probably shouldn't happen -- we shouldn't
11329                          * get CTL_ACTION_ERROR, or anything else.
11330                          */
11331                         break;
11332                 }
11333         }
11334
11335         return (CTL_RETVAL_COMPLETE);
11336 }
11337
11338 /*
11339  * This routine (with one exception) checks LUN flags that can be set by
11340  * commands ahead of us in the OOA queue.  These flags have to be checked
11341  * when a command initially comes in, and when we pull a command off the
11342  * blocked queue and are preparing to execute it.  The reason we have to
11343  * check these flags for commands on the blocked queue is that the LUN
11344  * state may have been changed by a command ahead of us while we're on the
11345  * blocked queue.
11346  *
11347  * Ordering is somewhat important with these checks, so please pay
11348  * careful attention to the placement of any new checks.
11349  */
11350 static int
11351 ctl_scsiio_lun_check(struct ctl_lun *lun,
11352     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11353 {
11354         struct ctl_softc *softc = lun->ctl_softc;
11355         int retval;
11356         uint32_t residx;
11357
11358         retval = 0;
11359
11360         mtx_assert(&lun->lun_lock, MA_OWNED);
11361
11362         /*
11363          * If this shelf is a secondary shelf controller, we have to reject
11364          * any media access commands.
11365          */
11366         if ((softc->flags & CTL_FLAG_ACTIVE_SHELF) == 0 &&
11367             (entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0) {
11368                 ctl_set_lun_standby(ctsio);
11369                 retval = 1;
11370                 goto bailout;
11371         }
11372
11373         if (entry->pattern & CTL_LUN_PAT_WRITE) {
11374                 if (lun->flags & CTL_LUN_READONLY) {
11375                         ctl_set_sense(ctsio, /*current_error*/ 1,
11376                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11377                             /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11378                         retval = 1;
11379                         goto bailout;
11380                 }
11381                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11382                     .eca_and_aen & SCP_SWP) != 0) {
11383                         ctl_set_sense(ctsio, /*current_error*/ 1,
11384                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11385                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11386                         retval = 1;
11387                         goto bailout;
11388                 }
11389         }
11390
11391         /*
11392          * Check for a reservation conflict.  If this command isn't allowed
11393          * even on reserved LUNs, and if this initiator isn't the one who
11394          * reserved us, reject the command with a reservation conflict.
11395          */
11396         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11397         if ((lun->flags & CTL_LUN_RESERVED)
11398          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11399                 if (lun->res_idx != residx) {
11400                         ctl_set_reservation_conflict(ctsio);
11401                         retval = 1;
11402                         goto bailout;
11403                 }
11404         }
11405
11406         if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11407             (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11408                 /* No reservation or command is allowed. */;
11409         } else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11410             (lun->res_type == SPR_TYPE_WR_EX ||
11411              lun->res_type == SPR_TYPE_WR_EX_RO ||
11412              lun->res_type == SPR_TYPE_WR_EX_AR)) {
11413                 /* The command is allowed for Write Exclusive resv. */;
11414         } else {
11415                 /*
11416                  * if we aren't registered or it's a res holder type
11417                  * reservation and this isn't the res holder then set a
11418                  * conflict.
11419                  */
11420                 if (ctl_get_prkey(lun, residx) == 0
11421                  || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11422                         ctl_set_reservation_conflict(ctsio);
11423                         retval = 1;
11424                         goto bailout;
11425                 }
11426
11427         }
11428
11429         if ((lun->flags & CTL_LUN_OFFLINE)
11430          && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11431                 ctl_set_lun_not_ready(ctsio);
11432                 retval = 1;
11433                 goto bailout;
11434         }
11435
11436         /*
11437          * If the LUN is stopped, see if this particular command is allowed
11438          * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11439          */
11440         if ((lun->flags & CTL_LUN_STOPPED)
11441          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11442                 /* "Logical unit not ready, initializing cmd. required" */
11443                 ctl_set_lun_stopped(ctsio);
11444                 retval = 1;
11445                 goto bailout;
11446         }
11447
11448         if ((lun->flags & CTL_LUN_INOPERABLE)
11449          && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11450                 /* "Medium format corrupted" */
11451                 ctl_set_medium_format_corrupted(ctsio);
11452                 retval = 1;
11453                 goto bailout;
11454         }
11455
11456 bailout:
11457         return (retval);
11458
11459 }
11460
11461 static void
11462 ctl_failover_io(union ctl_io *io, int have_lock)
11463 {
11464         ctl_set_busy(&io->scsiio);
11465         ctl_done(io);
11466 }
11467
11468 static void
11469 ctl_failover(void)
11470 {
11471         struct ctl_lun *lun;
11472         struct ctl_softc *softc;
11473         union ctl_io *next_io, *pending_io;
11474         union ctl_io *io;
11475         int lun_idx;
11476
11477         softc = control_softc;
11478
11479         mtx_lock(&softc->ctl_lock);
11480         /*
11481          * Remove any cmds from the other SC from the rtr queue.  These
11482          * will obviously only be for LUNs for which we're the primary.
11483          * We can't send status or get/send data for these commands.
11484          * Since they haven't been executed yet, we can just remove them.
11485          * We'll either abort them or delete them below, depending on
11486          * which HA mode we're in.
11487          */
11488 #ifdef notyet
11489         mtx_lock(&softc->queue_lock);
11490         for (io = (union ctl_io *)STAILQ_FIRST(&softc->rtr_queue);
11491              io != NULL; io = next_io) {
11492                 next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11493                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11494                         STAILQ_REMOVE(&softc->rtr_queue, &io->io_hdr,
11495                                       ctl_io_hdr, links);
11496         }
11497         mtx_unlock(&softc->queue_lock);
11498 #endif
11499
11500         for (lun_idx=0; lun_idx < softc->num_luns; lun_idx++) {
11501                 lun = softc->ctl_luns[lun_idx];
11502                 if (lun==NULL)
11503                         continue;
11504
11505                 /*
11506                  * Processor LUNs are primary on both sides.
11507                  * XXX will this always be true?
11508                  */
11509                 if (lun->be_lun->lun_type == T_PROCESSOR)
11510                         continue;
11511
11512                 if ((lun->flags & CTL_LUN_PRIMARY_SC)
11513                  && (softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11514                         printf("FAILOVER: primary lun %d\n", lun_idx);
11515                         /*
11516                          * Remove all commands from the other SC. First from the
11517                          * blocked queue then from the ooa queue. Once we have
11518                          * removed them. Call ctl_check_blocked to see if there
11519                          * is anything that can run.
11520                          */
11521                         for (io = (union ctl_io *)TAILQ_FIRST(
11522                              &lun->blocked_queue); io != NULL; io = next_io) {
11523
11524                                 next_io = (union ctl_io *)TAILQ_NEXT(
11525                                     &io->io_hdr, blocked_links);
11526
11527                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11528                                         TAILQ_REMOVE(&lun->blocked_queue,
11529                                                      &io->io_hdr,blocked_links);
11530                                         io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11531                                         TAILQ_REMOVE(&lun->ooa_queue,
11532                                                      &io->io_hdr, ooa_links);
11533
11534                                         ctl_free_io(io);
11535                                 }
11536                         }
11537
11538                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11539                              io != NULL; io = next_io) {
11540
11541                                 next_io = (union ctl_io *)TAILQ_NEXT(
11542                                     &io->io_hdr, ooa_links);
11543
11544                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11545
11546                                         TAILQ_REMOVE(&lun->ooa_queue,
11547                                                 &io->io_hdr,
11548                                                 ooa_links);
11549
11550                                         ctl_free_io(io);
11551                                 }
11552                         }
11553                         ctl_check_blocked(lun);
11554                 } else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11555                         && (softc->ha_mode == CTL_HA_MODE_XFER)) {
11556
11557                         printf("FAILOVER: primary lun %d\n", lun_idx);
11558                         /*
11559                          * Abort all commands from the other SC.  We can't
11560                          * send status back for them now.  These should get
11561                          * cleaned up when they are completed or come out
11562                          * for a datamove operation.
11563                          */
11564                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11565                              io != NULL; io = next_io) {
11566                                 next_io = (union ctl_io *)TAILQ_NEXT(
11567                                         &io->io_hdr, ooa_links);
11568
11569                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11570                                         io->io_hdr.flags |= CTL_FLAG_ABORT;
11571                         }
11572                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11573                         && (softc->ha_mode == CTL_HA_MODE_XFER)) {
11574
11575                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11576
11577                         lun->flags |= CTL_LUN_PRIMARY_SC;
11578
11579                         /*
11580                          * We send all I/O that was sent to this controller
11581                          * and redirected to the other side back with
11582                          * busy status, and have the initiator retry it.
11583                          * Figuring out how much data has been transferred,
11584                          * etc. and picking up where we left off would be 
11585                          * very tricky.
11586                          *
11587                          * XXX KDM need to remove I/O from the blocked
11588                          * queue as well!
11589                          */
11590                         for (pending_io = (union ctl_io *)TAILQ_FIRST(
11591                              &lun->ooa_queue); pending_io != NULL;
11592                              pending_io = next_io) {
11593
11594                                 next_io =  (union ctl_io *)TAILQ_NEXT(
11595                                         &pending_io->io_hdr, ooa_links);
11596
11597                                 pending_io->io_hdr.flags &=
11598                                         ~CTL_FLAG_SENT_2OTHER_SC;
11599
11600                                 if (pending_io->io_hdr.flags &
11601                                     CTL_FLAG_IO_ACTIVE) {
11602                                         pending_io->io_hdr.flags |=
11603                                                 CTL_FLAG_FAILOVER;
11604                                 } else {
11605                                         ctl_set_busy(&pending_io->scsiio);
11606                                         ctl_done(pending_io);
11607                                 }
11608                         }
11609
11610                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11611                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11612                         && (softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11613                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11614                         /*
11615                          * if the first io on the OOA is not on the RtR queue
11616                          * add it.
11617                          */
11618                         lun->flags |= CTL_LUN_PRIMARY_SC;
11619
11620                         pending_io = (union ctl_io *)TAILQ_FIRST(
11621                             &lun->ooa_queue);
11622                         if (pending_io==NULL) {
11623                                 printf("Nothing on OOA queue\n");
11624                                 continue;
11625                         }
11626
11627                         pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11628                         if ((pending_io->io_hdr.flags &
11629                              CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11630                                 pending_io->io_hdr.flags |=
11631                                     CTL_FLAG_IS_WAS_ON_RTR;
11632                                 ctl_enqueue_rtr(pending_io);
11633                         }
11634 #if 0
11635                         else
11636                         {
11637                                 printf("Tag 0x%04x is running\n",
11638                                       pending_io->scsiio.tag_num);
11639                         }
11640 #endif
11641
11642                         next_io = (union ctl_io *)TAILQ_NEXT(
11643                             &pending_io->io_hdr, ooa_links);
11644                         for (pending_io=next_io; pending_io != NULL;
11645                              pending_io = next_io) {
11646                                 pending_io->io_hdr.flags &=
11647                                     ~CTL_FLAG_SENT_2OTHER_SC;
11648                                 next_io = (union ctl_io *)TAILQ_NEXT(
11649                                         &pending_io->io_hdr, ooa_links);
11650                                 if (pending_io->io_hdr.flags &
11651                                     CTL_FLAG_IS_WAS_ON_RTR) {
11652 #if 0
11653                                         printf("Tag 0x%04x is running\n",
11654                                                 pending_io->scsiio.tag_num);
11655 #endif
11656                                         continue;
11657                                 }
11658
11659                                 switch (ctl_check_ooa(lun, pending_io,
11660                                     (union ctl_io *)TAILQ_PREV(
11661                                     &pending_io->io_hdr, ctl_ooaq,
11662                                     ooa_links))) {
11663
11664                                 case CTL_ACTION_BLOCK:
11665                                         TAILQ_INSERT_TAIL(&lun->blocked_queue,
11666                                                           &pending_io->io_hdr,
11667                                                           blocked_links);
11668                                         pending_io->io_hdr.flags |=
11669                                             CTL_FLAG_BLOCKED;
11670                                         break;
11671                                 case CTL_ACTION_PASS:
11672                                 case CTL_ACTION_SKIP:
11673                                         pending_io->io_hdr.flags |=
11674                                             CTL_FLAG_IS_WAS_ON_RTR;
11675                                         ctl_enqueue_rtr(pending_io);
11676                                         break;
11677                                 case CTL_ACTION_OVERLAP:
11678                                         ctl_set_overlapped_cmd(
11679                                             (struct ctl_scsiio *)pending_io);
11680                                         ctl_done(pending_io);
11681                                         break;
11682                                 case CTL_ACTION_OVERLAP_TAG:
11683                                         ctl_set_overlapped_tag(
11684                                             (struct ctl_scsiio *)pending_io,
11685                                             pending_io->scsiio.tag_num & 0xff);
11686                                         ctl_done(pending_io);
11687                                         break;
11688                                 case CTL_ACTION_ERROR:
11689                                 default:
11690                                         ctl_set_internal_failure(
11691                                                 (struct ctl_scsiio *)pending_io,
11692                                                 0,  // sks_valid
11693                                                 0); //retry count
11694                                         ctl_done(pending_io);
11695                                         break;
11696                                 }
11697                         }
11698
11699                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11700                 } else {
11701                         panic("Unhandled HA mode failover, LUN flags = %#x, "
11702                               "ha_mode = #%x", lun->flags, softc->ha_mode);
11703                 }
11704         }
11705         ctl_pause_rtr = 0;
11706         mtx_unlock(&softc->ctl_lock);
11707 }
11708
11709 static void
11710 ctl_clear_ua(struct ctl_softc *ctl_softc, uint32_t initidx,
11711              ctl_ua_type ua_type)
11712 {
11713         struct ctl_lun *lun;
11714         ctl_ua_type *pu;
11715
11716         mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
11717
11718         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
11719                 mtx_lock(&lun->lun_lock);
11720                 pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
11721                 if (pu != NULL)
11722                         pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua_type;
11723                 mtx_unlock(&lun->lun_lock);
11724         }
11725 }
11726
11727 static int
11728 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11729 {
11730         struct ctl_lun *lun;
11731         const struct ctl_cmd_entry *entry;
11732         uint32_t initidx, targ_lun;
11733         int retval;
11734
11735         retval = 0;
11736
11737         lun = NULL;
11738
11739         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11740         if ((targ_lun < CTL_MAX_LUNS)
11741          && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11742                 /*
11743                  * If the LUN is invalid, pretend that it doesn't exist.
11744                  * It will go away as soon as all pending I/O has been
11745                  * completed.
11746                  */
11747                 mtx_lock(&lun->lun_lock);
11748                 if (lun->flags & CTL_LUN_DISABLED) {
11749                         mtx_unlock(&lun->lun_lock);
11750                         lun = NULL;
11751                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11752                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11753                 } else {
11754                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11755                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11756                                 lun->be_lun;
11757                         if (lun->be_lun->lun_type == T_PROCESSOR) {
11758                                 ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11759                         }
11760
11761                         /*
11762                          * Every I/O goes into the OOA queue for a
11763                          * particular LUN, and stays there until completion.
11764                          */
11765 #ifdef CTL_TIME_IO
11766                         if (TAILQ_EMPTY(&lun->ooa_queue)) {
11767                                 lun->idle_time += getsbinuptime() -
11768                                     lun->last_busy;
11769                         }
11770 #endif
11771                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11772                             ooa_links);
11773                 }
11774         } else {
11775                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11776                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11777         }
11778
11779         /* Get command entry and return error if it is unsuppotyed. */
11780         entry = ctl_validate_command(ctsio);
11781         if (entry == NULL) {
11782                 if (lun)
11783                         mtx_unlock(&lun->lun_lock);
11784                 return (retval);
11785         }
11786
11787         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11788         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11789
11790         /*
11791          * Check to see whether we can send this command to LUNs that don't
11792          * exist.  This should pretty much only be the case for inquiry
11793          * and request sense.  Further checks, below, really require having
11794          * a LUN, so we can't really check the command anymore.  Just put
11795          * it on the rtr queue.
11796          */
11797         if (lun == NULL) {
11798                 if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11799                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11800                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11801                         return (retval);
11802                 }
11803
11804                 ctl_set_unsupported_lun(ctsio);
11805                 ctl_done((union ctl_io *)ctsio);
11806                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11807                 return (retval);
11808         } else {
11809                 /*
11810                  * Make sure we support this particular command on this LUN.
11811                  * e.g., we don't support writes to the control LUN.
11812                  */
11813                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11814                         mtx_unlock(&lun->lun_lock);
11815                         ctl_set_invalid_opcode(ctsio);
11816                         ctl_done((union ctl_io *)ctsio);
11817                         return (retval);
11818                 }
11819         }
11820
11821         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11822
11823 #ifdef CTL_WITH_CA
11824         /*
11825          * If we've got a request sense, it'll clear the contingent
11826          * allegiance condition.  Otherwise, if we have a CA condition for
11827          * this initiator, clear it, because it sent down a command other
11828          * than request sense.
11829          */
11830         if ((ctsio->cdb[0] != REQUEST_SENSE)
11831          && (ctl_is_set(lun->have_ca, initidx)))
11832                 ctl_clear_mask(lun->have_ca, initidx);
11833 #endif
11834
11835         /*
11836          * If the command has this flag set, it handles its own unit
11837          * attention reporting, we shouldn't do anything.  Otherwise we
11838          * check for any pending unit attentions, and send them back to the
11839          * initiator.  We only do this when a command initially comes in,
11840          * not when we pull it off the blocked queue.
11841          *
11842          * According to SAM-3, section 5.3.2, the order that things get
11843          * presented back to the host is basically unit attentions caused
11844          * by some sort of reset event, busy status, reservation conflicts
11845          * or task set full, and finally any other status.
11846          *
11847          * One issue here is that some of the unit attentions we report
11848          * don't fall into the "reset" category (e.g. "reported luns data
11849          * has changed").  So reporting it here, before the reservation
11850          * check, may be technically wrong.  I guess the only thing to do
11851          * would be to check for and report the reset events here, and then
11852          * check for the other unit attention types after we check for a
11853          * reservation conflict.
11854          *
11855          * XXX KDM need to fix this
11856          */
11857         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11858                 ctl_ua_type ua_type;
11859                 scsi_sense_data_type sense_format;
11860
11861                 if (lun->flags & CTL_LUN_SENSE_DESC)
11862                         sense_format = SSD_TYPE_DESC;
11863                 else
11864                         sense_format = SSD_TYPE_FIXED;
11865
11866                 ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11867                     sense_format);
11868                 if (ua_type != CTL_UA_NONE) {
11869                         mtx_unlock(&lun->lun_lock);
11870                         ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11871                         ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11872                         ctsio->sense_len = SSD_FULL_SIZE;
11873                         ctl_done((union ctl_io *)ctsio);
11874                         return (retval);
11875                 }
11876         }
11877
11878
11879         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11880                 mtx_unlock(&lun->lun_lock);
11881                 ctl_done((union ctl_io *)ctsio);
11882                 return (retval);
11883         }
11884
11885         /*
11886          * XXX CHD this is where we want to send IO to other side if
11887          * this LUN is secondary on this SC. We will need to make a copy
11888          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11889          * the copy we send as FROM_OTHER.
11890          * We also need to stuff the address of the original IO so we can
11891          * find it easily. Something similar will need be done on the other
11892          * side so when we are done we can find the copy.
11893          */
11894         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11895                 union ctl_ha_msg msg_info;
11896                 int isc_retval;
11897
11898                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11899
11900                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11901                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11902 #if 0
11903                 printf("1. ctsio %p\n", ctsio);
11904 #endif
11905                 msg_info.hdr.serializing_sc = NULL;
11906                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11907                 msg_info.scsi.tag_num = ctsio->tag_num;
11908                 msg_info.scsi.tag_type = ctsio->tag_type;
11909                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11910
11911                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11912
11913                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11914                     (void *)&msg_info, sizeof(msg_info), 0)) >
11915                     CTL_HA_STATUS_SUCCESS) {
11916                         printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11917                                isc_retval);
11918                         printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11919                 } else {
11920 #if 0
11921                         printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11922 #endif
11923                 }
11924
11925                 /*
11926                  * XXX KDM this I/O is off the incoming queue, but hasn't
11927                  * been inserted on any other queue.  We may need to come
11928                  * up with a holding queue while we wait for serialization
11929                  * so that we have an idea of what we're waiting for from
11930                  * the other side.
11931                  */
11932                 mtx_unlock(&lun->lun_lock);
11933                 return (retval);
11934         }
11935
11936         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11937                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11938                               ctl_ooaq, ooa_links))) {
11939         case CTL_ACTION_BLOCK:
11940                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11941                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11942                                   blocked_links);
11943                 mtx_unlock(&lun->lun_lock);
11944                 return (retval);
11945         case CTL_ACTION_PASS:
11946         case CTL_ACTION_SKIP:
11947                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11948                 mtx_unlock(&lun->lun_lock);
11949                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11950                 break;
11951         case CTL_ACTION_OVERLAP:
11952                 mtx_unlock(&lun->lun_lock);
11953                 ctl_set_overlapped_cmd(ctsio);
11954                 ctl_done((union ctl_io *)ctsio);
11955                 break;
11956         case CTL_ACTION_OVERLAP_TAG:
11957                 mtx_unlock(&lun->lun_lock);
11958                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11959                 ctl_done((union ctl_io *)ctsio);
11960                 break;
11961         case CTL_ACTION_ERROR:
11962         default:
11963                 mtx_unlock(&lun->lun_lock);
11964                 ctl_set_internal_failure(ctsio,
11965                                          /*sks_valid*/ 0,
11966                                          /*retry_count*/ 0);
11967                 ctl_done((union ctl_io *)ctsio);
11968                 break;
11969         }
11970         return (retval);
11971 }
11972
11973 const struct ctl_cmd_entry *
11974 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11975 {
11976         const struct ctl_cmd_entry *entry;
11977         int service_action;
11978
11979         entry = &ctl_cmd_table[ctsio->cdb[0]];
11980         if (sa)
11981                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11982         if (entry->flags & CTL_CMD_FLAG_SA5) {
11983                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11984                 entry = &((const struct ctl_cmd_entry *)
11985                     entry->execute)[service_action];
11986         }
11987         return (entry);
11988 }
11989
11990 const struct ctl_cmd_entry *
11991 ctl_validate_command(struct ctl_scsiio *ctsio)
11992 {
11993         const struct ctl_cmd_entry *entry;
11994         int i, sa;
11995         uint8_t diff;
11996
11997         entry = ctl_get_cmd_entry(ctsio, &sa);
11998         if (entry->execute == NULL) {
11999                 if (sa)
12000                         ctl_set_invalid_field(ctsio,
12001                                               /*sks_valid*/ 1,
12002                                               /*command*/ 1,
12003                                               /*field*/ 1,
12004                                               /*bit_valid*/ 1,
12005                                               /*bit*/ 4);
12006                 else
12007                         ctl_set_invalid_opcode(ctsio);
12008                 ctl_done((union ctl_io *)ctsio);
12009                 return (NULL);
12010         }
12011         KASSERT(entry->length > 0,
12012             ("Not defined length for command 0x%02x/0x%02x",
12013              ctsio->cdb[0], ctsio->cdb[1]));
12014         for (i = 1; i < entry->length; i++) {
12015                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
12016                 if (diff == 0)
12017                         continue;
12018                 ctl_set_invalid_field(ctsio,
12019                                       /*sks_valid*/ 1,
12020                                       /*command*/ 1,
12021                                       /*field*/ i,
12022                                       /*bit_valid*/ 1,
12023                                       /*bit*/ fls(diff) - 1);
12024                 ctl_done((union ctl_io *)ctsio);
12025                 return (NULL);
12026         }
12027         return (entry);
12028 }
12029
12030 static int
12031 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
12032 {
12033
12034         switch (lun_type) {
12035         case T_PROCESSOR:
12036                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
12037                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
12038                         return (0);
12039                 break;
12040         case T_DIRECT:
12041                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
12042                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
12043                         return (0);
12044                 break;
12045         default:
12046                 return (0);
12047         }
12048         return (1);
12049 }
12050
12051 static int
12052 ctl_scsiio(struct ctl_scsiio *ctsio)
12053 {
12054         int retval;
12055         const struct ctl_cmd_entry *entry;
12056
12057         retval = CTL_RETVAL_COMPLETE;
12058
12059         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
12060
12061         entry = ctl_get_cmd_entry(ctsio, NULL);
12062
12063         /*
12064          * If this I/O has been aborted, just send it straight to
12065          * ctl_done() without executing it.
12066          */
12067         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
12068                 ctl_done((union ctl_io *)ctsio);
12069                 goto bailout;
12070         }
12071
12072         /*
12073          * All the checks should have been handled by ctl_scsiio_precheck().
12074          * We should be clear now to just execute the I/O.
12075          */
12076         retval = entry->execute(ctsio);
12077
12078 bailout:
12079         return (retval);
12080 }
12081
12082 /*
12083  * Since we only implement one target right now, a bus reset simply resets
12084  * our single target.
12085  */
12086 static int
12087 ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
12088 {
12089         return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
12090 }
12091
12092 static int
12093 ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
12094                  ctl_ua_type ua_type)
12095 {
12096         struct ctl_lun *lun;
12097         int retval;
12098
12099         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12100                 union ctl_ha_msg msg_info;
12101
12102                 io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
12103                 msg_info.hdr.nexus = io->io_hdr.nexus;
12104                 if (ua_type==CTL_UA_TARG_RESET)
12105                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
12106                 else
12107                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
12108                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12109                 msg_info.hdr.original_sc = NULL;
12110                 msg_info.hdr.serializing_sc = NULL;
12111                 if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12112                     (void *)&msg_info, sizeof(msg_info), 0)) {
12113                 }
12114         }
12115         retval = 0;
12116
12117         mtx_lock(&softc->ctl_lock);
12118         STAILQ_FOREACH(lun, &softc->lun_list, links)
12119                 retval += ctl_lun_reset(lun, io, ua_type);
12120         mtx_unlock(&softc->ctl_lock);
12121
12122         return (retval);
12123 }
12124
12125 /*
12126  * The LUN should always be set.  The I/O is optional, and is used to
12127  * distinguish between I/Os sent by this initiator, and by other
12128  * initiators.  We set unit attention for initiators other than this one.
12129  * SAM-3 is vague on this point.  It does say that a unit attention should
12130  * be established for other initiators when a LUN is reset (see section
12131  * 5.7.3), but it doesn't specifically say that the unit attention should
12132  * be established for this particular initiator when a LUN is reset.  Here
12133  * is the relevant text, from SAM-3 rev 8:
12134  *
12135  * 5.7.2 When a SCSI initiator port aborts its own tasks
12136  *
12137  * When a SCSI initiator port causes its own task(s) to be aborted, no
12138  * notification that the task(s) have been aborted shall be returned to
12139  * the SCSI initiator port other than the completion response for the
12140  * command or task management function action that caused the task(s) to
12141  * be aborted and notification(s) associated with related effects of the
12142  * action (e.g., a reset unit attention condition).
12143  *
12144  * XXX KDM for now, we're setting unit attention for all initiators.
12145  */
12146 static int
12147 ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
12148 {
12149         union ctl_io *xio;
12150 #if 0
12151         uint32_t initidx;
12152 #endif
12153 #ifdef CTL_WITH_CA
12154         int i;
12155 #endif
12156
12157         mtx_lock(&lun->lun_lock);
12158         /*
12159          * Run through the OOA queue and abort each I/O.
12160          */
12161         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12162              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12163                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
12164         }
12165
12166         /*
12167          * This version sets unit attention for every
12168          */
12169 #if 0
12170         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12171         ctl_est_ua_all(lun, initidx, ua_type);
12172 #else
12173         ctl_est_ua_all(lun, -1, ua_type);
12174 #endif
12175
12176         /*
12177          * A reset (any kind, really) clears reservations established with
12178          * RESERVE/RELEASE.  It does not clear reservations established
12179          * with PERSISTENT RESERVE OUT, but we don't support that at the
12180          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
12181          * reservations made with the RESERVE/RELEASE commands, because
12182          * those commands are obsolete in SPC-3.
12183          */
12184         lun->flags &= ~CTL_LUN_RESERVED;
12185
12186 #ifdef CTL_WITH_CA
12187         for (i = 0; i < CTL_MAX_INITIATORS; i++)
12188                 ctl_clear_mask(lun->have_ca, i);
12189 #endif
12190         mtx_unlock(&lun->lun_lock);
12191
12192         return (0);
12193 }
12194
12195 static void
12196 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
12197     int other_sc)
12198 {
12199         union ctl_io *xio;
12200
12201         mtx_assert(&lun->lun_lock, MA_OWNED);
12202
12203         /*
12204          * Run through the OOA queue and attempt to find the given I/O.
12205          * The target port, initiator ID, tag type and tag number have to
12206          * match the values that we got from the initiator.  If we have an
12207          * untagged command to abort, simply abort the first untagged command
12208          * we come to.  We only allow one untagged command at a time of course.
12209          */
12210         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12211              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12212
12213                 if ((targ_port == UINT32_MAX ||
12214                      targ_port == xio->io_hdr.nexus.targ_port) &&
12215                     (init_id == UINT32_MAX ||
12216                      init_id == xio->io_hdr.nexus.initid.id)) {
12217                         if (targ_port != xio->io_hdr.nexus.targ_port ||
12218                             init_id != xio->io_hdr.nexus.initid.id)
12219                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12220                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12221                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12222                                 union ctl_ha_msg msg_info;
12223
12224                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
12225                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12226                                 msg_info.task.tag_num = xio->scsiio.tag_num;
12227                                 msg_info.task.tag_type = xio->scsiio.tag_type;
12228                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12229                                 msg_info.hdr.original_sc = NULL;
12230                                 msg_info.hdr.serializing_sc = NULL;
12231                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12232                                     (void *)&msg_info, sizeof(msg_info), 0);
12233                         }
12234                 }
12235         }
12236 }
12237
12238 static int
12239 ctl_abort_task_set(union ctl_io *io)
12240 {
12241         struct ctl_softc *softc = control_softc;
12242         struct ctl_lun *lun;
12243         uint32_t targ_lun;
12244
12245         /*
12246          * Look up the LUN.
12247          */
12248         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12249         mtx_lock(&softc->ctl_lock);
12250         if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
12251                 lun = softc->ctl_luns[targ_lun];
12252         else {
12253                 mtx_unlock(&softc->ctl_lock);
12254                 return (1);
12255         }
12256
12257         mtx_lock(&lun->lun_lock);
12258         mtx_unlock(&softc->ctl_lock);
12259         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12260                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12261                     io->io_hdr.nexus.initid.id,
12262                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12263         } else { /* CTL_TASK_CLEAR_TASK_SET */
12264                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12265                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12266         }
12267         mtx_unlock(&lun->lun_lock);
12268         return (0);
12269 }
12270
12271 static int
12272 ctl_i_t_nexus_reset(union ctl_io *io)
12273 {
12274         struct ctl_softc *softc = control_softc;
12275         struct ctl_lun *lun;
12276         uint32_t initidx, residx;
12277
12278         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12279         residx = ctl_get_resindex(&io->io_hdr.nexus);
12280         mtx_lock(&softc->ctl_lock);
12281         STAILQ_FOREACH(lun, &softc->lun_list, links) {
12282                 mtx_lock(&lun->lun_lock);
12283                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12284                     io->io_hdr.nexus.initid.id,
12285                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12286 #ifdef CTL_WITH_CA
12287                 ctl_clear_mask(lun->have_ca, initidx);
12288 #endif
12289                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
12290                         lun->flags &= ~CTL_LUN_RESERVED;
12291                 ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12292                 mtx_unlock(&lun->lun_lock);
12293         }
12294         mtx_unlock(&softc->ctl_lock);
12295         return (0);
12296 }
12297
12298 static int
12299 ctl_abort_task(union ctl_io *io)
12300 {
12301         union ctl_io *xio;
12302         struct ctl_lun *lun;
12303         struct ctl_softc *softc;
12304 #if 0
12305         struct sbuf sb;
12306         char printbuf[128];
12307 #endif
12308         int found;
12309         uint32_t targ_lun;
12310
12311         softc = control_softc;
12312         found = 0;
12313
12314         /*
12315          * Look up the LUN.
12316          */
12317         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12318         mtx_lock(&softc->ctl_lock);
12319         if ((targ_lun < CTL_MAX_LUNS)
12320          && (softc->ctl_luns[targ_lun] != NULL))
12321                 lun = softc->ctl_luns[targ_lun];
12322         else {
12323                 mtx_unlock(&softc->ctl_lock);
12324                 return (1);
12325         }
12326
12327 #if 0
12328         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12329                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12330 #endif
12331
12332         mtx_lock(&lun->lun_lock);
12333         mtx_unlock(&softc->ctl_lock);
12334         /*
12335          * Run through the OOA queue and attempt to find the given I/O.
12336          * The target port, initiator ID, tag type and tag number have to
12337          * match the values that we got from the initiator.  If we have an
12338          * untagged command to abort, simply abort the first untagged command
12339          * we come to.  We only allow one untagged command at a time of course.
12340          */
12341         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12342              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12343 #if 0
12344                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12345
12346                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12347                             lun->lun, xio->scsiio.tag_num,
12348                             xio->scsiio.tag_type,
12349                             (xio->io_hdr.blocked_links.tqe_prev
12350                             == NULL) ? "" : " BLOCKED",
12351                             (xio->io_hdr.flags &
12352                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12353                             (xio->io_hdr.flags &
12354                             CTL_FLAG_ABORT) ? " ABORT" : "",
12355                             (xio->io_hdr.flags &
12356                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12357                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12358                 sbuf_finish(&sb);
12359                 printf("%s\n", sbuf_data(&sb));
12360 #endif
12361
12362                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12363                  || (xio->io_hdr.nexus.initid.id != io->io_hdr.nexus.initid.id)
12364                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12365                         continue;
12366
12367                 /*
12368                  * If the abort says that the task is untagged, the
12369                  * task in the queue must be untagged.  Otherwise,
12370                  * we just check to see whether the tag numbers
12371                  * match.  This is because the QLogic firmware
12372                  * doesn't pass back the tag type in an abort
12373                  * request.
12374                  */
12375 #if 0
12376                 if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12377                   && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12378                  || (xio->scsiio.tag_num == io->taskio.tag_num))
12379 #endif
12380                 /*
12381                  * XXX KDM we've got problems with FC, because it
12382                  * doesn't send down a tag type with aborts.  So we
12383                  * can only really go by the tag number...
12384                  * This may cause problems with parallel SCSI.
12385                  * Need to figure that out!!
12386                  */
12387                 if (xio->scsiio.tag_num == io->taskio.tag_num) {
12388                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12389                         found = 1;
12390                         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12391                             !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12392                                 union ctl_ha_msg msg_info;
12393
12394                                 io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
12395                                 msg_info.hdr.nexus = io->io_hdr.nexus;
12396                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12397                                 msg_info.task.tag_num = io->taskio.tag_num;
12398                                 msg_info.task.tag_type = io->taskio.tag_type;
12399                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12400                                 msg_info.hdr.original_sc = NULL;
12401                                 msg_info.hdr.serializing_sc = NULL;
12402 #if 0
12403                                 printf("Sent Abort to other side\n");
12404 #endif
12405                                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12406                                     (void *)&msg_info, sizeof(msg_info), 0) !=
12407                                     CTL_HA_STATUS_SUCCESS) {
12408                                 }
12409                         }
12410 #if 0
12411                         printf("ctl_abort_task: found I/O to abort\n");
12412 #endif
12413                 }
12414         }
12415         mtx_unlock(&lun->lun_lock);
12416
12417         if (found == 0) {
12418                 /*
12419                  * This isn't really an error.  It's entirely possible for
12420                  * the abort and command completion to cross on the wire.
12421                  * This is more of an informative/diagnostic error.
12422                  */
12423 #if 0
12424                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12425                        "%d:%d:%d:%d tag %d type %d\n",
12426                        io->io_hdr.nexus.initid.id,
12427                        io->io_hdr.nexus.targ_port,
12428                        io->io_hdr.nexus.targ_target.id,
12429                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12430                        io->taskio.tag_type);
12431 #endif
12432         }
12433         return (0);
12434 }
12435
12436 static void
12437 ctl_run_task(union ctl_io *io)
12438 {
12439         struct ctl_softc *softc = control_softc;
12440         int retval = 1;
12441         const char *task_desc;
12442
12443         CTL_DEBUG_PRINT(("ctl_run_task\n"));
12444
12445         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12446             ("ctl_run_task: Unextected io_type %d\n",
12447              io->io_hdr.io_type));
12448
12449         task_desc = ctl_scsi_task_string(&io->taskio);
12450         if (task_desc != NULL) {
12451 #ifdef NEEDTOPORT
12452                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12453                             CTL_TASK_REPORT,
12454                             csevent_LogType_Trace,
12455                             csevent_Severity_Information,
12456                             csevent_AlertLevel_Green,
12457                             csevent_FRU_Firmware,
12458                             csevent_FRU_Unknown,
12459                             "CTL: received task: %s",task_desc);
12460 #endif
12461         } else {
12462 #ifdef NEEDTOPORT
12463                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12464                             CTL_TASK_REPORT,
12465                             csevent_LogType_Trace,
12466                             csevent_Severity_Information,
12467                             csevent_AlertLevel_Green,
12468                             csevent_FRU_Firmware,
12469                             csevent_FRU_Unknown,
12470                             "CTL: received unknown task "
12471                             "type: %d (%#x)",
12472                             io->taskio.task_action,
12473                             io->taskio.task_action);
12474 #endif
12475         }
12476         switch (io->taskio.task_action) {
12477         case CTL_TASK_ABORT_TASK:
12478                 retval = ctl_abort_task(io);
12479                 break;
12480         case CTL_TASK_ABORT_TASK_SET:
12481         case CTL_TASK_CLEAR_TASK_SET:
12482                 retval = ctl_abort_task_set(io);
12483                 break;
12484         case CTL_TASK_CLEAR_ACA:
12485                 break;
12486         case CTL_TASK_I_T_NEXUS_RESET:
12487                 retval = ctl_i_t_nexus_reset(io);
12488                 break;
12489         case CTL_TASK_LUN_RESET: {
12490                 struct ctl_lun *lun;
12491                 uint32_t targ_lun;
12492
12493                 targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12494                 mtx_lock(&softc->ctl_lock);
12495                 if ((targ_lun < CTL_MAX_LUNS)
12496                  && (softc->ctl_luns[targ_lun] != NULL))
12497                         lun = softc->ctl_luns[targ_lun];
12498                 else {
12499                         mtx_unlock(&softc->ctl_lock);
12500                         retval = 1;
12501                         break;
12502                 }
12503
12504                 if (!(io->io_hdr.flags &
12505                     CTL_FLAG_FROM_OTHER_SC)) {
12506                         union ctl_ha_msg msg_info;
12507
12508                         io->io_hdr.flags |=
12509                                 CTL_FLAG_SENT_2OTHER_SC;
12510                         msg_info.hdr.msg_type =
12511                                 CTL_MSG_MANAGE_TASKS;
12512                         msg_info.hdr.nexus = io->io_hdr.nexus;
12513                         msg_info.task.task_action =
12514                                 CTL_TASK_LUN_RESET;
12515                         msg_info.hdr.original_sc = NULL;
12516                         msg_info.hdr.serializing_sc = NULL;
12517                         if (CTL_HA_STATUS_SUCCESS !=
12518                             ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12519                             (void *)&msg_info,
12520                             sizeof(msg_info), 0)) {
12521                         }
12522                 }
12523
12524                 retval = ctl_lun_reset(lun, io,
12525                                        CTL_UA_LUN_RESET);
12526                 mtx_unlock(&softc->ctl_lock);
12527                 break;
12528         }
12529         case CTL_TASK_TARGET_RESET:
12530                 retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12531                 break;
12532         case CTL_TASK_BUS_RESET:
12533                 retval = ctl_bus_reset(softc, io);
12534                 break;
12535         case CTL_TASK_PORT_LOGIN:
12536                 break;
12537         case CTL_TASK_PORT_LOGOUT:
12538                 break;
12539         default:
12540                 printf("ctl_run_task: got unknown task management event %d\n",
12541                        io->taskio.task_action);
12542                 break;
12543         }
12544         if (retval == 0)
12545                 io->io_hdr.status = CTL_SUCCESS;
12546         else
12547                 io->io_hdr.status = CTL_ERROR;
12548         ctl_done(io);
12549 }
12550
12551 /*
12552  * For HA operation.  Handle commands that come in from the other
12553  * controller.
12554  */
12555 static void
12556 ctl_handle_isc(union ctl_io *io)
12557 {
12558         int free_io;
12559         struct ctl_lun *lun;
12560         struct ctl_softc *softc;
12561         uint32_t targ_lun;
12562
12563         softc = control_softc;
12564
12565         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12566         lun = softc->ctl_luns[targ_lun];
12567
12568         switch (io->io_hdr.msg_type) {
12569         case CTL_MSG_SERIALIZE:
12570                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12571                 break;
12572         case CTL_MSG_R2R: {
12573                 const struct ctl_cmd_entry *entry;
12574
12575                 /*
12576                  * This is only used in SER_ONLY mode.
12577                  */
12578                 free_io = 0;
12579                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12580                 mtx_lock(&lun->lun_lock);
12581                 if (ctl_scsiio_lun_check(lun,
12582                     entry, (struct ctl_scsiio *)io) != 0) {
12583                         mtx_unlock(&lun->lun_lock);
12584                         ctl_done(io);
12585                         break;
12586                 }
12587                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12588                 mtx_unlock(&lun->lun_lock);
12589                 ctl_enqueue_rtr(io);
12590                 break;
12591         }
12592         case CTL_MSG_FINISH_IO:
12593                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
12594                         free_io = 0;
12595                         ctl_done(io);
12596                 } else {
12597                         free_io = 1;
12598                         mtx_lock(&lun->lun_lock);
12599                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12600                                      ooa_links);
12601                         ctl_check_blocked(lun);
12602                         mtx_unlock(&lun->lun_lock);
12603                 }
12604                 break;
12605         case CTL_MSG_PERS_ACTION:
12606                 ctl_hndl_per_res_out_on_other_sc(
12607                         (union ctl_ha_msg *)&io->presio.pr_msg);
12608                 free_io = 1;
12609                 break;
12610         case CTL_MSG_BAD_JUJU:
12611                 free_io = 0;
12612                 ctl_done(io);
12613                 break;
12614         case CTL_MSG_DATAMOVE:
12615                 /* Only used in XFER mode */
12616                 free_io = 0;
12617                 ctl_datamove_remote(io);
12618                 break;
12619         case CTL_MSG_DATAMOVE_DONE:
12620                 /* Only used in XFER mode */
12621                 free_io = 0;
12622                 io->scsiio.be_move_done(io);
12623                 break;
12624         default:
12625                 free_io = 1;
12626                 printf("%s: Invalid message type %d\n",
12627                        __func__, io->io_hdr.msg_type);
12628                 break;
12629         }
12630         if (free_io)
12631                 ctl_free_io(io);
12632
12633 }
12634
12635
12636 /*
12637  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12638  * there is no match.
12639  */
12640 static ctl_lun_error_pattern
12641 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12642 {
12643         const struct ctl_cmd_entry *entry;
12644         ctl_lun_error_pattern filtered_pattern, pattern;
12645
12646         pattern = desc->error_pattern;
12647
12648         /*
12649          * XXX KDM we need more data passed into this function to match a
12650          * custom pattern, and we actually need to implement custom pattern
12651          * matching.
12652          */
12653         if (pattern & CTL_LUN_PAT_CMD)
12654                 return (CTL_LUN_PAT_CMD);
12655
12656         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12657                 return (CTL_LUN_PAT_ANY);
12658
12659         entry = ctl_get_cmd_entry(ctsio, NULL);
12660
12661         filtered_pattern = entry->pattern & pattern;
12662
12663         /*
12664          * If the user requested specific flags in the pattern (e.g.
12665          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12666          * flags.
12667          *
12668          * If the user did not specify any flags, it doesn't matter whether
12669          * or not the command supports the flags.
12670          */
12671         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12672              (pattern & ~CTL_LUN_PAT_MASK))
12673                 return (CTL_LUN_PAT_NONE);
12674
12675         /*
12676          * If the user asked for a range check, see if the requested LBA
12677          * range overlaps with this command's LBA range.
12678          */
12679         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12680                 uint64_t lba1;
12681                 uint64_t len1;
12682                 ctl_action action;
12683                 int retval;
12684
12685                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12686                 if (retval != 0)
12687                         return (CTL_LUN_PAT_NONE);
12688
12689                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12690                                               desc->lba_range.len, FALSE);
12691                 /*
12692                  * A "pass" means that the LBA ranges don't overlap, so
12693                  * this doesn't match the user's range criteria.
12694                  */
12695                 if (action == CTL_ACTION_PASS)
12696                         return (CTL_LUN_PAT_NONE);
12697         }
12698
12699         return (filtered_pattern);
12700 }
12701
12702 static void
12703 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12704 {
12705         struct ctl_error_desc *desc, *desc2;
12706
12707         mtx_assert(&lun->lun_lock, MA_OWNED);
12708
12709         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12710                 ctl_lun_error_pattern pattern;
12711                 /*
12712                  * Check to see whether this particular command matches
12713                  * the pattern in the descriptor.
12714                  */
12715                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12716                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12717                         continue;
12718
12719                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12720                 case CTL_LUN_INJ_ABORTED:
12721                         ctl_set_aborted(&io->scsiio);
12722                         break;
12723                 case CTL_LUN_INJ_MEDIUM_ERR:
12724                         ctl_set_medium_error(&io->scsiio);
12725                         break;
12726                 case CTL_LUN_INJ_UA:
12727                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12728                          * OCCURRED */
12729                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12730                         break;
12731                 case CTL_LUN_INJ_CUSTOM:
12732                         /*
12733                          * We're assuming the user knows what he is doing.
12734                          * Just copy the sense information without doing
12735                          * checks.
12736                          */
12737                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12738                               MIN(sizeof(desc->custom_sense),
12739                                   sizeof(io->scsiio.sense_data)));
12740                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12741                         io->scsiio.sense_len = SSD_FULL_SIZE;
12742                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12743                         break;
12744                 case CTL_LUN_INJ_NONE:
12745                 default:
12746                         /*
12747                          * If this is an error injection type we don't know
12748                          * about, clear the continuous flag (if it is set)
12749                          * so it will get deleted below.
12750                          */
12751                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12752                         break;
12753                 }
12754                 /*
12755                  * By default, each error injection action is a one-shot
12756                  */
12757                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12758                         continue;
12759
12760                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12761
12762                 free(desc, M_CTL);
12763         }
12764 }
12765
12766 #ifdef CTL_IO_DELAY
12767 static void
12768 ctl_datamove_timer_wakeup(void *arg)
12769 {
12770         union ctl_io *io;
12771
12772         io = (union ctl_io *)arg;
12773
12774         ctl_datamove(io);
12775 }
12776 #endif /* CTL_IO_DELAY */
12777
12778 void
12779 ctl_datamove(union ctl_io *io)
12780 {
12781         void (*fe_datamove)(union ctl_io *io);
12782
12783         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12784
12785         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12786
12787 #ifdef CTL_TIME_IO
12788         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12789                 char str[256];
12790                 char path_str[64];
12791                 struct sbuf sb;
12792
12793                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12794                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12795
12796                 sbuf_cat(&sb, path_str);
12797                 switch (io->io_hdr.io_type) {
12798                 case CTL_IO_SCSI:
12799                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12800                         sbuf_printf(&sb, "\n");
12801                         sbuf_cat(&sb, path_str);
12802                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12803                                     io->scsiio.tag_num, io->scsiio.tag_type);
12804                         break;
12805                 case CTL_IO_TASK:
12806                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12807                                     "Tag Type: %d\n", io->taskio.task_action,
12808                                     io->taskio.tag_num, io->taskio.tag_type);
12809                         break;
12810                 default:
12811                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12812                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12813                         break;
12814                 }
12815                 sbuf_cat(&sb, path_str);
12816                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12817                             (intmax_t)time_uptime - io->io_hdr.start_time);
12818                 sbuf_finish(&sb);
12819                 printf("%s", sbuf_data(&sb));
12820         }
12821 #endif /* CTL_TIME_IO */
12822
12823 #ifdef CTL_IO_DELAY
12824         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12825                 struct ctl_lun *lun;
12826
12827                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12828
12829                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12830         } else {
12831                 struct ctl_lun *lun;
12832
12833                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12834                 if ((lun != NULL)
12835                  && (lun->delay_info.datamove_delay > 0)) {
12836                         struct callout *callout;
12837
12838                         callout = (struct callout *)&io->io_hdr.timer_bytes;
12839                         callout_init(callout, /*mpsafe*/ 1);
12840                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12841                         callout_reset(callout,
12842                                       lun->delay_info.datamove_delay * hz,
12843                                       ctl_datamove_timer_wakeup, io);
12844                         if (lun->delay_info.datamove_type ==
12845                             CTL_DELAY_TYPE_ONESHOT)
12846                                 lun->delay_info.datamove_delay = 0;
12847                         return;
12848                 }
12849         }
12850 #endif
12851
12852         /*
12853          * This command has been aborted.  Set the port status, so we fail
12854          * the data move.
12855          */
12856         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12857                 printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12858                        io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12859                        io->io_hdr.nexus.targ_port,
12860                        (uintmax_t)io->io_hdr.nexus.targ_target.id,
12861                        io->io_hdr.nexus.targ_lun);
12862                 io->io_hdr.port_status = 31337;
12863                 /*
12864                  * Note that the backend, in this case, will get the
12865                  * callback in its context.  In other cases it may get
12866                  * called in the frontend's interrupt thread context.
12867                  */
12868                 io->scsiio.be_move_done(io);
12869                 return;
12870         }
12871
12872         /* Don't confuse frontend with zero length data move. */
12873         if (io->scsiio.kern_data_len == 0) {
12874                 io->scsiio.be_move_done(io);
12875                 return;
12876         }
12877
12878         /*
12879          * If we're in XFER mode and this I/O is from the other shelf
12880          * controller, we need to send the DMA to the other side to
12881          * actually transfer the data to/from the host.  In serialize only
12882          * mode the transfer happens below CTL and ctl_datamove() is only
12883          * called on the machine that originally received the I/O.
12884          */
12885         if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12886          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12887                 union ctl_ha_msg msg;
12888                 uint32_t sg_entries_sent;
12889                 int do_sg_copy;
12890                 int i;
12891
12892                 memset(&msg, 0, sizeof(msg));
12893                 msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12894                 msg.hdr.original_sc = io->io_hdr.original_sc;
12895                 msg.hdr.serializing_sc = io;
12896                 msg.hdr.nexus = io->io_hdr.nexus;
12897                 msg.dt.flags = io->io_hdr.flags;
12898                 /*
12899                  * We convert everything into a S/G list here.  We can't
12900                  * pass by reference, only by value between controllers.
12901                  * So we can't pass a pointer to the S/G list, only as many
12902                  * S/G entries as we can fit in here.  If it's possible for
12903                  * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12904                  * then we need to break this up into multiple transfers.
12905                  */
12906                 if (io->scsiio.kern_sg_entries == 0) {
12907                         msg.dt.kern_sg_entries = 1;
12908                         /*
12909                          * If this is in cached memory, flush the cache
12910                          * before we send the DMA request to the other
12911                          * controller.  We want to do this in either the
12912                          * read or the write case.  The read case is
12913                          * straightforward.  In the write case, we want to
12914                          * make sure nothing is in the local cache that
12915                          * could overwrite the DMAed data.
12916                          */
12917                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12918                                 /*
12919                                  * XXX KDM use bus_dmamap_sync() here.
12920                                  */
12921                         }
12922
12923                         /*
12924                          * Convert to a physical address if this is a
12925                          * virtual address.
12926                          */
12927                         if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12928                                 msg.dt.sg_list[0].addr =
12929                                         io->scsiio.kern_data_ptr;
12930                         } else {
12931                                 /*
12932                                  * XXX KDM use busdma here!
12933                                  */
12934 #if 0
12935                                 msg.dt.sg_list[0].addr = (void *)
12936                                         vtophys(io->scsiio.kern_data_ptr);
12937 #endif
12938                         }
12939
12940                         msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12941                         do_sg_copy = 0;
12942                 } else {
12943                         struct ctl_sg_entry *sgl;
12944
12945                         do_sg_copy = 1;
12946                         msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12947                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12948                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12949                                 /*
12950                                  * XXX KDM use bus_dmamap_sync() here.
12951                                  */
12952                         }
12953                 }
12954
12955                 msg.dt.kern_data_len = io->scsiio.kern_data_len;
12956                 msg.dt.kern_total_len = io->scsiio.kern_total_len;
12957                 msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12958                 msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12959                 msg.dt.sg_sequence = 0;
12960
12961                 /*
12962                  * Loop until we've sent all of the S/G entries.  On the
12963                  * other end, we'll recompose these S/G entries into one
12964                  * contiguous list before passing it to the
12965                  */
12966                 for (sg_entries_sent = 0; sg_entries_sent <
12967                      msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12968                         msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list)/
12969                                 sizeof(msg.dt.sg_list[0])),
12970                                 msg.dt.kern_sg_entries - sg_entries_sent);
12971
12972                         if (do_sg_copy != 0) {
12973                                 struct ctl_sg_entry *sgl;
12974                                 int j;
12975
12976                                 sgl = (struct ctl_sg_entry *)
12977                                         io->scsiio.kern_data_ptr;
12978                                 /*
12979                                  * If this is in cached memory, flush the cache
12980                                  * before we send the DMA request to the other
12981                                  * controller.  We want to do this in either
12982                                  * the * read or the write case.  The read
12983                                  * case is straightforward.  In the write
12984                                  * case, we want to make sure nothing is
12985                                  * in the local cache that could overwrite
12986                                  * the DMAed data.
12987                                  */
12988
12989                                 for (i = sg_entries_sent, j = 0;
12990                                      i < msg.dt.cur_sg_entries; i++, j++) {
12991                                         if ((io->io_hdr.flags &
12992                                              CTL_FLAG_NO_DATASYNC) == 0) {
12993                                                 /*
12994                                                  * XXX KDM use bus_dmamap_sync()
12995                                                  */
12996                                         }
12997                                         if ((io->io_hdr.flags &
12998                                              CTL_FLAG_BUS_ADDR) == 0) {
12999                                                 /*
13000                                                  * XXX KDM use busdma.
13001                                                  */
13002 #if 0
13003                                                 msg.dt.sg_list[j].addr =(void *)
13004                                                        vtophys(sgl[i].addr);
13005 #endif
13006                                         } else {
13007                                                 msg.dt.sg_list[j].addr =
13008                                                         sgl[i].addr;
13009                                         }
13010                                         msg.dt.sg_list[j].len = sgl[i].len;
13011                                 }
13012                         }
13013
13014                         sg_entries_sent += msg.dt.cur_sg_entries;
13015                         if (sg_entries_sent >= msg.dt.kern_sg_entries)
13016                                 msg.dt.sg_last = 1;
13017                         else
13018                                 msg.dt.sg_last = 0;
13019
13020                         /*
13021                          * XXX KDM drop and reacquire the lock here?
13022                          */
13023                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13024                             sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13025                                 /*
13026                                  * XXX do something here.
13027                                  */
13028                         }
13029
13030                         msg.dt.sent_sg_entries = sg_entries_sent;
13031                 }
13032                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13033                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
13034                         ctl_failover_io(io, /*have_lock*/ 0);
13035
13036         } else {
13037
13038                 /*
13039                  * Lookup the fe_datamove() function for this particular
13040                  * front end.
13041                  */
13042                 fe_datamove =
13043                     control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13044
13045                 fe_datamove(io);
13046         }
13047 }
13048
13049 static void
13050 ctl_send_datamove_done(union ctl_io *io, int have_lock)
13051 {
13052         union ctl_ha_msg msg;
13053         int isc_status;
13054
13055         memset(&msg, 0, sizeof(msg));
13056
13057         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
13058         msg.hdr.original_sc = io;
13059         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13060         msg.hdr.nexus = io->io_hdr.nexus;
13061         msg.hdr.status = io->io_hdr.status;
13062         msg.scsi.tag_num = io->scsiio.tag_num;
13063         msg.scsi.tag_type = io->scsiio.tag_type;
13064         msg.scsi.scsi_status = io->scsiio.scsi_status;
13065         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13066                sizeof(io->scsiio.sense_data));
13067         msg.scsi.sense_len = io->scsiio.sense_len;
13068         msg.scsi.sense_residual = io->scsiio.sense_residual;
13069         msg.scsi.fetd_status = io->io_hdr.port_status;
13070         msg.scsi.residual = io->scsiio.residual;
13071         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13072
13073         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13074                 ctl_failover_io(io, /*have_lock*/ have_lock);
13075                 return;
13076         }
13077
13078         isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
13079         if (isc_status > CTL_HA_STATUS_SUCCESS) {
13080                 /* XXX do something if this fails */
13081         }
13082
13083 }
13084
13085 /*
13086  * The DMA to the remote side is done, now we need to tell the other side
13087  * we're done so it can continue with its data movement.
13088  */
13089 static void
13090 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
13091 {
13092         union ctl_io *io;
13093
13094         io = rq->context;
13095
13096         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13097                 printf("%s: ISC DMA write failed with error %d", __func__,
13098                        rq->ret);
13099                 ctl_set_internal_failure(&io->scsiio,
13100                                          /*sks_valid*/ 1,
13101                                          /*retry_count*/ rq->ret);
13102         }
13103
13104         ctl_dt_req_free(rq);
13105
13106         /*
13107          * In this case, we had to malloc the memory locally.  Free it.
13108          */
13109         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13110                 int i;
13111                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13112                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13113         }
13114         /*
13115          * The data is in local and remote memory, so now we need to send
13116          * status (good or back) back to the other side.
13117          */
13118         ctl_send_datamove_done(io, /*have_lock*/ 0);
13119 }
13120
13121 /*
13122  * We've moved the data from the host/controller into local memory.  Now we
13123  * need to push it over to the remote controller's memory.
13124  */
13125 static int
13126 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
13127 {
13128         int retval;
13129
13130         retval = 0;
13131
13132         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
13133                                           ctl_datamove_remote_write_cb);
13134
13135         return (retval);
13136 }
13137
13138 static void
13139 ctl_datamove_remote_write(union ctl_io *io)
13140 {
13141         int retval;
13142         void (*fe_datamove)(union ctl_io *io);
13143
13144         /*
13145          * - Get the data from the host/HBA into local memory.
13146          * - DMA memory from the local controller to the remote controller.
13147          * - Send status back to the remote controller.
13148          */
13149
13150         retval = ctl_datamove_remote_sgl_setup(io);
13151         if (retval != 0)
13152                 return;
13153
13154         /* Switch the pointer over so the FETD knows what to do */
13155         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13156
13157         /*
13158          * Use a custom move done callback, since we need to send completion
13159          * back to the other controller, not to the backend on this side.
13160          */
13161         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
13162
13163         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13164
13165         fe_datamove(io);
13166
13167         return;
13168
13169 }
13170
13171 static int
13172 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
13173 {
13174 #if 0
13175         char str[256];
13176         char path_str[64];
13177         struct sbuf sb;
13178 #endif
13179
13180         /*
13181          * In this case, we had to malloc the memory locally.  Free it.
13182          */
13183         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13184                 int i;
13185                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13186                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13187         }
13188
13189 #if 0
13190         scsi_path_string(io, path_str, sizeof(path_str));
13191         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13192         sbuf_cat(&sb, path_str);
13193         scsi_command_string(&io->scsiio, NULL, &sb);
13194         sbuf_printf(&sb, "\n");
13195         sbuf_cat(&sb, path_str);
13196         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13197                     io->scsiio.tag_num, io->scsiio.tag_type);
13198         sbuf_cat(&sb, path_str);
13199         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
13200                     io->io_hdr.flags, io->io_hdr.status);
13201         sbuf_finish(&sb);
13202         printk("%s", sbuf_data(&sb));
13203 #endif
13204
13205
13206         /*
13207          * The read is done, now we need to send status (good or bad) back
13208          * to the other side.
13209          */
13210         ctl_send_datamove_done(io, /*have_lock*/ 0);
13211
13212         return (0);
13213 }
13214
13215 static void
13216 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
13217 {
13218         union ctl_io *io;
13219         void (*fe_datamove)(union ctl_io *io);
13220
13221         io = rq->context;
13222
13223         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13224                 printf("%s: ISC DMA read failed with error %d", __func__,
13225                        rq->ret);
13226                 ctl_set_internal_failure(&io->scsiio,
13227                                          /*sks_valid*/ 1,
13228                                          /*retry_count*/ rq->ret);
13229         }
13230
13231         ctl_dt_req_free(rq);
13232
13233         /* Switch the pointer over so the FETD knows what to do */
13234         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13235
13236         /*
13237          * Use a custom move done callback, since we need to send completion
13238          * back to the other controller, not to the backend on this side.
13239          */
13240         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13241
13242         /* XXX KDM add checks like the ones in ctl_datamove? */
13243
13244         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13245
13246         fe_datamove(io);
13247 }
13248
13249 static int
13250 ctl_datamove_remote_sgl_setup(union ctl_io *io)
13251 {
13252         struct ctl_sg_entry *local_sglist, *remote_sglist;
13253         struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13254         struct ctl_softc *softc;
13255         int retval;
13256         int i;
13257
13258         retval = 0;
13259         softc = control_softc;
13260
13261         local_sglist = io->io_hdr.local_sglist;
13262         local_dma_sglist = io->io_hdr.local_dma_sglist;
13263         remote_sglist = io->io_hdr.remote_sglist;
13264         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13265
13266         if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13267                 for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13268                         local_sglist[i].len = remote_sglist[i].len;
13269
13270                         /*
13271                          * XXX Detect the situation where the RS-level I/O
13272                          * redirector on the other side has already read the
13273                          * data off of the AOR RS on this side, and
13274                          * transferred it to remote (mirror) memory on the
13275                          * other side.  Since we already have the data in
13276                          * memory here, we just need to use it.
13277                          *
13278                          * XXX KDM this can probably be removed once we
13279                          * get the cache device code in and take the
13280                          * current AOR implementation out.
13281                          */
13282 #ifdef NEEDTOPORT
13283                         if ((remote_sglist[i].addr >=
13284                              (void *)vtophys(softc->mirr->addr))
13285                          && (remote_sglist[i].addr <
13286                              ((void *)vtophys(softc->mirr->addr) +
13287                              CacheMirrorOffset))) {
13288                                 local_sglist[i].addr = remote_sglist[i].addr -
13289                                         CacheMirrorOffset;
13290                                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13291                                      CTL_FLAG_DATA_IN)
13292                                         io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13293                         } else {
13294                                 local_sglist[i].addr = remote_sglist[i].addr +
13295                                         CacheMirrorOffset;
13296                         }
13297 #endif
13298 #if 0
13299                         printf("%s: local %p, remote %p, len %d\n",
13300                                __func__, local_sglist[i].addr,
13301                                remote_sglist[i].addr, local_sglist[i].len);
13302 #endif
13303                 }
13304         } else {
13305                 uint32_t len_to_go;
13306
13307                 /*
13308                  * In this case, we don't have automatically allocated
13309                  * memory for this I/O on this controller.  This typically
13310                  * happens with internal CTL I/O -- e.g. inquiry, mode
13311                  * sense, etc.  Anything coming from RAIDCore will have
13312                  * a mirror area available.
13313                  */
13314                 len_to_go = io->scsiio.kern_data_len;
13315
13316                 /*
13317                  * Clear the no datasync flag, we have to use malloced
13318                  * buffers.
13319                  */
13320                 io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13321
13322                 /*
13323                  * The difficult thing here is that the size of the various
13324                  * S/G segments may be different than the size from the
13325                  * remote controller.  That'll make it harder when DMAing
13326                  * the data back to the other side.
13327                  */
13328                 for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13329                      sizeof(io->io_hdr.remote_sglist[0])) &&
13330                      (len_to_go > 0); i++) {
13331                         local_sglist[i].len = MIN(len_to_go, 131072);
13332                         CTL_SIZE_8B(local_dma_sglist[i].len,
13333                                     local_sglist[i].len);
13334                         local_sglist[i].addr =
13335                                 malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13336
13337                         local_dma_sglist[i].addr = local_sglist[i].addr;
13338
13339                         if (local_sglist[i].addr == NULL) {
13340                                 int j;
13341
13342                                 printf("malloc failed for %zd bytes!",
13343                                        local_dma_sglist[i].len);
13344                                 for (j = 0; j < i; j++) {
13345                                         free(local_sglist[j].addr, M_CTL);
13346                                 }
13347                                 ctl_set_internal_failure(&io->scsiio,
13348                                                          /*sks_valid*/ 1,
13349                                                          /*retry_count*/ 4857);
13350                                 retval = 1;
13351                                 goto bailout_error;
13352                                 
13353                         }
13354                         /* XXX KDM do we need a sync here? */
13355
13356                         len_to_go -= local_sglist[i].len;
13357                 }
13358                 /*
13359                  * Reset the number of S/G entries accordingly.  The
13360                  * original number of S/G entries is available in
13361                  * rem_sg_entries.
13362                  */
13363                 io->scsiio.kern_sg_entries = i;
13364
13365 #if 0
13366                 printf("%s: kern_sg_entries = %d\n", __func__,
13367                        io->scsiio.kern_sg_entries);
13368                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13369                         printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13370                                local_sglist[i].addr, local_sglist[i].len,
13371                                local_dma_sglist[i].len);
13372 #endif
13373         }
13374
13375
13376         return (retval);
13377
13378 bailout_error:
13379
13380         ctl_send_datamove_done(io, /*have_lock*/ 0);
13381
13382         return (retval);
13383 }
13384
13385 static int
13386 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13387                          ctl_ha_dt_cb callback)
13388 {
13389         struct ctl_ha_dt_req *rq;
13390         struct ctl_sg_entry *remote_sglist, *local_sglist;
13391         struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13392         uint32_t local_used, remote_used, total_used;
13393         int retval;
13394         int i, j;
13395
13396         retval = 0;
13397
13398         rq = ctl_dt_req_alloc();
13399
13400         /*
13401          * If we failed to allocate the request, and if the DMA didn't fail
13402          * anyway, set busy status.  This is just a resource allocation
13403          * failure.
13404          */
13405         if ((rq == NULL)
13406          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13407                 ctl_set_busy(&io->scsiio);
13408
13409         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13410
13411                 if (rq != NULL)
13412                         ctl_dt_req_free(rq);
13413
13414                 /*
13415                  * The data move failed.  We need to return status back
13416                  * to the other controller.  No point in trying to DMA
13417                  * data to the remote controller.
13418                  */
13419
13420                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13421
13422                 retval = 1;
13423
13424                 goto bailout;
13425         }
13426
13427         local_sglist = io->io_hdr.local_sglist;
13428         local_dma_sglist = io->io_hdr.local_dma_sglist;
13429         remote_sglist = io->io_hdr.remote_sglist;
13430         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13431         local_used = 0;
13432         remote_used = 0;
13433         total_used = 0;
13434
13435         if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13436                 rq->ret = CTL_HA_STATUS_SUCCESS;
13437                 rq->context = io;
13438                 callback(rq);
13439                 goto bailout;
13440         }
13441
13442         /*
13443          * Pull/push the data over the wire from/to the other controller.
13444          * This takes into account the possibility that the local and
13445          * remote sglists may not be identical in terms of the size of
13446          * the elements and the number of elements.
13447          *
13448          * One fundamental assumption here is that the length allocated for
13449          * both the local and remote sglists is identical.  Otherwise, we've
13450          * essentially got a coding error of some sort.
13451          */
13452         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13453                 int isc_ret;
13454                 uint32_t cur_len, dma_length;
13455                 uint8_t *tmp_ptr;
13456
13457                 rq->id = CTL_HA_DATA_CTL;
13458                 rq->command = command;
13459                 rq->context = io;
13460
13461                 /*
13462                  * Both pointers should be aligned.  But it is possible
13463                  * that the allocation length is not.  They should both
13464                  * also have enough slack left over at the end, though,
13465                  * to round up to the next 8 byte boundary.
13466                  */
13467                 cur_len = MIN(local_sglist[i].len - local_used,
13468                               remote_sglist[j].len - remote_used);
13469
13470                 /*
13471                  * In this case, we have a size issue and need to decrease
13472                  * the size, except in the case where we actually have less
13473                  * than 8 bytes left.  In that case, we need to increase
13474                  * the DMA length to get the last bit.
13475                  */
13476                 if ((cur_len & 0x7) != 0) {
13477                         if (cur_len > 0x7) {
13478                                 cur_len = cur_len - (cur_len & 0x7);
13479                                 dma_length = cur_len;
13480                         } else {
13481                                 CTL_SIZE_8B(dma_length, cur_len);
13482                         }
13483
13484                 } else
13485                         dma_length = cur_len;
13486
13487                 /*
13488                  * If we had to allocate memory for this I/O, instead of using
13489                  * the non-cached mirror memory, we'll need to flush the cache
13490                  * before trying to DMA to the other controller.
13491                  *
13492                  * We could end up doing this multiple times for the same
13493                  * segment if we have a larger local segment than remote
13494                  * segment.  That shouldn't be an issue.
13495                  */
13496                 if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13497                         /*
13498                          * XXX KDM use bus_dmamap_sync() here.
13499                          */
13500                 }
13501
13502                 rq->size = dma_length;
13503
13504                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
13505                 tmp_ptr += local_used;
13506
13507                 /* Use physical addresses when talking to ISC hardware */
13508                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13509                         /* XXX KDM use busdma */
13510 #if 0
13511                         rq->local = vtophys(tmp_ptr);
13512 #endif
13513                 } else
13514                         rq->local = tmp_ptr;
13515
13516                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13517                 tmp_ptr += remote_used;
13518                 rq->remote = tmp_ptr;
13519
13520                 rq->callback = NULL;
13521
13522                 local_used += cur_len;
13523                 if (local_used >= local_sglist[i].len) {
13524                         i++;
13525                         local_used = 0;
13526                 }
13527
13528                 remote_used += cur_len;
13529                 if (remote_used >= remote_sglist[j].len) {
13530                         j++;
13531                         remote_used = 0;
13532                 }
13533                 total_used += cur_len;
13534
13535                 if (total_used >= io->scsiio.kern_data_len)
13536                         rq->callback = callback;
13537
13538                 if ((rq->size & 0x7) != 0) {
13539                         printf("%s: warning: size %d is not on 8b boundary\n",
13540                                __func__, rq->size);
13541                 }
13542                 if (((uintptr_t)rq->local & 0x7) != 0) {
13543                         printf("%s: warning: local %p not on 8b boundary\n",
13544                                __func__, rq->local);
13545                 }
13546                 if (((uintptr_t)rq->remote & 0x7) != 0) {
13547                         printf("%s: warning: remote %p not on 8b boundary\n",
13548                                __func__, rq->local);
13549                 }
13550 #if 0
13551                 printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13552                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13553                        rq->local, rq->remote, rq->size);
13554 #endif
13555
13556                 isc_ret = ctl_dt_single(rq);
13557                 if (isc_ret == CTL_HA_STATUS_WAIT)
13558                         continue;
13559
13560                 if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13561                         rq->ret = CTL_HA_STATUS_SUCCESS;
13562                 } else {
13563                         rq->ret = isc_ret;
13564                 }
13565                 callback(rq);
13566                 goto bailout;
13567         }
13568
13569 bailout:
13570         return (retval);
13571
13572 }
13573
13574 static void
13575 ctl_datamove_remote_read(union ctl_io *io)
13576 {
13577         int retval;
13578         int i;
13579
13580         /*
13581          * This will send an error to the other controller in the case of a
13582          * failure.
13583          */
13584         retval = ctl_datamove_remote_sgl_setup(io);
13585         if (retval != 0)
13586                 return;
13587
13588         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13589                                           ctl_datamove_remote_read_cb);
13590         if ((retval != 0)
13591          && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13592                 /*
13593                  * Make sure we free memory if there was an error..  The
13594                  * ctl_datamove_remote_xfer() function will send the
13595                  * datamove done message, or call the callback with an
13596                  * error if there is a problem.
13597                  */
13598                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13599                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13600         }
13601
13602         return;
13603 }
13604
13605 /*
13606  * Process a datamove request from the other controller.  This is used for
13607  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13608  * first.  Once that is complete, the data gets DMAed into the remote
13609  * controller's memory.  For reads, we DMA from the remote controller's
13610  * memory into our memory first, and then move it out to the FETD.
13611  */
13612 static void
13613 ctl_datamove_remote(union ctl_io *io)
13614 {
13615         struct ctl_softc *softc;
13616
13617         softc = control_softc;
13618
13619         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13620
13621         /*
13622          * Note that we look for an aborted I/O here, but don't do some of
13623          * the other checks that ctl_datamove() normally does.
13624          * We don't need to run the datamove delay code, since that should
13625          * have been done if need be on the other controller.
13626          */
13627         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13628                 printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13629                        io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13630                        io->io_hdr.nexus.targ_port,
13631                        io->io_hdr.nexus.targ_target.id,
13632                        io->io_hdr.nexus.targ_lun);
13633                 io->io_hdr.port_status = 31338;
13634                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13635                 return;
13636         }
13637
13638         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13639                 ctl_datamove_remote_write(io);
13640         } else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13641                 ctl_datamove_remote_read(io);
13642         } else {
13643                 union ctl_ha_msg msg;
13644                 struct scsi_sense_data *sense;
13645                 uint8_t sks[3];
13646                 int retry_count;
13647
13648                 memset(&msg, 0, sizeof(msg));
13649
13650                 msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13651                 msg.hdr.status = CTL_SCSI_ERROR;
13652                 msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13653
13654                 retry_count = 4243;
13655
13656                 sense = &msg.scsi.sense_data;
13657                 sks[0] = SSD_SCS_VALID;
13658                 sks[1] = (retry_count >> 8) & 0xff;
13659                 sks[2] = retry_count & 0xff;
13660
13661                 /* "Internal target failure" */
13662                 scsi_set_sense_data(sense,
13663                                     /*sense_format*/ SSD_TYPE_NONE,
13664                                     /*current_error*/ 1,
13665                                     /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13666                                     /*asc*/ 0x44,
13667                                     /*ascq*/ 0x00,
13668                                     /*type*/ SSD_ELEM_SKS,
13669                                     /*size*/ sizeof(sks),
13670                                     /*data*/ sks,
13671                                     SSD_ELEM_NONE);
13672
13673                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13674                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13675                         ctl_failover_io(io, /*have_lock*/ 1);
13676                         return;
13677                 }
13678
13679                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13680                     CTL_HA_STATUS_SUCCESS) {
13681                         /* XXX KDM what to do if this fails? */
13682                 }
13683                 return;
13684         }
13685         
13686 }
13687
13688 static int
13689 ctl_process_done(union ctl_io *io)
13690 {
13691         struct ctl_lun *lun;
13692         struct ctl_softc *softc = control_softc;
13693         void (*fe_done)(union ctl_io *io);
13694         uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13695
13696         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13697
13698         fe_done = softc->ctl_ports[targ_port]->fe_done;
13699
13700 #ifdef CTL_TIME_IO
13701         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13702                 char str[256];
13703                 char path_str[64];
13704                 struct sbuf sb;
13705
13706                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13707                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13708
13709                 sbuf_cat(&sb, path_str);
13710                 switch (io->io_hdr.io_type) {
13711                 case CTL_IO_SCSI:
13712                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13713                         sbuf_printf(&sb, "\n");
13714                         sbuf_cat(&sb, path_str);
13715                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13716                                     io->scsiio.tag_num, io->scsiio.tag_type);
13717                         break;
13718                 case CTL_IO_TASK:
13719                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13720                                     "Tag Type: %d\n", io->taskio.task_action,
13721                                     io->taskio.tag_num, io->taskio.tag_type);
13722                         break;
13723                 default:
13724                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13725                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13726                         break;
13727                 }
13728                 sbuf_cat(&sb, path_str);
13729                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13730                             (intmax_t)time_uptime - io->io_hdr.start_time);
13731                 sbuf_finish(&sb);
13732                 printf("%s", sbuf_data(&sb));
13733         }
13734 #endif /* CTL_TIME_IO */
13735
13736         switch (io->io_hdr.io_type) {
13737         case CTL_IO_SCSI:
13738                 break;
13739         case CTL_IO_TASK:
13740                 if (bootverbose || (ctl_debug & CTL_DEBUG_INFO))
13741                         ctl_io_error_print(io, NULL);
13742                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13743                         ctl_free_io(io);
13744                 else
13745                         fe_done(io);
13746                 return (CTL_RETVAL_COMPLETE);
13747         default:
13748                 panic("ctl_process_done: invalid io type %d\n",
13749                       io->io_hdr.io_type);
13750                 break; /* NOTREACHED */
13751         }
13752
13753         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13754         if (lun == NULL) {
13755                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13756                                  io->io_hdr.nexus.targ_mapped_lun));
13757                 goto bailout;
13758         }
13759
13760         mtx_lock(&lun->lun_lock);
13761
13762         /*
13763          * Check to see if we have any errors to inject here.  We only
13764          * inject errors for commands that don't already have errors set.
13765          */
13766         if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13767             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13768             ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13769                 ctl_inject_error(lun, io);
13770
13771         /*
13772          * XXX KDM how do we treat commands that aren't completed
13773          * successfully?
13774          *
13775          * XXX KDM should we also track I/O latency?
13776          */
13777         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13778             io->io_hdr.io_type == CTL_IO_SCSI) {
13779 #ifdef CTL_TIME_IO
13780                 struct bintime cur_bt;
13781 #endif
13782                 int type;
13783
13784                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13785                     CTL_FLAG_DATA_IN)
13786                         type = CTL_STATS_READ;
13787                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13788                     CTL_FLAG_DATA_OUT)
13789                         type = CTL_STATS_WRITE;
13790                 else
13791                         type = CTL_STATS_NO_IO;
13792
13793                 lun->stats.ports[targ_port].bytes[type] +=
13794                     io->scsiio.kern_total_len;
13795                 lun->stats.ports[targ_port].operations[type]++;
13796 #ifdef CTL_TIME_IO
13797                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13798                    &io->io_hdr.dma_bt);
13799                 lun->stats.ports[targ_port].num_dmas[type] +=
13800                     io->io_hdr.num_dmas;
13801                 getbintime(&cur_bt);
13802                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13803                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13804 #endif
13805         }
13806
13807         /*
13808          * Remove this from the OOA queue.
13809          */
13810         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13811 #ifdef CTL_TIME_IO
13812         if (TAILQ_EMPTY(&lun->ooa_queue))
13813                 lun->last_busy = getsbinuptime();
13814 #endif
13815
13816         /*
13817          * Run through the blocked queue on this LUN and see if anything
13818          * has become unblocked, now that this transaction is done.
13819          */
13820         ctl_check_blocked(lun);
13821
13822         /*
13823          * If the LUN has been invalidated, free it if there is nothing
13824          * left on its OOA queue.
13825          */
13826         if ((lun->flags & CTL_LUN_INVALID)
13827          && TAILQ_EMPTY(&lun->ooa_queue)) {
13828                 mtx_unlock(&lun->lun_lock);
13829                 mtx_lock(&softc->ctl_lock);
13830                 ctl_free_lun(lun);
13831                 mtx_unlock(&softc->ctl_lock);
13832         } else
13833                 mtx_unlock(&lun->lun_lock);
13834
13835 bailout:
13836
13837         /*
13838          * If this command has been aborted, make sure we set the status
13839          * properly.  The FETD is responsible for freeing the I/O and doing
13840          * whatever it needs to do to clean up its state.
13841          */
13842         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13843                 ctl_set_task_aborted(&io->scsiio);
13844
13845         /*
13846          * If enabled, print command error status.
13847          * We don't print UAs unless debugging was enabled explicitly.
13848          */
13849         do {
13850                 if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)
13851                         break;
13852                 if (!bootverbose && (ctl_debug & CTL_DEBUG_INFO) == 0)
13853                         break;
13854                 if ((ctl_debug & CTL_DEBUG_INFO) == 0 &&
13855                     ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR) &&
13856                      (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13857                         int error_code, sense_key, asc, ascq;
13858
13859                         scsi_extract_sense_len(&io->scsiio.sense_data,
13860                             io->scsiio.sense_len, &error_code, &sense_key,
13861                             &asc, &ascq, /*show_errors*/ 0);
13862                         if (sense_key == SSD_KEY_UNIT_ATTENTION)
13863                                 break;
13864                 }
13865
13866                 ctl_io_error_print(io, NULL);
13867         } while (0);
13868
13869         /*
13870          * Tell the FETD or the other shelf controller we're done with this
13871          * command.  Note that only SCSI commands get to this point.  Task
13872          * management commands are completed above.
13873          *
13874          * We only send status to the other controller if we're in XFER
13875          * mode.  In SER_ONLY mode, the I/O is done on the controller that
13876          * received the I/O (from CTL's perspective), and so the status is
13877          * generated there.
13878          * 
13879          * XXX KDM if we hold the lock here, we could cause a deadlock
13880          * if the frontend comes back in in this context to queue
13881          * something.
13882          */
13883         if ((softc->ha_mode == CTL_HA_MODE_XFER)
13884          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13885                 union ctl_ha_msg msg;
13886
13887                 memset(&msg, 0, sizeof(msg));
13888                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13889                 msg.hdr.original_sc = io->io_hdr.original_sc;
13890                 msg.hdr.nexus = io->io_hdr.nexus;
13891                 msg.hdr.status = io->io_hdr.status;
13892                 msg.scsi.scsi_status = io->scsiio.scsi_status;
13893                 msg.scsi.tag_num = io->scsiio.tag_num;
13894                 msg.scsi.tag_type = io->scsiio.tag_type;
13895                 msg.scsi.sense_len = io->scsiio.sense_len;
13896                 msg.scsi.sense_residual = io->scsiio.sense_residual;
13897                 msg.scsi.residual = io->scsiio.residual;
13898                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13899                        sizeof(io->scsiio.sense_data));
13900                 /*
13901                  * We copy this whether or not this is an I/O-related
13902                  * command.  Otherwise, we'd have to go and check to see
13903                  * whether it's a read/write command, and it really isn't
13904                  * worth it.
13905                  */
13906                 memcpy(&msg.scsi.lbalen,
13907                        &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13908                        sizeof(msg.scsi.lbalen));
13909
13910                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13911                                 sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13912                         /* XXX do something here */
13913                 }
13914
13915                 ctl_free_io(io);
13916         } else 
13917                 fe_done(io);
13918
13919         return (CTL_RETVAL_COMPLETE);
13920 }
13921
13922 #ifdef CTL_WITH_CA
13923 /*
13924  * Front end should call this if it doesn't do autosense.  When the request
13925  * sense comes back in from the initiator, we'll dequeue this and send it.
13926  */
13927 int
13928 ctl_queue_sense(union ctl_io *io)
13929 {
13930         struct ctl_lun *lun;
13931         struct ctl_port *port;
13932         struct ctl_softc *softc;
13933         uint32_t initidx, targ_lun;
13934
13935         softc = control_softc;
13936
13937         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13938
13939         /*
13940          * LUN lookup will likely move to the ctl_work_thread() once we
13941          * have our new queueing infrastructure (that doesn't put things on
13942          * a per-LUN queue initially).  That is so that we can handle
13943          * things like an INQUIRY to a LUN that we don't have enabled.  We
13944          * can't deal with that right now.
13945          */
13946         mtx_lock(&softc->ctl_lock);
13947
13948         /*
13949          * If we don't have a LUN for this, just toss the sense
13950          * information.
13951          */
13952         port = ctl_io_port(&ctsio->io_hdr);
13953         targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13954         if ((targ_lun < CTL_MAX_LUNS)
13955          && (softc->ctl_luns[targ_lun] != NULL))
13956                 lun = softc->ctl_luns[targ_lun];
13957         else
13958                 goto bailout;
13959
13960         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13961
13962         mtx_lock(&lun->lun_lock);
13963         /*
13964          * Already have CA set for this LUN...toss the sense information.
13965          */
13966         if (ctl_is_set(lun->have_ca, initidx)) {
13967                 mtx_unlock(&lun->lun_lock);
13968                 goto bailout;
13969         }
13970
13971         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13972                MIN(sizeof(lun->pending_sense[initidx]),
13973                sizeof(io->scsiio.sense_data)));
13974         ctl_set_mask(lun->have_ca, initidx);
13975         mtx_unlock(&lun->lun_lock);
13976
13977 bailout:
13978         mtx_unlock(&softc->ctl_lock);
13979
13980         ctl_free_io(io);
13981
13982         return (CTL_RETVAL_COMPLETE);
13983 }
13984 #endif
13985
13986 /*
13987  * Primary command inlet from frontend ports.  All SCSI and task I/O
13988  * requests must go through this function.
13989  */
13990 int
13991 ctl_queue(union ctl_io *io)
13992 {
13993         struct ctl_port *port;
13994
13995         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13996
13997 #ifdef CTL_TIME_IO
13998         io->io_hdr.start_time = time_uptime;
13999         getbintime(&io->io_hdr.start_bt);
14000 #endif /* CTL_TIME_IO */
14001
14002         /* Map FE-specific LUN ID into global one. */
14003         port = ctl_io_port(&io->io_hdr);
14004         io->io_hdr.nexus.targ_mapped_lun =
14005             ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
14006
14007         switch (io->io_hdr.io_type) {
14008         case CTL_IO_SCSI:
14009         case CTL_IO_TASK:
14010                 if (ctl_debug & CTL_DEBUG_CDB)
14011                         ctl_io_print(io);
14012                 ctl_enqueue_incoming(io);
14013                 break;
14014         default:
14015                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
14016                 return (EINVAL);
14017         }
14018
14019         return (CTL_RETVAL_COMPLETE);
14020 }
14021
14022 #ifdef CTL_IO_DELAY
14023 static void
14024 ctl_done_timer_wakeup(void *arg)
14025 {
14026         union ctl_io *io;
14027
14028         io = (union ctl_io *)arg;
14029         ctl_done(io);
14030 }
14031 #endif /* CTL_IO_DELAY */
14032
14033 void
14034 ctl_done(union ctl_io *io)
14035 {
14036
14037         /*
14038          * Enable this to catch duplicate completion issues.
14039          */
14040 #if 0
14041         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
14042                 printf("%s: type %d msg %d cdb %x iptl: "
14043                        "%d:%d:%d:%d tag 0x%04x "
14044                        "flag %#x status %x\n",
14045                         __func__,
14046                         io->io_hdr.io_type,
14047                         io->io_hdr.msg_type,
14048                         io->scsiio.cdb[0],
14049                         io->io_hdr.nexus.initid.id,
14050                         io->io_hdr.nexus.targ_port,
14051                         io->io_hdr.nexus.targ_target.id,
14052                         io->io_hdr.nexus.targ_lun,
14053                         (io->io_hdr.io_type ==
14054                         CTL_IO_TASK) ?
14055                         io->taskio.tag_num :
14056                         io->scsiio.tag_num,
14057                         io->io_hdr.flags,
14058                         io->io_hdr.status);
14059         } else
14060                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
14061 #endif
14062
14063         /*
14064          * This is an internal copy of an I/O, and should not go through
14065          * the normal done processing logic.
14066          */
14067         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
14068                 return;
14069
14070         /*
14071          * We need to send a msg to the serializing shelf to finish the IO
14072          * as well.  We don't send a finish message to the other shelf if
14073          * this is a task management command.  Task management commands
14074          * aren't serialized in the OOA queue, but rather just executed on
14075          * both shelf controllers for commands that originated on that
14076          * controller.
14077          */
14078         if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
14079          && (io->io_hdr.io_type != CTL_IO_TASK)) {
14080                 union ctl_ha_msg msg_io;
14081
14082                 msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
14083                 msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
14084                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
14085                     sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
14086                 }
14087                 /* continue on to finish IO */
14088         }
14089 #ifdef CTL_IO_DELAY
14090         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
14091                 struct ctl_lun *lun;
14092
14093                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14094
14095                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
14096         } else {
14097                 struct ctl_lun *lun;
14098
14099                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14100
14101                 if ((lun != NULL)
14102                  && (lun->delay_info.done_delay > 0)) {
14103                         struct callout *callout;
14104
14105                         callout = (struct callout *)&io->io_hdr.timer_bytes;
14106                         callout_init(callout, /*mpsafe*/ 1);
14107                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
14108                         callout_reset(callout,
14109                                       lun->delay_info.done_delay * hz,
14110                                       ctl_done_timer_wakeup, io);
14111                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
14112                                 lun->delay_info.done_delay = 0;
14113                         return;
14114                 }
14115         }
14116 #endif /* CTL_IO_DELAY */
14117
14118         ctl_enqueue_done(io);
14119 }
14120
14121 int
14122 ctl_isc(struct ctl_scsiio *ctsio)
14123 {
14124         struct ctl_lun *lun;
14125         int retval;
14126
14127         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14128
14129         CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
14130
14131         CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
14132
14133         retval = lun->backend->data_submit((union ctl_io *)ctsio);
14134
14135         return (retval);
14136 }
14137
14138
14139 static void
14140 ctl_work_thread(void *arg)
14141 {
14142         struct ctl_thread *thr = (struct ctl_thread *)arg;
14143         struct ctl_softc *softc = thr->ctl_softc;
14144         union ctl_io *io;
14145         int retval;
14146
14147         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
14148
14149         for (;;) {
14150                 retval = 0;
14151
14152                 /*
14153                  * We handle the queues in this order:
14154                  * - ISC
14155                  * - done queue (to free up resources, unblock other commands)
14156                  * - RtR queue
14157                  * - incoming queue
14158                  *
14159                  * If those queues are empty, we break out of the loop and
14160                  * go to sleep.
14161                  */
14162                 mtx_lock(&thr->queue_lock);
14163                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
14164                 if (io != NULL) {
14165                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
14166                         mtx_unlock(&thr->queue_lock);
14167                         ctl_handle_isc(io);
14168                         continue;
14169                 }
14170                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
14171                 if (io != NULL) {
14172                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
14173                         /* clear any blocked commands, call fe_done */
14174                         mtx_unlock(&thr->queue_lock);
14175                         retval = ctl_process_done(io);
14176                         continue;
14177                 }
14178                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
14179                 if (io != NULL) {
14180                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
14181                         mtx_unlock(&thr->queue_lock);
14182                         if (io->io_hdr.io_type == CTL_IO_TASK)
14183                                 ctl_run_task(io);
14184                         else
14185                                 ctl_scsiio_precheck(softc, &io->scsiio);
14186                         continue;
14187                 }
14188                 if (!ctl_pause_rtr) {
14189                         io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
14190                         if (io != NULL) {
14191                                 STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
14192                                 mtx_unlock(&thr->queue_lock);
14193                                 retval = ctl_scsiio(&io->scsiio);
14194                                 if (retval != CTL_RETVAL_COMPLETE)
14195                                         CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
14196                                 continue;
14197                         }
14198                 }
14199
14200                 /* Sleep until we have something to do. */
14201                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
14202         }
14203 }
14204
14205 static void
14206 ctl_lun_thread(void *arg)
14207 {
14208         struct ctl_softc *softc = (struct ctl_softc *)arg;
14209         struct ctl_be_lun *be_lun;
14210         int retval;
14211
14212         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
14213
14214         for (;;) {
14215                 retval = 0;
14216                 mtx_lock(&softc->ctl_lock);
14217                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
14218                 if (be_lun != NULL) {
14219                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
14220                         mtx_unlock(&softc->ctl_lock);
14221                         ctl_create_lun(be_lun);
14222                         continue;
14223                 }
14224
14225                 /* Sleep until we have something to do. */
14226                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
14227                     PDROP | PRIBIO, "-", 0);
14228         }
14229 }
14230
14231 static void
14232 ctl_thresh_thread(void *arg)
14233 {
14234         struct ctl_softc *softc = (struct ctl_softc *)arg;
14235         struct ctl_lun *lun;
14236         struct ctl_be_lun *be_lun;
14237         struct scsi_da_rw_recovery_page *rwpage;
14238         struct ctl_logical_block_provisioning_page *page;
14239         const char *attr;
14240         uint64_t thres, val;
14241         int i, e;
14242
14243         CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
14244
14245         for (;;) {
14246                 mtx_lock(&softc->ctl_lock);
14247                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
14248                         be_lun = lun->be_lun;
14249                         if ((lun->flags & CTL_LUN_DISABLED) ||
14250                             (lun->flags & CTL_LUN_OFFLINE) ||
14251                             lun->backend->lun_attr == NULL)
14252                                 continue;
14253                         rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
14254                         if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
14255                                 continue;
14256                         e = 0;
14257                         page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
14258                         for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
14259                                 if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
14260                                         continue;
14261                                 thres = scsi_4btoul(page->descr[i].count);
14262                                 thres <<= CTL_LBP_EXPONENT;
14263                                 switch (page->descr[i].resource) {
14264                                 case 0x01:
14265                                         attr = "blocksavail";
14266                                         break;
14267                                 case 0x02:
14268                                         attr = "blocksused";
14269                                         break;
14270                                 case 0xf1:
14271                                         attr = "poolblocksavail";
14272                                         break;
14273                                 case 0xf2:
14274                                         attr = "poolblocksused";
14275                                         break;
14276                                 default:
14277                                         continue;
14278                                 }
14279                                 mtx_unlock(&softc->ctl_lock); // XXX
14280                                 val = lun->backend->lun_attr(
14281                                     lun->be_lun->be_lun, attr);
14282                                 mtx_lock(&softc->ctl_lock);
14283                                 if (val == UINT64_MAX)
14284                                         continue;
14285                                 if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
14286                                     == SLBPPD_ARMING_INC)
14287                                         e |= (val >= thres);
14288                                 else
14289                                         e |= (val <= thres);
14290                         }
14291                         mtx_lock(&lun->lun_lock);
14292                         if (e) {
14293                                 if (lun->lasttpt == 0 ||
14294                                     time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
14295                                         lun->lasttpt = time_uptime;
14296                                         ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14297                                 }
14298                         } else {
14299                                 lun->lasttpt = 0;
14300                                 ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14301                         }
14302                         mtx_unlock(&lun->lun_lock);
14303                 }
14304                 mtx_unlock(&softc->ctl_lock);
14305                 pause("-", CTL_LBP_PERIOD * hz);
14306         }
14307 }
14308
14309 static void
14310 ctl_enqueue_incoming(union ctl_io *io)
14311 {
14312         struct ctl_softc *softc = control_softc;
14313         struct ctl_thread *thr;
14314         u_int idx;
14315
14316         idx = (io->io_hdr.nexus.targ_port * 127 +
14317                io->io_hdr.nexus.initid.id) % worker_threads;
14318         thr = &softc->threads[idx];
14319         mtx_lock(&thr->queue_lock);
14320         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14321         mtx_unlock(&thr->queue_lock);
14322         wakeup(thr);
14323 }
14324
14325 static void
14326 ctl_enqueue_rtr(union ctl_io *io)
14327 {
14328         struct ctl_softc *softc = control_softc;
14329         struct ctl_thread *thr;
14330
14331         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14332         mtx_lock(&thr->queue_lock);
14333         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14334         mtx_unlock(&thr->queue_lock);
14335         wakeup(thr);
14336 }
14337
14338 static void
14339 ctl_enqueue_done(union ctl_io *io)
14340 {
14341         struct ctl_softc *softc = control_softc;
14342         struct ctl_thread *thr;
14343
14344         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14345         mtx_lock(&thr->queue_lock);
14346         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14347         mtx_unlock(&thr->queue_lock);
14348         wakeup(thr);
14349 }
14350
14351 static void
14352 ctl_enqueue_isc(union ctl_io *io)
14353 {
14354         struct ctl_softc *softc = control_softc;
14355         struct ctl_thread *thr;
14356
14357         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14358         mtx_lock(&thr->queue_lock);
14359         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14360         mtx_unlock(&thr->queue_lock);
14361         wakeup(thr);
14362 }
14363
14364 /* Initialization and failover */
14365
14366 void
14367 ctl_init_isc_msg(void)
14368 {
14369         printf("CTL: Still calling this thing\n");
14370 }
14371
14372 /*
14373  * Init component
14374  *      Initializes component into configuration defined by bootMode
14375  *      (see hasc-sv.c)
14376  *      returns hasc_Status:
14377  *              OK
14378  *              ERROR - fatal error
14379  */
14380 static ctl_ha_comp_status
14381 ctl_isc_init(struct ctl_ha_component *c)
14382 {
14383         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14384
14385         c->status = ret;
14386         return ret;
14387 }
14388
14389 /* Start component
14390  *      Starts component in state requested. If component starts successfully,
14391  *      it must set its own state to the requestrd state
14392  *      When requested state is HASC_STATE_HA, the component may refine it
14393  *      by adding _SLAVE or _MASTER flags.
14394  *      Currently allowed state transitions are:
14395  *      UNKNOWN->HA             - initial startup
14396  *      UNKNOWN->SINGLE - initial startup when no parter detected
14397  *      HA->SINGLE              - failover
14398  * returns ctl_ha_comp_status:
14399  *              OK      - component successfully started in requested state
14400  *              FAILED  - could not start the requested state, failover may
14401  *                        be possible
14402  *              ERROR   - fatal error detected, no future startup possible
14403  */
14404 static ctl_ha_comp_status
14405 ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14406 {
14407         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14408
14409         printf("%s: go\n", __func__);
14410
14411         // UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14412         if (c->state == CTL_HA_STATE_UNKNOWN ) {
14413                 control_softc->is_single = 0;
14414                 if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14415                     != CTL_HA_STATUS_SUCCESS) {
14416                         printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14417                         ret = CTL_HA_COMP_STATUS_ERROR;
14418                 }
14419         } else if (CTL_HA_STATE_IS_HA(c->state)
14420                 && CTL_HA_STATE_IS_SINGLE(state)){
14421                 // HA->SINGLE transition
14422                 ctl_failover();
14423                 control_softc->is_single = 1;
14424         } else {
14425                 printf("ctl_isc_start:Invalid state transition %X->%X\n",
14426                        c->state, state);
14427                 ret = CTL_HA_COMP_STATUS_ERROR;
14428         }
14429         if (CTL_HA_STATE_IS_SINGLE(state))
14430                 control_softc->is_single = 1;
14431
14432         c->state = state;
14433         c->status = ret;
14434         return ret;
14435 }
14436
14437 /*
14438  * Quiesce component
14439  * The component must clear any error conditions (set status to OK) and
14440  * prepare itself to another Start call
14441  * returns ctl_ha_comp_status:
14442  *      OK
14443  *      ERROR
14444  */
14445 static ctl_ha_comp_status
14446 ctl_isc_quiesce(struct ctl_ha_component *c)
14447 {
14448         int ret = CTL_HA_COMP_STATUS_OK;
14449
14450         ctl_pause_rtr = 1;
14451         c->status = ret;
14452         return ret;
14453 }
14454
14455 struct ctl_ha_component ctl_ha_component_ctlisc =
14456 {
14457         .name = "CTL ISC",
14458         .state = CTL_HA_STATE_UNKNOWN,
14459         .init = ctl_isc_init,
14460         .start = ctl_isc_start,
14461         .quiesce = ctl_isc_quiesce
14462 };
14463
14464 /*
14465  *  vim: ts=8
14466  */