]> CyberLeo.Net >> Repos - FreeBSD/releng/10.2.git/blob - sys/cam/ctl/ctl.c
- Copy stable/10@285827 to releng/10.2 in preparation for 10.2-RC1
[FreeBSD/releng/10.2.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, int lun_id);
389 static int ctl_ioctl_lun_disable(void *arg, 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);
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         STAILQ_INIT(&softc->lun_list);
1134         STAILQ_INIT(&softc->pending_lun_queue);
1135         STAILQ_INIT(&softc->fe_list);
1136         STAILQ_INIT(&softc->port_list);
1137         STAILQ_INIT(&softc->be_list);
1138         ctl_tpc_init(softc);
1139
1140         if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1141                             &other_pool) != 0)
1142         {
1143                 printf("ctl: can't allocate %d entry other SC pool, "
1144                        "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1145                 return (ENOMEM);
1146         }
1147         softc->othersc_pool = other_pool;
1148
1149         if (worker_threads <= 0)
1150                 worker_threads = max(1, mp_ncpus / 4);
1151         if (worker_threads > CTL_MAX_THREADS)
1152                 worker_threads = CTL_MAX_THREADS;
1153
1154         for (i = 0; i < worker_threads; i++) {
1155                 struct ctl_thread *thr = &softc->threads[i];
1156
1157                 mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1158                 thr->ctl_softc = softc;
1159                 STAILQ_INIT(&thr->incoming_queue);
1160                 STAILQ_INIT(&thr->rtr_queue);
1161                 STAILQ_INIT(&thr->done_queue);
1162                 STAILQ_INIT(&thr->isc_queue);
1163
1164                 error = kproc_kthread_add(ctl_work_thread, thr,
1165                     &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1166                 if (error != 0) {
1167                         printf("error creating CTL work thread!\n");
1168                         ctl_pool_free(other_pool);
1169                         return (error);
1170                 }
1171         }
1172         error = kproc_kthread_add(ctl_lun_thread, softc,
1173             &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1174         if (error != 0) {
1175                 printf("error creating CTL lun thread!\n");
1176                 ctl_pool_free(other_pool);
1177                 return (error);
1178         }
1179         error = kproc_kthread_add(ctl_thresh_thread, softc,
1180             &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1181         if (error != 0) {
1182                 printf("error creating CTL threshold thread!\n");
1183                 ctl_pool_free(other_pool);
1184                 return (error);
1185         }
1186         if (bootverbose)
1187                 printf("ctl: CAM Target Layer loaded\n");
1188
1189         /*
1190          * Initialize the ioctl front end.
1191          */
1192         ctl_frontend_register(&ioctl_frontend);
1193         port = &softc->ioctl_info.port;
1194         port->frontend = &ioctl_frontend;
1195         sprintf(softc->ioctl_info.port_name, "ioctl");
1196         port->port_type = CTL_PORT_IOCTL;
1197         port->num_requested_ctl_io = 100;
1198         port->port_name = softc->ioctl_info.port_name;
1199         port->port_online = ctl_ioctl_online;
1200         port->port_offline = ctl_ioctl_offline;
1201         port->onoff_arg = &softc->ioctl_info;
1202         port->lun_enable = ctl_ioctl_lun_enable;
1203         port->lun_disable = ctl_ioctl_lun_disable;
1204         port->targ_lun_arg = &softc->ioctl_info;
1205         port->fe_datamove = ctl_ioctl_datamove;
1206         port->fe_done = ctl_ioctl_done;
1207         port->max_targets = 15;
1208         port->max_target_id = 15;
1209
1210         if (ctl_port_register(&softc->ioctl_info.port) != 0) {
1211                 printf("ctl: ioctl front end registration failed, will "
1212                        "continue anyway\n");
1213         }
1214
1215         SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1216             OID_AUTO, "ha_state", CTLTYPE_INT | CTLFLAG_RWTUN,
1217             softc, 0, ctl_ha_state_sysctl, "I", "HA state for this head");
1218
1219 #ifdef CTL_IO_DELAY
1220         if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1221                 printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1222                        sizeof(struct callout), CTL_TIMER_BYTES);
1223                 return (EINVAL);
1224         }
1225 #endif /* CTL_IO_DELAY */
1226
1227         return (0);
1228 }
1229
1230 void
1231 ctl_shutdown(void)
1232 {
1233         struct ctl_softc *softc;
1234         struct ctl_lun *lun, *next_lun;
1235
1236         softc = (struct ctl_softc *)control_softc;
1237
1238         if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1239                 printf("ctl: ioctl front end deregistration failed\n");
1240
1241         mtx_lock(&softc->ctl_lock);
1242
1243         /*
1244          * Free up each LUN.
1245          */
1246         for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1247                 next_lun = STAILQ_NEXT(lun, links);
1248                 ctl_free_lun(lun);
1249         }
1250
1251         mtx_unlock(&softc->ctl_lock);
1252
1253         ctl_frontend_deregister(&ioctl_frontend);
1254
1255 #if 0
1256         ctl_shutdown_thread(softc->work_thread);
1257         mtx_destroy(&softc->queue_lock);
1258 #endif
1259
1260         ctl_tpc_shutdown(softc);
1261         uma_zdestroy(softc->io_zone);
1262         mtx_destroy(&softc->ctl_lock);
1263
1264         destroy_dev(softc->dev);
1265
1266         sysctl_ctx_free(&softc->sysctl_ctx);
1267
1268         free(control_softc, M_DEVBUF);
1269         control_softc = NULL;
1270
1271         if (bootverbose)
1272                 printf("ctl: CAM Target Layer unloaded\n");
1273 }
1274
1275 static int
1276 ctl_module_event_handler(module_t mod, int what, void *arg)
1277 {
1278
1279         switch (what) {
1280         case MOD_LOAD:
1281                 return (ctl_init());
1282         case MOD_UNLOAD:
1283                 return (EBUSY);
1284         default:
1285                 return (EOPNOTSUPP);
1286         }
1287 }
1288
1289 /*
1290  * XXX KDM should we do some access checks here?  Bump a reference count to
1291  * prevent a CTL module from being unloaded while someone has it open?
1292  */
1293 static int
1294 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1295 {
1296         return (0);
1297 }
1298
1299 static int
1300 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1301 {
1302         return (0);
1303 }
1304
1305 int
1306 ctl_port_enable(ctl_port_type port_type)
1307 {
1308         struct ctl_softc *softc = control_softc;
1309         struct ctl_port *port;
1310
1311         if (softc->is_single == 0) {
1312                 union ctl_ha_msg msg_info;
1313                 int isc_retval;
1314
1315 #if 0
1316                 printf("%s: HA mode, synchronizing frontend enable\n",
1317                         __func__);
1318 #endif
1319                 msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1320                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1321                         sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1322                         printf("Sync msg send error retval %d\n", isc_retval);
1323                 }
1324                 if (!rcv_sync_msg) {
1325                         isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1326                                 sizeof(msg_info), 1);
1327                 }
1328 #if 0
1329                 printf("CTL:Frontend Enable\n");
1330         } else {
1331                 printf("%s: single mode, skipping frontend synchronization\n",
1332                         __func__);
1333 #endif
1334         }
1335
1336         STAILQ_FOREACH(port, &softc->port_list, links) {
1337                 if (port_type & port->port_type)
1338                 {
1339 #if 0
1340                         printf("port %d\n", port->targ_port);
1341 #endif
1342                         ctl_port_online(port);
1343                 }
1344         }
1345
1346         return (0);
1347 }
1348
1349 int
1350 ctl_port_disable(ctl_port_type port_type)
1351 {
1352         struct ctl_softc *softc;
1353         struct ctl_port *port;
1354
1355         softc = control_softc;
1356
1357         STAILQ_FOREACH(port, &softc->port_list, links) {
1358                 if (port_type & port->port_type)
1359                         ctl_port_offline(port);
1360         }
1361
1362         return (0);
1363 }
1364
1365 /*
1366  * Returns 0 for success, 1 for failure.
1367  * Currently the only failure mode is if there aren't enough entries
1368  * allocated.  So, in case of a failure, look at num_entries_dropped,
1369  * reallocate and try again.
1370  */
1371 int
1372 ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1373               int *num_entries_filled, int *num_entries_dropped,
1374               ctl_port_type port_type, int no_virtual)
1375 {
1376         struct ctl_softc *softc;
1377         struct ctl_port *port;
1378         int entries_dropped, entries_filled;
1379         int retval;
1380         int i;
1381
1382         softc = control_softc;
1383
1384         retval = 0;
1385         entries_filled = 0;
1386         entries_dropped = 0;
1387
1388         i = 0;
1389         mtx_lock(&softc->ctl_lock);
1390         STAILQ_FOREACH(port, &softc->port_list, links) {
1391                 struct ctl_port_entry *entry;
1392
1393                 if ((port->port_type & port_type) == 0)
1394                         continue;
1395
1396                 if ((no_virtual != 0)
1397                  && (port->virtual_port != 0))
1398                         continue;
1399
1400                 if (entries_filled >= num_entries_alloced) {
1401                         entries_dropped++;
1402                         continue;
1403                 }
1404                 entry = &entries[i];
1405
1406                 entry->port_type = port->port_type;
1407                 strlcpy(entry->port_name, port->port_name,
1408                         sizeof(entry->port_name));
1409                 entry->physical_port = port->physical_port;
1410                 entry->virtual_port = port->virtual_port;
1411                 entry->wwnn = port->wwnn;
1412                 entry->wwpn = port->wwpn;
1413
1414                 i++;
1415                 entries_filled++;
1416         }
1417
1418         mtx_unlock(&softc->ctl_lock);
1419
1420         if (entries_dropped > 0)
1421                 retval = 1;
1422
1423         *num_entries_dropped = entries_dropped;
1424         *num_entries_filled = entries_filled;
1425
1426         return (retval);
1427 }
1428
1429 static void
1430 ctl_ioctl_online(void *arg)
1431 {
1432         struct ctl_ioctl_info *ioctl_info;
1433
1434         ioctl_info = (struct ctl_ioctl_info *)arg;
1435
1436         ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1437 }
1438
1439 static void
1440 ctl_ioctl_offline(void *arg)
1441 {
1442         struct ctl_ioctl_info *ioctl_info;
1443
1444         ioctl_info = (struct ctl_ioctl_info *)arg;
1445
1446         ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1447 }
1448
1449 /*
1450  * Remove an initiator by port number and initiator ID.
1451  * Returns 0 for success, -1 for failure.
1452  */
1453 int
1454 ctl_remove_initiator(struct ctl_port *port, int iid)
1455 {
1456         struct ctl_softc *softc = control_softc;
1457
1458         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1459
1460         if (iid > CTL_MAX_INIT_PER_PORT) {
1461                 printf("%s: initiator ID %u > maximun %u!\n",
1462                        __func__, iid, CTL_MAX_INIT_PER_PORT);
1463                 return (-1);
1464         }
1465
1466         mtx_lock(&softc->ctl_lock);
1467         port->wwpn_iid[iid].in_use--;
1468         port->wwpn_iid[iid].last_use = time_uptime;
1469         mtx_unlock(&softc->ctl_lock);
1470
1471         return (0);
1472 }
1473
1474 /*
1475  * Add an initiator to the initiator map.
1476  * Returns iid for success, < 0 for failure.
1477  */
1478 int
1479 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1480 {
1481         struct ctl_softc *softc = control_softc;
1482         time_t best_time;
1483         int i, best;
1484
1485         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1486
1487         if (iid >= CTL_MAX_INIT_PER_PORT) {
1488                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1489                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1490                 free(name, M_CTL);
1491                 return (-1);
1492         }
1493
1494         mtx_lock(&softc->ctl_lock);
1495
1496         if (iid < 0 && (wwpn != 0 || name != NULL)) {
1497                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1498                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1499                                 iid = i;
1500                                 break;
1501                         }
1502                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
1503                             strcmp(name, port->wwpn_iid[i].name) == 0) {
1504                                 iid = i;
1505                                 break;
1506                         }
1507                 }
1508         }
1509
1510         if (iid < 0) {
1511                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1512                         if (port->wwpn_iid[i].in_use == 0 &&
1513                             port->wwpn_iid[i].wwpn == 0 &&
1514                             port->wwpn_iid[i].name == NULL) {
1515                                 iid = i;
1516                                 break;
1517                         }
1518                 }
1519         }
1520
1521         if (iid < 0) {
1522                 best = -1;
1523                 best_time = INT32_MAX;
1524                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1525                         if (port->wwpn_iid[i].in_use == 0) {
1526                                 if (port->wwpn_iid[i].last_use < best_time) {
1527                                         best = i;
1528                                         best_time = port->wwpn_iid[i].last_use;
1529                                 }
1530                         }
1531                 }
1532                 iid = best;
1533         }
1534
1535         if (iid < 0) {
1536                 mtx_unlock(&softc->ctl_lock);
1537                 free(name, M_CTL);
1538                 return (-2);
1539         }
1540
1541         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1542                 /*
1543                  * This is not an error yet.
1544                  */
1545                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1546 #if 0
1547                         printf("%s: port %d iid %u WWPN %#jx arrived"
1548                             " again\n", __func__, port->targ_port,
1549                             iid, (uintmax_t)wwpn);
1550 #endif
1551                         goto take;
1552                 }
1553                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1554                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
1555 #if 0
1556                         printf("%s: port %d iid %u name '%s' arrived"
1557                             " again\n", __func__, port->targ_port,
1558                             iid, name);
1559 #endif
1560                         goto take;
1561                 }
1562
1563                 /*
1564                  * This is an error, but what do we do about it?  The
1565                  * driver is telling us we have a new WWPN for this
1566                  * initiator ID, so we pretty much need to use it.
1567                  */
1568                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1569                     " but WWPN %#jx '%s' is still at that address\n",
1570                     __func__, port->targ_port, iid, wwpn, name,
1571                     (uintmax_t)port->wwpn_iid[iid].wwpn,
1572                     port->wwpn_iid[iid].name);
1573
1574                 /*
1575                  * XXX KDM clear have_ca and ua_pending on each LUN for
1576                  * this initiator.
1577                  */
1578         }
1579 take:
1580         free(port->wwpn_iid[iid].name, M_CTL);
1581         port->wwpn_iid[iid].name = name;
1582         port->wwpn_iid[iid].wwpn = wwpn;
1583         port->wwpn_iid[iid].in_use++;
1584         mtx_unlock(&softc->ctl_lock);
1585
1586         return (iid);
1587 }
1588
1589 static int
1590 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1591 {
1592         int len;
1593
1594         switch (port->port_type) {
1595         case CTL_PORT_FC:
1596         {
1597                 struct scsi_transportid_fcp *id =
1598                     (struct scsi_transportid_fcp *)buf;
1599                 if (port->wwpn_iid[iid].wwpn == 0)
1600                         return (0);
1601                 memset(id, 0, sizeof(*id));
1602                 id->format_protocol = SCSI_PROTO_FC;
1603                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1604                 return (sizeof(*id));
1605         }
1606         case CTL_PORT_ISCSI:
1607         {
1608                 struct scsi_transportid_iscsi_port *id =
1609                     (struct scsi_transportid_iscsi_port *)buf;
1610                 if (port->wwpn_iid[iid].name == NULL)
1611                         return (0);
1612                 memset(id, 0, 256);
1613                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1614                     SCSI_PROTO_ISCSI;
1615                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1616                 len = roundup2(min(len, 252), 4);
1617                 scsi_ulto2b(len, id->additional_length);
1618                 return (sizeof(*id) + len);
1619         }
1620         case CTL_PORT_SAS:
1621         {
1622                 struct scsi_transportid_sas *id =
1623                     (struct scsi_transportid_sas *)buf;
1624                 if (port->wwpn_iid[iid].wwpn == 0)
1625                         return (0);
1626                 memset(id, 0, sizeof(*id));
1627                 id->format_protocol = SCSI_PROTO_SAS;
1628                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1629                 return (sizeof(*id));
1630         }
1631         default:
1632         {
1633                 struct scsi_transportid_spi *id =
1634                     (struct scsi_transportid_spi *)buf;
1635                 memset(id, 0, sizeof(*id));
1636                 id->format_protocol = SCSI_PROTO_SPI;
1637                 scsi_ulto2b(iid, id->scsi_addr);
1638                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1639                 return (sizeof(*id));
1640         }
1641         }
1642 }
1643
1644 static int
1645 ctl_ioctl_lun_enable(void *arg, int lun_id)
1646 {
1647         return (0);
1648 }
1649
1650 static int
1651 ctl_ioctl_lun_disable(void *arg, int lun_id)
1652 {
1653         return (0);
1654 }
1655
1656 /*
1657  * Data movement routine for the CTL ioctl frontend port.
1658  */
1659 static int
1660 ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1661 {
1662         struct ctl_sg_entry *ext_sglist, *kern_sglist;
1663         struct ctl_sg_entry ext_entry, kern_entry;
1664         int ext_sglen, ext_sg_entries, kern_sg_entries;
1665         int ext_sg_start, ext_offset;
1666         int len_to_copy, len_copied;
1667         int kern_watermark, ext_watermark;
1668         int ext_sglist_malloced;
1669         int i, j;
1670
1671         ext_sglist_malloced = 0;
1672         ext_sg_start = 0;
1673         ext_offset = 0;
1674
1675         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1676
1677         /*
1678          * If this flag is set, fake the data transfer.
1679          */
1680         if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1681                 ctsio->ext_data_filled = ctsio->ext_data_len;
1682                 goto bailout;
1683         }
1684
1685         /*
1686          * To simplify things here, if we have a single buffer, stick it in
1687          * a S/G entry and just make it a single entry S/G list.
1688          */
1689         if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1690                 int len_seen;
1691
1692                 ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1693
1694                 ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1695                                                            M_WAITOK);
1696                 ext_sglist_malloced = 1;
1697                 if (copyin(ctsio->ext_data_ptr, ext_sglist,
1698                                    ext_sglen) != 0) {
1699                         ctl_set_internal_failure(ctsio,
1700                                                  /*sks_valid*/ 0,
1701                                                  /*retry_count*/ 0);
1702                         goto bailout;
1703                 }
1704                 ext_sg_entries = ctsio->ext_sg_entries;
1705                 len_seen = 0;
1706                 for (i = 0; i < ext_sg_entries; i++) {
1707                         if ((len_seen + ext_sglist[i].len) >=
1708                              ctsio->ext_data_filled) {
1709                                 ext_sg_start = i;
1710                                 ext_offset = ctsio->ext_data_filled - len_seen;
1711                                 break;
1712                         }
1713                         len_seen += ext_sglist[i].len;
1714                 }
1715         } else {
1716                 ext_sglist = &ext_entry;
1717                 ext_sglist->addr = ctsio->ext_data_ptr;
1718                 ext_sglist->len = ctsio->ext_data_len;
1719                 ext_sg_entries = 1;
1720                 ext_sg_start = 0;
1721                 ext_offset = ctsio->ext_data_filled;
1722         }
1723
1724         if (ctsio->kern_sg_entries > 0) {
1725                 kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1726                 kern_sg_entries = ctsio->kern_sg_entries;
1727         } else {
1728                 kern_sglist = &kern_entry;
1729                 kern_sglist->addr = ctsio->kern_data_ptr;
1730                 kern_sglist->len = ctsio->kern_data_len;
1731                 kern_sg_entries = 1;
1732         }
1733
1734
1735         kern_watermark = 0;
1736         ext_watermark = ext_offset;
1737         len_copied = 0;
1738         for (i = ext_sg_start, j = 0;
1739              i < ext_sg_entries && j < kern_sg_entries;) {
1740                 uint8_t *ext_ptr, *kern_ptr;
1741
1742                 len_to_copy = MIN(ext_sglist[i].len - ext_watermark,
1743                                   kern_sglist[j].len - kern_watermark);
1744
1745                 ext_ptr = (uint8_t *)ext_sglist[i].addr;
1746                 ext_ptr = ext_ptr + ext_watermark;
1747                 if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1748                         /*
1749                          * XXX KDM fix this!
1750                          */
1751                         panic("need to implement bus address support");
1752 #if 0
1753                         kern_ptr = bus_to_virt(kern_sglist[j].addr);
1754 #endif
1755                 } else
1756                         kern_ptr = (uint8_t *)kern_sglist[j].addr;
1757                 kern_ptr = kern_ptr + kern_watermark;
1758
1759                 kern_watermark += len_to_copy;
1760                 ext_watermark += len_to_copy;
1761
1762                 if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1763                      CTL_FLAG_DATA_IN) {
1764                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1765                                          "bytes to user\n", len_to_copy));
1766                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1767                                          "to %p\n", kern_ptr, ext_ptr));
1768                         if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1769                                 ctl_set_internal_failure(ctsio,
1770                                                          /*sks_valid*/ 0,
1771                                                          /*retry_count*/ 0);
1772                                 goto bailout;
1773                         }
1774                 } else {
1775                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1776                                          "bytes from user\n", len_to_copy));
1777                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1778                                          "to %p\n", ext_ptr, kern_ptr));
1779                         if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1780                                 ctl_set_internal_failure(ctsio,
1781                                                          /*sks_valid*/ 0,
1782                                                          /*retry_count*/0);
1783                                 goto bailout;
1784                         }
1785                 }
1786
1787                 len_copied += len_to_copy;
1788
1789                 if (ext_sglist[i].len == ext_watermark) {
1790                         i++;
1791                         ext_watermark = 0;
1792                 }
1793
1794                 if (kern_sglist[j].len == kern_watermark) {
1795                         j++;
1796                         kern_watermark = 0;
1797                 }
1798         }
1799
1800         ctsio->ext_data_filled += len_copied;
1801
1802         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1803                          "kern_sg_entries: %d\n", ext_sg_entries,
1804                          kern_sg_entries));
1805         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1806                          "kern_data_len = %d\n", ctsio->ext_data_len,
1807                          ctsio->kern_data_len));
1808
1809
1810         /* XXX KDM set residual?? */
1811 bailout:
1812
1813         if (ext_sglist_malloced != 0)
1814                 free(ext_sglist, M_CTL);
1815
1816         return (CTL_RETVAL_COMPLETE);
1817 }
1818
1819 /*
1820  * Serialize a command that went down the "wrong" side, and so was sent to
1821  * this controller for execution.  The logic is a little different than the
1822  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1823  * sent back to the other side, but in the success case, we execute the
1824  * command on this side (XFER mode) or tell the other side to execute it
1825  * (SER_ONLY mode).
1826  */
1827 static int
1828 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1829 {
1830         struct ctl_softc *softc;
1831         union ctl_ha_msg msg_info;
1832         struct ctl_lun *lun;
1833         int retval = 0;
1834         uint32_t targ_lun;
1835
1836         softc = control_softc;
1837
1838         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1839         lun = softc->ctl_luns[targ_lun];
1840         if (lun==NULL)
1841         {
1842                 /*
1843                  * Why isn't LUN defined? The other side wouldn't
1844                  * send a cmd if the LUN is undefined.
1845                  */
1846                 printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1847
1848                 /* "Logical unit not supported" */
1849                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1850                                    lun,
1851                                    /*sense_format*/SSD_TYPE_NONE,
1852                                    /*current_error*/ 1,
1853                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1854                                    /*asc*/ 0x25,
1855                                    /*ascq*/ 0x00,
1856                                    SSD_ELEM_NONE);
1857
1858                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1859                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1860                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1861                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1862                 msg_info.hdr.serializing_sc = NULL;
1863                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1864                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1865                                 sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1866                 }
1867                 return(1);
1868
1869         }
1870
1871         mtx_lock(&lun->lun_lock);
1872         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1873
1874         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1875                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1876                  ooa_links))) {
1877         case CTL_ACTION_BLOCK:
1878                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1879                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1880                                   blocked_links);
1881                 break;
1882         case CTL_ACTION_PASS:
1883         case CTL_ACTION_SKIP:
1884                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
1885                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1886                         ctl_enqueue_rtr((union ctl_io *)ctsio);
1887                 } else {
1888
1889                         /* send msg back to other side */
1890                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1891                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1892                         msg_info.hdr.msg_type = CTL_MSG_R2R;
1893 #if 0
1894                         printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1895 #endif
1896                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1897                             sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1898                         }
1899                 }
1900                 break;
1901         case CTL_ACTION_OVERLAP:
1902                 /* OVERLAPPED COMMANDS ATTEMPTED */
1903                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1904                                    lun,
1905                                    /*sense_format*/SSD_TYPE_NONE,
1906                                    /*current_error*/ 1,
1907                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1908                                    /*asc*/ 0x4E,
1909                                    /*ascq*/ 0x00,
1910                                    SSD_ELEM_NONE);
1911
1912                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1913                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1914                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1915                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1916                 msg_info.hdr.serializing_sc = NULL;
1917                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1918 #if 0
1919                 printf("BAD JUJU:Major Bummer Overlap\n");
1920 #endif
1921                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1922                 retval = 1;
1923                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1924                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1925                 }
1926                 break;
1927         case CTL_ACTION_OVERLAP_TAG:
1928                 /* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1929                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1930                                    lun,
1931                                    /*sense_format*/SSD_TYPE_NONE,
1932                                    /*current_error*/ 1,
1933                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1934                                    /*asc*/ 0x4D,
1935                                    /*ascq*/ ctsio->tag_num & 0xff,
1936                                    SSD_ELEM_NONE);
1937
1938                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1939                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1940                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1941                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1942                 msg_info.hdr.serializing_sc = NULL;
1943                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1944 #if 0
1945                 printf("BAD JUJU:Major Bummer Overlap Tag\n");
1946 #endif
1947                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1948                 retval = 1;
1949                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1950                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1951                 }
1952                 break;
1953         case CTL_ACTION_ERROR:
1954         default:
1955                 /* "Internal target failure" */
1956                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1957                                    lun,
1958                                    /*sense_format*/SSD_TYPE_NONE,
1959                                    /*current_error*/ 1,
1960                                    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1961                                    /*asc*/ 0x44,
1962                                    /*ascq*/ 0x00,
1963                                    SSD_ELEM_NONE);
1964
1965                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1966                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1967                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1968                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1969                 msg_info.hdr.serializing_sc = NULL;
1970                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1971 #if 0
1972                 printf("BAD JUJU:Major Bummer HW Error\n");
1973 #endif
1974                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1975                 retval = 1;
1976                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1977                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1978                 }
1979                 break;
1980         }
1981         mtx_unlock(&lun->lun_lock);
1982         return (retval);
1983 }
1984
1985 static int
1986 ctl_ioctl_submit_wait(union ctl_io *io)
1987 {
1988         struct ctl_fe_ioctl_params params;
1989         ctl_fe_ioctl_state last_state;
1990         int done, retval;
1991
1992         retval = 0;
1993
1994         bzero(&params, sizeof(params));
1995
1996         mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1997         cv_init(&params.sem, "ctlioccv");
1998         params.state = CTL_IOCTL_INPROG;
1999         last_state = params.state;
2000
2001         io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
2002
2003         CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
2004
2005         /* This shouldn't happen */
2006         if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
2007                 return (retval);
2008
2009         done = 0;
2010
2011         do {
2012                 mtx_lock(&params.ioctl_mtx);
2013                 /*
2014                  * Check the state here, and don't sleep if the state has
2015                  * already changed (i.e. wakeup has already occured, but we
2016                  * weren't waiting yet).
2017                  */
2018                 if (params.state == last_state) {
2019                         /* XXX KDM cv_wait_sig instead? */
2020                         cv_wait(&params.sem, &params.ioctl_mtx);
2021                 }
2022                 last_state = params.state;
2023
2024                 switch (params.state) {
2025                 case CTL_IOCTL_INPROG:
2026                         /* Why did we wake up? */
2027                         /* XXX KDM error here? */
2028                         mtx_unlock(&params.ioctl_mtx);
2029                         break;
2030                 case CTL_IOCTL_DATAMOVE:
2031                         CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
2032
2033                         /*
2034                          * change last_state back to INPROG to avoid
2035                          * deadlock on subsequent data moves.
2036                          */
2037                         params.state = last_state = CTL_IOCTL_INPROG;
2038
2039                         mtx_unlock(&params.ioctl_mtx);
2040                         ctl_ioctl_do_datamove(&io->scsiio);
2041                         /*
2042                          * Note that in some cases, most notably writes,
2043                          * this will queue the I/O and call us back later.
2044                          * In other cases, generally reads, this routine
2045                          * will immediately call back and wake us up,
2046                          * probably using our own context.
2047                          */
2048                         io->scsiio.be_move_done(io);
2049                         break;
2050                 case CTL_IOCTL_DONE:
2051                         mtx_unlock(&params.ioctl_mtx);
2052                         CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
2053                         done = 1;
2054                         break;
2055                 default:
2056                         mtx_unlock(&params.ioctl_mtx);
2057                         /* XXX KDM error here? */
2058                         break;
2059                 }
2060         } while (done == 0);
2061
2062         mtx_destroy(&params.ioctl_mtx);
2063         cv_destroy(&params.sem);
2064
2065         return (CTL_RETVAL_COMPLETE);
2066 }
2067
2068 static void
2069 ctl_ioctl_datamove(union ctl_io *io)
2070 {
2071         struct ctl_fe_ioctl_params *params;
2072
2073         params = (struct ctl_fe_ioctl_params *)
2074                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2075
2076         mtx_lock(&params->ioctl_mtx);
2077         params->state = CTL_IOCTL_DATAMOVE;
2078         cv_broadcast(&params->sem);
2079         mtx_unlock(&params->ioctl_mtx);
2080 }
2081
2082 static void
2083 ctl_ioctl_done(union ctl_io *io)
2084 {
2085         struct ctl_fe_ioctl_params *params;
2086
2087         params = (struct ctl_fe_ioctl_params *)
2088                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2089
2090         mtx_lock(&params->ioctl_mtx);
2091         params->state = CTL_IOCTL_DONE;
2092         cv_broadcast(&params->sem);
2093         mtx_unlock(&params->ioctl_mtx);
2094 }
2095
2096 static void
2097 ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2098 {
2099         struct ctl_fe_ioctl_startstop_info *sd_info;
2100
2101         sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2102
2103         sd_info->hs_info.status = metatask->status;
2104         sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2105         sd_info->hs_info.luns_complete =
2106                 metatask->taskinfo.startstop.luns_complete;
2107         sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2108
2109         cv_broadcast(&sd_info->sem);
2110 }
2111
2112 static void
2113 ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2114 {
2115         struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2116
2117         fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2118
2119         mtx_lock(fe_bbr_info->lock);
2120         fe_bbr_info->bbr_info->status = metatask->status;
2121         fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2122         fe_bbr_info->wakeup_done = 1;
2123         mtx_unlock(fe_bbr_info->lock);
2124
2125         cv_broadcast(&fe_bbr_info->sem);
2126 }
2127
2128 /*
2129  * Returns 0 for success, errno for failure.
2130  */
2131 static int
2132 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2133                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2134 {
2135         union ctl_io *io;
2136         int retval;
2137
2138         retval = 0;
2139
2140         mtx_lock(&lun->lun_lock);
2141         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2142              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2143              ooa_links)) {
2144                 struct ctl_ooa_entry *entry;
2145
2146                 /*
2147                  * If we've got more than we can fit, just count the
2148                  * remaining entries.
2149                  */
2150                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2151                         continue;
2152
2153                 entry = &kern_entries[*cur_fill_num];
2154
2155                 entry->tag_num = io->scsiio.tag_num;
2156                 entry->lun_num = lun->lun;
2157 #ifdef CTL_TIME_IO
2158                 entry->start_bt = io->io_hdr.start_bt;
2159 #endif
2160                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2161                 entry->cdb_len = io->scsiio.cdb_len;
2162                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2163                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2164
2165                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2166                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2167
2168                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2169                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2170
2171                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2172                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2173
2174                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2175                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2176         }
2177         mtx_unlock(&lun->lun_lock);
2178
2179         return (retval);
2180 }
2181
2182 static void *
2183 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2184                  size_t error_str_len)
2185 {
2186         void *kptr;
2187
2188         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2189
2190         if (copyin(user_addr, kptr, len) != 0) {
2191                 snprintf(error_str, error_str_len, "Error copying %d bytes "
2192                          "from user address %p to kernel address %p", len,
2193                          user_addr, kptr);
2194                 free(kptr, M_CTL);
2195                 return (NULL);
2196         }
2197
2198         return (kptr);
2199 }
2200
2201 static void
2202 ctl_free_args(int num_args, struct ctl_be_arg *args)
2203 {
2204         int i;
2205
2206         if (args == NULL)
2207                 return;
2208
2209         for (i = 0; i < num_args; i++) {
2210                 free(args[i].kname, M_CTL);
2211                 free(args[i].kvalue, M_CTL);
2212         }
2213
2214         free(args, M_CTL);
2215 }
2216
2217 static struct ctl_be_arg *
2218 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2219                 char *error_str, size_t error_str_len)
2220 {
2221         struct ctl_be_arg *args;
2222         int i;
2223
2224         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2225                                 error_str, error_str_len);
2226
2227         if (args == NULL)
2228                 goto bailout;
2229
2230         for (i = 0; i < num_args; i++) {
2231                 args[i].kname = NULL;
2232                 args[i].kvalue = NULL;
2233         }
2234
2235         for (i = 0; i < num_args; i++) {
2236                 uint8_t *tmpptr;
2237
2238                 args[i].kname = ctl_copyin_alloc(args[i].name,
2239                         args[i].namelen, error_str, error_str_len);
2240                 if (args[i].kname == NULL)
2241                         goto bailout;
2242
2243                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2244                         snprintf(error_str, error_str_len, "Argument %d "
2245                                  "name is not NUL-terminated", i);
2246                         goto bailout;
2247                 }
2248
2249                 if (args[i].flags & CTL_BEARG_RD) {
2250                         tmpptr = ctl_copyin_alloc(args[i].value,
2251                                 args[i].vallen, error_str, error_str_len);
2252                         if (tmpptr == NULL)
2253                                 goto bailout;
2254                         if ((args[i].flags & CTL_BEARG_ASCII)
2255                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2256                                 snprintf(error_str, error_str_len, "Argument "
2257                                     "%d value is not NUL-terminated", i);
2258                                 goto bailout;
2259                         }
2260                         args[i].kvalue = tmpptr;
2261                 } else {
2262                         args[i].kvalue = malloc(args[i].vallen,
2263                             M_CTL, M_WAITOK | M_ZERO);
2264                 }
2265         }
2266
2267         return (args);
2268 bailout:
2269
2270         ctl_free_args(num_args, args);
2271
2272         return (NULL);
2273 }
2274
2275 static void
2276 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2277 {
2278         int i;
2279
2280         for (i = 0; i < num_args; i++) {
2281                 if (args[i].flags & CTL_BEARG_WR)
2282                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2283         }
2284 }
2285
2286 /*
2287  * Escape characters that are illegal or not recommended in XML.
2288  */
2289 int
2290 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2291 {
2292         char *end = str + size;
2293         int retval;
2294
2295         retval = 0;
2296
2297         for (; *str && str < end; str++) {
2298                 switch (*str) {
2299                 case '&':
2300                         retval = sbuf_printf(sb, "&amp;");
2301                         break;
2302                 case '>':
2303                         retval = sbuf_printf(sb, "&gt;");
2304                         break;
2305                 case '<':
2306                         retval = sbuf_printf(sb, "&lt;");
2307                         break;
2308                 default:
2309                         retval = sbuf_putc(sb, *str);
2310                         break;
2311                 }
2312
2313                 if (retval != 0)
2314                         break;
2315
2316         }
2317
2318         return (retval);
2319 }
2320
2321 static void
2322 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2323 {
2324         struct scsi_vpd_id_descriptor *desc;
2325         int i;
2326
2327         if (id == NULL || id->len < 4)
2328                 return;
2329         desc = (struct scsi_vpd_id_descriptor *)id->data;
2330         switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2331         case SVPD_ID_TYPE_T10:
2332                 sbuf_printf(sb, "t10.");
2333                 break;
2334         case SVPD_ID_TYPE_EUI64:
2335                 sbuf_printf(sb, "eui.");
2336                 break;
2337         case SVPD_ID_TYPE_NAA:
2338                 sbuf_printf(sb, "naa.");
2339                 break;
2340         case SVPD_ID_TYPE_SCSI_NAME:
2341                 break;
2342         }
2343         switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2344         case SVPD_ID_CODESET_BINARY:
2345                 for (i = 0; i < desc->length; i++)
2346                         sbuf_printf(sb, "%02x", desc->identifier[i]);
2347                 break;
2348         case SVPD_ID_CODESET_ASCII:
2349                 sbuf_printf(sb, "%.*s", (int)desc->length,
2350                     (char *)desc->identifier);
2351                 break;
2352         case SVPD_ID_CODESET_UTF8:
2353                 sbuf_printf(sb, "%s", (char *)desc->identifier);
2354                 break;
2355         }
2356 }
2357
2358 static int
2359 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2360           struct thread *td)
2361 {
2362         struct ctl_softc *softc;
2363         int retval;
2364
2365         softc = control_softc;
2366
2367         retval = 0;
2368
2369         switch (cmd) {
2370         case CTL_IO: {
2371                 union ctl_io *io;
2372                 void *pool_tmp;
2373
2374                 /*
2375                  * If we haven't been "enabled", don't allow any SCSI I/O
2376                  * to this FETD.
2377                  */
2378                 if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2379                         retval = EPERM;
2380                         break;
2381                 }
2382
2383                 io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2384
2385                 /*
2386                  * Need to save the pool reference so it doesn't get
2387                  * spammed by the user's ctl_io.
2388                  */
2389                 pool_tmp = io->io_hdr.pool;
2390                 memcpy(io, (void *)addr, sizeof(*io));
2391                 io->io_hdr.pool = pool_tmp;
2392
2393                 /*
2394                  * No status yet, so make sure the status is set properly.
2395                  */
2396                 io->io_hdr.status = CTL_STATUS_NONE;
2397
2398                 /*
2399                  * The user sets the initiator ID, target and LUN IDs.
2400                  */
2401                 io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2402                 io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2403                 if ((io->io_hdr.io_type == CTL_IO_SCSI)
2404                  && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2405                         io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2406
2407                 retval = ctl_ioctl_submit_wait(io);
2408
2409                 if (retval != 0) {
2410                         ctl_free_io(io);
2411                         break;
2412                 }
2413
2414                 memcpy((void *)addr, io, sizeof(*io));
2415
2416                 /* return this to our pool */
2417                 ctl_free_io(io);
2418
2419                 break;
2420         }
2421         case CTL_ENABLE_PORT:
2422         case CTL_DISABLE_PORT:
2423         case CTL_SET_PORT_WWNS: {
2424                 struct ctl_port *port;
2425                 struct ctl_port_entry *entry;
2426
2427                 entry = (struct ctl_port_entry *)addr;
2428                 
2429                 mtx_lock(&softc->ctl_lock);
2430                 STAILQ_FOREACH(port, &softc->port_list, links) {
2431                         int action, done;
2432
2433                         action = 0;
2434                         done = 0;
2435
2436                         if ((entry->port_type == CTL_PORT_NONE)
2437                          && (entry->targ_port == port->targ_port)) {
2438                                 /*
2439                                  * If the user only wants to enable or
2440                                  * disable or set WWNs on a specific port,
2441                                  * do the operation and we're done.
2442                                  */
2443                                 action = 1;
2444                                 done = 1;
2445                         } else if (entry->port_type & port->port_type) {
2446                                 /*
2447                                  * Compare the user's type mask with the
2448                                  * particular frontend type to see if we
2449                                  * have a match.
2450                                  */
2451                                 action = 1;
2452                                 done = 0;
2453
2454                                 /*
2455                                  * Make sure the user isn't trying to set
2456                                  * WWNs on multiple ports at the same time.
2457                                  */
2458                                 if (cmd == CTL_SET_PORT_WWNS) {
2459                                         printf("%s: Can't set WWNs on "
2460                                                "multiple ports\n", __func__);
2461                                         retval = EINVAL;
2462                                         break;
2463                                 }
2464                         }
2465                         if (action != 0) {
2466                                 /*
2467                                  * XXX KDM we have to drop the lock here,
2468                                  * because the online/offline operations
2469                                  * can potentially block.  We need to
2470                                  * reference count the frontends so they
2471                                  * can't go away,
2472                                  */
2473                                 mtx_unlock(&softc->ctl_lock);
2474
2475                                 if (cmd == CTL_ENABLE_PORT) {
2476                                         ctl_port_online(port);
2477                                 } else if (cmd == CTL_DISABLE_PORT) {
2478                                         ctl_port_offline(port);
2479                                 }
2480
2481                                 mtx_lock(&softc->ctl_lock);
2482
2483                                 if (cmd == CTL_SET_PORT_WWNS)
2484                                         ctl_port_set_wwns(port,
2485                                             (entry->flags & CTL_PORT_WWNN_VALID) ?
2486                                             1 : 0, entry->wwnn,
2487                                             (entry->flags & CTL_PORT_WWPN_VALID) ?
2488                                             1 : 0, entry->wwpn);
2489                         }
2490                         if (done != 0)
2491                                 break;
2492                 }
2493                 mtx_unlock(&softc->ctl_lock);
2494                 break;
2495         }
2496         case CTL_GET_PORT_LIST: {
2497                 struct ctl_port *port;
2498                 struct ctl_port_list *list;
2499                 int i;
2500
2501                 list = (struct ctl_port_list *)addr;
2502
2503                 if (list->alloc_len != (list->alloc_num *
2504                     sizeof(struct ctl_port_entry))) {
2505                         printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2506                                "alloc_num %u * sizeof(struct ctl_port_entry) "
2507                                "%zu\n", __func__, list->alloc_len,
2508                                list->alloc_num, sizeof(struct ctl_port_entry));
2509                         retval = EINVAL;
2510                         break;
2511                 }
2512                 list->fill_len = 0;
2513                 list->fill_num = 0;
2514                 list->dropped_num = 0;
2515                 i = 0;
2516                 mtx_lock(&softc->ctl_lock);
2517                 STAILQ_FOREACH(port, &softc->port_list, links) {
2518                         struct ctl_port_entry entry, *list_entry;
2519
2520                         if (list->fill_num >= list->alloc_num) {
2521                                 list->dropped_num++;
2522                                 continue;
2523                         }
2524
2525                         entry.port_type = port->port_type;
2526                         strlcpy(entry.port_name, port->port_name,
2527                                 sizeof(entry.port_name));
2528                         entry.targ_port = port->targ_port;
2529                         entry.physical_port = port->physical_port;
2530                         entry.virtual_port = port->virtual_port;
2531                         entry.wwnn = port->wwnn;
2532                         entry.wwpn = port->wwpn;
2533                         if (port->status & CTL_PORT_STATUS_ONLINE)
2534                                 entry.online = 1;
2535                         else
2536                                 entry.online = 0;
2537
2538                         list_entry = &list->entries[i];
2539
2540                         retval = copyout(&entry, list_entry, sizeof(entry));
2541                         if (retval != 0) {
2542                                 printf("%s: CTL_GET_PORT_LIST: copyout "
2543                                        "returned %d\n", __func__, retval);
2544                                 break;
2545                         }
2546                         i++;
2547                         list->fill_num++;
2548                         list->fill_len += sizeof(entry);
2549                 }
2550                 mtx_unlock(&softc->ctl_lock);
2551
2552                 /*
2553                  * If this is non-zero, we had a copyout fault, so there's
2554                  * probably no point in attempting to set the status inside
2555                  * the structure.
2556                  */
2557                 if (retval != 0)
2558                         break;
2559
2560                 if (list->dropped_num > 0)
2561                         list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2562                 else
2563                         list->status = CTL_PORT_LIST_OK;
2564                 break;
2565         }
2566         case CTL_DUMP_OOA: {
2567                 struct ctl_lun *lun;
2568                 union ctl_io *io;
2569                 char printbuf[128];
2570                 struct sbuf sb;
2571
2572                 mtx_lock(&softc->ctl_lock);
2573                 printf("Dumping OOA queues:\n");
2574                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2575                         mtx_lock(&lun->lun_lock);
2576                         for (io = (union ctl_io *)TAILQ_FIRST(
2577                              &lun->ooa_queue); io != NULL;
2578                              io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2579                              ooa_links)) {
2580                                 sbuf_new(&sb, printbuf, sizeof(printbuf),
2581                                          SBUF_FIXEDLEN);
2582                                 sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2583                                             (intmax_t)lun->lun,
2584                                             io->scsiio.tag_num,
2585                                             (io->io_hdr.flags &
2586                                             CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2587                                             (io->io_hdr.flags &
2588                                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2589                                             (io->io_hdr.flags &
2590                                             CTL_FLAG_ABORT) ? " ABORT" : "",
2591                                             (io->io_hdr.flags &
2592                                         CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2593                                 ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2594                                 sbuf_finish(&sb);
2595                                 printf("%s\n", sbuf_data(&sb));
2596                         }
2597                         mtx_unlock(&lun->lun_lock);
2598                 }
2599                 printf("OOA queues dump done\n");
2600                 mtx_unlock(&softc->ctl_lock);
2601                 break;
2602         }
2603         case CTL_GET_OOA: {
2604                 struct ctl_lun *lun;
2605                 struct ctl_ooa *ooa_hdr;
2606                 struct ctl_ooa_entry *entries;
2607                 uint32_t cur_fill_num;
2608
2609                 ooa_hdr = (struct ctl_ooa *)addr;
2610
2611                 if ((ooa_hdr->alloc_len == 0)
2612                  || (ooa_hdr->alloc_num == 0)) {
2613                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2614                                "must be non-zero\n", __func__,
2615                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2616                         retval = EINVAL;
2617                         break;
2618                 }
2619
2620                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2621                     sizeof(struct ctl_ooa_entry))) {
2622                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2623                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2624                                __func__, ooa_hdr->alloc_len,
2625                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2626                         retval = EINVAL;
2627                         break;
2628                 }
2629
2630                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2631                 if (entries == NULL) {
2632                         printf("%s: could not allocate %d bytes for OOA "
2633                                "dump\n", __func__, ooa_hdr->alloc_len);
2634                         retval = ENOMEM;
2635                         break;
2636                 }
2637
2638                 mtx_lock(&softc->ctl_lock);
2639                 if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2640                  && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2641                   || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2642                         mtx_unlock(&softc->ctl_lock);
2643                         free(entries, M_CTL);
2644                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2645                                __func__, (uintmax_t)ooa_hdr->lun_num);
2646                         retval = EINVAL;
2647                         break;
2648                 }
2649
2650                 cur_fill_num = 0;
2651
2652                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2653                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2654                                 retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2655                                         ooa_hdr, entries);
2656                                 if (retval != 0)
2657                                         break;
2658                         }
2659                         if (retval != 0) {
2660                                 mtx_unlock(&softc->ctl_lock);
2661                                 free(entries, M_CTL);
2662                                 break;
2663                         }
2664                 } else {
2665                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2666
2667                         retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2668                                                     entries);
2669                 }
2670                 mtx_unlock(&softc->ctl_lock);
2671
2672                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2673                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2674                         sizeof(struct ctl_ooa_entry);
2675                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2676                 if (retval != 0) {
2677                         printf("%s: error copying out %d bytes for OOA dump\n", 
2678                                __func__, ooa_hdr->fill_len);
2679                 }
2680
2681                 getbintime(&ooa_hdr->cur_bt);
2682
2683                 if (cur_fill_num > ooa_hdr->alloc_num) {
2684                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2685                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2686                 } else {
2687                         ooa_hdr->dropped_num = 0;
2688                         ooa_hdr->status = CTL_OOA_OK;
2689                 }
2690
2691                 free(entries, M_CTL);
2692                 break;
2693         }
2694         case CTL_CHECK_OOA: {
2695                 union ctl_io *io;
2696                 struct ctl_lun *lun;
2697                 struct ctl_ooa_info *ooa_info;
2698
2699
2700                 ooa_info = (struct ctl_ooa_info *)addr;
2701
2702                 if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2703                         ooa_info->status = CTL_OOA_INVALID_LUN;
2704                         break;
2705                 }
2706                 mtx_lock(&softc->ctl_lock);
2707                 lun = softc->ctl_luns[ooa_info->lun_id];
2708                 if (lun == NULL) {
2709                         mtx_unlock(&softc->ctl_lock);
2710                         ooa_info->status = CTL_OOA_INVALID_LUN;
2711                         break;
2712                 }
2713                 mtx_lock(&lun->lun_lock);
2714                 mtx_unlock(&softc->ctl_lock);
2715                 ooa_info->num_entries = 0;
2716                 for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2717                      io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2718                      &io->io_hdr, ooa_links)) {
2719                         ooa_info->num_entries++;
2720                 }
2721                 mtx_unlock(&lun->lun_lock);
2722
2723                 ooa_info->status = CTL_OOA_SUCCESS;
2724
2725                 break;
2726         }
2727         case CTL_HARD_START:
2728         case CTL_HARD_STOP: {
2729                 struct ctl_fe_ioctl_startstop_info ss_info;
2730                 struct cfi_metatask *metatask;
2731                 struct mtx hs_mtx;
2732
2733                 mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2734
2735                 cv_init(&ss_info.sem, "hard start/stop cv" );
2736
2737                 metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2738                 if (metatask == NULL) {
2739                         retval = ENOMEM;
2740                         mtx_destroy(&hs_mtx);
2741                         break;
2742                 }
2743
2744                 if (cmd == CTL_HARD_START)
2745                         metatask->tasktype = CFI_TASK_STARTUP;
2746                 else
2747                         metatask->tasktype = CFI_TASK_SHUTDOWN;
2748
2749                 metatask->callback = ctl_ioctl_hard_startstop_callback;
2750                 metatask->callback_arg = &ss_info;
2751
2752                 cfi_action(metatask);
2753
2754                 /* Wait for the callback */
2755                 mtx_lock(&hs_mtx);
2756                 cv_wait_sig(&ss_info.sem, &hs_mtx);
2757                 mtx_unlock(&hs_mtx);
2758
2759                 /*
2760                  * All information has been copied from the metatask by the
2761                  * time cv_broadcast() is called, so we free the metatask here.
2762                  */
2763                 cfi_free_metatask(metatask);
2764
2765                 memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2766
2767                 mtx_destroy(&hs_mtx);
2768                 break;
2769         }
2770         case CTL_BBRREAD: {
2771                 struct ctl_bbrread_info *bbr_info;
2772                 struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2773                 struct mtx bbr_mtx;
2774                 struct cfi_metatask *metatask;
2775
2776                 bbr_info = (struct ctl_bbrread_info *)addr;
2777
2778                 bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2779
2780                 bzero(&bbr_mtx, sizeof(bbr_mtx));
2781                 mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2782
2783                 fe_bbr_info.bbr_info = bbr_info;
2784                 fe_bbr_info.lock = &bbr_mtx;
2785
2786                 cv_init(&fe_bbr_info.sem, "BBR read cv");
2787                 metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2788
2789                 if (metatask == NULL) {
2790                         mtx_destroy(&bbr_mtx);
2791                         cv_destroy(&fe_bbr_info.sem);
2792                         retval = ENOMEM;
2793                         break;
2794                 }
2795                 metatask->tasktype = CFI_TASK_BBRREAD;
2796                 metatask->callback = ctl_ioctl_bbrread_callback;
2797                 metatask->callback_arg = &fe_bbr_info;
2798                 metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2799                 metatask->taskinfo.bbrread.lba = bbr_info->lba;
2800                 metatask->taskinfo.bbrread.len = bbr_info->len;
2801
2802                 cfi_action(metatask);
2803
2804                 mtx_lock(&bbr_mtx);
2805                 while (fe_bbr_info.wakeup_done == 0)
2806                         cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2807                 mtx_unlock(&bbr_mtx);
2808
2809                 bbr_info->status = metatask->status;
2810                 bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2811                 bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2812                 memcpy(&bbr_info->sense_data,
2813                        &metatask->taskinfo.bbrread.sense_data,
2814                        MIN(sizeof(bbr_info->sense_data),
2815                            sizeof(metatask->taskinfo.bbrread.sense_data)));
2816
2817                 cfi_free_metatask(metatask);
2818
2819                 mtx_destroy(&bbr_mtx);
2820                 cv_destroy(&fe_bbr_info.sem);
2821
2822                 break;
2823         }
2824         case CTL_DELAY_IO: {
2825                 struct ctl_io_delay_info *delay_info;
2826 #ifdef CTL_IO_DELAY
2827                 struct ctl_lun *lun;
2828 #endif /* CTL_IO_DELAY */
2829
2830                 delay_info = (struct ctl_io_delay_info *)addr;
2831
2832 #ifdef CTL_IO_DELAY
2833                 mtx_lock(&softc->ctl_lock);
2834
2835                 if ((delay_info->lun_id >= CTL_MAX_LUNS)
2836                  || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2837                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2838                 } else {
2839                         lun = softc->ctl_luns[delay_info->lun_id];
2840                         mtx_lock(&lun->lun_lock);
2841
2842                         delay_info->status = CTL_DELAY_STATUS_OK;
2843
2844                         switch (delay_info->delay_type) {
2845                         case CTL_DELAY_TYPE_CONT:
2846                                 break;
2847                         case CTL_DELAY_TYPE_ONESHOT:
2848                                 break;
2849                         default:
2850                                 delay_info->status =
2851                                         CTL_DELAY_STATUS_INVALID_TYPE;
2852                                 break;
2853                         }
2854
2855                         switch (delay_info->delay_loc) {
2856                         case CTL_DELAY_LOC_DATAMOVE:
2857                                 lun->delay_info.datamove_type =
2858                                         delay_info->delay_type;
2859                                 lun->delay_info.datamove_delay =
2860                                         delay_info->delay_secs;
2861                                 break;
2862                         case CTL_DELAY_LOC_DONE:
2863                                 lun->delay_info.done_type =
2864                                         delay_info->delay_type;
2865                                 lun->delay_info.done_delay =
2866                                         delay_info->delay_secs;
2867                                 break;
2868                         default:
2869                                 delay_info->status =
2870                                         CTL_DELAY_STATUS_INVALID_LOC;
2871                                 break;
2872                         }
2873                         mtx_unlock(&lun->lun_lock);
2874                 }
2875
2876                 mtx_unlock(&softc->ctl_lock);
2877 #else
2878                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2879 #endif /* CTL_IO_DELAY */
2880                 break;
2881         }
2882         case CTL_REALSYNC_SET: {
2883                 int *syncstate;
2884
2885                 syncstate = (int *)addr;
2886
2887                 mtx_lock(&softc->ctl_lock);
2888                 switch (*syncstate) {
2889                 case 0:
2890                         softc->flags &= ~CTL_FLAG_REAL_SYNC;
2891                         break;
2892                 case 1:
2893                         softc->flags |= CTL_FLAG_REAL_SYNC;
2894                         break;
2895                 default:
2896                         retval = EINVAL;
2897                         break;
2898                 }
2899                 mtx_unlock(&softc->ctl_lock);
2900                 break;
2901         }
2902         case CTL_REALSYNC_GET: {
2903                 int *syncstate;
2904
2905                 syncstate = (int*)addr;
2906
2907                 mtx_lock(&softc->ctl_lock);
2908                 if (softc->flags & CTL_FLAG_REAL_SYNC)
2909                         *syncstate = 1;
2910                 else
2911                         *syncstate = 0;
2912                 mtx_unlock(&softc->ctl_lock);
2913
2914                 break;
2915         }
2916         case CTL_SETSYNC:
2917         case CTL_GETSYNC: {
2918                 struct ctl_sync_info *sync_info;
2919                 struct ctl_lun *lun;
2920
2921                 sync_info = (struct ctl_sync_info *)addr;
2922
2923                 mtx_lock(&softc->ctl_lock);
2924                 lun = softc->ctl_luns[sync_info->lun_id];
2925                 if (lun == NULL) {
2926                         mtx_unlock(&softc->ctl_lock);
2927                         sync_info->status = CTL_GS_SYNC_NO_LUN;
2928                 }
2929                 /*
2930                  * Get or set the sync interval.  We're not bounds checking
2931                  * in the set case, hopefully the user won't do something
2932                  * silly.
2933                  */
2934                 mtx_lock(&lun->lun_lock);
2935                 mtx_unlock(&softc->ctl_lock);
2936                 if (cmd == CTL_GETSYNC)
2937                         sync_info->sync_interval = lun->sync_interval;
2938                 else
2939                         lun->sync_interval = sync_info->sync_interval;
2940                 mtx_unlock(&lun->lun_lock);
2941
2942                 sync_info->status = CTL_GS_SYNC_OK;
2943
2944                 break;
2945         }
2946         case CTL_GETSTATS: {
2947                 struct ctl_stats *stats;
2948                 struct ctl_lun *lun;
2949                 int i;
2950
2951                 stats = (struct ctl_stats *)addr;
2952
2953                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2954                      stats->alloc_len) {
2955                         stats->status = CTL_SS_NEED_MORE_SPACE;
2956                         stats->num_luns = softc->num_luns;
2957                         break;
2958                 }
2959                 /*
2960                  * XXX KDM no locking here.  If the LUN list changes,
2961                  * things can blow up.
2962                  */
2963                 for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2964                      i++, lun = STAILQ_NEXT(lun, links)) {
2965                         retval = copyout(&lun->stats, &stats->lun_stats[i],
2966                                          sizeof(lun->stats));
2967                         if (retval != 0)
2968                                 break;
2969                 }
2970                 stats->num_luns = softc->num_luns;
2971                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2972                                  softc->num_luns;
2973                 stats->status = CTL_SS_OK;
2974 #ifdef CTL_TIME_IO
2975                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
2976 #else
2977                 stats->flags = CTL_STATS_FLAG_NONE;
2978 #endif
2979                 getnanouptime(&stats->timestamp);
2980                 break;
2981         }
2982         case CTL_ERROR_INJECT: {
2983                 struct ctl_error_desc *err_desc, *new_err_desc;
2984                 struct ctl_lun *lun;
2985
2986                 err_desc = (struct ctl_error_desc *)addr;
2987
2988                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2989                                       M_WAITOK | M_ZERO);
2990                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2991
2992                 mtx_lock(&softc->ctl_lock);
2993                 lun = softc->ctl_luns[err_desc->lun_id];
2994                 if (lun == NULL) {
2995                         mtx_unlock(&softc->ctl_lock);
2996                         free(new_err_desc, M_CTL);
2997                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2998                                __func__, (uintmax_t)err_desc->lun_id);
2999                         retval = EINVAL;
3000                         break;
3001                 }
3002                 mtx_lock(&lun->lun_lock);
3003                 mtx_unlock(&softc->ctl_lock);
3004
3005                 /*
3006                  * We could do some checking here to verify the validity
3007                  * of the request, but given the complexity of error
3008                  * injection requests, the checking logic would be fairly
3009                  * complex.
3010                  *
3011                  * For now, if the request is invalid, it just won't get
3012                  * executed and might get deleted.
3013                  */
3014                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
3015
3016                 /*
3017                  * XXX KDM check to make sure the serial number is unique,
3018                  * in case we somehow manage to wrap.  That shouldn't
3019                  * happen for a very long time, but it's the right thing to
3020                  * do.
3021                  */
3022                 new_err_desc->serial = lun->error_serial;
3023                 err_desc->serial = lun->error_serial;
3024                 lun->error_serial++;
3025
3026                 mtx_unlock(&lun->lun_lock);
3027                 break;
3028         }
3029         case CTL_ERROR_INJECT_DELETE: {
3030                 struct ctl_error_desc *delete_desc, *desc, *desc2;
3031                 struct ctl_lun *lun;
3032                 int delete_done;
3033
3034                 delete_desc = (struct ctl_error_desc *)addr;
3035                 delete_done = 0;
3036
3037                 mtx_lock(&softc->ctl_lock);
3038                 lun = softc->ctl_luns[delete_desc->lun_id];
3039                 if (lun == NULL) {
3040                         mtx_unlock(&softc->ctl_lock);
3041                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
3042                                __func__, (uintmax_t)delete_desc->lun_id);
3043                         retval = EINVAL;
3044                         break;
3045                 }
3046                 mtx_lock(&lun->lun_lock);
3047                 mtx_unlock(&softc->ctl_lock);
3048                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
3049                         if (desc->serial != delete_desc->serial)
3050                                 continue;
3051
3052                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
3053                                       links);
3054                         free(desc, M_CTL);
3055                         delete_done = 1;
3056                 }
3057                 mtx_unlock(&lun->lun_lock);
3058                 if (delete_done == 0) {
3059                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
3060                                "error serial %ju on LUN %u\n", __func__, 
3061                                delete_desc->serial, delete_desc->lun_id);
3062                         retval = EINVAL;
3063                         break;
3064                 }
3065                 break;
3066         }
3067         case CTL_DUMP_STRUCTS: {
3068                 int i, j, k;
3069                 struct ctl_port *port;
3070                 struct ctl_frontend *fe;
3071
3072                 mtx_lock(&softc->ctl_lock);
3073                 printf("CTL Persistent Reservation information start:\n");
3074                 for (i = 0; i < CTL_MAX_LUNS; i++) {
3075                         struct ctl_lun *lun;
3076
3077                         lun = softc->ctl_luns[i];
3078
3079                         if ((lun == NULL)
3080                          || ((lun->flags & CTL_LUN_DISABLED) != 0))
3081                                 continue;
3082
3083                         for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
3084                                 if (lun->pr_keys[j] == NULL)
3085                                         continue;
3086                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3087                                         if (lun->pr_keys[j][k] == 0)
3088                                                 continue;
3089                                         printf("  LUN %d port %d iid %d key "
3090                                                "%#jx\n", i, j, k,
3091                                                (uintmax_t)lun->pr_keys[j][k]);
3092                                 }
3093                         }
3094                 }
3095                 printf("CTL Persistent Reservation information end\n");
3096                 printf("CTL Ports:\n");
3097                 STAILQ_FOREACH(port, &softc->port_list, links) {
3098                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3099                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3100                                port->frontend->name, port->port_type,
3101                                port->physical_port, port->virtual_port,
3102                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3103                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3104                                 if (port->wwpn_iid[j].in_use == 0 &&
3105                                     port->wwpn_iid[j].wwpn == 0 &&
3106                                     port->wwpn_iid[j].name == NULL)
3107                                         continue;
3108
3109                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
3110                                     j, port->wwpn_iid[j].in_use,
3111                                     (uintmax_t)port->wwpn_iid[j].wwpn,
3112                                     port->wwpn_iid[j].name);
3113                         }
3114                 }
3115                 printf("CTL Port information end\n");
3116                 mtx_unlock(&softc->ctl_lock);
3117                 /*
3118                  * XXX KDM calling this without a lock.  We'd likely want
3119                  * to drop the lock before calling the frontend's dump
3120                  * routine anyway.
3121                  */
3122                 printf("CTL Frontends:\n");
3123                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
3124                         printf("  Frontend '%s'\n", fe->name);
3125                         if (fe->fe_dump != NULL)
3126                                 fe->fe_dump();
3127                 }
3128                 printf("CTL Frontend information end\n");
3129                 break;
3130         }
3131         case CTL_LUN_REQ: {
3132                 struct ctl_lun_req *lun_req;
3133                 struct ctl_backend_driver *backend;
3134
3135                 lun_req = (struct ctl_lun_req *)addr;
3136
3137                 backend = ctl_backend_find(lun_req->backend);
3138                 if (backend == NULL) {
3139                         lun_req->status = CTL_LUN_ERROR;
3140                         snprintf(lun_req->error_str,
3141                                  sizeof(lun_req->error_str),
3142                                  "Backend \"%s\" not found.",
3143                                  lun_req->backend);
3144                         break;
3145                 }
3146                 if (lun_req->num_be_args > 0) {
3147                         lun_req->kern_be_args = ctl_copyin_args(
3148                                 lun_req->num_be_args,
3149                                 lun_req->be_args,
3150                                 lun_req->error_str,
3151                                 sizeof(lun_req->error_str));
3152                         if (lun_req->kern_be_args == NULL) {
3153                                 lun_req->status = CTL_LUN_ERROR;
3154                                 break;
3155                         }
3156                 }
3157
3158                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3159
3160                 if (lun_req->num_be_args > 0) {
3161                         ctl_copyout_args(lun_req->num_be_args,
3162                                       lun_req->kern_be_args);
3163                         ctl_free_args(lun_req->num_be_args,
3164                                       lun_req->kern_be_args);
3165                 }
3166                 break;
3167         }
3168         case CTL_LUN_LIST: {
3169                 struct sbuf *sb;
3170                 struct ctl_lun *lun;
3171                 struct ctl_lun_list *list;
3172                 struct ctl_option *opt;
3173
3174                 list = (struct ctl_lun_list *)addr;
3175
3176                 /*
3177                  * Allocate a fixed length sbuf here, based on the length
3178                  * of the user's buffer.  We could allocate an auto-extending
3179                  * buffer, and then tell the user how much larger our
3180                  * amount of data is than his buffer, but that presents
3181                  * some problems:
3182                  *
3183                  * 1.  The sbuf(9) routines use a blocking malloc, and so
3184                  *     we can't hold a lock while calling them with an
3185                  *     auto-extending buffer.
3186                  *
3187                  * 2.  There is not currently a LUN reference counting
3188                  *     mechanism, outside of outstanding transactions on
3189                  *     the LUN's OOA queue.  So a LUN could go away on us
3190                  *     while we're getting the LUN number, backend-specific
3191                  *     information, etc.  Thus, given the way things
3192                  *     currently work, we need to hold the CTL lock while
3193                  *     grabbing LUN information.
3194                  *
3195                  * So, from the user's standpoint, the best thing to do is
3196                  * allocate what he thinks is a reasonable buffer length,
3197                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3198                  * double the buffer length and try again.  (And repeat
3199                  * that until he succeeds.)
3200                  */
3201                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3202                 if (sb == NULL) {
3203                         list->status = CTL_LUN_LIST_ERROR;
3204                         snprintf(list->error_str, sizeof(list->error_str),
3205                                  "Unable to allocate %d bytes for LUN list",
3206                                  list->alloc_len);
3207                         break;
3208                 }
3209
3210                 sbuf_printf(sb, "<ctllunlist>\n");
3211
3212                 mtx_lock(&softc->ctl_lock);
3213                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3214                         mtx_lock(&lun->lun_lock);
3215                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3216                                              (uintmax_t)lun->lun);
3217
3218                         /*
3219                          * Bail out as soon as we see that we've overfilled
3220                          * the buffer.
3221                          */
3222                         if (retval != 0)
3223                                 break;
3224
3225                         retval = sbuf_printf(sb, "\t<backend_type>%s"
3226                                              "</backend_type>\n",
3227                                              (lun->backend == NULL) ?  "none" :
3228                                              lun->backend->name);
3229
3230                         if (retval != 0)
3231                                 break;
3232
3233                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3234                                              lun->be_lun->lun_type);
3235
3236                         if (retval != 0)
3237                                 break;
3238
3239                         if (lun->backend == NULL) {
3240                                 retval = sbuf_printf(sb, "</lun>\n");
3241                                 if (retval != 0)
3242                                         break;
3243                                 continue;
3244                         }
3245
3246                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3247                                              (lun->be_lun->maxlba > 0) ?
3248                                              lun->be_lun->maxlba + 1 : 0);
3249
3250                         if (retval != 0)
3251                                 break;
3252
3253                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3254                                              lun->be_lun->blocksize);
3255
3256                         if (retval != 0)
3257                                 break;
3258
3259                         retval = sbuf_printf(sb, "\t<serial_number>");
3260
3261                         if (retval != 0)
3262                                 break;
3263
3264                         retval = ctl_sbuf_printf_esc(sb,
3265                             lun->be_lun->serial_num,
3266                             sizeof(lun->be_lun->serial_num));
3267
3268                         if (retval != 0)
3269                                 break;
3270
3271                         retval = sbuf_printf(sb, "</serial_number>\n");
3272                 
3273                         if (retval != 0)
3274                                 break;
3275
3276                         retval = sbuf_printf(sb, "\t<device_id>");
3277
3278                         if (retval != 0)
3279                                 break;
3280
3281                         retval = ctl_sbuf_printf_esc(sb,
3282                             lun->be_lun->device_id,
3283                             sizeof(lun->be_lun->device_id));
3284
3285                         if (retval != 0)
3286                                 break;
3287
3288                         retval = sbuf_printf(sb, "</device_id>\n");
3289
3290                         if (retval != 0)
3291                                 break;
3292
3293                         if (lun->backend->lun_info != NULL) {
3294                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3295                                 if (retval != 0)
3296                                         break;
3297                         }
3298                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3299                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3300                                     opt->name, opt->value, opt->name);
3301                                 if (retval != 0)
3302                                         break;
3303                         }
3304
3305                         retval = sbuf_printf(sb, "</lun>\n");
3306
3307                         if (retval != 0)
3308                                 break;
3309                         mtx_unlock(&lun->lun_lock);
3310                 }
3311                 if (lun != NULL)
3312                         mtx_unlock(&lun->lun_lock);
3313                 mtx_unlock(&softc->ctl_lock);
3314
3315                 if ((retval != 0)
3316                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3317                         retval = 0;
3318                         sbuf_delete(sb);
3319                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3320                         snprintf(list->error_str, sizeof(list->error_str),
3321                                  "Out of space, %d bytes is too small",
3322                                  list->alloc_len);
3323                         break;
3324                 }
3325
3326                 sbuf_finish(sb);
3327
3328                 retval = copyout(sbuf_data(sb), list->lun_xml,
3329                                  sbuf_len(sb) + 1);
3330
3331                 list->fill_len = sbuf_len(sb) + 1;
3332                 list->status = CTL_LUN_LIST_OK;
3333                 sbuf_delete(sb);
3334                 break;
3335         }
3336         case CTL_ISCSI: {
3337                 struct ctl_iscsi *ci;
3338                 struct ctl_frontend *fe;
3339
3340                 ci = (struct ctl_iscsi *)addr;
3341
3342                 fe = ctl_frontend_find("iscsi");
3343                 if (fe == NULL) {
3344                         ci->status = CTL_ISCSI_ERROR;
3345                         snprintf(ci->error_str, sizeof(ci->error_str),
3346                             "Frontend \"iscsi\" not found.");
3347                         break;
3348                 }
3349
3350                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3351                 break;
3352         }
3353         case CTL_PORT_REQ: {
3354                 struct ctl_req *req;
3355                 struct ctl_frontend *fe;
3356
3357                 req = (struct ctl_req *)addr;
3358
3359                 fe = ctl_frontend_find(req->driver);
3360                 if (fe == NULL) {
3361                         req->status = CTL_LUN_ERROR;
3362                         snprintf(req->error_str, sizeof(req->error_str),
3363                             "Frontend \"%s\" not found.", req->driver);
3364                         break;
3365                 }
3366                 if (req->num_args > 0) {
3367                         req->kern_args = ctl_copyin_args(req->num_args,
3368                             req->args, req->error_str, sizeof(req->error_str));
3369                         if (req->kern_args == NULL) {
3370                                 req->status = CTL_LUN_ERROR;
3371                                 break;
3372                         }
3373                 }
3374
3375                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3376
3377                 if (req->num_args > 0) {
3378                         ctl_copyout_args(req->num_args, req->kern_args);
3379                         ctl_free_args(req->num_args, req->kern_args);
3380                 }
3381                 break;
3382         }
3383         case CTL_PORT_LIST: {
3384                 struct sbuf *sb;
3385                 struct ctl_port *port;
3386                 struct ctl_lun_list *list;
3387                 struct ctl_option *opt;
3388                 int j;
3389                 uint32_t plun;
3390
3391                 list = (struct ctl_lun_list *)addr;
3392
3393                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3394                 if (sb == NULL) {
3395                         list->status = CTL_LUN_LIST_ERROR;
3396                         snprintf(list->error_str, sizeof(list->error_str),
3397                                  "Unable to allocate %d bytes for LUN list",
3398                                  list->alloc_len);
3399                         break;
3400                 }
3401
3402                 sbuf_printf(sb, "<ctlportlist>\n");
3403
3404                 mtx_lock(&softc->ctl_lock);
3405                 STAILQ_FOREACH(port, &softc->port_list, links) {
3406                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3407                                              (uintmax_t)port->targ_port);
3408
3409                         /*
3410                          * Bail out as soon as we see that we've overfilled
3411                          * the buffer.
3412                          */
3413                         if (retval != 0)
3414                                 break;
3415
3416                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3417                             "</frontend_type>\n", port->frontend->name);
3418                         if (retval != 0)
3419                                 break;
3420
3421                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3422                                              port->port_type);
3423                         if (retval != 0)
3424                                 break;
3425
3426                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3427                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3428                         if (retval != 0)
3429                                 break;
3430
3431                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3432                             port->port_name);
3433                         if (retval != 0)
3434                                 break;
3435
3436                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3437                             port->physical_port);
3438                         if (retval != 0)
3439                                 break;
3440
3441                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3442                             port->virtual_port);
3443                         if (retval != 0)
3444                                 break;
3445
3446                         if (port->target_devid != NULL) {
3447                                 sbuf_printf(sb, "\t<target>");
3448                                 ctl_id_sbuf(port->target_devid, sb);
3449                                 sbuf_printf(sb, "</target>\n");
3450                         }
3451
3452                         if (port->port_devid != NULL) {
3453                                 sbuf_printf(sb, "\t<port>");
3454                                 ctl_id_sbuf(port->port_devid, sb);
3455                                 sbuf_printf(sb, "</port>\n");
3456                         }
3457
3458                         if (port->port_info != NULL) {
3459                                 retval = port->port_info(port->onoff_arg, sb);
3460                                 if (retval != 0)
3461                                         break;
3462                         }
3463                         STAILQ_FOREACH(opt, &port->options, links) {
3464                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3465                                     opt->name, opt->value, opt->name);
3466                                 if (retval != 0)
3467                                         break;
3468                         }
3469
3470                         if (port->lun_map != NULL) {
3471                                 sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3472                                 for (j = 0; j < CTL_MAX_LUNS; j++) {
3473                                         plun = ctl_lun_map_from_port(port, j);
3474                                         if (plun >= CTL_MAX_LUNS)
3475                                                 continue;
3476                                         sbuf_printf(sb,
3477                                             "\t<lun id=\"%u\">%u</lun>\n",
3478                                             j, plun);
3479                                 }
3480                         }
3481
3482                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3483                                 if (port->wwpn_iid[j].in_use == 0 ||
3484                                     (port->wwpn_iid[j].wwpn == 0 &&
3485                                      port->wwpn_iid[j].name == NULL))
3486                                         continue;
3487
3488                                 if (port->wwpn_iid[j].name != NULL)
3489                                         retval = sbuf_printf(sb,
3490                                             "\t<initiator id=\"%u\">%s</initiator>\n",
3491                                             j, port->wwpn_iid[j].name);
3492                                 else
3493                                         retval = sbuf_printf(sb,
3494                                             "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3495                                             j, port->wwpn_iid[j].wwpn);
3496                                 if (retval != 0)
3497                                         break;
3498                         }
3499                         if (retval != 0)
3500                                 break;
3501
3502                         retval = sbuf_printf(sb, "</targ_port>\n");
3503                         if (retval != 0)
3504                                 break;
3505                 }
3506                 mtx_unlock(&softc->ctl_lock);
3507
3508                 if ((retval != 0)
3509                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3510                         retval = 0;
3511                         sbuf_delete(sb);
3512                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3513                         snprintf(list->error_str, sizeof(list->error_str),
3514                                  "Out of space, %d bytes is too small",
3515                                  list->alloc_len);
3516                         break;
3517                 }
3518
3519                 sbuf_finish(sb);
3520
3521                 retval = copyout(sbuf_data(sb), list->lun_xml,
3522                                  sbuf_len(sb) + 1);
3523
3524                 list->fill_len = sbuf_len(sb) + 1;
3525                 list->status = CTL_LUN_LIST_OK;
3526                 sbuf_delete(sb);
3527                 break;
3528         }
3529         case CTL_LUN_MAP: {
3530                 struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3531                 struct ctl_port *port;
3532
3533                 mtx_lock(&softc->ctl_lock);
3534                 if (lm->port >= CTL_MAX_PORTS ||
3535                     (port = softc->ctl_ports[lm->port]) == NULL) {
3536                         mtx_unlock(&softc->ctl_lock);
3537                         return (ENXIO);
3538                 }
3539                 mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3540                 if (lm->plun < CTL_MAX_LUNS) {
3541                         if (lm->lun == UINT32_MAX)
3542                                 retval = ctl_lun_map_unset(port, lm->plun);
3543                         else if (lm->lun < CTL_MAX_LUNS &&
3544                             softc->ctl_luns[lm->lun] != NULL)
3545                                 retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3546                         else
3547                                 return (ENXIO);
3548                 } else if (lm->plun == UINT32_MAX) {
3549                         if (lm->lun == UINT32_MAX)
3550                                 retval = ctl_lun_map_deinit(port);
3551                         else
3552                                 retval = ctl_lun_map_init(port);
3553                 } else
3554                         return (ENXIO);
3555                 break;
3556         }
3557         default: {
3558                 /* XXX KDM should we fix this? */
3559 #if 0
3560                 struct ctl_backend_driver *backend;
3561                 unsigned int type;
3562                 int found;
3563
3564                 found = 0;
3565
3566                 /*
3567                  * We encode the backend type as the ioctl type for backend
3568                  * ioctls.  So parse it out here, and then search for a
3569                  * backend of this type.
3570                  */
3571                 type = _IOC_TYPE(cmd);
3572
3573                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3574                         if (backend->type == type) {
3575                                 found = 1;
3576                                 break;
3577                         }
3578                 }
3579                 if (found == 0) {
3580                         printf("ctl: unknown ioctl command %#lx or backend "
3581                                "%d\n", cmd, type);
3582                         retval = EINVAL;
3583                         break;
3584                 }
3585                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3586 #endif
3587                 retval = ENOTTY;
3588                 break;
3589         }
3590         }
3591         return (retval);
3592 }
3593
3594 uint32_t
3595 ctl_get_initindex(struct ctl_nexus *nexus)
3596 {
3597         if (nexus->targ_port < CTL_MAX_PORTS)
3598                 return (nexus->initid.id +
3599                         (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3600         else
3601                 return (nexus->initid.id +
3602                        ((nexus->targ_port - CTL_MAX_PORTS) *
3603                         CTL_MAX_INIT_PER_PORT));
3604 }
3605
3606 uint32_t
3607 ctl_get_resindex(struct ctl_nexus *nexus)
3608 {
3609         return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3610 }
3611
3612 uint32_t
3613 ctl_port_idx(int port_num)
3614 {
3615         if (port_num < CTL_MAX_PORTS)
3616                 return(port_num);
3617         else
3618                 return(port_num - CTL_MAX_PORTS);
3619 }
3620
3621 int
3622 ctl_lun_map_init(struct ctl_port *port)
3623 {
3624         struct ctl_softc *softc = control_softc;
3625         struct ctl_lun *lun;
3626         uint32_t i;
3627
3628         if (port->lun_map == NULL)
3629                 port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3630                     M_CTL, M_NOWAIT);
3631         if (port->lun_map == NULL)
3632                 return (ENOMEM);
3633         for (i = 0; i < CTL_MAX_LUNS; i++)
3634                 port->lun_map[i] = UINT32_MAX;
3635         if (port->status & CTL_PORT_STATUS_ONLINE) {
3636                 STAILQ_FOREACH(lun, &softc->lun_list, links)
3637                         port->lun_disable(port->targ_lun_arg, lun->lun);
3638         }
3639         return (0);
3640 }
3641
3642 int
3643 ctl_lun_map_deinit(struct ctl_port *port)
3644 {
3645         struct ctl_softc *softc = control_softc;
3646         struct ctl_lun *lun;
3647
3648         if (port->lun_map == NULL)
3649                 return (0);
3650         free(port->lun_map, M_CTL);
3651         port->lun_map = NULL;
3652         if (port->status & CTL_PORT_STATUS_ONLINE) {
3653                 STAILQ_FOREACH(lun, &softc->lun_list, links)
3654                         port->lun_enable(port->targ_lun_arg, lun->lun);
3655         }
3656         return (0);
3657 }
3658
3659 int
3660 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3661 {
3662         int status;
3663         uint32_t old;
3664
3665         if (port->lun_map == NULL) {
3666                 status = ctl_lun_map_init(port);
3667                 if (status != 0)
3668                         return (status);
3669         }
3670         old = port->lun_map[plun];
3671         port->lun_map[plun] = glun;
3672         if ((port->status & CTL_PORT_STATUS_ONLINE) && old >= CTL_MAX_LUNS)
3673                 port->lun_enable(port->targ_lun_arg, plun);
3674         return (0);
3675 }
3676
3677 int
3678 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3679 {
3680         uint32_t old;
3681
3682         if (port->lun_map == NULL)
3683                 return (0);
3684         old = port->lun_map[plun];
3685         port->lun_map[plun] = UINT32_MAX;
3686         if ((port->status & CTL_PORT_STATUS_ONLINE) && old < CTL_MAX_LUNS)
3687                 port->lun_disable(port->targ_lun_arg, plun);
3688         return (0);
3689 }
3690
3691 uint32_t
3692 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3693 {
3694
3695         if (port == NULL)
3696                 return (UINT32_MAX);
3697         if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3698                 return (lun_id);
3699         return (port->lun_map[lun_id]);
3700 }
3701
3702 uint32_t
3703 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3704 {
3705         uint32_t i;
3706
3707         if (port == NULL)
3708                 return (UINT32_MAX);
3709         if (port->lun_map == NULL)
3710                 return (lun_id);
3711         for (i = 0; i < CTL_MAX_LUNS; i++) {
3712                 if (port->lun_map[i] == lun_id)
3713                         return (i);
3714         }
3715         return (UINT32_MAX);
3716 }
3717
3718 static struct ctl_port *
3719 ctl_io_port(struct ctl_io_hdr *io_hdr)
3720 {
3721         int port_num;
3722
3723         port_num = io_hdr->nexus.targ_port;
3724         return (control_softc->ctl_ports[ctl_port_idx(port_num)]);
3725 }
3726
3727 /*
3728  * Note:  This only works for bitmask sizes that are at least 32 bits, and
3729  * that are a power of 2.
3730  */
3731 int
3732 ctl_ffz(uint32_t *mask, uint32_t size)
3733 {
3734         uint32_t num_chunks, num_pieces;
3735         int i, j;
3736
3737         num_chunks = (size >> 5);
3738         if (num_chunks == 0)
3739                 num_chunks++;
3740         num_pieces = MIN((sizeof(uint32_t) * 8), size);
3741
3742         for (i = 0; i < num_chunks; i++) {
3743                 for (j = 0; j < num_pieces; j++) {
3744                         if ((mask[i] & (1 << j)) == 0)
3745                                 return ((i << 5) + j);
3746                 }
3747         }
3748
3749         return (-1);
3750 }
3751
3752 int
3753 ctl_set_mask(uint32_t *mask, uint32_t bit)
3754 {
3755         uint32_t chunk, piece;
3756
3757         chunk = bit >> 5;
3758         piece = bit % (sizeof(uint32_t) * 8);
3759
3760         if ((mask[chunk] & (1 << piece)) != 0)
3761                 return (-1);
3762         else
3763                 mask[chunk] |= (1 << piece);
3764
3765         return (0);
3766 }
3767
3768 int
3769 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3770 {
3771         uint32_t chunk, piece;
3772
3773         chunk = bit >> 5;
3774         piece = bit % (sizeof(uint32_t) * 8);
3775
3776         if ((mask[chunk] & (1 << piece)) == 0)
3777                 return (-1);
3778         else
3779                 mask[chunk] &= ~(1 << piece);
3780
3781         return (0);
3782 }
3783
3784 int
3785 ctl_is_set(uint32_t *mask, uint32_t bit)
3786 {
3787         uint32_t chunk, piece;
3788
3789         chunk = bit >> 5;
3790         piece = bit % (sizeof(uint32_t) * 8);
3791
3792         if ((mask[chunk] & (1 << piece)) == 0)
3793                 return (0);
3794         else
3795                 return (1);
3796 }
3797
3798 static uint64_t
3799 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3800 {
3801         uint64_t *t;
3802
3803         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3804         if (t == NULL)
3805                 return (0);
3806         return (t[residx % CTL_MAX_INIT_PER_PORT]);
3807 }
3808
3809 static void
3810 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3811 {
3812         uint64_t *t;
3813
3814         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3815         if (t == NULL)
3816                 return;
3817         t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3818 }
3819
3820 static void
3821 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3822 {
3823         uint64_t *p;
3824         u_int i;
3825
3826         i = residx/CTL_MAX_INIT_PER_PORT;
3827         if (lun->pr_keys[i] != NULL)
3828                 return;
3829         mtx_unlock(&lun->lun_lock);
3830         p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3831             M_WAITOK | M_ZERO);
3832         mtx_lock(&lun->lun_lock);
3833         if (lun->pr_keys[i] == NULL)
3834                 lun->pr_keys[i] = p;
3835         else
3836                 free(p, M_CTL);
3837 }
3838
3839 static void
3840 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3841 {
3842         uint64_t *t;
3843
3844         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3845         KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3846         t[residx % CTL_MAX_INIT_PER_PORT] = key;
3847 }
3848
3849 /*
3850  * ctl_softc, pool_name, total_ctl_io are passed in.
3851  * npool is passed out.
3852  */
3853 int
3854 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3855                 uint32_t total_ctl_io, void **npool)
3856 {
3857 #ifdef IO_POOLS
3858         struct ctl_io_pool *pool;
3859
3860         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3861                                             M_NOWAIT | M_ZERO);
3862         if (pool == NULL)
3863                 return (ENOMEM);
3864
3865         snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3866         pool->ctl_softc = ctl_softc;
3867         pool->zone = uma_zsecond_create(pool->name, NULL,
3868             NULL, NULL, NULL, ctl_softc->io_zone);
3869         /* uma_prealloc(pool->zone, total_ctl_io); */
3870
3871         *npool = pool;
3872 #else
3873         *npool = ctl_softc->io_zone;
3874 #endif
3875         return (0);
3876 }
3877
3878 void
3879 ctl_pool_free(struct ctl_io_pool *pool)
3880 {
3881
3882         if (pool == NULL)
3883                 return;
3884
3885 #ifdef IO_POOLS
3886         uma_zdestroy(pool->zone);
3887         free(pool, M_CTL);
3888 #endif
3889 }
3890
3891 union ctl_io *
3892 ctl_alloc_io(void *pool_ref)
3893 {
3894         union ctl_io *io;
3895 #ifdef IO_POOLS
3896         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3897
3898         io = uma_zalloc(pool->zone, M_WAITOK);
3899 #else
3900         io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3901 #endif
3902         if (io != NULL)
3903                 io->io_hdr.pool = pool_ref;
3904         return (io);
3905 }
3906
3907 union ctl_io *
3908 ctl_alloc_io_nowait(void *pool_ref)
3909 {
3910         union ctl_io *io;
3911 #ifdef IO_POOLS
3912         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3913
3914         io = uma_zalloc(pool->zone, M_NOWAIT);
3915 #else
3916         io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3917 #endif
3918         if (io != NULL)
3919                 io->io_hdr.pool = pool_ref;
3920         return (io);
3921 }
3922
3923 void
3924 ctl_free_io(union ctl_io *io)
3925 {
3926 #ifdef IO_POOLS
3927         struct ctl_io_pool *pool;
3928 #endif
3929
3930         if (io == NULL)
3931                 return;
3932
3933 #ifdef IO_POOLS
3934         pool = (struct ctl_io_pool *)io->io_hdr.pool;
3935         uma_zfree(pool->zone, io);
3936 #else
3937         uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3938 #endif
3939 }
3940
3941 void
3942 ctl_zero_io(union ctl_io *io)
3943 {
3944         void *pool_ref;
3945
3946         if (io == NULL)
3947                 return;
3948
3949         /*
3950          * May need to preserve linked list pointers at some point too.
3951          */
3952         pool_ref = io->io_hdr.pool;
3953         memset(io, 0, sizeof(*io));
3954         io->io_hdr.pool = pool_ref;
3955 }
3956
3957 /*
3958  * This routine is currently used for internal copies of ctl_ios that need
3959  * to persist for some reason after we've already returned status to the
3960  * FETD.  (Thus the flag set.)
3961  *
3962  * XXX XXX
3963  * Note that this makes a blind copy of all fields in the ctl_io, except
3964  * for the pool reference.  This includes any memory that has been
3965  * allocated!  That memory will no longer be valid after done has been
3966  * called, so this would be VERY DANGEROUS for command that actually does
3967  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3968  * start and stop commands, which don't transfer any data, so this is not a
3969  * problem.  If it is used for anything else, the caller would also need to
3970  * allocate data buffer space and this routine would need to be modified to
3971  * copy the data buffer(s) as well.
3972  */
3973 void
3974 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3975 {
3976         void *pool_ref;
3977
3978         if ((src == NULL)
3979          || (dest == NULL))
3980                 return;
3981
3982         /*
3983          * May need to preserve linked list pointers at some point too.
3984          */
3985         pool_ref = dest->io_hdr.pool;
3986
3987         memcpy(dest, src, MIN(sizeof(*src), sizeof(*dest)));
3988
3989         dest->io_hdr.pool = pool_ref;
3990         /*
3991          * We need to know that this is an internal copy, and doesn't need
3992          * to get passed back to the FETD that allocated it.
3993          */
3994         dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3995 }
3996
3997 int
3998 ctl_expand_number(const char *buf, uint64_t *num)
3999 {
4000         char *endptr;
4001         uint64_t number;
4002         unsigned shift;
4003
4004         number = strtoq(buf, &endptr, 0);
4005
4006         switch (tolower((unsigned char)*endptr)) {
4007         case 'e':
4008                 shift = 60;
4009                 break;
4010         case 'p':
4011                 shift = 50;
4012                 break;
4013         case 't':
4014                 shift = 40;
4015                 break;
4016         case 'g':
4017                 shift = 30;
4018                 break;
4019         case 'm':
4020                 shift = 20;
4021                 break;
4022         case 'k':
4023                 shift = 10;
4024                 break;
4025         case 'b':
4026         case '\0': /* No unit. */
4027                 *num = number;
4028                 return (0);
4029         default:
4030                 /* Unrecognized unit. */
4031                 return (-1);
4032         }
4033
4034         if ((number << shift) >> shift != number) {
4035                 /* Overflow */
4036                 return (-1);
4037         }
4038         *num = number << shift;
4039         return (0);
4040 }
4041
4042
4043 /*
4044  * This routine could be used in the future to load default and/or saved
4045  * mode page parameters for a particuar lun.
4046  */
4047 static int
4048 ctl_init_page_index(struct ctl_lun *lun)
4049 {
4050         int i;
4051         struct ctl_page_index *page_index;
4052         const char *value;
4053         uint64_t ival;
4054
4055         memcpy(&lun->mode_pages.index, page_index_template,
4056                sizeof(page_index_template));
4057
4058         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4059
4060                 page_index = &lun->mode_pages.index[i];
4061                 /*
4062                  * If this is a disk-only mode page, there's no point in
4063                  * setting it up.  For some pages, we have to have some
4064                  * basic information about the disk in order to calculate the
4065                  * mode page data.
4066                  */
4067                 if ((lun->be_lun->lun_type != T_DIRECT)
4068                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4069                         continue;
4070
4071                 switch (page_index->page_code & SMPH_PC_MASK) {
4072                 case SMS_RW_ERROR_RECOVERY_PAGE: {
4073                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4074                                 panic("subpage is incorrect!");
4075                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4076                                &rw_er_page_default,
4077                                sizeof(rw_er_page_default));
4078                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4079                                &rw_er_page_changeable,
4080                                sizeof(rw_er_page_changeable));
4081                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4082                                &rw_er_page_default,
4083                                sizeof(rw_er_page_default));
4084                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4085                                &rw_er_page_default,
4086                                sizeof(rw_er_page_default));
4087                         page_index->page_data =
4088                                 (uint8_t *)lun->mode_pages.rw_er_page;
4089                         break;
4090                 }
4091                 case SMS_FORMAT_DEVICE_PAGE: {
4092                         struct scsi_format_page *format_page;
4093
4094                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4095                                 panic("subpage is incorrect!");
4096
4097                         /*
4098                          * Sectors per track are set above.  Bytes per
4099                          * sector need to be set here on a per-LUN basis.
4100                          */
4101                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4102                                &format_page_default,
4103                                sizeof(format_page_default));
4104                         memcpy(&lun->mode_pages.format_page[
4105                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
4106                                sizeof(format_page_changeable));
4107                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4108                                &format_page_default,
4109                                sizeof(format_page_default));
4110                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4111                                &format_page_default,
4112                                sizeof(format_page_default));
4113
4114                         format_page = &lun->mode_pages.format_page[
4115                                 CTL_PAGE_CURRENT];
4116                         scsi_ulto2b(lun->be_lun->blocksize,
4117                                     format_page->bytes_per_sector);
4118
4119                         format_page = &lun->mode_pages.format_page[
4120                                 CTL_PAGE_DEFAULT];
4121                         scsi_ulto2b(lun->be_lun->blocksize,
4122                                     format_page->bytes_per_sector);
4123
4124                         format_page = &lun->mode_pages.format_page[
4125                                 CTL_PAGE_SAVED];
4126                         scsi_ulto2b(lun->be_lun->blocksize,
4127                                     format_page->bytes_per_sector);
4128
4129                         page_index->page_data =
4130                                 (uint8_t *)lun->mode_pages.format_page;
4131                         break;
4132                 }
4133                 case SMS_RIGID_DISK_PAGE: {
4134                         struct scsi_rigid_disk_page *rigid_disk_page;
4135                         uint32_t sectors_per_cylinder;
4136                         uint64_t cylinders;
4137 #ifndef __XSCALE__
4138                         int shift;
4139 #endif /* !__XSCALE__ */
4140
4141                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4142                                 panic("invalid subpage value %d",
4143                                       page_index->subpage);
4144
4145                         /*
4146                          * Rotation rate and sectors per track are set
4147                          * above.  We calculate the cylinders here based on
4148                          * capacity.  Due to the number of heads and
4149                          * sectors per track we're using, smaller arrays
4150                          * may turn out to have 0 cylinders.  Linux and
4151                          * FreeBSD don't pay attention to these mode pages
4152                          * to figure out capacity, but Solaris does.  It
4153                          * seems to deal with 0 cylinders just fine, and
4154                          * works out a fake geometry based on the capacity.
4155                          */
4156                         memcpy(&lun->mode_pages.rigid_disk_page[
4157                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4158                                sizeof(rigid_disk_page_default));
4159                         memcpy(&lun->mode_pages.rigid_disk_page[
4160                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4161                                sizeof(rigid_disk_page_changeable));
4162
4163                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4164                                 CTL_DEFAULT_HEADS;
4165
4166                         /*
4167                          * The divide method here will be more accurate,
4168                          * probably, but results in floating point being
4169                          * used in the kernel on i386 (__udivdi3()).  On the
4170                          * XScale, though, __udivdi3() is implemented in
4171                          * software.
4172                          *
4173                          * The shift method for cylinder calculation is
4174                          * accurate if sectors_per_cylinder is a power of
4175                          * 2.  Otherwise it might be slightly off -- you
4176                          * might have a bit of a truncation problem.
4177                          */
4178 #ifdef  __XSCALE__
4179                         cylinders = (lun->be_lun->maxlba + 1) /
4180                                 sectors_per_cylinder;
4181 #else
4182                         for (shift = 31; shift > 0; shift--) {
4183                                 if (sectors_per_cylinder & (1 << shift))
4184                                         break;
4185                         }
4186                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
4187 #endif
4188
4189                         /*
4190                          * We've basically got 3 bytes, or 24 bits for the
4191                          * cylinder size in the mode page.  If we're over,
4192                          * just round down to 2^24.
4193                          */
4194                         if (cylinders > 0xffffff)
4195                                 cylinders = 0xffffff;
4196
4197                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4198                                 CTL_PAGE_DEFAULT];
4199                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4200
4201                         if ((value = ctl_get_opt(&lun->be_lun->options,
4202                             "rpm")) != NULL) {
4203                                 scsi_ulto2b(strtol(value, NULL, 0),
4204                                      rigid_disk_page->rotation_rate);
4205                         }
4206
4207                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4208                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4209                                sizeof(rigid_disk_page_default));
4210                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4211                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4212                                sizeof(rigid_disk_page_default));
4213
4214                         page_index->page_data =
4215                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
4216                         break;
4217                 }
4218                 case SMS_CACHING_PAGE: {
4219                         struct scsi_caching_page *caching_page;
4220
4221                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4222                                 panic("invalid subpage value %d",
4223                                       page_index->subpage);
4224                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4225                                &caching_page_default,
4226                                sizeof(caching_page_default));
4227                         memcpy(&lun->mode_pages.caching_page[
4228                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4229                                sizeof(caching_page_changeable));
4230                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4231                                &caching_page_default,
4232                                sizeof(caching_page_default));
4233                         caching_page = &lun->mode_pages.caching_page[
4234                             CTL_PAGE_SAVED];
4235                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
4236                         if (value != NULL && strcmp(value, "off") == 0)
4237                                 caching_page->flags1 &= ~SCP_WCE;
4238                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
4239                         if (value != NULL && strcmp(value, "off") == 0)
4240                                 caching_page->flags1 |= SCP_RCD;
4241                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4242                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4243                                sizeof(caching_page_default));
4244                         page_index->page_data =
4245                                 (uint8_t *)lun->mode_pages.caching_page;
4246                         break;
4247                 }
4248                 case SMS_CONTROL_MODE_PAGE: {
4249                         struct scsi_control_page *control_page;
4250
4251                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4252                                 panic("invalid subpage value %d",
4253                                       page_index->subpage);
4254
4255                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4256                                &control_page_default,
4257                                sizeof(control_page_default));
4258                         memcpy(&lun->mode_pages.control_page[
4259                                CTL_PAGE_CHANGEABLE], &control_page_changeable,
4260                                sizeof(control_page_changeable));
4261                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4262                                &control_page_default,
4263                                sizeof(control_page_default));
4264                         control_page = &lun->mode_pages.control_page[
4265                             CTL_PAGE_SAVED];
4266                         value = ctl_get_opt(&lun->be_lun->options, "reordering");
4267                         if (value != NULL && strcmp(value, "unrestricted") == 0) {
4268                                 control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4269                                 control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4270                         }
4271                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4272                                &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4273                                sizeof(control_page_default));
4274                         page_index->page_data =
4275                                 (uint8_t *)lun->mode_pages.control_page;
4276                         break;
4277
4278                 }
4279                 case SMS_INFO_EXCEPTIONS_PAGE: {
4280                         switch (page_index->subpage) {
4281                         case SMS_SUBPAGE_PAGE_0:
4282                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4283                                        &ie_page_default,
4284                                        sizeof(ie_page_default));
4285                                 memcpy(&lun->mode_pages.ie_page[
4286                                        CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4287                                        sizeof(ie_page_changeable));
4288                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4289                                        &ie_page_default,
4290                                        sizeof(ie_page_default));
4291                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4292                                        &ie_page_default,
4293                                        sizeof(ie_page_default));
4294                                 page_index->page_data =
4295                                         (uint8_t *)lun->mode_pages.ie_page;
4296                                 break;
4297                         case 0x02: {
4298                                 struct ctl_logical_block_provisioning_page *page;
4299
4300                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4301                                        &lbp_page_default,
4302                                        sizeof(lbp_page_default));
4303                                 memcpy(&lun->mode_pages.lbp_page[
4304                                        CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4305                                        sizeof(lbp_page_changeable));
4306                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4307                                        &lbp_page_default,
4308                                        sizeof(lbp_page_default));
4309                                 page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4310                                 value = ctl_get_opt(&lun->be_lun->options,
4311                                     "avail-threshold");
4312                                 if (value != NULL &&
4313                                     ctl_expand_number(value, &ival) == 0) {
4314                                         page->descr[0].flags |= SLBPPD_ENABLED |
4315                                             SLBPPD_ARMING_DEC;
4316                                         if (lun->be_lun->blocksize)
4317                                                 ival /= lun->be_lun->blocksize;
4318                                         else
4319                                                 ival /= 512;
4320                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4321                                             page->descr[0].count);
4322                                 }
4323                                 value = ctl_get_opt(&lun->be_lun->options,
4324                                     "used-threshold");
4325                                 if (value != NULL &&
4326                                     ctl_expand_number(value, &ival) == 0) {
4327                                         page->descr[1].flags |= SLBPPD_ENABLED |
4328                                             SLBPPD_ARMING_INC;
4329                                         if (lun->be_lun->blocksize)
4330                                                 ival /= lun->be_lun->blocksize;
4331                                         else
4332                                                 ival /= 512;
4333                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4334                                             page->descr[1].count);
4335                                 }
4336                                 value = ctl_get_opt(&lun->be_lun->options,
4337                                     "pool-avail-threshold");
4338                                 if (value != NULL &&
4339                                     ctl_expand_number(value, &ival) == 0) {
4340                                         page->descr[2].flags |= SLBPPD_ENABLED |
4341                                             SLBPPD_ARMING_DEC;
4342                                         if (lun->be_lun->blocksize)
4343                                                 ival /= lun->be_lun->blocksize;
4344                                         else
4345                                                 ival /= 512;
4346                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4347                                             page->descr[2].count);
4348                                 }
4349                                 value = ctl_get_opt(&lun->be_lun->options,
4350                                     "pool-used-threshold");
4351                                 if (value != NULL &&
4352                                     ctl_expand_number(value, &ival) == 0) {
4353                                         page->descr[3].flags |= SLBPPD_ENABLED |
4354                                             SLBPPD_ARMING_INC;
4355                                         if (lun->be_lun->blocksize)
4356                                                 ival /= lun->be_lun->blocksize;
4357                                         else
4358                                                 ival /= 512;
4359                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4360                                             page->descr[3].count);
4361                                 }
4362                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4363                                        &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4364                                        sizeof(lbp_page_default));
4365                                 page_index->page_data =
4366                                         (uint8_t *)lun->mode_pages.lbp_page;
4367                         }}
4368                         break;
4369                 }
4370                 case SMS_VENDOR_SPECIFIC_PAGE:{
4371                         switch (page_index->subpage) {
4372                         case DBGCNF_SUBPAGE_CODE: {
4373                                 struct copan_debugconf_subpage *current_page,
4374                                                                *saved_page;
4375
4376                                 memcpy(&lun->mode_pages.debugconf_subpage[
4377                                        CTL_PAGE_CURRENT],
4378                                        &debugconf_page_default,
4379                                        sizeof(debugconf_page_default));
4380                                 memcpy(&lun->mode_pages.debugconf_subpage[
4381                                        CTL_PAGE_CHANGEABLE],
4382                                        &debugconf_page_changeable,
4383                                        sizeof(debugconf_page_changeable));
4384                                 memcpy(&lun->mode_pages.debugconf_subpage[
4385                                        CTL_PAGE_DEFAULT],
4386                                        &debugconf_page_default,
4387                                        sizeof(debugconf_page_default));
4388                                 memcpy(&lun->mode_pages.debugconf_subpage[
4389                                        CTL_PAGE_SAVED],
4390                                        &debugconf_page_default,
4391                                        sizeof(debugconf_page_default));
4392                                 page_index->page_data =
4393                                         (uint8_t *)lun->mode_pages.debugconf_subpage;
4394
4395                                 current_page = (struct copan_debugconf_subpage *)
4396                                         (page_index->page_data +
4397                                          (page_index->page_len *
4398                                           CTL_PAGE_CURRENT));
4399                                 saved_page = (struct copan_debugconf_subpage *)
4400                                         (page_index->page_data +
4401                                          (page_index->page_len *
4402                                           CTL_PAGE_SAVED));
4403                                 break;
4404                         }
4405                         default:
4406                                 panic("invalid subpage value %d",
4407                                       page_index->subpage);
4408                                 break;
4409                         }
4410                         break;
4411                 }
4412                 default:
4413                         panic("invalid page value %d",
4414                               page_index->page_code & SMPH_PC_MASK);
4415                         break;
4416         }
4417         }
4418
4419         return (CTL_RETVAL_COMPLETE);
4420 }
4421
4422 static int
4423 ctl_init_log_page_index(struct ctl_lun *lun)
4424 {
4425         struct ctl_page_index *page_index;
4426         int i, j, k, prev;
4427
4428         memcpy(&lun->log_pages.index, log_page_index_template,
4429                sizeof(log_page_index_template));
4430
4431         prev = -1;
4432         for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4433
4434                 page_index = &lun->log_pages.index[i];
4435                 /*
4436                  * If this is a disk-only mode page, there's no point in
4437                  * setting it up.  For some pages, we have to have some
4438                  * basic information about the disk in order to calculate the
4439                  * mode page data.
4440                  */
4441                 if ((lun->be_lun->lun_type != T_DIRECT)
4442                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4443                         continue;
4444
4445                 if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4446                      lun->backend->lun_attr == NULL)
4447                         continue;
4448
4449                 if (page_index->page_code != prev) {
4450                         lun->log_pages.pages_page[j] = page_index->page_code;
4451                         prev = page_index->page_code;
4452                         j++;
4453                 }
4454                 lun->log_pages.subpages_page[k*2] = page_index->page_code;
4455                 lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4456                 k++;
4457         }
4458         lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4459         lun->log_pages.index[0].page_len = j;
4460         lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4461         lun->log_pages.index[1].page_len = k * 2;
4462         lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4463         lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4464         lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4465         lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4466
4467         return (CTL_RETVAL_COMPLETE);
4468 }
4469
4470 static int
4471 hex2bin(const char *str, uint8_t *buf, int buf_size)
4472 {
4473         int i;
4474         u_char c;
4475
4476         memset(buf, 0, buf_size);
4477         while (isspace(str[0]))
4478                 str++;
4479         if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4480                 str += 2;
4481         buf_size *= 2;
4482         for (i = 0; str[i] != 0 && i < buf_size; i++) {
4483                 c = str[i];
4484                 if (isdigit(c))
4485                         c -= '0';
4486                 else if (isalpha(c))
4487                         c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4488                 else
4489                         break;
4490                 if (c >= 16)
4491                         break;
4492                 if ((i & 1) == 0)
4493                         buf[i / 2] |= (c << 4);
4494                 else
4495                         buf[i / 2] |= c;
4496         }
4497         return ((i + 1) / 2);
4498 }
4499
4500 /*
4501  * LUN allocation.
4502  *
4503  * Requirements:
4504  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4505  *   wants us to allocate the LUN and he can block.
4506  * - ctl_softc is always set
4507  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4508  *
4509  * Returns 0 for success, non-zero (errno) for failure.
4510  */
4511 static int
4512 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4513               struct ctl_be_lun *const be_lun)
4514 {
4515         struct ctl_lun *nlun, *lun;
4516         struct scsi_vpd_id_descriptor *desc;
4517         struct scsi_vpd_id_t10 *t10id;
4518         const char *eui, *naa, *scsiname, *vendor, *value;
4519         int lun_number, i, lun_malloced;
4520         int devidlen, idlen1, idlen2 = 0, len;
4521
4522         if (be_lun == NULL)
4523                 return (EINVAL);
4524
4525         /*
4526          * We currently only support Direct Access or Processor LUN types.
4527          */
4528         switch (be_lun->lun_type) {
4529         case T_DIRECT:
4530                 break;
4531         case T_PROCESSOR:
4532                 break;
4533         case T_SEQUENTIAL:
4534         case T_CHANGER:
4535         default:
4536                 be_lun->lun_config_status(be_lun->be_lun,
4537                                           CTL_LUN_CONFIG_FAILURE);
4538                 break;
4539         }
4540         if (ctl_lun == NULL) {
4541                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4542                 lun_malloced = 1;
4543         } else {
4544                 lun_malloced = 0;
4545                 lun = ctl_lun;
4546         }
4547
4548         memset(lun, 0, sizeof(*lun));
4549         if (lun_malloced)
4550                 lun->flags = CTL_LUN_MALLOCED;
4551
4552         /* Generate LUN ID. */
4553         devidlen = max(CTL_DEVID_MIN_LEN,
4554             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4555         idlen1 = sizeof(*t10id) + devidlen;
4556         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4557         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4558         if (scsiname != NULL) {
4559                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4560                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4561         }
4562         eui = ctl_get_opt(&be_lun->options, "eui");
4563         if (eui != NULL) {
4564                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4565         }
4566         naa = ctl_get_opt(&be_lun->options, "naa");
4567         if (naa != NULL) {
4568                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4569         }
4570         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4571             M_CTL, M_WAITOK | M_ZERO);
4572         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4573         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4574         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4575         desc->length = idlen1;
4576         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4577         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4578         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4579                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4580         } else {
4581                 strncpy(t10id->vendor, vendor,
4582                     min(sizeof(t10id->vendor), strlen(vendor)));
4583         }
4584         strncpy((char *)t10id->vendor_spec_id,
4585             (char *)be_lun->device_id, devidlen);
4586         if (scsiname != NULL) {
4587                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4588                     desc->length);
4589                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4590                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4591                     SVPD_ID_TYPE_SCSI_NAME;
4592                 desc->length = idlen2;
4593                 strlcpy(desc->identifier, scsiname, idlen2);
4594         }
4595         if (eui != NULL) {
4596                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4597                     desc->length);
4598                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4599                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4600                     SVPD_ID_TYPE_EUI64;
4601                 desc->length = hex2bin(eui, desc->identifier, 16);
4602                 desc->length = desc->length > 12 ? 16 :
4603                     (desc->length > 8 ? 12 : 8);
4604                 len -= 16 - desc->length;
4605         }
4606         if (naa != NULL) {
4607                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4608                     desc->length);
4609                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4610                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4611                     SVPD_ID_TYPE_NAA;
4612                 desc->length = hex2bin(naa, desc->identifier, 16);
4613                 desc->length = desc->length > 8 ? 16 : 8;
4614                 len -= 16 - desc->length;
4615         }
4616         lun->lun_devid->len = len;
4617
4618         mtx_lock(&ctl_softc->ctl_lock);
4619         /*
4620          * See if the caller requested a particular LUN number.  If so, see
4621          * if it is available.  Otherwise, allocate the first available LUN.
4622          */
4623         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4624                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4625                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4626                         mtx_unlock(&ctl_softc->ctl_lock);
4627                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4628                                 printf("ctl: requested LUN ID %d is higher "
4629                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4630                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4631                         } else {
4632                                 /*
4633                                  * XXX KDM return an error, or just assign
4634                                  * another LUN ID in this case??
4635                                  */
4636                                 printf("ctl: requested LUN ID %d is already "
4637                                        "in use\n", be_lun->req_lun_id);
4638                         }
4639                         if (lun->flags & CTL_LUN_MALLOCED)
4640                                 free(lun, M_CTL);
4641                         be_lun->lun_config_status(be_lun->be_lun,
4642                                                   CTL_LUN_CONFIG_FAILURE);
4643                         return (ENOSPC);
4644                 }
4645                 lun_number = be_lun->req_lun_id;
4646         } else {
4647                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4648                 if (lun_number == -1) {
4649                         mtx_unlock(&ctl_softc->ctl_lock);
4650                         printf("ctl: can't allocate LUN, out of LUNs\n");
4651                         if (lun->flags & CTL_LUN_MALLOCED)
4652                                 free(lun, M_CTL);
4653                         be_lun->lun_config_status(be_lun->be_lun,
4654                                                   CTL_LUN_CONFIG_FAILURE);
4655                         return (ENOSPC);
4656                 }
4657         }
4658         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4659
4660         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4661         lun->lun = lun_number;
4662         lun->be_lun = be_lun;
4663         /*
4664          * The processor LUN is always enabled.  Disk LUNs come on line
4665          * disabled, and must be enabled by the backend.
4666          */
4667         lun->flags |= CTL_LUN_DISABLED;
4668         lun->backend = be_lun->be;
4669         be_lun->ctl_lun = lun;
4670         be_lun->lun_id = lun_number;
4671         atomic_add_int(&be_lun->be->num_luns, 1);
4672         if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4673                 lun->flags |= CTL_LUN_OFFLINE;
4674
4675         if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4676                 lun->flags |= CTL_LUN_STOPPED;
4677
4678         if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4679                 lun->flags |= CTL_LUN_INOPERABLE;
4680
4681         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4682                 lun->flags |= CTL_LUN_PRIMARY_SC;
4683
4684         value = ctl_get_opt(&be_lun->options, "readonly");
4685         if (value != NULL && strcmp(value, "on") == 0)
4686                 lun->flags |= CTL_LUN_READONLY;
4687
4688         lun->serseq = CTL_LUN_SERSEQ_OFF;
4689         if (be_lun->flags & CTL_LUN_FLAG_SERSEQ_READ)
4690                 lun->serseq = CTL_LUN_SERSEQ_READ;
4691         value = ctl_get_opt(&be_lun->options, "serseq");
4692         if (value != NULL && strcmp(value, "on") == 0)
4693                 lun->serseq = CTL_LUN_SERSEQ_ON;
4694         else if (value != NULL && strcmp(value, "read") == 0)
4695                 lun->serseq = CTL_LUN_SERSEQ_READ;
4696         else if (value != NULL && strcmp(value, "off") == 0)
4697                 lun->serseq = CTL_LUN_SERSEQ_OFF;
4698
4699         lun->ctl_softc = ctl_softc;
4700 #ifdef CTL_TIME_IO
4701         lun->last_busy = getsbinuptime();
4702 #endif
4703         TAILQ_INIT(&lun->ooa_queue);
4704         TAILQ_INIT(&lun->blocked_queue);
4705         STAILQ_INIT(&lun->error_list);
4706         ctl_tpc_lun_init(lun);
4707
4708         /*
4709          * Initialize the mode and log page index.
4710          */
4711         ctl_init_page_index(lun);
4712         ctl_init_log_page_index(lun);
4713
4714         /*
4715          * Now, before we insert this lun on the lun list, set the lun
4716          * inventory changed UA for all other luns.
4717          */
4718         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4719                 mtx_lock(&nlun->lun_lock);
4720                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4721                 mtx_unlock(&nlun->lun_lock);
4722         }
4723
4724         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4725
4726         ctl_softc->ctl_luns[lun_number] = lun;
4727
4728         ctl_softc->num_luns++;
4729
4730         /* Setup statistics gathering */
4731         lun->stats.device_type = be_lun->lun_type;
4732         lun->stats.lun_number = lun_number;
4733         if (lun->stats.device_type == T_DIRECT)
4734                 lun->stats.blocksize = be_lun->blocksize;
4735         else
4736                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4737         for (i = 0;i < CTL_MAX_PORTS;i++)
4738                 lun->stats.ports[i].targ_port = i;
4739
4740         mtx_unlock(&ctl_softc->ctl_lock);
4741
4742         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4743         return (0);
4744 }
4745
4746 /*
4747  * Delete a LUN.
4748  * Assumptions:
4749  * - LUN has already been marked invalid and any pending I/O has been taken
4750  *   care of.
4751  */
4752 static int
4753 ctl_free_lun(struct ctl_lun *lun)
4754 {
4755         struct ctl_softc *softc;
4756         struct ctl_lun *nlun;
4757         int i;
4758
4759         softc = lun->ctl_softc;
4760
4761         mtx_assert(&softc->ctl_lock, MA_OWNED);
4762
4763         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4764
4765         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4766
4767         softc->ctl_luns[lun->lun] = NULL;
4768
4769         if (!TAILQ_EMPTY(&lun->ooa_queue))
4770                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4771
4772         softc->num_luns--;
4773
4774         /*
4775          * Tell the backend to free resources, if this LUN has a backend.
4776          */
4777         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4778         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4779
4780         ctl_tpc_lun_shutdown(lun);
4781         mtx_destroy(&lun->lun_lock);
4782         free(lun->lun_devid, M_CTL);
4783         for (i = 0; i < CTL_MAX_PORTS; i++)
4784                 free(lun->pending_ua[i], M_CTL);
4785         for (i = 0; i < 2 * CTL_MAX_PORTS; i++)
4786                 free(lun->pr_keys[i], M_CTL);
4787         free(lun->write_buffer, M_CTL);
4788         if (lun->flags & CTL_LUN_MALLOCED)
4789                 free(lun, M_CTL);
4790
4791         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4792                 mtx_lock(&nlun->lun_lock);
4793                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4794                 mtx_unlock(&nlun->lun_lock);
4795         }
4796
4797         return (0);
4798 }
4799
4800 static void
4801 ctl_create_lun(struct ctl_be_lun *be_lun)
4802 {
4803         struct ctl_softc *softc;
4804
4805         softc = control_softc;
4806
4807         /*
4808          * ctl_alloc_lun() should handle all potential failure cases.
4809          */
4810         ctl_alloc_lun(softc, NULL, be_lun);
4811 }
4812
4813 int
4814 ctl_add_lun(struct ctl_be_lun *be_lun)
4815 {
4816         struct ctl_softc *softc = control_softc;
4817
4818         mtx_lock(&softc->ctl_lock);
4819         STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4820         mtx_unlock(&softc->ctl_lock);
4821         wakeup(&softc->pending_lun_queue);
4822
4823         return (0);
4824 }
4825
4826 int
4827 ctl_enable_lun(struct ctl_be_lun *be_lun)
4828 {
4829         struct ctl_softc *softc;
4830         struct ctl_port *port, *nport;
4831         struct ctl_lun *lun;
4832         int retval;
4833
4834         lun = (struct ctl_lun *)be_lun->ctl_lun;
4835         softc = lun->ctl_softc;
4836
4837         mtx_lock(&softc->ctl_lock);
4838         mtx_lock(&lun->lun_lock);
4839         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4840                 /*
4841                  * eh?  Why did we get called if the LUN is already
4842                  * enabled?
4843                  */
4844                 mtx_unlock(&lun->lun_lock);
4845                 mtx_unlock(&softc->ctl_lock);
4846                 return (0);
4847         }
4848         lun->flags &= ~CTL_LUN_DISABLED;
4849         mtx_unlock(&lun->lun_lock);
4850
4851         for (port = STAILQ_FIRST(&softc->port_list); port != NULL; port = nport) {
4852                 nport = STAILQ_NEXT(port, links);
4853                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4854                     port->lun_map != NULL)
4855                         continue;
4856
4857                 /*
4858                  * Drop the lock while we call the FETD's enable routine.
4859                  * This can lead to a callback into CTL (at least in the
4860                  * case of the internal initiator frontend.
4861                  */
4862                 mtx_unlock(&softc->ctl_lock);
4863                 retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4864                 mtx_lock(&softc->ctl_lock);
4865                 if (retval != 0) {
4866                         printf("%s: FETD %s port %d returned error "
4867                                "%d for lun_enable on lun %jd\n",
4868                                __func__, port->port_name, port->targ_port,
4869                                retval, (intmax_t)lun->lun);
4870                 }
4871         }
4872
4873         mtx_unlock(&softc->ctl_lock);
4874
4875         return (0);
4876 }
4877
4878 int
4879 ctl_disable_lun(struct ctl_be_lun *be_lun)
4880 {
4881         struct ctl_softc *softc;
4882         struct ctl_port *port;
4883         struct ctl_lun *lun;
4884         int retval;
4885
4886         lun = (struct ctl_lun *)be_lun->ctl_lun;
4887         softc = lun->ctl_softc;
4888
4889         mtx_lock(&softc->ctl_lock);
4890         mtx_lock(&lun->lun_lock);
4891         if (lun->flags & CTL_LUN_DISABLED) {
4892                 mtx_unlock(&lun->lun_lock);
4893                 mtx_unlock(&softc->ctl_lock);
4894                 return (0);
4895         }
4896         lun->flags |= CTL_LUN_DISABLED;
4897         mtx_unlock(&lun->lun_lock);
4898
4899         STAILQ_FOREACH(port, &softc->port_list, links) {
4900                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4901                     port->lun_map != NULL)
4902                         continue;
4903                 mtx_unlock(&softc->ctl_lock);
4904                 /*
4905                  * Drop the lock before we call the frontend's disable
4906                  * routine, to avoid lock order reversals.
4907                  *
4908                  * XXX KDM what happens if the frontend list changes while
4909                  * we're traversing it?  It's unlikely, but should be handled.
4910                  */
4911                 retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4912                 mtx_lock(&softc->ctl_lock);
4913                 if (retval != 0) {
4914                         printf("%s: FETD %s port %d returned error "
4915                                "%d for lun_disable on lun %jd\n",
4916                                __func__, port->port_name, port->targ_port,
4917                                retval, (intmax_t)lun->lun);
4918                 }
4919         }
4920
4921         mtx_unlock(&softc->ctl_lock);
4922
4923         return (0);
4924 }
4925
4926 int
4927 ctl_start_lun(struct ctl_be_lun *be_lun)
4928 {
4929         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4930
4931         mtx_lock(&lun->lun_lock);
4932         lun->flags &= ~CTL_LUN_STOPPED;
4933         mtx_unlock(&lun->lun_lock);
4934         return (0);
4935 }
4936
4937 int
4938 ctl_stop_lun(struct ctl_be_lun *be_lun)
4939 {
4940         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4941
4942         mtx_lock(&lun->lun_lock);
4943         lun->flags |= CTL_LUN_STOPPED;
4944         mtx_unlock(&lun->lun_lock);
4945         return (0);
4946 }
4947
4948 int
4949 ctl_lun_offline(struct ctl_be_lun *be_lun)
4950 {
4951         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4952
4953         mtx_lock(&lun->lun_lock);
4954         lun->flags |= CTL_LUN_OFFLINE;
4955         mtx_unlock(&lun->lun_lock);
4956         return (0);
4957 }
4958
4959 int
4960 ctl_lun_online(struct ctl_be_lun *be_lun)
4961 {
4962         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4963
4964         mtx_lock(&lun->lun_lock);
4965         lun->flags &= ~CTL_LUN_OFFLINE;
4966         mtx_unlock(&lun->lun_lock);
4967         return (0);
4968 }
4969
4970 int
4971 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4972 {
4973         struct ctl_softc *softc;
4974         struct ctl_lun *lun;
4975
4976         lun = (struct ctl_lun *)be_lun->ctl_lun;
4977         softc = lun->ctl_softc;
4978
4979         mtx_lock(&lun->lun_lock);
4980
4981         /*
4982          * The LUN needs to be disabled before it can be marked invalid.
4983          */
4984         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4985                 mtx_unlock(&lun->lun_lock);
4986                 return (-1);
4987         }
4988         /*
4989          * Mark the LUN invalid.
4990          */
4991         lun->flags |= CTL_LUN_INVALID;
4992
4993         /*
4994          * If there is nothing in the OOA queue, go ahead and free the LUN.
4995          * If we have something in the OOA queue, we'll free it when the
4996          * last I/O completes.
4997          */
4998         if (TAILQ_EMPTY(&lun->ooa_queue)) {
4999                 mtx_unlock(&lun->lun_lock);
5000                 mtx_lock(&softc->ctl_lock);
5001                 ctl_free_lun(lun);
5002                 mtx_unlock(&softc->ctl_lock);
5003         } else
5004                 mtx_unlock(&lun->lun_lock);
5005
5006         return (0);
5007 }
5008
5009 int
5010 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5011 {
5012         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5013
5014         mtx_lock(&lun->lun_lock);
5015         lun->flags |= CTL_LUN_INOPERABLE;
5016         mtx_unlock(&lun->lun_lock);
5017         return (0);
5018 }
5019
5020 int
5021 ctl_lun_operable(struct ctl_be_lun *be_lun)
5022 {
5023         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5024
5025         mtx_lock(&lun->lun_lock);
5026         lun->flags &= ~CTL_LUN_INOPERABLE;
5027         mtx_unlock(&lun->lun_lock);
5028         return (0);
5029 }
5030
5031 void
5032 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5033 {
5034         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5035
5036         mtx_lock(&lun->lun_lock);
5037         ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGED);
5038         mtx_unlock(&lun->lun_lock);
5039 }
5040
5041 /*
5042  * Backend "memory move is complete" callback for requests that never
5043  * make it down to say RAIDCore's configuration code.
5044  */
5045 int
5046 ctl_config_move_done(union ctl_io *io)
5047 {
5048         int retval;
5049
5050         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5051         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5052             ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5053
5054         if ((io->io_hdr.port_status != 0) &&
5055             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5056              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5057                 /*
5058                  * For hardware error sense keys, the sense key
5059                  * specific value is defined to be a retry count,
5060                  * but we use it to pass back an internal FETD
5061                  * error code.  XXX KDM  Hopefully the FETD is only
5062                  * using 16 bits for an error code, since that's
5063                  * all the space we have in the sks field.
5064                  */
5065                 ctl_set_internal_failure(&io->scsiio,
5066                                          /*sks_valid*/ 1,
5067                                          /*retry_count*/
5068                                          io->io_hdr.port_status);
5069         }
5070
5071         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5072             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5073              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5074             ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5075                 /*
5076                  * XXX KDM just assuming a single pointer here, and not a
5077                  * S/G list.  If we start using S/G lists for config data,
5078                  * we'll need to know how to clean them up here as well.
5079                  */
5080                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5081                         free(io->scsiio.kern_data_ptr, M_CTL);
5082                 ctl_done(io);
5083                 retval = CTL_RETVAL_COMPLETE;
5084         } else {
5085                 /*
5086                  * XXX KDM now we need to continue data movement.  Some
5087                  * options:
5088                  * - call ctl_scsiio() again?  We don't do this for data
5089                  *   writes, because for those at least we know ahead of
5090                  *   time where the write will go and how long it is.  For
5091                  *   config writes, though, that information is largely
5092                  *   contained within the write itself, thus we need to
5093                  *   parse out the data again.
5094                  *
5095                  * - Call some other function once the data is in?
5096                  */
5097                 if (ctl_debug & CTL_DEBUG_CDB_DATA)
5098                         ctl_data_print(io);
5099
5100                 /*
5101                  * XXX KDM call ctl_scsiio() again for now, and check flag
5102                  * bits to see whether we're allocated or not.
5103                  */
5104                 retval = ctl_scsiio(&io->scsiio);
5105         }
5106         return (retval);
5107 }
5108
5109 /*
5110  * This gets called by a backend driver when it is done with a
5111  * data_submit method.
5112  */
5113 void
5114 ctl_data_submit_done(union ctl_io *io)
5115 {
5116         /*
5117          * If the IO_CONT flag is set, we need to call the supplied
5118          * function to continue processing the I/O, instead of completing
5119          * the I/O just yet.
5120          *
5121          * If there is an error, though, we don't want to keep processing.
5122          * Instead, just send status back to the initiator.
5123          */
5124         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5125             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5126             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5127              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5128                 io->scsiio.io_cont(io);
5129                 return;
5130         }
5131         ctl_done(io);
5132 }
5133
5134 /*
5135  * This gets called by a backend driver when it is done with a
5136  * configuration write.
5137  */
5138 void
5139 ctl_config_write_done(union ctl_io *io)
5140 {
5141         uint8_t *buf;
5142
5143         /*
5144          * If the IO_CONT flag is set, we need to call the supplied
5145          * function to continue processing the I/O, instead of completing
5146          * the I/O just yet.
5147          *
5148          * If there is an error, though, we don't want to keep processing.
5149          * Instead, just send status back to the initiator.
5150          */
5151         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5152             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5153             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5154              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5155                 io->scsiio.io_cont(io);
5156                 return;
5157         }
5158         /*
5159          * Since a configuration write can be done for commands that actually
5160          * have data allocated, like write buffer, and commands that have
5161          * no data, like start/stop unit, we need to check here.
5162          */
5163         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5164                 buf = io->scsiio.kern_data_ptr;
5165         else
5166                 buf = NULL;
5167         ctl_done(io);
5168         if (buf)
5169                 free(buf, M_CTL);
5170 }
5171
5172 void
5173 ctl_config_read_done(union ctl_io *io)
5174 {
5175         uint8_t *buf;
5176
5177         /*
5178          * If there is some error -- we are done, skip data transfer.
5179          */
5180         if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5181             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5182              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5183                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5184                         buf = io->scsiio.kern_data_ptr;
5185                 else
5186                         buf = NULL;
5187                 ctl_done(io);
5188                 if (buf)
5189                         free(buf, M_CTL);
5190                 return;
5191         }
5192
5193         /*
5194          * If the IO_CONT flag is set, we need to call the supplied
5195          * function to continue processing the I/O, instead of completing
5196          * the I/O just yet.
5197          */
5198         if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5199                 io->scsiio.io_cont(io);
5200                 return;
5201         }
5202
5203         ctl_datamove(io);
5204 }
5205
5206 /*
5207  * SCSI release command.
5208  */
5209 int
5210 ctl_scsi_release(struct ctl_scsiio *ctsio)
5211 {
5212         int length, longid, thirdparty_id, resv_id;
5213         struct ctl_lun *lun;
5214         uint32_t residx;
5215
5216         length = 0;
5217         resv_id = 0;
5218
5219         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5220
5221         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5222         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5223
5224         switch (ctsio->cdb[0]) {
5225         case RELEASE_10: {
5226                 struct scsi_release_10 *cdb;
5227
5228                 cdb = (struct scsi_release_10 *)ctsio->cdb;
5229
5230                 if (cdb->byte2 & SR10_LONGID)
5231                         longid = 1;
5232                 else
5233                         thirdparty_id = cdb->thirdparty_id;
5234
5235                 resv_id = cdb->resv_id;
5236                 length = scsi_2btoul(cdb->length);
5237                 break;
5238         }
5239         }
5240
5241
5242         /*
5243          * XXX KDM right now, we only support LUN reservation.  We don't
5244          * support 3rd party reservations, or extent reservations, which
5245          * might actually need the parameter list.  If we've gotten this
5246          * far, we've got a LUN reservation.  Anything else got kicked out
5247          * above.  So, according to SPC, ignore the length.
5248          */
5249         length = 0;
5250
5251         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5252          && (length > 0)) {
5253                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5254                 ctsio->kern_data_len = length;
5255                 ctsio->kern_total_len = length;
5256                 ctsio->kern_data_resid = 0;
5257                 ctsio->kern_rel_offset = 0;
5258                 ctsio->kern_sg_entries = 0;
5259                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5260                 ctsio->be_move_done = ctl_config_move_done;
5261                 ctl_datamove((union ctl_io *)ctsio);
5262
5263                 return (CTL_RETVAL_COMPLETE);
5264         }
5265
5266         if (length > 0)
5267                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5268
5269         mtx_lock(&lun->lun_lock);
5270
5271         /*
5272          * According to SPC, it is not an error for an intiator to attempt
5273          * to release a reservation on a LUN that isn't reserved, or that
5274          * is reserved by another initiator.  The reservation can only be
5275          * released, though, by the initiator who made it or by one of
5276          * several reset type events.
5277          */
5278         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5279                         lun->flags &= ~CTL_LUN_RESERVED;
5280
5281         mtx_unlock(&lun->lun_lock);
5282
5283         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5284                 free(ctsio->kern_data_ptr, M_CTL);
5285                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5286         }
5287
5288         ctl_set_success(ctsio);
5289         ctl_done((union ctl_io *)ctsio);
5290         return (CTL_RETVAL_COMPLETE);
5291 }
5292
5293 int
5294 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5295 {
5296         int extent, thirdparty, longid;
5297         int resv_id, length;
5298         uint64_t thirdparty_id;
5299         struct ctl_lun *lun;
5300         uint32_t residx;
5301
5302         extent = 0;
5303         thirdparty = 0;
5304         longid = 0;
5305         resv_id = 0;
5306         length = 0;
5307         thirdparty_id = 0;
5308
5309         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5310
5311         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5312         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5313
5314         switch (ctsio->cdb[0]) {
5315         case RESERVE_10: {
5316                 struct scsi_reserve_10 *cdb;
5317
5318                 cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5319
5320                 if (cdb->byte2 & SR10_LONGID)
5321                         longid = 1;
5322                 else
5323                         thirdparty_id = cdb->thirdparty_id;
5324
5325                 resv_id = cdb->resv_id;
5326                 length = scsi_2btoul(cdb->length);
5327                 break;
5328         }
5329         }
5330
5331         /*
5332          * XXX KDM right now, we only support LUN reservation.  We don't
5333          * support 3rd party reservations, or extent reservations, which
5334          * might actually need the parameter list.  If we've gotten this
5335          * far, we've got a LUN reservation.  Anything else got kicked out
5336          * above.  So, according to SPC, ignore the length.
5337          */
5338         length = 0;
5339
5340         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5341          && (length > 0)) {
5342                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5343                 ctsio->kern_data_len = length;
5344                 ctsio->kern_total_len = length;
5345                 ctsio->kern_data_resid = 0;
5346                 ctsio->kern_rel_offset = 0;
5347                 ctsio->kern_sg_entries = 0;
5348                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5349                 ctsio->be_move_done = ctl_config_move_done;
5350                 ctl_datamove((union ctl_io *)ctsio);
5351
5352                 return (CTL_RETVAL_COMPLETE);
5353         }
5354
5355         if (length > 0)
5356                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5357
5358         mtx_lock(&lun->lun_lock);
5359         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5360                 ctl_set_reservation_conflict(ctsio);
5361                 goto bailout;
5362         }
5363
5364         lun->flags |= CTL_LUN_RESERVED;
5365         lun->res_idx = residx;
5366
5367         ctl_set_success(ctsio);
5368
5369 bailout:
5370         mtx_unlock(&lun->lun_lock);
5371
5372         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5373                 free(ctsio->kern_data_ptr, M_CTL);
5374                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5375         }
5376
5377         ctl_done((union ctl_io *)ctsio);
5378         return (CTL_RETVAL_COMPLETE);
5379 }
5380
5381 int
5382 ctl_start_stop(struct ctl_scsiio *ctsio)
5383 {
5384         struct scsi_start_stop_unit *cdb;
5385         struct ctl_lun *lun;
5386         int retval;
5387
5388         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5389
5390         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5391         retval = 0;
5392
5393         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5394
5395         /*
5396          * XXX KDM
5397          * We don't support the immediate bit on a stop unit.  In order to
5398          * do that, we would need to code up a way to know that a stop is
5399          * pending, and hold off any new commands until it completes, one
5400          * way or another.  Then we could accept or reject those commands
5401          * depending on its status.  We would almost need to do the reverse
5402          * of what we do below for an immediate start -- return the copy of
5403          * the ctl_io to the FETD with status to send to the host (and to
5404          * free the copy!) and then free the original I/O once the stop
5405          * actually completes.  That way, the OOA queue mechanism can work
5406          * to block commands that shouldn't proceed.  Another alternative
5407          * would be to put the copy in the queue in place of the original,
5408          * and return the original back to the caller.  That could be
5409          * slightly safer..
5410          */
5411         if ((cdb->byte2 & SSS_IMMED)
5412          && ((cdb->how & SSS_START) == 0)) {
5413                 ctl_set_invalid_field(ctsio,
5414                                       /*sks_valid*/ 1,
5415                                       /*command*/ 1,
5416                                       /*field*/ 1,
5417                                       /*bit_valid*/ 1,
5418                                       /*bit*/ 0);
5419                 ctl_done((union ctl_io *)ctsio);
5420                 return (CTL_RETVAL_COMPLETE);
5421         }
5422
5423         if ((lun->flags & CTL_LUN_PR_RESERVED)
5424          && ((cdb->how & SSS_START)==0)) {
5425                 uint32_t residx;
5426
5427                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5428                 if (ctl_get_prkey(lun, residx) == 0
5429                  || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5430
5431                         ctl_set_reservation_conflict(ctsio);
5432                         ctl_done((union ctl_io *)ctsio);
5433                         return (CTL_RETVAL_COMPLETE);
5434                 }
5435         }
5436
5437         /*
5438          * If there is no backend on this device, we can't start or stop
5439          * it.  In theory we shouldn't get any start/stop commands in the
5440          * first place at this level if the LUN doesn't have a backend.
5441          * That should get stopped by the command decode code.
5442          */
5443         if (lun->backend == NULL) {
5444                 ctl_set_invalid_opcode(ctsio);
5445                 ctl_done((union ctl_io *)ctsio);
5446                 return (CTL_RETVAL_COMPLETE);
5447         }
5448
5449         /*
5450          * XXX KDM Copan-specific offline behavior.
5451          * Figure out a reasonable way to port this?
5452          */
5453 #ifdef NEEDTOPORT
5454         mtx_lock(&lun->lun_lock);
5455
5456         if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5457          && (lun->flags & CTL_LUN_OFFLINE)) {
5458                 /*
5459                  * If the LUN is offline, and the on/offline bit isn't set,
5460                  * reject the start or stop.  Otherwise, let it through.
5461                  */
5462                 mtx_unlock(&lun->lun_lock);
5463                 ctl_set_lun_not_ready(ctsio);
5464                 ctl_done((union ctl_io *)ctsio);
5465         } else {
5466                 mtx_unlock(&lun->lun_lock);
5467 #endif /* NEEDTOPORT */
5468                 /*
5469                  * This could be a start or a stop when we're online,
5470                  * or a stop/offline or start/online.  A start or stop when
5471                  * we're offline is covered in the case above.
5472                  */
5473                 /*
5474                  * In the non-immediate case, we send the request to
5475                  * the backend and return status to the user when
5476                  * it is done.
5477                  *
5478                  * In the immediate case, we allocate a new ctl_io
5479                  * to hold a copy of the request, and send that to
5480                  * the backend.  We then set good status on the
5481                  * user's request and return it immediately.
5482                  */
5483                 if (cdb->byte2 & SSS_IMMED) {
5484                         union ctl_io *new_io;
5485
5486                         new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5487                         ctl_copy_io((union ctl_io *)ctsio, new_io);
5488                         retval = lun->backend->config_write(new_io);
5489                         ctl_set_success(ctsio);
5490                         ctl_done((union ctl_io *)ctsio);
5491                 } else {
5492                         retval = lun->backend->config_write(
5493                                 (union ctl_io *)ctsio);
5494                 }
5495 #ifdef NEEDTOPORT
5496         }
5497 #endif
5498         return (retval);
5499 }
5500
5501 /*
5502  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5503  * we don't really do anything with the LBA and length fields if the user
5504  * passes them in.  Instead we'll just flush out the cache for the entire
5505  * LUN.
5506  */
5507 int
5508 ctl_sync_cache(struct ctl_scsiio *ctsio)
5509 {
5510         struct ctl_lun *lun;
5511         struct ctl_softc *softc;
5512         uint64_t starting_lba;
5513         uint32_t block_count;
5514         int retval;
5515
5516         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5517
5518         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5519         softc = lun->ctl_softc;
5520         retval = 0;
5521
5522         switch (ctsio->cdb[0]) {
5523         case SYNCHRONIZE_CACHE: {
5524                 struct scsi_sync_cache *cdb;
5525                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5526
5527                 starting_lba = scsi_4btoul(cdb->begin_lba);
5528                 block_count = scsi_2btoul(cdb->lb_count);
5529                 break;
5530         }
5531         case SYNCHRONIZE_CACHE_16: {
5532                 struct scsi_sync_cache_16 *cdb;
5533                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5534
5535                 starting_lba = scsi_8btou64(cdb->begin_lba);
5536                 block_count = scsi_4btoul(cdb->lb_count);
5537                 break;
5538         }
5539         default:
5540                 ctl_set_invalid_opcode(ctsio);
5541                 ctl_done((union ctl_io *)ctsio);
5542                 goto bailout;
5543                 break; /* NOTREACHED */
5544         }
5545
5546         /*
5547          * We check the LBA and length, but don't do anything with them.
5548          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5549          * get flushed.  This check will just help satisfy anyone who wants
5550          * to see an error for an out of range LBA.
5551          */
5552         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5553                 ctl_set_lba_out_of_range(ctsio);
5554                 ctl_done((union ctl_io *)ctsio);
5555                 goto bailout;
5556         }
5557
5558         /*
5559          * If this LUN has no backend, we can't flush the cache anyway.
5560          */
5561         if (lun->backend == NULL) {
5562                 ctl_set_invalid_opcode(ctsio);
5563                 ctl_done((union ctl_io *)ctsio);
5564                 goto bailout;
5565         }
5566
5567         /*
5568          * Check to see whether we're configured to send the SYNCHRONIZE
5569          * CACHE command directly to the back end.
5570          */
5571         mtx_lock(&lun->lun_lock);
5572         if ((softc->flags & CTL_FLAG_REAL_SYNC)
5573          && (++(lun->sync_count) >= lun->sync_interval)) {
5574                 lun->sync_count = 0;
5575                 mtx_unlock(&lun->lun_lock);
5576                 retval = lun->backend->config_write((union ctl_io *)ctsio);
5577         } else {
5578                 mtx_unlock(&lun->lun_lock);
5579                 ctl_set_success(ctsio);
5580                 ctl_done((union ctl_io *)ctsio);
5581         }
5582
5583 bailout:
5584
5585         return (retval);
5586 }
5587
5588 int
5589 ctl_format(struct ctl_scsiio *ctsio)
5590 {
5591         struct scsi_format *cdb;
5592         struct ctl_lun *lun;
5593         int length, defect_list_len;
5594
5595         CTL_DEBUG_PRINT(("ctl_format\n"));
5596
5597         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5598
5599         cdb = (struct scsi_format *)ctsio->cdb;
5600
5601         length = 0;
5602         if (cdb->byte2 & SF_FMTDATA) {
5603                 if (cdb->byte2 & SF_LONGLIST)
5604                         length = sizeof(struct scsi_format_header_long);
5605                 else
5606                         length = sizeof(struct scsi_format_header_short);
5607         }
5608
5609         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5610          && (length > 0)) {
5611                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5612                 ctsio->kern_data_len = length;
5613                 ctsio->kern_total_len = length;
5614                 ctsio->kern_data_resid = 0;
5615                 ctsio->kern_rel_offset = 0;
5616                 ctsio->kern_sg_entries = 0;
5617                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5618                 ctsio->be_move_done = ctl_config_move_done;
5619                 ctl_datamove((union ctl_io *)ctsio);
5620
5621                 return (CTL_RETVAL_COMPLETE);
5622         }
5623
5624         defect_list_len = 0;
5625
5626         if (cdb->byte2 & SF_FMTDATA) {
5627                 if (cdb->byte2 & SF_LONGLIST) {
5628                         struct scsi_format_header_long *header;
5629
5630                         header = (struct scsi_format_header_long *)
5631                                 ctsio->kern_data_ptr;
5632
5633                         defect_list_len = scsi_4btoul(header->defect_list_len);
5634                         if (defect_list_len != 0) {
5635                                 ctl_set_invalid_field(ctsio,
5636                                                       /*sks_valid*/ 1,
5637                                                       /*command*/ 0,
5638                                                       /*field*/ 2,
5639                                                       /*bit_valid*/ 0,
5640                                                       /*bit*/ 0);
5641                                 goto bailout;
5642                         }
5643                 } else {
5644                         struct scsi_format_header_short *header;
5645
5646                         header = (struct scsi_format_header_short *)
5647                                 ctsio->kern_data_ptr;
5648
5649                         defect_list_len = scsi_2btoul(header->defect_list_len);
5650                         if (defect_list_len != 0) {
5651                                 ctl_set_invalid_field(ctsio,
5652                                                       /*sks_valid*/ 1,
5653                                                       /*command*/ 0,
5654                                                       /*field*/ 2,
5655                                                       /*bit_valid*/ 0,
5656                                                       /*bit*/ 0);
5657                                 goto bailout;
5658                         }
5659                 }
5660         }
5661
5662         /*
5663          * The format command will clear out the "Medium format corrupted"
5664          * status if set by the configuration code.  That status is really
5665          * just a way to notify the host that we have lost the media, and
5666          * get them to issue a command that will basically make them think
5667          * they're blowing away the media.
5668          */
5669         mtx_lock(&lun->lun_lock);
5670         lun->flags &= ~CTL_LUN_INOPERABLE;
5671         mtx_unlock(&lun->lun_lock);
5672
5673         ctl_set_success(ctsio);
5674 bailout:
5675
5676         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5677                 free(ctsio->kern_data_ptr, M_CTL);
5678                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5679         }
5680
5681         ctl_done((union ctl_io *)ctsio);
5682         return (CTL_RETVAL_COMPLETE);
5683 }
5684
5685 int
5686 ctl_read_buffer(struct ctl_scsiio *ctsio)
5687 {
5688         struct scsi_read_buffer *cdb;
5689         struct ctl_lun *lun;
5690         int buffer_offset, len;
5691         static uint8_t descr[4];
5692         static uint8_t echo_descr[4] = { 0 };
5693
5694         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5695
5696         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5697         cdb = (struct scsi_read_buffer *)ctsio->cdb;
5698
5699         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5700             (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5701             (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5702                 ctl_set_invalid_field(ctsio,
5703                                       /*sks_valid*/ 1,
5704                                       /*command*/ 1,
5705                                       /*field*/ 1,
5706                                       /*bit_valid*/ 1,
5707                                       /*bit*/ 4);
5708                 ctl_done((union ctl_io *)ctsio);
5709                 return (CTL_RETVAL_COMPLETE);
5710         }
5711
5712         len = scsi_3btoul(cdb->length);
5713         buffer_offset = scsi_3btoul(cdb->offset);
5714
5715         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5716                 ctl_set_invalid_field(ctsio,
5717                                       /*sks_valid*/ 1,
5718                                       /*command*/ 1,
5719                                       /*field*/ 6,
5720                                       /*bit_valid*/ 0,
5721                                       /*bit*/ 0);
5722                 ctl_done((union ctl_io *)ctsio);
5723                 return (CTL_RETVAL_COMPLETE);
5724         }
5725
5726         if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5727                 descr[0] = 0;
5728                 scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5729                 ctsio->kern_data_ptr = descr;
5730                 len = min(len, sizeof(descr));
5731         } else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5732                 ctsio->kern_data_ptr = echo_descr;
5733                 len = min(len, sizeof(echo_descr));
5734         } else {
5735                 if (lun->write_buffer == NULL) {
5736                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5737                             M_CTL, M_WAITOK);
5738                 }
5739                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5740         }
5741         ctsio->kern_data_len = len;
5742         ctsio->kern_total_len = len;
5743         ctsio->kern_data_resid = 0;
5744         ctsio->kern_rel_offset = 0;
5745         ctsio->kern_sg_entries = 0;
5746         ctl_set_success(ctsio);
5747         ctsio->be_move_done = ctl_config_move_done;
5748         ctl_datamove((union ctl_io *)ctsio);
5749         return (CTL_RETVAL_COMPLETE);
5750 }
5751
5752 int
5753 ctl_write_buffer(struct ctl_scsiio *ctsio)
5754 {
5755         struct scsi_write_buffer *cdb;
5756         struct ctl_lun *lun;
5757         int buffer_offset, len;
5758
5759         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5760
5761         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5762         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5763
5764         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5765                 ctl_set_invalid_field(ctsio,
5766                                       /*sks_valid*/ 1,
5767                                       /*command*/ 1,
5768                                       /*field*/ 1,
5769                                       /*bit_valid*/ 1,
5770                                       /*bit*/ 4);
5771                 ctl_done((union ctl_io *)ctsio);
5772                 return (CTL_RETVAL_COMPLETE);
5773         }
5774
5775         len = scsi_3btoul(cdb->length);
5776         buffer_offset = scsi_3btoul(cdb->offset);
5777
5778         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5779                 ctl_set_invalid_field(ctsio,
5780                                       /*sks_valid*/ 1,
5781                                       /*command*/ 1,
5782                                       /*field*/ 6,
5783                                       /*bit_valid*/ 0,
5784                                       /*bit*/ 0);
5785                 ctl_done((union ctl_io *)ctsio);
5786                 return (CTL_RETVAL_COMPLETE);
5787         }
5788
5789         /*
5790          * If we've got a kernel request that hasn't been malloced yet,
5791          * malloc it and tell the caller the data buffer is here.
5792          */
5793         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5794                 if (lun->write_buffer == NULL) {
5795                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5796                             M_CTL, M_WAITOK);
5797                 }
5798                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5799                 ctsio->kern_data_len = len;
5800                 ctsio->kern_total_len = len;
5801                 ctsio->kern_data_resid = 0;
5802                 ctsio->kern_rel_offset = 0;
5803                 ctsio->kern_sg_entries = 0;
5804                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5805                 ctsio->be_move_done = ctl_config_move_done;
5806                 ctl_datamove((union ctl_io *)ctsio);
5807
5808                 return (CTL_RETVAL_COMPLETE);
5809         }
5810
5811         ctl_set_success(ctsio);
5812         ctl_done((union ctl_io *)ctsio);
5813         return (CTL_RETVAL_COMPLETE);
5814 }
5815
5816 int
5817 ctl_write_same(struct ctl_scsiio *ctsio)
5818 {
5819         struct ctl_lun *lun;
5820         struct ctl_lba_len_flags *lbalen;
5821         uint64_t lba;
5822         uint32_t num_blocks;
5823         int len, retval;
5824         uint8_t byte2;
5825
5826         retval = CTL_RETVAL_COMPLETE;
5827
5828         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5829
5830         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5831
5832         switch (ctsio->cdb[0]) {
5833         case WRITE_SAME_10: {
5834                 struct scsi_write_same_10 *cdb;
5835
5836                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5837
5838                 lba = scsi_4btoul(cdb->addr);
5839                 num_blocks = scsi_2btoul(cdb->length);
5840                 byte2 = cdb->byte2;
5841                 break;
5842         }
5843         case WRITE_SAME_16: {
5844                 struct scsi_write_same_16 *cdb;
5845
5846                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5847
5848                 lba = scsi_8btou64(cdb->addr);
5849                 num_blocks = scsi_4btoul(cdb->length);
5850                 byte2 = cdb->byte2;
5851                 break;
5852         }
5853         default:
5854                 /*
5855                  * We got a command we don't support.  This shouldn't
5856                  * happen, commands should be filtered out above us.
5857                  */
5858                 ctl_set_invalid_opcode(ctsio);
5859                 ctl_done((union ctl_io *)ctsio);
5860
5861                 return (CTL_RETVAL_COMPLETE);
5862                 break; /* NOTREACHED */
5863         }
5864
5865         /* NDOB and ANCHOR flags can be used only together with UNMAP */
5866         if ((byte2 & SWS_UNMAP) == 0 &&
5867             (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5868                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5869                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5870                 ctl_done((union ctl_io *)ctsio);
5871                 return (CTL_RETVAL_COMPLETE);
5872         }
5873
5874         /*
5875          * The first check is to make sure we're in bounds, the second
5876          * check is to catch wrap-around problems.  If the lba + num blocks
5877          * is less than the lba, then we've wrapped around and the block
5878          * range is invalid anyway.
5879          */
5880         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5881          || ((lba + num_blocks) < lba)) {
5882                 ctl_set_lba_out_of_range(ctsio);
5883                 ctl_done((union ctl_io *)ctsio);
5884                 return (CTL_RETVAL_COMPLETE);
5885         }
5886
5887         /* Zero number of blocks means "to the last logical block" */
5888         if (num_blocks == 0) {
5889                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5890                         ctl_set_invalid_field(ctsio,
5891                                               /*sks_valid*/ 0,
5892                                               /*command*/ 1,
5893                                               /*field*/ 0,
5894                                               /*bit_valid*/ 0,
5895                                               /*bit*/ 0);
5896                         ctl_done((union ctl_io *)ctsio);
5897                         return (CTL_RETVAL_COMPLETE);
5898                 }
5899                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
5900         }
5901
5902         len = lun->be_lun->blocksize;
5903
5904         /*
5905          * If we've got a kernel request that hasn't been malloced yet,
5906          * malloc it and tell the caller the data buffer is here.
5907          */
5908         if ((byte2 & SWS_NDOB) == 0 &&
5909             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5910                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5911                 ctsio->kern_data_len = len;
5912                 ctsio->kern_total_len = len;
5913                 ctsio->kern_data_resid = 0;
5914                 ctsio->kern_rel_offset = 0;
5915                 ctsio->kern_sg_entries = 0;
5916                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5917                 ctsio->be_move_done = ctl_config_move_done;
5918                 ctl_datamove((union ctl_io *)ctsio);
5919
5920                 return (CTL_RETVAL_COMPLETE);
5921         }
5922
5923         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5924         lbalen->lba = lba;
5925         lbalen->len = num_blocks;
5926         lbalen->flags = byte2;
5927         retval = lun->backend->config_write((union ctl_io *)ctsio);
5928
5929         return (retval);
5930 }
5931
5932 int
5933 ctl_unmap(struct ctl_scsiio *ctsio)
5934 {
5935         struct ctl_lun *lun;
5936         struct scsi_unmap *cdb;
5937         struct ctl_ptr_len_flags *ptrlen;
5938         struct scsi_unmap_header *hdr;
5939         struct scsi_unmap_desc *buf, *end, *endnz, *range;
5940         uint64_t lba;
5941         uint32_t num_blocks;
5942         int len, retval;
5943         uint8_t byte2;
5944
5945         retval = CTL_RETVAL_COMPLETE;
5946
5947         CTL_DEBUG_PRINT(("ctl_unmap\n"));
5948
5949         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5950         cdb = (struct scsi_unmap *)ctsio->cdb;
5951
5952         len = scsi_2btoul(cdb->length);
5953         byte2 = cdb->byte2;
5954
5955         /*
5956          * If we've got a kernel request that hasn't been malloced yet,
5957          * malloc it and tell the caller the data buffer is here.
5958          */
5959         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5960                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5961                 ctsio->kern_data_len = len;
5962                 ctsio->kern_total_len = len;
5963                 ctsio->kern_data_resid = 0;
5964                 ctsio->kern_rel_offset = 0;
5965                 ctsio->kern_sg_entries = 0;
5966                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5967                 ctsio->be_move_done = ctl_config_move_done;
5968                 ctl_datamove((union ctl_io *)ctsio);
5969
5970                 return (CTL_RETVAL_COMPLETE);
5971         }
5972
5973         len = ctsio->kern_total_len - ctsio->kern_data_resid;
5974         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5975         if (len < sizeof (*hdr) ||
5976             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5977             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5978             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5979                 ctl_set_invalid_field(ctsio,
5980                                       /*sks_valid*/ 0,
5981                                       /*command*/ 0,
5982                                       /*field*/ 0,
5983                                       /*bit_valid*/ 0,
5984                                       /*bit*/ 0);
5985                 goto done;
5986         }
5987         len = scsi_2btoul(hdr->desc_length);
5988         buf = (struct scsi_unmap_desc *)(hdr + 1);
5989         end = buf + len / sizeof(*buf);
5990
5991         endnz = buf;
5992         for (range = buf; range < end; range++) {
5993                 lba = scsi_8btou64(range->lba);
5994                 num_blocks = scsi_4btoul(range->length);
5995                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5996                  || ((lba + num_blocks) < lba)) {
5997                         ctl_set_lba_out_of_range(ctsio);
5998                         ctl_done((union ctl_io *)ctsio);
5999                         return (CTL_RETVAL_COMPLETE);
6000                 }
6001                 if (num_blocks != 0)
6002                         endnz = range + 1;
6003         }
6004
6005         /*
6006          * Block backend can not handle zero last range.
6007          * Filter it out and return if there is nothing left.
6008          */
6009         len = (uint8_t *)endnz - (uint8_t *)buf;
6010         if (len == 0) {
6011                 ctl_set_success(ctsio);
6012                 goto done;
6013         }
6014
6015         mtx_lock(&lun->lun_lock);
6016         ptrlen = (struct ctl_ptr_len_flags *)
6017             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6018         ptrlen->ptr = (void *)buf;
6019         ptrlen->len = len;
6020         ptrlen->flags = byte2;
6021         ctl_check_blocked(lun);
6022         mtx_unlock(&lun->lun_lock);
6023
6024         retval = lun->backend->config_write((union ctl_io *)ctsio);
6025         return (retval);
6026
6027 done:
6028         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
6029                 free(ctsio->kern_data_ptr, M_CTL);
6030                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
6031         }
6032         ctl_done((union ctl_io *)ctsio);
6033         return (CTL_RETVAL_COMPLETE);
6034 }
6035
6036 /*
6037  * Note that this function currently doesn't actually do anything inside
6038  * CTL to enforce things if the DQue bit is turned on.
6039  *
6040  * Also note that this function can't be used in the default case, because
6041  * the DQue bit isn't set in the changeable mask for the control mode page
6042  * anyway.  This is just here as an example for how to implement a page
6043  * handler, and a placeholder in case we want to allow the user to turn
6044  * tagged queueing on and off.
6045  *
6046  * The D_SENSE bit handling is functional, however, and will turn
6047  * descriptor sense on and off for a given LUN.
6048  */
6049 int
6050 ctl_control_page_handler(struct ctl_scsiio *ctsio,
6051                          struct ctl_page_index *page_index, uint8_t *page_ptr)
6052 {
6053         struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6054         struct ctl_lun *lun;
6055         int set_ua;
6056         uint32_t initidx;
6057
6058         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6059         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6060         set_ua = 0;
6061
6062         user_cp = (struct scsi_control_page *)page_ptr;
6063         current_cp = (struct scsi_control_page *)
6064                 (page_index->page_data + (page_index->page_len *
6065                 CTL_PAGE_CURRENT));
6066         saved_cp = (struct scsi_control_page *)
6067                 (page_index->page_data + (page_index->page_len *
6068                 CTL_PAGE_SAVED));
6069
6070         mtx_lock(&lun->lun_lock);
6071         if (((current_cp->rlec & SCP_DSENSE) == 0)
6072          && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6073                 /*
6074                  * Descriptor sense is currently turned off and the user
6075                  * wants to turn it on.
6076                  */
6077                 current_cp->rlec |= SCP_DSENSE;
6078                 saved_cp->rlec |= SCP_DSENSE;
6079                 lun->flags |= CTL_LUN_SENSE_DESC;
6080                 set_ua = 1;
6081         } else if (((current_cp->rlec & SCP_DSENSE) != 0)
6082                 && ((user_cp->rlec & SCP_DSENSE) == 0)) {
6083                 /*
6084                  * Descriptor sense is currently turned on, and the user
6085                  * wants to turn it off.
6086                  */
6087                 current_cp->rlec &= ~SCP_DSENSE;
6088                 saved_cp->rlec &= ~SCP_DSENSE;
6089                 lun->flags &= ~CTL_LUN_SENSE_DESC;
6090                 set_ua = 1;
6091         }
6092         if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6093             (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6094                 current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6095                 current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6096                 saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6097                 saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6098                 set_ua = 1;
6099         }
6100         if ((current_cp->eca_and_aen & SCP_SWP) !=
6101             (user_cp->eca_and_aen & SCP_SWP)) {
6102                 current_cp->eca_and_aen &= ~SCP_SWP;
6103                 current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6104                 saved_cp->eca_and_aen &= ~SCP_SWP;
6105                 saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6106                 set_ua = 1;
6107         }
6108         if (set_ua != 0)
6109                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6110         mtx_unlock(&lun->lun_lock);
6111
6112         return (0);
6113 }
6114
6115 int
6116 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6117                      struct ctl_page_index *page_index, uint8_t *page_ptr)
6118 {
6119         struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6120         struct ctl_lun *lun;
6121         int set_ua;
6122         uint32_t initidx;
6123
6124         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6125         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6126         set_ua = 0;
6127
6128         user_cp = (struct scsi_caching_page *)page_ptr;
6129         current_cp = (struct scsi_caching_page *)
6130                 (page_index->page_data + (page_index->page_len *
6131                 CTL_PAGE_CURRENT));
6132         saved_cp = (struct scsi_caching_page *)
6133                 (page_index->page_data + (page_index->page_len *
6134                 CTL_PAGE_SAVED));
6135
6136         mtx_lock(&lun->lun_lock);
6137         if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6138             (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6139                 current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6140                 current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6141                 saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6142                 saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6143                 set_ua = 1;
6144         }
6145         if (set_ua != 0)
6146                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6147         mtx_unlock(&lun->lun_lock);
6148
6149         return (0);
6150 }
6151
6152 int
6153 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6154                                 struct ctl_page_index *page_index,
6155                                 uint8_t *page_ptr)
6156 {
6157         uint8_t *c;
6158         int i;
6159
6160         c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6161         ctl_time_io_secs =
6162                 (c[0] << 8) |
6163                 (c[1] << 0) |
6164                 0;
6165         CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6166         printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6167         printf("page data:");
6168         for (i=0; i<8; i++)
6169                 printf(" %.2x",page_ptr[i]);
6170         printf("\n");
6171         return (0);
6172 }
6173
6174 int
6175 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6176                                struct ctl_page_index *page_index,
6177                                int pc)
6178 {
6179         struct copan_debugconf_subpage *page;
6180
6181         page = (struct copan_debugconf_subpage *)page_index->page_data +
6182                 (page_index->page_len * pc);
6183
6184         switch (pc) {
6185         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6186         case SMS_PAGE_CTRL_DEFAULT >> 6:
6187         case SMS_PAGE_CTRL_SAVED >> 6:
6188                 /*
6189                  * We don't update the changable or default bits for this page.
6190                  */
6191                 break;
6192         case SMS_PAGE_CTRL_CURRENT >> 6:
6193                 page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6194                 page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6195                 break;
6196         default:
6197 #ifdef NEEDTOPORT
6198                 EPRINT(0, "Invalid PC %d!!", pc);
6199 #endif /* NEEDTOPORT */
6200                 break;
6201         }
6202         return (0);
6203 }
6204
6205
6206 static int
6207 ctl_do_mode_select(union ctl_io *io)
6208 {
6209         struct scsi_mode_page_header *page_header;
6210         struct ctl_page_index *page_index;
6211         struct ctl_scsiio *ctsio;
6212         int control_dev, page_len;
6213         int page_len_offset, page_len_size;
6214         union ctl_modepage_info *modepage_info;
6215         struct ctl_lun *lun;
6216         int *len_left, *len_used;
6217         int retval, i;
6218
6219         ctsio = &io->scsiio;
6220         page_index = NULL;
6221         page_len = 0;
6222         retval = CTL_RETVAL_COMPLETE;
6223
6224         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6225
6226         if (lun->be_lun->lun_type != T_DIRECT)
6227                 control_dev = 1;
6228         else
6229                 control_dev = 0;
6230
6231         modepage_info = (union ctl_modepage_info *)
6232                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6233         len_left = &modepage_info->header.len_left;
6234         len_used = &modepage_info->header.len_used;
6235
6236 do_next_page:
6237
6238         page_header = (struct scsi_mode_page_header *)
6239                 (ctsio->kern_data_ptr + *len_used);
6240
6241         if (*len_left == 0) {
6242                 free(ctsio->kern_data_ptr, M_CTL);
6243                 ctl_set_success(ctsio);
6244                 ctl_done((union ctl_io *)ctsio);
6245                 return (CTL_RETVAL_COMPLETE);
6246         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6247
6248                 free(ctsio->kern_data_ptr, M_CTL);
6249                 ctl_set_param_len_error(ctsio);
6250                 ctl_done((union ctl_io *)ctsio);
6251                 return (CTL_RETVAL_COMPLETE);
6252
6253         } else if ((page_header->page_code & SMPH_SPF)
6254                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6255
6256                 free(ctsio->kern_data_ptr, M_CTL);
6257                 ctl_set_param_len_error(ctsio);
6258                 ctl_done((union ctl_io *)ctsio);
6259                 return (CTL_RETVAL_COMPLETE);
6260         }
6261
6262
6263         /*
6264          * XXX KDM should we do something with the block descriptor?
6265          */
6266         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6267
6268                 if ((control_dev != 0)
6269                  && (lun->mode_pages.index[i].page_flags &
6270                      CTL_PAGE_FLAG_DISK_ONLY))
6271                         continue;
6272
6273                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6274                     (page_header->page_code & SMPH_PC_MASK))
6275                         continue;
6276
6277                 /*
6278                  * If neither page has a subpage code, then we've got a
6279                  * match.
6280                  */
6281                 if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6282                  && ((page_header->page_code & SMPH_SPF) == 0)) {
6283                         page_index = &lun->mode_pages.index[i];
6284                         page_len = page_header->page_length;
6285                         break;
6286                 }
6287
6288                 /*
6289                  * If both pages have subpages, then the subpage numbers
6290                  * have to match.
6291                  */
6292                 if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6293                   && (page_header->page_code & SMPH_SPF)) {
6294                         struct scsi_mode_page_header_sp *sph;
6295
6296                         sph = (struct scsi_mode_page_header_sp *)page_header;
6297
6298                         if (lun->mode_pages.index[i].subpage ==
6299                             sph->subpage) {
6300                                 page_index = &lun->mode_pages.index[i];
6301                                 page_len = scsi_2btoul(sph->page_length);
6302                                 break;
6303                         }
6304                 }
6305         }
6306
6307         /*
6308          * If we couldn't find the page, or if we don't have a mode select
6309          * handler for it, send back an error to the user.
6310          */
6311         if ((page_index == NULL)
6312          || (page_index->select_handler == NULL)) {
6313                 ctl_set_invalid_field(ctsio,
6314                                       /*sks_valid*/ 1,
6315                                       /*command*/ 0,
6316                                       /*field*/ *len_used,
6317                                       /*bit_valid*/ 0,
6318                                       /*bit*/ 0);
6319                 free(ctsio->kern_data_ptr, M_CTL);
6320                 ctl_done((union ctl_io *)ctsio);
6321                 return (CTL_RETVAL_COMPLETE);
6322         }
6323
6324         if (page_index->page_code & SMPH_SPF) {
6325                 page_len_offset = 2;
6326                 page_len_size = 2;
6327         } else {
6328                 page_len_size = 1;
6329                 page_len_offset = 1;
6330         }
6331
6332         /*
6333          * If the length the initiator gives us isn't the one we specify in
6334          * the mode page header, or if they didn't specify enough data in
6335          * the CDB to avoid truncating this page, kick out the request.
6336          */
6337         if ((page_len != (page_index->page_len - page_len_offset -
6338                           page_len_size))
6339          || (*len_left < page_index->page_len)) {
6340
6341
6342                 ctl_set_invalid_field(ctsio,
6343                                       /*sks_valid*/ 1,
6344                                       /*command*/ 0,
6345                                       /*field*/ *len_used + page_len_offset,
6346                                       /*bit_valid*/ 0,
6347                                       /*bit*/ 0);
6348                 free(ctsio->kern_data_ptr, M_CTL);
6349                 ctl_done((union ctl_io *)ctsio);
6350                 return (CTL_RETVAL_COMPLETE);
6351         }
6352
6353         /*
6354          * Run through the mode page, checking to make sure that the bits
6355          * the user changed are actually legal for him to change.
6356          */
6357         for (i = 0; i < page_index->page_len; i++) {
6358                 uint8_t *user_byte, *change_mask, *current_byte;
6359                 int bad_bit;
6360                 int j;
6361
6362                 user_byte = (uint8_t *)page_header + i;
6363                 change_mask = page_index->page_data +
6364                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6365                 current_byte = page_index->page_data +
6366                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6367
6368                 /*
6369                  * Check to see whether the user set any bits in this byte
6370                  * that he is not allowed to set.
6371                  */
6372                 if ((*user_byte & ~(*change_mask)) ==
6373                     (*current_byte & ~(*change_mask)))
6374                         continue;
6375
6376                 /*
6377                  * Go through bit by bit to determine which one is illegal.
6378                  */
6379                 bad_bit = 0;
6380                 for (j = 7; j >= 0; j--) {
6381                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6382                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6383                                 bad_bit = i;
6384                                 break;
6385                         }
6386                 }
6387                 ctl_set_invalid_field(ctsio,
6388                                       /*sks_valid*/ 1,
6389                                       /*command*/ 0,
6390                                       /*field*/ *len_used + i,
6391                                       /*bit_valid*/ 1,
6392                                       /*bit*/ bad_bit);
6393                 free(ctsio->kern_data_ptr, M_CTL);
6394                 ctl_done((union ctl_io *)ctsio);
6395                 return (CTL_RETVAL_COMPLETE);
6396         }
6397
6398         /*
6399          * Decrement these before we call the page handler, since we may
6400          * end up getting called back one way or another before the handler
6401          * returns to this context.
6402          */
6403         *len_left -= page_index->page_len;
6404         *len_used += page_index->page_len;
6405
6406         retval = page_index->select_handler(ctsio, page_index,
6407                                             (uint8_t *)page_header);
6408
6409         /*
6410          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6411          * wait until this queued command completes to finish processing
6412          * the mode page.  If it returns anything other than
6413          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6414          * already set the sense information, freed the data pointer, and
6415          * completed the io for us.
6416          */
6417         if (retval != CTL_RETVAL_COMPLETE)
6418                 goto bailout_no_done;
6419
6420         /*
6421          * If the initiator sent us more than one page, parse the next one.
6422          */
6423         if (*len_left > 0)
6424                 goto do_next_page;
6425
6426         ctl_set_success(ctsio);
6427         free(ctsio->kern_data_ptr, M_CTL);
6428         ctl_done((union ctl_io *)ctsio);
6429
6430 bailout_no_done:
6431
6432         return (CTL_RETVAL_COMPLETE);
6433
6434 }
6435
6436 int
6437 ctl_mode_select(struct ctl_scsiio *ctsio)
6438 {
6439         int param_len, pf, sp;
6440         int header_size, bd_len;
6441         int len_left, len_used;
6442         struct ctl_page_index *page_index;
6443         struct ctl_lun *lun;
6444         int control_dev, page_len;
6445         union ctl_modepage_info *modepage_info;
6446         int retval;
6447
6448         pf = 0;
6449         sp = 0;
6450         page_len = 0;
6451         len_used = 0;
6452         len_left = 0;
6453         retval = 0;
6454         bd_len = 0;
6455         page_index = NULL;
6456
6457         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6458
6459         if (lun->be_lun->lun_type != T_DIRECT)
6460                 control_dev = 1;
6461         else
6462                 control_dev = 0;
6463
6464         switch (ctsio->cdb[0]) {
6465         case MODE_SELECT_6: {
6466                 struct scsi_mode_select_6 *cdb;
6467
6468                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6469
6470                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6471                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6472
6473                 param_len = cdb->length;
6474                 header_size = sizeof(struct scsi_mode_header_6);
6475                 break;
6476         }
6477         case MODE_SELECT_10: {
6478                 struct scsi_mode_select_10 *cdb;
6479
6480                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6481
6482                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6483                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6484
6485                 param_len = scsi_2btoul(cdb->length);
6486                 header_size = sizeof(struct scsi_mode_header_10);
6487                 break;
6488         }
6489         default:
6490                 ctl_set_invalid_opcode(ctsio);
6491                 ctl_done((union ctl_io *)ctsio);
6492                 return (CTL_RETVAL_COMPLETE);
6493                 break; /* NOTREACHED */
6494         }
6495
6496         /*
6497          * From SPC-3:
6498          * "A parameter list length of zero indicates that the Data-Out Buffer
6499          * shall be empty. This condition shall not be considered as an error."
6500          */
6501         if (param_len == 0) {
6502                 ctl_set_success(ctsio);
6503                 ctl_done((union ctl_io *)ctsio);
6504                 return (CTL_RETVAL_COMPLETE);
6505         }
6506
6507         /*
6508          * Since we'll hit this the first time through, prior to
6509          * allocation, we don't need to free a data buffer here.
6510          */
6511         if (param_len < header_size) {
6512                 ctl_set_param_len_error(ctsio);
6513                 ctl_done((union ctl_io *)ctsio);
6514                 return (CTL_RETVAL_COMPLETE);
6515         }
6516
6517         /*
6518          * Allocate the data buffer and grab the user's data.  In theory,
6519          * we shouldn't have to sanity check the parameter list length here
6520          * because the maximum size is 64K.  We should be able to malloc
6521          * that much without too many problems.
6522          */
6523         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6524                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6525                 ctsio->kern_data_len = param_len;
6526                 ctsio->kern_total_len = param_len;
6527                 ctsio->kern_data_resid = 0;
6528                 ctsio->kern_rel_offset = 0;
6529                 ctsio->kern_sg_entries = 0;
6530                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6531                 ctsio->be_move_done = ctl_config_move_done;
6532                 ctl_datamove((union ctl_io *)ctsio);
6533
6534                 return (CTL_RETVAL_COMPLETE);
6535         }
6536
6537         switch (ctsio->cdb[0]) {
6538         case MODE_SELECT_6: {
6539                 struct scsi_mode_header_6 *mh6;
6540
6541                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6542                 bd_len = mh6->blk_desc_len;
6543                 break;
6544         }
6545         case MODE_SELECT_10: {
6546                 struct scsi_mode_header_10 *mh10;
6547
6548                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6549                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6550                 break;
6551         }
6552         default:
6553                 panic("Invalid CDB type %#x", ctsio->cdb[0]);
6554                 break;
6555         }
6556
6557         if (param_len < (header_size + bd_len)) {
6558                 free(ctsio->kern_data_ptr, M_CTL);
6559                 ctl_set_param_len_error(ctsio);
6560                 ctl_done((union ctl_io *)ctsio);
6561                 return (CTL_RETVAL_COMPLETE);
6562         }
6563
6564         /*
6565          * Set the IO_CONT flag, so that if this I/O gets passed to
6566          * ctl_config_write_done(), it'll get passed back to
6567          * ctl_do_mode_select() for further processing, or completion if
6568          * we're all done.
6569          */
6570         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6571         ctsio->io_cont = ctl_do_mode_select;
6572
6573         modepage_info = (union ctl_modepage_info *)
6574                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6575
6576         memset(modepage_info, 0, sizeof(*modepage_info));
6577
6578         len_left = param_len - header_size - bd_len;
6579         len_used = header_size + bd_len;
6580
6581         modepage_info->header.len_left = len_left;
6582         modepage_info->header.len_used = len_used;
6583
6584         return (ctl_do_mode_select((union ctl_io *)ctsio));
6585 }
6586
6587 int
6588 ctl_mode_sense(struct ctl_scsiio *ctsio)
6589 {
6590         struct ctl_lun *lun;
6591         int pc, page_code, dbd, llba, subpage;
6592         int alloc_len, page_len, header_len, total_len;
6593         struct scsi_mode_block_descr *block_desc;
6594         struct ctl_page_index *page_index;
6595         int control_dev;
6596
6597         dbd = 0;
6598         llba = 0;
6599         block_desc = NULL;
6600         page_index = NULL;
6601
6602         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6603
6604         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6605
6606         if (lun->be_lun->lun_type != T_DIRECT)
6607                 control_dev = 1;
6608         else
6609                 control_dev = 0;
6610
6611         switch (ctsio->cdb[0]) {
6612         case MODE_SENSE_6: {
6613                 struct scsi_mode_sense_6 *cdb;
6614
6615                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6616
6617                 header_len = sizeof(struct scsi_mode_hdr_6);
6618                 if (cdb->byte2 & SMS_DBD)
6619                         dbd = 1;
6620                 else
6621                         header_len += sizeof(struct scsi_mode_block_descr);
6622
6623                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6624                 page_code = cdb->page & SMS_PAGE_CODE;
6625                 subpage = cdb->subpage;
6626                 alloc_len = cdb->length;
6627                 break;
6628         }
6629         case MODE_SENSE_10: {
6630                 struct scsi_mode_sense_10 *cdb;
6631
6632                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6633
6634                 header_len = sizeof(struct scsi_mode_hdr_10);
6635
6636                 if (cdb->byte2 & SMS_DBD)
6637                         dbd = 1;
6638                 else
6639                         header_len += sizeof(struct scsi_mode_block_descr);
6640                 if (cdb->byte2 & SMS10_LLBAA)
6641                         llba = 1;
6642                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6643                 page_code = cdb->page & SMS_PAGE_CODE;
6644                 subpage = cdb->subpage;
6645                 alloc_len = scsi_2btoul(cdb->length);
6646                 break;
6647         }
6648         default:
6649                 ctl_set_invalid_opcode(ctsio);
6650                 ctl_done((union ctl_io *)ctsio);
6651                 return (CTL_RETVAL_COMPLETE);
6652                 break; /* NOTREACHED */
6653         }
6654
6655         /*
6656          * We have to make a first pass through to calculate the size of
6657          * the pages that match the user's query.  Then we allocate enough
6658          * memory to hold it, and actually copy the data into the buffer.
6659          */
6660         switch (page_code) {
6661         case SMS_ALL_PAGES_PAGE: {
6662                 int i;
6663
6664                 page_len = 0;
6665
6666                 /*
6667                  * At the moment, values other than 0 and 0xff here are
6668                  * reserved according to SPC-3.
6669                  */
6670                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6671                  && (subpage != SMS_SUBPAGE_ALL)) {
6672                         ctl_set_invalid_field(ctsio,
6673                                               /*sks_valid*/ 1,
6674                                               /*command*/ 1,
6675                                               /*field*/ 3,
6676                                               /*bit_valid*/ 0,
6677                                               /*bit*/ 0);
6678                         ctl_done((union ctl_io *)ctsio);
6679                         return (CTL_RETVAL_COMPLETE);
6680                 }
6681
6682                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6683                         if ((control_dev != 0)
6684                          && (lun->mode_pages.index[i].page_flags &
6685                              CTL_PAGE_FLAG_DISK_ONLY))
6686                                 continue;
6687
6688                         /*
6689                          * We don't use this subpage if the user didn't
6690                          * request all subpages.
6691                          */
6692                         if ((lun->mode_pages.index[i].subpage != 0)
6693                          && (subpage == SMS_SUBPAGE_PAGE_0))
6694                                 continue;
6695
6696 #if 0
6697                         printf("found page %#x len %d\n",
6698                                lun->mode_pages.index[i].page_code &
6699                                SMPH_PC_MASK,
6700                                lun->mode_pages.index[i].page_len);
6701 #endif
6702                         page_len += lun->mode_pages.index[i].page_len;
6703                 }
6704                 break;
6705         }
6706         default: {
6707                 int i;
6708
6709                 page_len = 0;
6710
6711                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6712                         /* Look for the right page code */
6713                         if ((lun->mode_pages.index[i].page_code &
6714                              SMPH_PC_MASK) != page_code)
6715                                 continue;
6716
6717                         /* Look for the right subpage or the subpage wildcard*/
6718                         if ((lun->mode_pages.index[i].subpage != subpage)
6719                          && (subpage != SMS_SUBPAGE_ALL))
6720                                 continue;
6721
6722                         /* Make sure the page is supported for this dev type */
6723                         if ((control_dev != 0)
6724                          && (lun->mode_pages.index[i].page_flags &
6725                              CTL_PAGE_FLAG_DISK_ONLY))
6726                                 continue;
6727
6728 #if 0
6729                         printf("found page %#x len %d\n",
6730                                lun->mode_pages.index[i].page_code &
6731                                SMPH_PC_MASK,
6732                                lun->mode_pages.index[i].page_len);
6733 #endif
6734
6735                         page_len += lun->mode_pages.index[i].page_len;
6736                 }
6737
6738                 if (page_len == 0) {
6739                         ctl_set_invalid_field(ctsio,
6740                                               /*sks_valid*/ 1,
6741                                               /*command*/ 1,
6742                                               /*field*/ 2,
6743                                               /*bit_valid*/ 1,
6744                                               /*bit*/ 5);
6745                         ctl_done((union ctl_io *)ctsio);
6746                         return (CTL_RETVAL_COMPLETE);
6747                 }
6748                 break;
6749         }
6750         }
6751
6752         total_len = header_len + page_len;
6753 #if 0
6754         printf("header_len = %d, page_len = %d, total_len = %d\n",
6755                header_len, page_len, total_len);
6756 #endif
6757
6758         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6759         ctsio->kern_sg_entries = 0;
6760         ctsio->kern_data_resid = 0;
6761         ctsio->kern_rel_offset = 0;
6762         if (total_len < alloc_len) {
6763                 ctsio->residual = alloc_len - total_len;
6764                 ctsio->kern_data_len = total_len;
6765                 ctsio->kern_total_len = total_len;
6766         } else {
6767                 ctsio->residual = 0;
6768                 ctsio->kern_data_len = alloc_len;
6769                 ctsio->kern_total_len = alloc_len;
6770         }
6771
6772         switch (ctsio->cdb[0]) {
6773         case MODE_SENSE_6: {
6774                 struct scsi_mode_hdr_6 *header;
6775
6776                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6777
6778                 header->datalen = MIN(total_len - 1, 254);
6779                 if (control_dev == 0) {
6780                         header->dev_specific = 0x10; /* DPOFUA */
6781                         if ((lun->flags & CTL_LUN_READONLY) ||
6782                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6783                             .eca_and_aen & SCP_SWP) != 0)
6784                                     header->dev_specific |= 0x80; /* WP */
6785                 }
6786                 if (dbd)
6787                         header->block_descr_len = 0;
6788                 else
6789                         header->block_descr_len =
6790                                 sizeof(struct scsi_mode_block_descr);
6791                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6792                 break;
6793         }
6794         case MODE_SENSE_10: {
6795                 struct scsi_mode_hdr_10 *header;
6796                 int datalen;
6797
6798                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6799
6800                 datalen = MIN(total_len - 2, 65533);
6801                 scsi_ulto2b(datalen, header->datalen);
6802                 if (control_dev == 0) {
6803                         header->dev_specific = 0x10; /* DPOFUA */
6804                         if ((lun->flags & CTL_LUN_READONLY) ||
6805                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6806                             .eca_and_aen & SCP_SWP) != 0)
6807                                     header->dev_specific |= 0x80; /* WP */
6808                 }
6809                 if (dbd)
6810                         scsi_ulto2b(0, header->block_descr_len);
6811                 else
6812                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6813                                     header->block_descr_len);
6814                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6815                 break;
6816         }
6817         default:
6818                 panic("invalid CDB type %#x", ctsio->cdb[0]);
6819                 break; /* NOTREACHED */
6820         }
6821
6822         /*
6823          * If we've got a disk, use its blocksize in the block
6824          * descriptor.  Otherwise, just set it to 0.
6825          */
6826         if (dbd == 0) {
6827                 if (control_dev == 0)
6828                         scsi_ulto3b(lun->be_lun->blocksize,
6829                                     block_desc->block_len);
6830                 else
6831                         scsi_ulto3b(0, block_desc->block_len);
6832         }
6833
6834         switch (page_code) {
6835         case SMS_ALL_PAGES_PAGE: {
6836                 int i, data_used;
6837
6838                 data_used = header_len;
6839                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6840                         struct ctl_page_index *page_index;
6841
6842                         page_index = &lun->mode_pages.index[i];
6843
6844                         if ((control_dev != 0)
6845                          && (page_index->page_flags &
6846                             CTL_PAGE_FLAG_DISK_ONLY))
6847                                 continue;
6848
6849                         /*
6850                          * We don't use this subpage if the user didn't
6851                          * request all subpages.  We already checked (above)
6852                          * to make sure the user only specified a subpage
6853                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6854                          */
6855                         if ((page_index->subpage != 0)
6856                          && (subpage == SMS_SUBPAGE_PAGE_0))
6857                                 continue;
6858
6859                         /*
6860                          * Call the handler, if it exists, to update the
6861                          * page to the latest values.
6862                          */
6863                         if (page_index->sense_handler != NULL)
6864                                 page_index->sense_handler(ctsio, page_index,pc);
6865
6866                         memcpy(ctsio->kern_data_ptr + data_used,
6867                                page_index->page_data +
6868                                (page_index->page_len * pc),
6869                                page_index->page_len);
6870                         data_used += page_index->page_len;
6871                 }
6872                 break;
6873         }
6874         default: {
6875                 int i, data_used;
6876
6877                 data_used = header_len;
6878
6879                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6880                         struct ctl_page_index *page_index;
6881
6882                         page_index = &lun->mode_pages.index[i];
6883
6884                         /* Look for the right page code */
6885                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6886                                 continue;
6887
6888                         /* Look for the right subpage or the subpage wildcard*/
6889                         if ((page_index->subpage != subpage)
6890                          && (subpage != SMS_SUBPAGE_ALL))
6891                                 continue;
6892
6893                         /* Make sure the page is supported for this dev type */
6894                         if ((control_dev != 0)
6895                          && (page_index->page_flags &
6896                              CTL_PAGE_FLAG_DISK_ONLY))
6897                                 continue;
6898
6899                         /*
6900                          * Call the handler, if it exists, to update the
6901                          * page to the latest values.
6902                          */
6903                         if (page_index->sense_handler != NULL)
6904                                 page_index->sense_handler(ctsio, page_index,pc);
6905
6906                         memcpy(ctsio->kern_data_ptr + data_used,
6907                                page_index->page_data +
6908                                (page_index->page_len * pc),
6909                                page_index->page_len);
6910                         data_used += page_index->page_len;
6911                 }
6912                 break;
6913         }
6914         }
6915
6916         ctl_set_success(ctsio);
6917         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6918         ctsio->be_move_done = ctl_config_move_done;
6919         ctl_datamove((union ctl_io *)ctsio);
6920         return (CTL_RETVAL_COMPLETE);
6921 }
6922
6923 int
6924 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6925                                struct ctl_page_index *page_index,
6926                                int pc)
6927 {
6928         struct ctl_lun *lun;
6929         struct scsi_log_param_header *phdr;
6930         uint8_t *data;
6931         uint64_t val;
6932
6933         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6934         data = page_index->page_data;
6935
6936         if (lun->backend->lun_attr != NULL &&
6937             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6938              != UINT64_MAX) {
6939                 phdr = (struct scsi_log_param_header *)data;
6940                 scsi_ulto2b(0x0001, phdr->param_code);
6941                 phdr->param_control = SLP_LBIN | SLP_LP;
6942                 phdr->param_len = 8;
6943                 data = (uint8_t *)(phdr + 1);
6944                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6945                 data[4] = 0x02; /* per-pool */
6946                 data += phdr->param_len;
6947         }
6948
6949         if (lun->backend->lun_attr != NULL &&
6950             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6951              != UINT64_MAX) {
6952                 phdr = (struct scsi_log_param_header *)data;
6953                 scsi_ulto2b(0x0002, phdr->param_code);
6954                 phdr->param_control = SLP_LBIN | SLP_LP;
6955                 phdr->param_len = 8;
6956                 data = (uint8_t *)(phdr + 1);
6957                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6958                 data[4] = 0x01; /* per-LUN */
6959                 data += phdr->param_len;
6960         }
6961
6962         if (lun->backend->lun_attr != NULL &&
6963             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6964              != UINT64_MAX) {
6965                 phdr = (struct scsi_log_param_header *)data;
6966                 scsi_ulto2b(0x00f1, phdr->param_code);
6967                 phdr->param_control = SLP_LBIN | SLP_LP;
6968                 phdr->param_len = 8;
6969                 data = (uint8_t *)(phdr + 1);
6970                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6971                 data[4] = 0x02; /* per-pool */
6972                 data += phdr->param_len;
6973         }
6974
6975         if (lun->backend->lun_attr != NULL &&
6976             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6977              != UINT64_MAX) {
6978                 phdr = (struct scsi_log_param_header *)data;
6979                 scsi_ulto2b(0x00f2, phdr->param_code);
6980                 phdr->param_control = SLP_LBIN | SLP_LP;
6981                 phdr->param_len = 8;
6982                 data = (uint8_t *)(phdr + 1);
6983                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6984                 data[4] = 0x02; /* per-pool */
6985                 data += phdr->param_len;
6986         }
6987
6988         page_index->page_len = data - page_index->page_data;
6989         return (0);
6990 }
6991
6992 int
6993 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6994                                struct ctl_page_index *page_index,
6995                                int pc)
6996 {
6997         struct ctl_lun *lun;
6998         struct stat_page *data;
6999         uint64_t rn, wn, rb, wb;
7000         struct bintime rt, wt;
7001         int i;
7002
7003         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7004         data = (struct stat_page *)page_index->page_data;
7005
7006         scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
7007         data->sap.hdr.param_control = SLP_LBIN;
7008         data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
7009             sizeof(struct scsi_log_param_header);
7010         rn = wn = rb = wb = 0;
7011         bintime_clear(&rt);
7012         bintime_clear(&wt);
7013         for (i = 0; i < CTL_MAX_PORTS; i++) {
7014                 rn += lun->stats.ports[i].operations[CTL_STATS_READ];
7015                 wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
7016                 rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
7017                 wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
7018                 bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
7019                 bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
7020         }
7021         scsi_u64to8b(rn, data->sap.read_num);
7022         scsi_u64to8b(wn, data->sap.write_num);
7023         if (lun->stats.blocksize > 0) {
7024                 scsi_u64to8b(wb / lun->stats.blocksize,
7025                     data->sap.recvieved_lba);
7026                 scsi_u64to8b(rb / lun->stats.blocksize,
7027                     data->sap.transmitted_lba);
7028         }
7029         scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
7030             data->sap.read_int);
7031         scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
7032             data->sap.write_int);
7033         scsi_u64to8b(0, data->sap.weighted_num);
7034         scsi_u64to8b(0, data->sap.weighted_int);
7035         scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
7036         data->it.hdr.param_control = SLP_LBIN;
7037         data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
7038             sizeof(struct scsi_log_param_header);
7039 #ifdef CTL_TIME_IO
7040         scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
7041 #endif
7042         scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
7043         data->it.hdr.param_control = SLP_LBIN;
7044         data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
7045             sizeof(struct scsi_log_param_header);
7046         scsi_ulto4b(3, data->ti.exponent);
7047         scsi_ulto4b(1, data->ti.integer);
7048
7049         page_index->page_len = sizeof(*data);
7050         return (0);
7051 }
7052
7053 int
7054 ctl_log_sense(struct ctl_scsiio *ctsio)
7055 {
7056         struct ctl_lun *lun;
7057         int i, pc, page_code, subpage;
7058         int alloc_len, total_len;
7059         struct ctl_page_index *page_index;
7060         struct scsi_log_sense *cdb;
7061         struct scsi_log_header *header;
7062
7063         CTL_DEBUG_PRINT(("ctl_log_sense\n"));
7064
7065         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7066         cdb = (struct scsi_log_sense *)ctsio->cdb;
7067         pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
7068         page_code = cdb->page & SLS_PAGE_CODE;
7069         subpage = cdb->subpage;
7070         alloc_len = scsi_2btoul(cdb->length);
7071
7072         page_index = NULL;
7073         for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
7074                 page_index = &lun->log_pages.index[i];
7075
7076                 /* Look for the right page code */
7077                 if ((page_index->page_code & SL_PAGE_CODE) != page_code)
7078                         continue;
7079
7080                 /* Look for the right subpage or the subpage wildcard*/
7081                 if (page_index->subpage != subpage)
7082                         continue;
7083
7084                 break;
7085         }
7086         if (i >= CTL_NUM_LOG_PAGES) {
7087                 ctl_set_invalid_field(ctsio,
7088                                       /*sks_valid*/ 1,
7089                                       /*command*/ 1,
7090                                       /*field*/ 2,
7091                                       /*bit_valid*/ 0,
7092                                       /*bit*/ 0);
7093                 ctl_done((union ctl_io *)ctsio);
7094                 return (CTL_RETVAL_COMPLETE);
7095         }
7096
7097         total_len = sizeof(struct scsi_log_header) + page_index->page_len;
7098
7099         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7100         ctsio->kern_sg_entries = 0;
7101         ctsio->kern_data_resid = 0;
7102         ctsio->kern_rel_offset = 0;
7103         if (total_len < alloc_len) {
7104                 ctsio->residual = alloc_len - total_len;
7105                 ctsio->kern_data_len = total_len;
7106                 ctsio->kern_total_len = total_len;
7107         } else {
7108                 ctsio->residual = 0;
7109                 ctsio->kern_data_len = alloc_len;
7110                 ctsio->kern_total_len = alloc_len;
7111         }
7112
7113         header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7114         header->page = page_index->page_code;
7115         if (page_index->subpage) {
7116                 header->page |= SL_SPF;
7117                 header->subpage = page_index->subpage;
7118         }
7119         scsi_ulto2b(page_index->page_len, header->datalen);
7120
7121         /*
7122          * Call the handler, if it exists, to update the
7123          * page to the latest values.
7124          */
7125         if (page_index->sense_handler != NULL)
7126                 page_index->sense_handler(ctsio, page_index, pc);
7127
7128         memcpy(header + 1, page_index->page_data, page_index->page_len);
7129
7130         ctl_set_success(ctsio);
7131         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7132         ctsio->be_move_done = ctl_config_move_done;
7133         ctl_datamove((union ctl_io *)ctsio);
7134         return (CTL_RETVAL_COMPLETE);
7135 }
7136
7137 int
7138 ctl_read_capacity(struct ctl_scsiio *ctsio)
7139 {
7140         struct scsi_read_capacity *cdb;
7141         struct scsi_read_capacity_data *data;
7142         struct ctl_lun *lun;
7143         uint32_t lba;
7144
7145         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7146
7147         cdb = (struct scsi_read_capacity *)ctsio->cdb;
7148
7149         lba = scsi_4btoul(cdb->addr);
7150         if (((cdb->pmi & SRC_PMI) == 0)
7151          && (lba != 0)) {
7152                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7153                                       /*sks_valid*/ 1,
7154                                       /*command*/ 1,
7155                                       /*field*/ 2,
7156                                       /*bit_valid*/ 0,
7157                                       /*bit*/ 0);
7158                 ctl_done((union ctl_io *)ctsio);
7159                 return (CTL_RETVAL_COMPLETE);
7160         }
7161
7162         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7163
7164         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7165         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7166         ctsio->residual = 0;
7167         ctsio->kern_data_len = sizeof(*data);
7168         ctsio->kern_total_len = sizeof(*data);
7169         ctsio->kern_data_resid = 0;
7170         ctsio->kern_rel_offset = 0;
7171         ctsio->kern_sg_entries = 0;
7172
7173         /*
7174          * If the maximum LBA is greater than 0xfffffffe, the user must
7175          * issue a SERVICE ACTION IN (16) command, with the read capacity
7176          * serivce action set.
7177          */
7178         if (lun->be_lun->maxlba > 0xfffffffe)
7179                 scsi_ulto4b(0xffffffff, data->addr);
7180         else
7181                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7182
7183         /*
7184          * XXX KDM this may not be 512 bytes...
7185          */
7186         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7187
7188         ctl_set_success(ctsio);
7189         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7190         ctsio->be_move_done = ctl_config_move_done;
7191         ctl_datamove((union ctl_io *)ctsio);
7192         return (CTL_RETVAL_COMPLETE);
7193 }
7194
7195 int
7196 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7197 {
7198         struct scsi_read_capacity_16 *cdb;
7199         struct scsi_read_capacity_data_long *data;
7200         struct ctl_lun *lun;
7201         uint64_t lba;
7202         uint32_t alloc_len;
7203
7204         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7205
7206         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7207
7208         alloc_len = scsi_4btoul(cdb->alloc_len);
7209         lba = scsi_8btou64(cdb->addr);
7210
7211         if ((cdb->reladr & SRC16_PMI)
7212          && (lba != 0)) {
7213                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7214                                       /*sks_valid*/ 1,
7215                                       /*command*/ 1,
7216                                       /*field*/ 2,
7217                                       /*bit_valid*/ 0,
7218                                       /*bit*/ 0);
7219                 ctl_done((union ctl_io *)ctsio);
7220                 return (CTL_RETVAL_COMPLETE);
7221         }
7222
7223         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7224
7225         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7226         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7227
7228         if (sizeof(*data) < alloc_len) {
7229                 ctsio->residual = alloc_len - sizeof(*data);
7230                 ctsio->kern_data_len = sizeof(*data);
7231                 ctsio->kern_total_len = sizeof(*data);
7232         } else {
7233                 ctsio->residual = 0;
7234                 ctsio->kern_data_len = alloc_len;
7235                 ctsio->kern_total_len = alloc_len;
7236         }
7237         ctsio->kern_data_resid = 0;
7238         ctsio->kern_rel_offset = 0;
7239         ctsio->kern_sg_entries = 0;
7240
7241         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7242         /* XXX KDM this may not be 512 bytes... */
7243         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7244         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7245         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7246         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7247                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7248
7249         ctl_set_success(ctsio);
7250         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7251         ctsio->be_move_done = ctl_config_move_done;
7252         ctl_datamove((union ctl_io *)ctsio);
7253         return (CTL_RETVAL_COMPLETE);
7254 }
7255
7256 int
7257 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7258 {
7259         struct scsi_get_lba_status *cdb;
7260         struct scsi_get_lba_status_data *data;
7261         struct ctl_lun *lun;
7262         struct ctl_lba_len_flags *lbalen;
7263         uint64_t lba;
7264         uint32_t alloc_len, total_len;
7265         int retval;
7266
7267         CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7268
7269         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7270         cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7271         lba = scsi_8btou64(cdb->addr);
7272         alloc_len = scsi_4btoul(cdb->alloc_len);
7273
7274         if (lba > lun->be_lun->maxlba) {
7275                 ctl_set_lba_out_of_range(ctsio);
7276                 ctl_done((union ctl_io *)ctsio);
7277                 return (CTL_RETVAL_COMPLETE);
7278         }
7279
7280         total_len = sizeof(*data) + sizeof(data->descr[0]);
7281         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7282         data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7283
7284         if (total_len < alloc_len) {
7285                 ctsio->residual = alloc_len - total_len;
7286                 ctsio->kern_data_len = total_len;
7287                 ctsio->kern_total_len = total_len;
7288         } else {
7289                 ctsio->residual = 0;
7290                 ctsio->kern_data_len = alloc_len;
7291                 ctsio->kern_total_len = alloc_len;
7292         }
7293         ctsio->kern_data_resid = 0;
7294         ctsio->kern_rel_offset = 0;
7295         ctsio->kern_sg_entries = 0;
7296
7297         /* Fill dummy data in case backend can't tell anything. */
7298         scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7299         scsi_u64to8b(lba, data->descr[0].addr);
7300         scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7301             data->descr[0].length);
7302         data->descr[0].status = 0; /* Mapped or unknown. */
7303
7304         ctl_set_success(ctsio);
7305         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7306         ctsio->be_move_done = ctl_config_move_done;
7307
7308         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7309         lbalen->lba = lba;
7310         lbalen->len = total_len;
7311         lbalen->flags = 0;
7312         retval = lun->backend->config_read((union ctl_io *)ctsio);
7313         return (CTL_RETVAL_COMPLETE);
7314 }
7315
7316 int
7317 ctl_read_defect(struct ctl_scsiio *ctsio)
7318 {
7319         struct scsi_read_defect_data_10 *ccb10;
7320         struct scsi_read_defect_data_12 *ccb12;
7321         struct scsi_read_defect_data_hdr_10 *data10;
7322         struct scsi_read_defect_data_hdr_12 *data12;
7323         uint32_t alloc_len, data_len;
7324         uint8_t format;
7325
7326         CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7327
7328         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7329                 ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7330                 format = ccb10->format;
7331                 alloc_len = scsi_2btoul(ccb10->alloc_length);
7332                 data_len = sizeof(*data10);
7333         } else {
7334                 ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7335                 format = ccb12->format;
7336                 alloc_len = scsi_4btoul(ccb12->alloc_length);
7337                 data_len = sizeof(*data12);
7338         }
7339         if (alloc_len == 0) {
7340                 ctl_set_success(ctsio);
7341                 ctl_done((union ctl_io *)ctsio);
7342                 return (CTL_RETVAL_COMPLETE);
7343         }
7344
7345         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7346         if (data_len < alloc_len) {
7347                 ctsio->residual = alloc_len - data_len;
7348                 ctsio->kern_data_len = data_len;
7349                 ctsio->kern_total_len = data_len;
7350         } else {
7351                 ctsio->residual = 0;
7352                 ctsio->kern_data_len = alloc_len;
7353                 ctsio->kern_total_len = alloc_len;
7354         }
7355         ctsio->kern_data_resid = 0;
7356         ctsio->kern_rel_offset = 0;
7357         ctsio->kern_sg_entries = 0;
7358
7359         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7360                 data10 = (struct scsi_read_defect_data_hdr_10 *)
7361                     ctsio->kern_data_ptr;
7362                 data10->format = format;
7363                 scsi_ulto2b(0, data10->length);
7364         } else {
7365                 data12 = (struct scsi_read_defect_data_hdr_12 *)
7366                     ctsio->kern_data_ptr;
7367                 data12->format = format;
7368                 scsi_ulto2b(0, data12->generation);
7369                 scsi_ulto4b(0, data12->length);
7370         }
7371
7372         ctl_set_success(ctsio);
7373         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7374         ctsio->be_move_done = ctl_config_move_done;
7375         ctl_datamove((union ctl_io *)ctsio);
7376         return (CTL_RETVAL_COMPLETE);
7377 }
7378
7379 int
7380 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7381 {
7382         struct scsi_maintenance_in *cdb;
7383         int retval;
7384         int alloc_len, ext, total_len = 0, g, p, pc, pg, gs, os;
7385         int num_target_port_groups, num_target_ports;
7386         struct ctl_lun *lun;
7387         struct ctl_softc *softc;
7388         struct ctl_port *port;
7389         struct scsi_target_group_data *rtg_ptr;
7390         struct scsi_target_group_data_extended *rtg_ext_ptr;
7391         struct scsi_target_port_group_descriptor *tpg_desc;
7392
7393         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7394
7395         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7396         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7397         softc = lun->ctl_softc;
7398
7399         retval = CTL_RETVAL_COMPLETE;
7400
7401         switch (cdb->byte2 & STG_PDF_MASK) {
7402         case STG_PDF_LENGTH:
7403                 ext = 0;
7404                 break;
7405         case STG_PDF_EXTENDED:
7406                 ext = 1;
7407                 break;
7408         default:
7409                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7410                                       /*sks_valid*/ 1,
7411                                       /*command*/ 1,
7412                                       /*field*/ 2,
7413                                       /*bit_valid*/ 1,
7414                                       /*bit*/ 5);
7415                 ctl_done((union ctl_io *)ctsio);
7416                 return(retval);
7417         }
7418
7419         if (softc->is_single)
7420                 num_target_port_groups = 1;
7421         else
7422                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7423         num_target_ports = 0;
7424         mtx_lock(&softc->ctl_lock);
7425         STAILQ_FOREACH(port, &softc->port_list, links) {
7426                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7427                         continue;
7428                 if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7429                         continue;
7430                 num_target_ports++;
7431         }
7432         mtx_unlock(&softc->ctl_lock);
7433
7434         if (ext)
7435                 total_len = sizeof(struct scsi_target_group_data_extended);
7436         else
7437                 total_len = sizeof(struct scsi_target_group_data);
7438         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7439                 num_target_port_groups +
7440             sizeof(struct scsi_target_port_descriptor) *
7441                 num_target_ports * num_target_port_groups;
7442
7443         alloc_len = scsi_4btoul(cdb->length);
7444
7445         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7446
7447         ctsio->kern_sg_entries = 0;
7448
7449         if (total_len < alloc_len) {
7450                 ctsio->residual = alloc_len - total_len;
7451                 ctsio->kern_data_len = total_len;
7452                 ctsio->kern_total_len = total_len;
7453         } else {
7454                 ctsio->residual = 0;
7455                 ctsio->kern_data_len = alloc_len;
7456                 ctsio->kern_total_len = alloc_len;
7457         }
7458         ctsio->kern_data_resid = 0;
7459         ctsio->kern_rel_offset = 0;
7460
7461         if (ext) {
7462                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7463                     ctsio->kern_data_ptr;
7464                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7465                 rtg_ext_ptr->format_type = 0x10;
7466                 rtg_ext_ptr->implicit_transition_time = 0;
7467                 tpg_desc = &rtg_ext_ptr->groups[0];
7468         } else {
7469                 rtg_ptr = (struct scsi_target_group_data *)
7470                     ctsio->kern_data_ptr;
7471                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7472                 tpg_desc = &rtg_ptr->groups[0];
7473         }
7474
7475         mtx_lock(&softc->ctl_lock);
7476         pg = softc->port_offset / CTL_MAX_PORTS;
7477         if (softc->flags & CTL_FLAG_ACTIVE_SHELF) {
7478                 if (softc->ha_mode == CTL_HA_MODE_ACT_STBY) {
7479                         gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7480                         os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7481                 } else if (lun->flags & CTL_LUN_PRIMARY_SC) {
7482                         gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7483                         os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7484                 } else {
7485                         gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7486                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7487                 }
7488         } else {
7489                 gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7490                 os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7491         }
7492         for (g = 0; g < num_target_port_groups; g++) {
7493                 tpg_desc->pref_state = (g == pg) ? gs : os;
7494                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP;
7495                 scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7496                 tpg_desc->status = TPG_IMPLICIT;
7497                 pc = 0;
7498                 STAILQ_FOREACH(port, &softc->port_list, links) {
7499                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7500                                 continue;
7501                         if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7502                                 continue;
7503                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7504                         scsi_ulto2b(p, tpg_desc->descriptors[pc].
7505                             relative_target_port_identifier);
7506                         pc++;
7507                 }
7508                 tpg_desc->target_port_count = pc;
7509                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7510                     &tpg_desc->descriptors[pc];
7511         }
7512         mtx_unlock(&softc->ctl_lock);
7513
7514         ctl_set_success(ctsio);
7515         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7516         ctsio->be_move_done = ctl_config_move_done;
7517         ctl_datamove((union ctl_io *)ctsio);
7518         return(retval);
7519 }
7520
7521 int
7522 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7523 {
7524         struct ctl_lun *lun;
7525         struct scsi_report_supported_opcodes *cdb;
7526         const struct ctl_cmd_entry *entry, *sentry;
7527         struct scsi_report_supported_opcodes_all *all;
7528         struct scsi_report_supported_opcodes_descr *descr;
7529         struct scsi_report_supported_opcodes_one *one;
7530         int retval;
7531         int alloc_len, total_len;
7532         int opcode, service_action, i, j, num;
7533
7534         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7535
7536         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7537         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7538
7539         retval = CTL_RETVAL_COMPLETE;
7540
7541         opcode = cdb->requested_opcode;
7542         service_action = scsi_2btoul(cdb->requested_service_action);
7543         switch (cdb->options & RSO_OPTIONS_MASK) {
7544         case RSO_OPTIONS_ALL:
7545                 num = 0;
7546                 for (i = 0; i < 256; i++) {
7547                         entry = &ctl_cmd_table[i];
7548                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7549                                 for (j = 0; j < 32; j++) {
7550                                         sentry = &((const struct ctl_cmd_entry *)
7551                                             entry->execute)[j];
7552                                         if (ctl_cmd_applicable(
7553                                             lun->be_lun->lun_type, sentry))
7554                                                 num++;
7555                                 }
7556                         } else {
7557                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7558                                     entry))
7559                                         num++;
7560                         }
7561                 }
7562                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7563                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7564                 break;
7565         case RSO_OPTIONS_OC:
7566                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7567                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7568                                               /*sks_valid*/ 1,
7569                                               /*command*/ 1,
7570                                               /*field*/ 2,
7571                                               /*bit_valid*/ 1,
7572                                               /*bit*/ 2);
7573                         ctl_done((union ctl_io *)ctsio);
7574                         return (CTL_RETVAL_COMPLETE);
7575                 }
7576                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7577                 break;
7578         case RSO_OPTIONS_OC_SA:
7579                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7580                     service_action >= 32) {
7581                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7582                                               /*sks_valid*/ 1,
7583                                               /*command*/ 1,
7584                                               /*field*/ 2,
7585                                               /*bit_valid*/ 1,
7586                                               /*bit*/ 2);
7587                         ctl_done((union ctl_io *)ctsio);
7588                         return (CTL_RETVAL_COMPLETE);
7589                 }
7590                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7591                 break;
7592         default:
7593                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7594                                       /*sks_valid*/ 1,
7595                                       /*command*/ 1,
7596                                       /*field*/ 2,
7597                                       /*bit_valid*/ 1,
7598                                       /*bit*/ 2);
7599                 ctl_done((union ctl_io *)ctsio);
7600                 return (CTL_RETVAL_COMPLETE);
7601         }
7602
7603         alloc_len = scsi_4btoul(cdb->length);
7604
7605         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7606
7607         ctsio->kern_sg_entries = 0;
7608
7609         if (total_len < alloc_len) {
7610                 ctsio->residual = alloc_len - total_len;
7611                 ctsio->kern_data_len = total_len;
7612                 ctsio->kern_total_len = total_len;
7613         } else {
7614                 ctsio->residual = 0;
7615                 ctsio->kern_data_len = alloc_len;
7616                 ctsio->kern_total_len = alloc_len;
7617         }
7618         ctsio->kern_data_resid = 0;
7619         ctsio->kern_rel_offset = 0;
7620
7621         switch (cdb->options & RSO_OPTIONS_MASK) {
7622         case RSO_OPTIONS_ALL:
7623                 all = (struct scsi_report_supported_opcodes_all *)
7624                     ctsio->kern_data_ptr;
7625                 num = 0;
7626                 for (i = 0; i < 256; i++) {
7627                         entry = &ctl_cmd_table[i];
7628                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7629                                 for (j = 0; j < 32; j++) {
7630                                         sentry = &((const struct ctl_cmd_entry *)
7631                                             entry->execute)[j];
7632                                         if (!ctl_cmd_applicable(
7633                                             lun->be_lun->lun_type, sentry))
7634                                                 continue;
7635                                         descr = &all->descr[num++];
7636                                         descr->opcode = i;
7637                                         scsi_ulto2b(j, descr->service_action);
7638                                         descr->flags = RSO_SERVACTV;
7639                                         scsi_ulto2b(sentry->length,
7640                                             descr->cdb_length);
7641                                 }
7642                         } else {
7643                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7644                                     entry))
7645                                         continue;
7646                                 descr = &all->descr[num++];
7647                                 descr->opcode = i;
7648                                 scsi_ulto2b(0, descr->service_action);
7649                                 descr->flags = 0;
7650                                 scsi_ulto2b(entry->length, descr->cdb_length);
7651                         }
7652                 }
7653                 scsi_ulto4b(
7654                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7655                     all->length);
7656                 break;
7657         case RSO_OPTIONS_OC:
7658                 one = (struct scsi_report_supported_opcodes_one *)
7659                     ctsio->kern_data_ptr;
7660                 entry = &ctl_cmd_table[opcode];
7661                 goto fill_one;
7662         case RSO_OPTIONS_OC_SA:
7663                 one = (struct scsi_report_supported_opcodes_one *)
7664                     ctsio->kern_data_ptr;
7665                 entry = &ctl_cmd_table[opcode];
7666                 entry = &((const struct ctl_cmd_entry *)
7667                     entry->execute)[service_action];
7668 fill_one:
7669                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7670                         one->support = 3;
7671                         scsi_ulto2b(entry->length, one->cdb_length);
7672                         one->cdb_usage[0] = opcode;
7673                         memcpy(&one->cdb_usage[1], entry->usage,
7674                             entry->length - 1);
7675                 } else
7676                         one->support = 1;
7677                 break;
7678         }
7679
7680         ctl_set_success(ctsio);
7681         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7682         ctsio->be_move_done = ctl_config_move_done;
7683         ctl_datamove((union ctl_io *)ctsio);
7684         return(retval);
7685 }
7686
7687 int
7688 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7689 {
7690         struct scsi_report_supported_tmf *cdb;
7691         struct scsi_report_supported_tmf_data *data;
7692         int retval;
7693         int alloc_len, total_len;
7694
7695         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7696
7697         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7698
7699         retval = CTL_RETVAL_COMPLETE;
7700
7701         total_len = sizeof(struct scsi_report_supported_tmf_data);
7702         alloc_len = scsi_4btoul(cdb->length);
7703
7704         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7705
7706         ctsio->kern_sg_entries = 0;
7707
7708         if (total_len < alloc_len) {
7709                 ctsio->residual = alloc_len - total_len;
7710                 ctsio->kern_data_len = total_len;
7711                 ctsio->kern_total_len = total_len;
7712         } else {
7713                 ctsio->residual = 0;
7714                 ctsio->kern_data_len = alloc_len;
7715                 ctsio->kern_total_len = alloc_len;
7716         }
7717         ctsio->kern_data_resid = 0;
7718         ctsio->kern_rel_offset = 0;
7719
7720         data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7721         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7722         data->byte2 |= RST_ITNRS;
7723
7724         ctl_set_success(ctsio);
7725         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7726         ctsio->be_move_done = ctl_config_move_done;
7727         ctl_datamove((union ctl_io *)ctsio);
7728         return (retval);
7729 }
7730
7731 int
7732 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7733 {
7734         struct scsi_report_timestamp *cdb;
7735         struct scsi_report_timestamp_data *data;
7736         struct timeval tv;
7737         int64_t timestamp;
7738         int retval;
7739         int alloc_len, total_len;
7740
7741         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7742
7743         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7744
7745         retval = CTL_RETVAL_COMPLETE;
7746
7747         total_len = sizeof(struct scsi_report_timestamp_data);
7748         alloc_len = scsi_4btoul(cdb->length);
7749
7750         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7751
7752         ctsio->kern_sg_entries = 0;
7753
7754         if (total_len < alloc_len) {
7755                 ctsio->residual = alloc_len - total_len;
7756                 ctsio->kern_data_len = total_len;
7757                 ctsio->kern_total_len = total_len;
7758         } else {
7759                 ctsio->residual = 0;
7760                 ctsio->kern_data_len = alloc_len;
7761                 ctsio->kern_total_len = alloc_len;
7762         }
7763         ctsio->kern_data_resid = 0;
7764         ctsio->kern_rel_offset = 0;
7765
7766         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7767         scsi_ulto2b(sizeof(*data) - 2, data->length);
7768         data->origin = RTS_ORIG_OUTSIDE;
7769         getmicrotime(&tv);
7770         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7771         scsi_ulto4b(timestamp >> 16, data->timestamp);
7772         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7773
7774         ctl_set_success(ctsio);
7775         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7776         ctsio->be_move_done = ctl_config_move_done;
7777         ctl_datamove((union ctl_io *)ctsio);
7778         return (retval);
7779 }
7780
7781 int
7782 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7783 {
7784         struct scsi_per_res_in *cdb;
7785         int alloc_len, total_len = 0;
7786         /* struct scsi_per_res_in_rsrv in_data; */
7787         struct ctl_lun *lun;
7788         struct ctl_softc *softc;
7789         uint64_t key;
7790
7791         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7792
7793         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7794
7795         alloc_len = scsi_2btoul(cdb->length);
7796
7797         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7798         softc = lun->ctl_softc;
7799
7800 retry:
7801         mtx_lock(&lun->lun_lock);
7802         switch (cdb->action) {
7803         case SPRI_RK: /* read keys */
7804                 total_len = sizeof(struct scsi_per_res_in_keys) +
7805                         lun->pr_key_count *
7806                         sizeof(struct scsi_per_res_key);
7807                 break;
7808         case SPRI_RR: /* read reservation */
7809                 if (lun->flags & CTL_LUN_PR_RESERVED)
7810                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7811                 else
7812                         total_len = sizeof(struct scsi_per_res_in_header);
7813                 break;
7814         case SPRI_RC: /* report capabilities */
7815                 total_len = sizeof(struct scsi_per_res_cap);
7816                 break;
7817         case SPRI_RS: /* read full status */
7818                 total_len = sizeof(struct scsi_per_res_in_header) +
7819                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7820                     lun->pr_key_count;
7821                 break;
7822         default:
7823                 panic("Invalid PR type %x", cdb->action);
7824         }
7825         mtx_unlock(&lun->lun_lock);
7826
7827         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7828
7829         if (total_len < alloc_len) {
7830                 ctsio->residual = alloc_len - total_len;
7831                 ctsio->kern_data_len = total_len;
7832                 ctsio->kern_total_len = total_len;
7833         } else {
7834                 ctsio->residual = 0;
7835                 ctsio->kern_data_len = alloc_len;
7836                 ctsio->kern_total_len = alloc_len;
7837         }
7838
7839         ctsio->kern_data_resid = 0;
7840         ctsio->kern_rel_offset = 0;
7841         ctsio->kern_sg_entries = 0;
7842
7843         mtx_lock(&lun->lun_lock);
7844         switch (cdb->action) {
7845         case SPRI_RK: { // read keys
7846         struct scsi_per_res_in_keys *res_keys;
7847                 int i, key_count;
7848
7849                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7850
7851                 /*
7852                  * We had to drop the lock to allocate our buffer, which
7853                  * leaves time for someone to come in with another
7854                  * persistent reservation.  (That is unlikely, though,
7855                  * since this should be the only persistent reservation
7856                  * command active right now.)
7857                  */
7858                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7859                     (lun->pr_key_count *
7860                      sizeof(struct scsi_per_res_key)))){
7861                         mtx_unlock(&lun->lun_lock);
7862                         free(ctsio->kern_data_ptr, M_CTL);
7863                         printf("%s: reservation length changed, retrying\n",
7864                                __func__);
7865                         goto retry;
7866                 }
7867
7868                 scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7869
7870                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7871                              lun->pr_key_count, res_keys->header.length);
7872
7873                 for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7874                         if ((key = ctl_get_prkey(lun, i)) == 0)
7875                                 continue;
7876
7877                         /*
7878                          * We used lun->pr_key_count to calculate the
7879                          * size to allocate.  If it turns out the number of
7880                          * initiators with the registered flag set is
7881                          * larger than that (i.e. they haven't been kept in
7882                          * sync), we've got a problem.
7883                          */
7884                         if (key_count >= lun->pr_key_count) {
7885 #ifdef NEEDTOPORT
7886                                 csevent_log(CSC_CTL | CSC_SHELF_SW |
7887                                             CTL_PR_ERROR,
7888                                             csevent_LogType_Fault,
7889                                             csevent_AlertLevel_Yellow,
7890                                             csevent_FRU_ShelfController,
7891                                             csevent_FRU_Firmware,
7892                                         csevent_FRU_Unknown,
7893                                             "registered keys %d >= key "
7894                                             "count %d", key_count,
7895                                             lun->pr_key_count);
7896 #endif
7897                                 key_count++;
7898                                 continue;
7899                         }
7900                         scsi_u64to8b(key, res_keys->keys[key_count].key);
7901                         key_count++;
7902                 }
7903                 break;
7904         }
7905         case SPRI_RR: { // read reservation
7906                 struct scsi_per_res_in_rsrv *res;
7907                 int tmp_len, header_only;
7908
7909                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7910
7911                 scsi_ulto4b(lun->PRGeneration, res->header.generation);
7912
7913                 if (lun->flags & CTL_LUN_PR_RESERVED)
7914                 {
7915                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7916                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7917                                     res->header.length);
7918                         header_only = 0;
7919                 } else {
7920                         tmp_len = sizeof(struct scsi_per_res_in_header);
7921                         scsi_ulto4b(0, res->header.length);
7922                         header_only = 1;
7923                 }
7924
7925                 /*
7926                  * We had to drop the lock to allocate our buffer, which
7927                  * leaves time for someone to come in with another
7928                  * persistent reservation.  (That is unlikely, though,
7929                  * since this should be the only persistent reservation
7930                  * command active right now.)
7931                  */
7932                 if (tmp_len != total_len) {
7933                         mtx_unlock(&lun->lun_lock);
7934                         free(ctsio->kern_data_ptr, M_CTL);
7935                         printf("%s: reservation status changed, retrying\n",
7936                                __func__);
7937                         goto retry;
7938                 }
7939
7940                 /*
7941                  * No reservation held, so we're done.
7942                  */
7943                 if (header_only != 0)
7944                         break;
7945
7946                 /*
7947                  * If the registration is an All Registrants type, the key
7948                  * is 0, since it doesn't really matter.
7949                  */
7950                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7951                         scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7952                             res->data.reservation);
7953                 }
7954                 res->data.scopetype = lun->res_type;
7955                 break;
7956         }
7957         case SPRI_RC:     //report capabilities
7958         {
7959                 struct scsi_per_res_cap *res_cap;
7960                 uint16_t type_mask;
7961
7962                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7963                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7964                 res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7965                 type_mask = SPRI_TM_WR_EX_AR |
7966                             SPRI_TM_EX_AC_RO |
7967                             SPRI_TM_WR_EX_RO |
7968                             SPRI_TM_EX_AC |
7969                             SPRI_TM_WR_EX |
7970                             SPRI_TM_EX_AC_AR;
7971                 scsi_ulto2b(type_mask, res_cap->type_mask);
7972                 break;
7973         }
7974         case SPRI_RS: { // read full status
7975                 struct scsi_per_res_in_full *res_status;
7976                 struct scsi_per_res_in_full_desc *res_desc;
7977                 struct ctl_port *port;
7978                 int i, len;
7979
7980                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7981
7982                 /*
7983                  * We had to drop the lock to allocate our buffer, which
7984                  * leaves time for someone to come in with another
7985                  * persistent reservation.  (That is unlikely, though,
7986                  * since this should be the only persistent reservation
7987                  * command active right now.)
7988                  */
7989                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
7990                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7991                      lun->pr_key_count)){
7992                         mtx_unlock(&lun->lun_lock);
7993                         free(ctsio->kern_data_ptr, M_CTL);
7994                         printf("%s: reservation length changed, retrying\n",
7995                                __func__);
7996                         goto retry;
7997                 }
7998
7999                 scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
8000
8001                 res_desc = &res_status->desc[0];
8002                 for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
8003                         if ((key = ctl_get_prkey(lun, i)) == 0)
8004                                 continue;
8005
8006                         scsi_u64to8b(key, res_desc->res_key.key);
8007                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
8008                             (lun->pr_res_idx == i ||
8009                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
8010                                 res_desc->flags = SPRI_FULL_R_HOLDER;
8011                                 res_desc->scopetype = lun->res_type;
8012                         }
8013                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
8014                             res_desc->rel_trgt_port_id);
8015                         len = 0;
8016                         port = softc->ctl_ports[
8017                             ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
8018                         if (port != NULL)
8019                                 len = ctl_create_iid(port,
8020                                     i % CTL_MAX_INIT_PER_PORT,
8021                                     res_desc->transport_id);
8022                         scsi_ulto4b(len, res_desc->additional_length);
8023                         res_desc = (struct scsi_per_res_in_full_desc *)
8024                             &res_desc->transport_id[len];
8025                 }
8026                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
8027                     res_status->header.length);
8028                 break;
8029         }
8030         default:
8031                 /*
8032                  * This is a bug, because we just checked for this above,
8033                  * and should have returned an error.
8034                  */
8035                 panic("Invalid PR type %x", cdb->action);
8036                 break; /* NOTREACHED */
8037         }
8038         mtx_unlock(&lun->lun_lock);
8039
8040         ctl_set_success(ctsio);
8041         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8042         ctsio->be_move_done = ctl_config_move_done;
8043         ctl_datamove((union ctl_io *)ctsio);
8044         return (CTL_RETVAL_COMPLETE);
8045 }
8046
8047 static void
8048 ctl_est_res_ua(struct ctl_lun *lun, uint32_t residx, ctl_ua_type ua)
8049 {
8050         int off = lun->ctl_softc->persis_offset;
8051
8052         if (residx >= off && residx < off + CTL_MAX_INITIATORS)
8053                 ctl_est_ua(lun, residx - off, ua);
8054 }
8055
8056 /*
8057  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
8058  * it should return.
8059  */
8060 static int
8061 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
8062                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
8063                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
8064                 struct scsi_per_res_out_parms* param)
8065 {
8066         union ctl_ha_msg persis_io;
8067         int retval, i;
8068         int isc_retval;
8069
8070         retval = 0;
8071
8072         mtx_lock(&lun->lun_lock);
8073         if (sa_res_key == 0) {
8074                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8075                         /* validate scope and type */
8076                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8077                              SPR_LU_SCOPE) {
8078                                 mtx_unlock(&lun->lun_lock);
8079                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8080                                                       /*sks_valid*/ 1,
8081                                                       /*command*/ 1,
8082                                                       /*field*/ 2,
8083                                                       /*bit_valid*/ 1,
8084                                                       /*bit*/ 4);
8085                                 ctl_done((union ctl_io *)ctsio);
8086                                 return (1);
8087                         }
8088
8089                         if (type>8 || type==2 || type==4 || type==0) {
8090                                 mtx_unlock(&lun->lun_lock);
8091                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8092                                                       /*sks_valid*/ 1,
8093                                                       /*command*/ 1,
8094                                                       /*field*/ 2,
8095                                                       /*bit_valid*/ 1,
8096                                                       /*bit*/ 0);
8097                                 ctl_done((union ctl_io *)ctsio);
8098                                 return (1);
8099                         }
8100
8101                         /*
8102                          * Unregister everybody else and build UA for
8103                          * them
8104                          */
8105                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8106                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8107                                         continue;
8108
8109                                 ctl_clr_prkey(lun, i);
8110                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8111                         }
8112                         lun->pr_key_count = 1;
8113                         lun->res_type = type;
8114                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8115                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8116                                 lun->pr_res_idx = residx;
8117
8118                         /* send msg to other side */
8119                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8120                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8121                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8122                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8123                         persis_io.pr.pr_info.res_type = type;
8124                         memcpy(persis_io.pr.pr_info.sa_res_key,
8125                                param->serv_act_res_key,
8126                                sizeof(param->serv_act_res_key));
8127                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8128                              &persis_io, sizeof(persis_io), 0)) >
8129                              CTL_HA_STATUS_SUCCESS) {
8130                                 printf("CTL:Persis Out error returned "
8131                                        "from ctl_ha_msg_send %d\n",
8132                                        isc_retval);
8133                         }
8134                 } else {
8135                         /* not all registrants */
8136                         mtx_unlock(&lun->lun_lock);
8137                         free(ctsio->kern_data_ptr, M_CTL);
8138                         ctl_set_invalid_field(ctsio,
8139                                               /*sks_valid*/ 1,
8140                                               /*command*/ 0,
8141                                               /*field*/ 8,
8142                                               /*bit_valid*/ 0,
8143                                               /*bit*/ 0);
8144                         ctl_done((union ctl_io *)ctsio);
8145                         return (1);
8146                 }
8147         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8148                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
8149                 int found = 0;
8150
8151                 if (res_key == sa_res_key) {
8152                         /* special case */
8153                         /*
8154                          * The spec implies this is not good but doesn't
8155                          * say what to do. There are two choices either
8156                          * generate a res conflict or check condition
8157                          * with illegal field in parameter data. Since
8158                          * that is what is done when the sa_res_key is
8159                          * zero I'll take that approach since this has
8160                          * to do with the sa_res_key.
8161                          */
8162                         mtx_unlock(&lun->lun_lock);
8163                         free(ctsio->kern_data_ptr, M_CTL);
8164                         ctl_set_invalid_field(ctsio,
8165                                               /*sks_valid*/ 1,
8166                                               /*command*/ 0,
8167                                               /*field*/ 8,
8168                                               /*bit_valid*/ 0,
8169                                               /*bit*/ 0);
8170                         ctl_done((union ctl_io *)ctsio);
8171                         return (1);
8172                 }
8173
8174                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8175                         if (ctl_get_prkey(lun, i) != sa_res_key)
8176                                 continue;
8177
8178                         found = 1;
8179                         ctl_clr_prkey(lun, i);
8180                         lun->pr_key_count--;
8181                         ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8182                 }
8183                 if (!found) {
8184                         mtx_unlock(&lun->lun_lock);
8185                         free(ctsio->kern_data_ptr, M_CTL);
8186                         ctl_set_reservation_conflict(ctsio);
8187                         ctl_done((union ctl_io *)ctsio);
8188                         return (CTL_RETVAL_COMPLETE);
8189                 }
8190                 /* send msg to other side */
8191                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8192                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8193                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8194                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
8195                 persis_io.pr.pr_info.res_type = type;
8196                 memcpy(persis_io.pr.pr_info.sa_res_key,
8197                        param->serv_act_res_key,
8198                        sizeof(param->serv_act_res_key));
8199                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8200                      &persis_io, sizeof(persis_io), 0)) >
8201                      CTL_HA_STATUS_SUCCESS) {
8202                         printf("CTL:Persis Out error returned from "
8203                                "ctl_ha_msg_send %d\n", isc_retval);
8204                 }
8205         } else {
8206                 /* Reserved but not all registrants */
8207                 /* sa_res_key is res holder */
8208                 if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8209                         /* validate scope and type */
8210                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8211                              SPR_LU_SCOPE) {
8212                                 mtx_unlock(&lun->lun_lock);
8213                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8214                                                       /*sks_valid*/ 1,
8215                                                       /*command*/ 1,
8216                                                       /*field*/ 2,
8217                                                       /*bit_valid*/ 1,
8218                                                       /*bit*/ 4);
8219                                 ctl_done((union ctl_io *)ctsio);
8220                                 return (1);
8221                         }
8222
8223                         if (type>8 || type==2 || type==4 || type==0) {
8224                                 mtx_unlock(&lun->lun_lock);
8225                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8226                                                       /*sks_valid*/ 1,
8227                                                       /*command*/ 1,
8228                                                       /*field*/ 2,
8229                                                       /*bit_valid*/ 1,
8230                                                       /*bit*/ 0);
8231                                 ctl_done((union ctl_io *)ctsio);
8232                                 return (1);
8233                         }
8234
8235                         /*
8236                          * Do the following:
8237                          * if sa_res_key != res_key remove all
8238                          * registrants w/sa_res_key and generate UA
8239                          * for these registrants(Registrations
8240                          * Preempted) if it wasn't an exclusive
8241                          * reservation generate UA(Reservations
8242                          * Preempted) for all other registered nexuses
8243                          * if the type has changed. Establish the new
8244                          * reservation and holder. If res_key and
8245                          * sa_res_key are the same do the above
8246                          * except don't unregister the res holder.
8247                          */
8248
8249                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8250                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8251                                         continue;
8252
8253                                 if (sa_res_key == ctl_get_prkey(lun, i)) {
8254                                         ctl_clr_prkey(lun, i);
8255                                         lun->pr_key_count--;
8256                                         ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8257                                 } else if (type != lun->res_type
8258                                         && (lun->res_type == SPR_TYPE_WR_EX_RO
8259                                          || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8260                                         ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
8261                                 }
8262                         }
8263                         lun->res_type = type;
8264                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8265                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8266                                 lun->pr_res_idx = residx;
8267                         else
8268                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8269
8270                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8271                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8272                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8273                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8274                         persis_io.pr.pr_info.res_type = type;
8275                         memcpy(persis_io.pr.pr_info.sa_res_key,
8276                                param->serv_act_res_key,
8277                                sizeof(param->serv_act_res_key));
8278                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8279                              &persis_io, sizeof(persis_io), 0)) >
8280                              CTL_HA_STATUS_SUCCESS) {
8281                                 printf("CTL:Persis Out error returned "
8282                                        "from ctl_ha_msg_send %d\n",
8283                                        isc_retval);
8284                         }
8285                 } else {
8286                         /*
8287                          * sa_res_key is not the res holder just
8288                          * remove registrants
8289                          */
8290                         int found=0;
8291
8292                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8293                                 if (sa_res_key != ctl_get_prkey(lun, i))
8294                                         continue;
8295
8296                                 found = 1;
8297                                 ctl_clr_prkey(lun, i);
8298                                 lun->pr_key_count--;
8299                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8300                         }
8301
8302                         if (!found) {
8303                                 mtx_unlock(&lun->lun_lock);
8304                                 free(ctsio->kern_data_ptr, M_CTL);
8305                                 ctl_set_reservation_conflict(ctsio);
8306                                 ctl_done((union ctl_io *)ctsio);
8307                                 return (1);
8308                         }
8309                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8310                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8311                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8312                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8313                         persis_io.pr.pr_info.res_type = type;
8314                         memcpy(persis_io.pr.pr_info.sa_res_key,
8315                                param->serv_act_res_key,
8316                                sizeof(param->serv_act_res_key));
8317                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8318                              &persis_io, sizeof(persis_io), 0)) >
8319                              CTL_HA_STATUS_SUCCESS) {
8320                                 printf("CTL:Persis Out error returned "
8321                                        "from ctl_ha_msg_send %d\n",
8322                                 isc_retval);
8323                         }
8324                 }
8325         }
8326
8327         lun->PRGeneration++;
8328         mtx_unlock(&lun->lun_lock);
8329
8330         return (retval);
8331 }
8332
8333 static void
8334 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8335 {
8336         uint64_t sa_res_key;
8337         int i;
8338
8339         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8340
8341         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8342          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8343          || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8344                 if (sa_res_key == 0) {
8345                         /*
8346                          * Unregister everybody else and build UA for
8347                          * them
8348                          */
8349                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8350                                 if (i == msg->pr.pr_info.residx ||
8351                                     ctl_get_prkey(lun, i) == 0)
8352                                         continue;
8353
8354                                 ctl_clr_prkey(lun, i);
8355                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8356                         }
8357
8358                         lun->pr_key_count = 1;
8359                         lun->res_type = msg->pr.pr_info.res_type;
8360                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8361                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8362                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8363                 } else {
8364                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8365                                 if (sa_res_key == ctl_get_prkey(lun, i))
8366                                         continue;
8367
8368                                 ctl_clr_prkey(lun, i);
8369                                 lun->pr_key_count--;
8370                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8371                         }
8372                 }
8373         } else {
8374                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8375                         if (i == msg->pr.pr_info.residx ||
8376                             ctl_get_prkey(lun, i) == 0)
8377                                 continue;
8378
8379                         if (sa_res_key == ctl_get_prkey(lun, i)) {
8380                                 ctl_clr_prkey(lun, i);
8381                                 lun->pr_key_count--;
8382                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8383                         } else if (msg->pr.pr_info.res_type != lun->res_type
8384                                 && (lun->res_type == SPR_TYPE_WR_EX_RO
8385                                  || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8386                                 ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
8387                         }
8388                 }
8389                 lun->res_type = msg->pr.pr_info.res_type;
8390                 if (lun->res_type != SPR_TYPE_WR_EX_AR
8391                  && lun->res_type != SPR_TYPE_EX_AC_AR)
8392                         lun->pr_res_idx = msg->pr.pr_info.residx;
8393                 else
8394                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8395         }
8396         lun->PRGeneration++;
8397
8398 }
8399
8400
8401 int
8402 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8403 {
8404         int retval;
8405         int isc_retval;
8406         u_int32_t param_len;
8407         struct scsi_per_res_out *cdb;
8408         struct ctl_lun *lun;
8409         struct scsi_per_res_out_parms* param;
8410         struct ctl_softc *softc;
8411         uint32_t residx;
8412         uint64_t res_key, sa_res_key, key;
8413         uint8_t type;
8414         union ctl_ha_msg persis_io;
8415         int    i;
8416
8417         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8418
8419         retval = CTL_RETVAL_COMPLETE;
8420
8421         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8422         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8423         softc = lun->ctl_softc;
8424
8425         /*
8426          * We only support whole-LUN scope.  The scope & type are ignored for
8427          * register, register and ignore existing key and clear.
8428          * We sometimes ignore scope and type on preempts too!!
8429          * Verify reservation type here as well.
8430          */
8431         type = cdb->scope_type & SPR_TYPE_MASK;
8432         if ((cdb->action == SPRO_RESERVE)
8433          || (cdb->action == SPRO_RELEASE)) {
8434                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8435                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8436                                               /*sks_valid*/ 1,
8437                                               /*command*/ 1,
8438                                               /*field*/ 2,
8439                                               /*bit_valid*/ 1,
8440                                               /*bit*/ 4);
8441                         ctl_done((union ctl_io *)ctsio);
8442                         return (CTL_RETVAL_COMPLETE);
8443                 }
8444
8445                 if (type>8 || type==2 || type==4 || type==0) {
8446                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8447                                               /*sks_valid*/ 1,
8448                                               /*command*/ 1,
8449                                               /*field*/ 2,
8450                                               /*bit_valid*/ 1,
8451                                               /*bit*/ 0);
8452                         ctl_done((union ctl_io *)ctsio);
8453                         return (CTL_RETVAL_COMPLETE);
8454                 }
8455         }
8456
8457         param_len = scsi_4btoul(cdb->length);
8458
8459         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8460                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8461                 ctsio->kern_data_len = param_len;
8462                 ctsio->kern_total_len = param_len;
8463                 ctsio->kern_data_resid = 0;
8464                 ctsio->kern_rel_offset = 0;
8465                 ctsio->kern_sg_entries = 0;
8466                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8467                 ctsio->be_move_done = ctl_config_move_done;
8468                 ctl_datamove((union ctl_io *)ctsio);
8469
8470                 return (CTL_RETVAL_COMPLETE);
8471         }
8472
8473         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8474
8475         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8476         res_key = scsi_8btou64(param->res_key.key);
8477         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8478
8479         /*
8480          * Validate the reservation key here except for SPRO_REG_IGNO
8481          * This must be done for all other service actions
8482          */
8483         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8484                 mtx_lock(&lun->lun_lock);
8485                 if ((key = ctl_get_prkey(lun, residx)) != 0) {
8486                         if (res_key != key) {
8487                                 /*
8488                                  * The current key passed in doesn't match
8489                                  * the one the initiator previously
8490                                  * registered.
8491                                  */
8492                                 mtx_unlock(&lun->lun_lock);
8493                                 free(ctsio->kern_data_ptr, M_CTL);
8494                                 ctl_set_reservation_conflict(ctsio);
8495                                 ctl_done((union ctl_io *)ctsio);
8496                                 return (CTL_RETVAL_COMPLETE);
8497                         }
8498                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8499                         /*
8500                          * We are not registered
8501                          */
8502                         mtx_unlock(&lun->lun_lock);
8503                         free(ctsio->kern_data_ptr, M_CTL);
8504                         ctl_set_reservation_conflict(ctsio);
8505                         ctl_done((union ctl_io *)ctsio);
8506                         return (CTL_RETVAL_COMPLETE);
8507                 } else if (res_key != 0) {
8508                         /*
8509                          * We are not registered and trying to register but
8510                          * the register key isn't zero.
8511                          */
8512                         mtx_unlock(&lun->lun_lock);
8513                         free(ctsio->kern_data_ptr, M_CTL);
8514                         ctl_set_reservation_conflict(ctsio);
8515                         ctl_done((union ctl_io *)ctsio);
8516                         return (CTL_RETVAL_COMPLETE);
8517                 }
8518                 mtx_unlock(&lun->lun_lock);
8519         }
8520
8521         switch (cdb->action & SPRO_ACTION_MASK) {
8522         case SPRO_REGISTER:
8523         case SPRO_REG_IGNO: {
8524
8525 #if 0
8526                 printf("Registration received\n");
8527 #endif
8528
8529                 /*
8530                  * We don't support any of these options, as we report in
8531                  * the read capabilities request (see
8532                  * ctl_persistent_reserve_in(), above).
8533                  */
8534                 if ((param->flags & SPR_SPEC_I_PT)
8535                  || (param->flags & SPR_ALL_TG_PT)
8536                  || (param->flags & SPR_APTPL)) {
8537                         int bit_ptr;
8538
8539                         if (param->flags & SPR_APTPL)
8540                                 bit_ptr = 0;
8541                         else if (param->flags & SPR_ALL_TG_PT)
8542                                 bit_ptr = 2;
8543                         else /* SPR_SPEC_I_PT */
8544                                 bit_ptr = 3;
8545
8546                         free(ctsio->kern_data_ptr, M_CTL);
8547                         ctl_set_invalid_field(ctsio,
8548                                               /*sks_valid*/ 1,
8549                                               /*command*/ 0,
8550                                               /*field*/ 20,
8551                                               /*bit_valid*/ 1,
8552                                               /*bit*/ bit_ptr);
8553                         ctl_done((union ctl_io *)ctsio);
8554                         return (CTL_RETVAL_COMPLETE);
8555                 }
8556
8557                 mtx_lock(&lun->lun_lock);
8558
8559                 /*
8560                  * The initiator wants to clear the
8561                  * key/unregister.
8562                  */
8563                 if (sa_res_key == 0) {
8564                         if ((res_key == 0
8565                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8566                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8567                           && ctl_get_prkey(lun, residx) == 0)) {
8568                                 mtx_unlock(&lun->lun_lock);
8569                                 goto done;
8570                         }
8571
8572                         ctl_clr_prkey(lun, residx);
8573                         lun->pr_key_count--;
8574
8575                         if (residx == lun->pr_res_idx) {
8576                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8577                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8578
8579                                 if ((lun->res_type == SPR_TYPE_WR_EX_RO
8580                                   || lun->res_type == SPR_TYPE_EX_AC_RO)
8581                                  && lun->pr_key_count) {
8582                                         /*
8583                                          * If the reservation is a registrants
8584                                          * only type we need to generate a UA
8585                                          * for other registered inits.  The
8586                                          * sense code should be RESERVATIONS
8587                                          * RELEASED
8588                                          */
8589
8590                                         for (i = 0; i < CTL_MAX_INITIATORS;i++){
8591                                                 if (ctl_get_prkey(lun, i +
8592                                                     softc->persis_offset) == 0)
8593                                                         continue;
8594                                                 ctl_est_ua(lun, i,
8595                                                     CTL_UA_RES_RELEASE);
8596                                         }
8597                                 }
8598                                 lun->res_type = 0;
8599                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8600                                 if (lun->pr_key_count==0) {
8601                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8602                                         lun->res_type = 0;
8603                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8604                                 }
8605                         }
8606                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8607                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8608                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8609                         persis_io.pr.pr_info.residx = residx;
8610                         if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8611                              &persis_io, sizeof(persis_io), 0 )) >
8612                              CTL_HA_STATUS_SUCCESS) {
8613                                 printf("CTL:Persis Out error returned from "
8614                                        "ctl_ha_msg_send %d\n", isc_retval);
8615                         }
8616                 } else /* sa_res_key != 0 */ {
8617
8618                         /*
8619                          * If we aren't registered currently then increment
8620                          * the key count and set the registered flag.
8621                          */
8622                         ctl_alloc_prkey(lun, residx);
8623                         if (ctl_get_prkey(lun, residx) == 0)
8624                                 lun->pr_key_count++;
8625                         ctl_set_prkey(lun, residx, sa_res_key);
8626
8627                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8628                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8629                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8630                         persis_io.pr.pr_info.residx = residx;
8631                         memcpy(persis_io.pr.pr_info.sa_res_key,
8632                                param->serv_act_res_key,
8633                                sizeof(param->serv_act_res_key));
8634                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8635                              &persis_io, sizeof(persis_io), 0)) >
8636                              CTL_HA_STATUS_SUCCESS) {
8637                                 printf("CTL:Persis Out error returned from "
8638                                        "ctl_ha_msg_send %d\n", isc_retval);
8639                         }
8640                 }
8641                 lun->PRGeneration++;
8642                 mtx_unlock(&lun->lun_lock);
8643
8644                 break;
8645         }
8646         case SPRO_RESERVE:
8647 #if 0
8648                 printf("Reserve executed type %d\n", type);
8649 #endif
8650                 mtx_lock(&lun->lun_lock);
8651                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8652                         /*
8653                          * if this isn't the reservation holder and it's
8654                          * not a "all registrants" type or if the type is
8655                          * different then we have a conflict
8656                          */
8657                         if ((lun->pr_res_idx != residx
8658                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8659                          || lun->res_type != type) {
8660                                 mtx_unlock(&lun->lun_lock);
8661                                 free(ctsio->kern_data_ptr, M_CTL);
8662                                 ctl_set_reservation_conflict(ctsio);
8663                                 ctl_done((union ctl_io *)ctsio);
8664                                 return (CTL_RETVAL_COMPLETE);
8665                         }
8666                         mtx_unlock(&lun->lun_lock);
8667                 } else /* create a reservation */ {
8668                         /*
8669                          * If it's not an "all registrants" type record
8670                          * reservation holder
8671                          */
8672                         if (type != SPR_TYPE_WR_EX_AR
8673                          && type != SPR_TYPE_EX_AC_AR)
8674                                 lun->pr_res_idx = residx; /* Res holder */
8675                         else
8676                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8677
8678                         lun->flags |= CTL_LUN_PR_RESERVED;
8679                         lun->res_type = type;
8680
8681                         mtx_unlock(&lun->lun_lock);
8682
8683                         /* send msg to other side */
8684                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8685                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8686                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8687                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8688                         persis_io.pr.pr_info.res_type = type;
8689                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8690                              &persis_io, sizeof(persis_io), 0)) >
8691                              CTL_HA_STATUS_SUCCESS) {
8692                                 printf("CTL:Persis Out error returned from "
8693                                        "ctl_ha_msg_send %d\n", isc_retval);
8694                         }
8695                 }
8696                 break;
8697
8698         case SPRO_RELEASE:
8699                 mtx_lock(&lun->lun_lock);
8700                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8701                         /* No reservation exists return good status */
8702                         mtx_unlock(&lun->lun_lock);
8703                         goto done;
8704                 }
8705                 /*
8706                  * Is this nexus a reservation holder?
8707                  */
8708                 if (lun->pr_res_idx != residx
8709                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8710                         /*
8711                          * not a res holder return good status but
8712                          * do nothing
8713                          */
8714                         mtx_unlock(&lun->lun_lock);
8715                         goto done;
8716                 }
8717
8718                 if (lun->res_type != type) {
8719                         mtx_unlock(&lun->lun_lock);
8720                         free(ctsio->kern_data_ptr, M_CTL);
8721                         ctl_set_illegal_pr_release(ctsio);
8722                         ctl_done((union ctl_io *)ctsio);
8723                         return (CTL_RETVAL_COMPLETE);
8724                 }
8725
8726                 /* okay to release */
8727                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8728                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8729                 lun->res_type = 0;
8730
8731                 /*
8732                  * if this isn't an exclusive access
8733                  * res generate UA for all other
8734                  * registrants.
8735                  */
8736                 if (type != SPR_TYPE_EX_AC
8737                  && type != SPR_TYPE_WR_EX) {
8738                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8739                                 if (i == residx ||
8740                                     ctl_get_prkey(lun,
8741                                      i + softc->persis_offset) == 0)
8742                                         continue;
8743                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8744                         }
8745                 }
8746                 mtx_unlock(&lun->lun_lock);
8747                 /* Send msg to other side */
8748                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8749                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8750                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8751                 if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8752                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8753                         printf("CTL:Persis Out error returned from "
8754                                "ctl_ha_msg_send %d\n", isc_retval);
8755                 }
8756                 break;
8757
8758         case SPRO_CLEAR:
8759                 /* send msg to other side */
8760
8761                 mtx_lock(&lun->lun_lock);
8762                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8763                 lun->res_type = 0;
8764                 lun->pr_key_count = 0;
8765                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8766
8767                 ctl_clr_prkey(lun, residx);
8768                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8769                         if (ctl_get_prkey(lun, i) != 0) {
8770                                 ctl_clr_prkey(lun, i);
8771                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8772                         }
8773                 lun->PRGeneration++;
8774                 mtx_unlock(&lun->lun_lock);
8775                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8776                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8777                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8778                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8779                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8780                         printf("CTL:Persis Out error returned from "
8781                                "ctl_ha_msg_send %d\n", isc_retval);
8782                 }
8783                 break;
8784
8785         case SPRO_PREEMPT:
8786         case SPRO_PRE_ABO: {
8787                 int nretval;
8788
8789                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8790                                           residx, ctsio, cdb, param);
8791                 if (nretval != 0)
8792                         return (CTL_RETVAL_COMPLETE);
8793                 break;
8794         }
8795         default:
8796                 panic("Invalid PR type %x", cdb->action);
8797         }
8798
8799 done:
8800         free(ctsio->kern_data_ptr, M_CTL);
8801         ctl_set_success(ctsio);
8802         ctl_done((union ctl_io *)ctsio);
8803
8804         return (retval);
8805 }
8806
8807 /*
8808  * This routine is for handling a message from the other SC pertaining to
8809  * persistent reserve out. All the error checking will have been done
8810  * so only perorming the action need be done here to keep the two
8811  * in sync.
8812  */
8813 static void
8814 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8815 {
8816         struct ctl_lun *lun;
8817         struct ctl_softc *softc;
8818         int i;
8819         uint32_t targ_lun;
8820
8821         softc = control_softc;
8822
8823         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8824         lun = softc->ctl_luns[targ_lun];
8825         mtx_lock(&lun->lun_lock);
8826         switch(msg->pr.pr_info.action) {
8827         case CTL_PR_REG_KEY:
8828                 ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8829                 if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8830                         lun->pr_key_count++;
8831                 ctl_set_prkey(lun, msg->pr.pr_info.residx,
8832                     scsi_8btou64(msg->pr.pr_info.sa_res_key));
8833                 lun->PRGeneration++;
8834                 break;
8835
8836         case CTL_PR_UNREG_KEY:
8837                 ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8838                 lun->pr_key_count--;
8839
8840                 /* XXX Need to see if the reservation has been released */
8841                 /* if so do we need to generate UA? */
8842                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8843                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8844                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8845
8846                         if ((lun->res_type == SPR_TYPE_WR_EX_RO
8847                           || lun->res_type == SPR_TYPE_EX_AC_RO)
8848                          && lun->pr_key_count) {
8849                                 /*
8850                                  * If the reservation is a registrants
8851                                  * only type we need to generate a UA
8852                                  * for other registered inits.  The
8853                                  * sense code should be RESERVATIONS
8854                                  * RELEASED
8855                                  */
8856
8857                                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8858                                         if (ctl_get_prkey(lun, i +
8859                                             softc->persis_offset) == 0)
8860                                                 continue;
8861
8862                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8863                                 }
8864                         }
8865                         lun->res_type = 0;
8866                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8867                         if (lun->pr_key_count==0) {
8868                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8869                                 lun->res_type = 0;
8870                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8871                         }
8872                 }
8873                 lun->PRGeneration++;
8874                 break;
8875
8876         case CTL_PR_RESERVE:
8877                 lun->flags |= CTL_LUN_PR_RESERVED;
8878                 lun->res_type = msg->pr.pr_info.res_type;
8879                 lun->pr_res_idx = msg->pr.pr_info.residx;
8880
8881                 break;
8882
8883         case CTL_PR_RELEASE:
8884                 /*
8885                  * if this isn't an exclusive access res generate UA for all
8886                  * other registrants.
8887                  */
8888                 if (lun->res_type != SPR_TYPE_EX_AC
8889                  && lun->res_type != SPR_TYPE_WR_EX) {
8890                         for (i = 0; i < CTL_MAX_INITIATORS; i++)
8891                                 if (ctl_get_prkey(lun, i + softc->persis_offset) != 0)
8892                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8893                 }
8894
8895                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8896                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8897                 lun->res_type = 0;
8898                 break;
8899
8900         case CTL_PR_PREEMPT:
8901                 ctl_pro_preempt_other(lun, msg);
8902                 break;
8903         case CTL_PR_CLEAR:
8904                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8905                 lun->res_type = 0;
8906                 lun->pr_key_count = 0;
8907                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8908
8909                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8910                         if (ctl_get_prkey(lun, i) == 0)
8911                                 continue;
8912                         ctl_clr_prkey(lun, i);
8913                         ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8914                 }
8915                 lun->PRGeneration++;
8916                 break;
8917         }
8918
8919         mtx_unlock(&lun->lun_lock);
8920 }
8921
8922 int
8923 ctl_read_write(struct ctl_scsiio *ctsio)
8924 {
8925         struct ctl_lun *lun;
8926         struct ctl_lba_len_flags *lbalen;
8927         uint64_t lba;
8928         uint32_t num_blocks;
8929         int flags, retval;
8930         int isread;
8931
8932         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8933
8934         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8935
8936         flags = 0;
8937         retval = CTL_RETVAL_COMPLETE;
8938
8939         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8940               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8941         switch (ctsio->cdb[0]) {
8942         case READ_6:
8943         case WRITE_6: {
8944                 struct scsi_rw_6 *cdb;
8945
8946                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
8947
8948                 lba = scsi_3btoul(cdb->addr);
8949                 /* only 5 bits are valid in the most significant address byte */
8950                 lba &= 0x1fffff;
8951                 num_blocks = cdb->length;
8952                 /*
8953                  * This is correct according to SBC-2.
8954                  */
8955                 if (num_blocks == 0)
8956                         num_blocks = 256;
8957                 break;
8958         }
8959         case READ_10:
8960         case WRITE_10: {
8961                 struct scsi_rw_10 *cdb;
8962
8963                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
8964                 if (cdb->byte2 & SRW10_FUA)
8965                         flags |= CTL_LLF_FUA;
8966                 if (cdb->byte2 & SRW10_DPO)
8967                         flags |= CTL_LLF_DPO;
8968                 lba = scsi_4btoul(cdb->addr);
8969                 num_blocks = scsi_2btoul(cdb->length);
8970                 break;
8971         }
8972         case WRITE_VERIFY_10: {
8973                 struct scsi_write_verify_10 *cdb;
8974
8975                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8976                 flags |= CTL_LLF_FUA;
8977                 if (cdb->byte2 & SWV_DPO)
8978                         flags |= CTL_LLF_DPO;
8979                 lba = scsi_4btoul(cdb->addr);
8980                 num_blocks = scsi_2btoul(cdb->length);
8981                 break;
8982         }
8983         case READ_12:
8984         case WRITE_12: {
8985                 struct scsi_rw_12 *cdb;
8986
8987                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
8988                 if (cdb->byte2 & SRW12_FUA)
8989                         flags |= CTL_LLF_FUA;
8990                 if (cdb->byte2 & SRW12_DPO)
8991                         flags |= CTL_LLF_DPO;
8992                 lba = scsi_4btoul(cdb->addr);
8993                 num_blocks = scsi_4btoul(cdb->length);
8994                 break;
8995         }
8996         case WRITE_VERIFY_12: {
8997                 struct scsi_write_verify_12 *cdb;
8998
8999                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
9000                 flags |= CTL_LLF_FUA;
9001                 if (cdb->byte2 & SWV_DPO)
9002                         flags |= CTL_LLF_DPO;
9003                 lba = scsi_4btoul(cdb->addr);
9004                 num_blocks = scsi_4btoul(cdb->length);
9005                 break;
9006         }
9007         case READ_16:
9008         case WRITE_16: {
9009                 struct scsi_rw_16 *cdb;
9010
9011                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9012                 if (cdb->byte2 & SRW12_FUA)
9013                         flags |= CTL_LLF_FUA;
9014                 if (cdb->byte2 & SRW12_DPO)
9015                         flags |= CTL_LLF_DPO;
9016                 lba = scsi_8btou64(cdb->addr);
9017                 num_blocks = scsi_4btoul(cdb->length);
9018                 break;
9019         }
9020         case WRITE_ATOMIC_16: {
9021                 struct scsi_rw_16 *cdb;
9022
9023                 if (lun->be_lun->atomicblock == 0) {
9024                         ctl_set_invalid_opcode(ctsio);
9025                         ctl_done((union ctl_io *)ctsio);
9026                         return (CTL_RETVAL_COMPLETE);
9027                 }
9028
9029                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9030                 if (cdb->byte2 & SRW12_FUA)
9031                         flags |= CTL_LLF_FUA;
9032                 if (cdb->byte2 & SRW12_DPO)
9033                         flags |= CTL_LLF_DPO;
9034                 lba = scsi_8btou64(cdb->addr);
9035                 num_blocks = scsi_4btoul(cdb->length);
9036                 if (num_blocks > lun->be_lun->atomicblock) {
9037                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
9038                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
9039                             /*bit*/ 0);
9040                         ctl_done((union ctl_io *)ctsio);
9041                         return (CTL_RETVAL_COMPLETE);
9042                 }
9043                 break;
9044         }
9045         case WRITE_VERIFY_16: {
9046                 struct scsi_write_verify_16 *cdb;
9047
9048                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9049                 flags |= CTL_LLF_FUA;
9050                 if (cdb->byte2 & SWV_DPO)
9051                         flags |= CTL_LLF_DPO;
9052                 lba = scsi_8btou64(cdb->addr);
9053                 num_blocks = scsi_4btoul(cdb->length);
9054                 break;
9055         }
9056         default:
9057                 /*
9058                  * We got a command we don't support.  This shouldn't
9059                  * happen, commands should be filtered out above us.
9060                  */
9061                 ctl_set_invalid_opcode(ctsio);
9062                 ctl_done((union ctl_io *)ctsio);
9063
9064                 return (CTL_RETVAL_COMPLETE);
9065                 break; /* NOTREACHED */
9066         }
9067
9068         /*
9069          * The first check is to make sure we're in bounds, the second
9070          * check is to catch wrap-around problems.  If the lba + num blocks
9071          * is less than the lba, then we've wrapped around and the block
9072          * range is invalid anyway.
9073          */
9074         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9075          || ((lba + num_blocks) < lba)) {
9076                 ctl_set_lba_out_of_range(ctsio);
9077                 ctl_done((union ctl_io *)ctsio);
9078                 return (CTL_RETVAL_COMPLETE);
9079         }
9080
9081         /*
9082          * According to SBC-3, a transfer length of 0 is not an error.
9083          * Note that this cannot happen with WRITE(6) or READ(6), since 0
9084          * translates to 256 blocks for those commands.
9085          */
9086         if (num_blocks == 0) {
9087                 ctl_set_success(ctsio);
9088                 ctl_done((union ctl_io *)ctsio);
9089                 return (CTL_RETVAL_COMPLETE);
9090         }
9091
9092         /* Set FUA and/or DPO if caches are disabled. */
9093         if (isread) {
9094                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9095                     SCP_RCD) != 0)
9096                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9097         } else {
9098                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9099                     SCP_WCE) == 0)
9100                         flags |= CTL_LLF_FUA;
9101         }
9102
9103         lbalen = (struct ctl_lba_len_flags *)
9104             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9105         lbalen->lba = lba;
9106         lbalen->len = num_blocks;
9107         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9108
9109         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9110         ctsio->kern_rel_offset = 0;
9111
9112         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9113
9114         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9115
9116         return (retval);
9117 }
9118
9119 static int
9120 ctl_cnw_cont(union ctl_io *io)
9121 {
9122         struct ctl_scsiio *ctsio;
9123         struct ctl_lun *lun;
9124         struct ctl_lba_len_flags *lbalen;
9125         int retval;
9126
9127         ctsio = &io->scsiio;
9128         ctsio->io_hdr.status = CTL_STATUS_NONE;
9129         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9130         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9131         lbalen = (struct ctl_lba_len_flags *)
9132             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9133         lbalen->flags &= ~CTL_LLF_COMPARE;
9134         lbalen->flags |= CTL_LLF_WRITE;
9135
9136         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9137         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9138         return (retval);
9139 }
9140
9141 int
9142 ctl_cnw(struct ctl_scsiio *ctsio)
9143 {
9144         struct ctl_lun *lun;
9145         struct ctl_lba_len_flags *lbalen;
9146         uint64_t lba;
9147         uint32_t num_blocks;
9148         int flags, retval;
9149
9150         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9151
9152         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9153
9154         flags = 0;
9155         retval = CTL_RETVAL_COMPLETE;
9156
9157         switch (ctsio->cdb[0]) {
9158         case COMPARE_AND_WRITE: {
9159                 struct scsi_compare_and_write *cdb;
9160
9161                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9162                 if (cdb->byte2 & SRW10_FUA)
9163                         flags |= CTL_LLF_FUA;
9164                 if (cdb->byte2 & SRW10_DPO)
9165                         flags |= CTL_LLF_DPO;
9166                 lba = scsi_8btou64(cdb->addr);
9167                 num_blocks = cdb->length;
9168                 break;
9169         }
9170         default:
9171                 /*
9172                  * We got a command we don't support.  This shouldn't
9173                  * happen, commands should be filtered out above us.
9174                  */
9175                 ctl_set_invalid_opcode(ctsio);
9176                 ctl_done((union ctl_io *)ctsio);
9177
9178                 return (CTL_RETVAL_COMPLETE);
9179                 break; /* NOTREACHED */
9180         }
9181
9182         /*
9183          * The first check is to make sure we're in bounds, the second
9184          * check is to catch wrap-around problems.  If the lba + num blocks
9185          * is less than the lba, then we've wrapped around and the block
9186          * range is invalid anyway.
9187          */
9188         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9189          || ((lba + num_blocks) < lba)) {
9190                 ctl_set_lba_out_of_range(ctsio);
9191                 ctl_done((union ctl_io *)ctsio);
9192                 return (CTL_RETVAL_COMPLETE);
9193         }
9194
9195         /*
9196          * According to SBC-3, a transfer length of 0 is not an error.
9197          */
9198         if (num_blocks == 0) {
9199                 ctl_set_success(ctsio);
9200                 ctl_done((union ctl_io *)ctsio);
9201                 return (CTL_RETVAL_COMPLETE);
9202         }
9203
9204         /* Set FUA if write cache is disabled. */
9205         if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9206             SCP_WCE) == 0)
9207                 flags |= CTL_LLF_FUA;
9208
9209         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9210         ctsio->kern_rel_offset = 0;
9211
9212         /*
9213          * Set the IO_CONT flag, so that if this I/O gets passed to
9214          * ctl_data_submit_done(), it'll get passed back to
9215          * ctl_ctl_cnw_cont() for further processing.
9216          */
9217         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9218         ctsio->io_cont = ctl_cnw_cont;
9219
9220         lbalen = (struct ctl_lba_len_flags *)
9221             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9222         lbalen->lba = lba;
9223         lbalen->len = num_blocks;
9224         lbalen->flags = CTL_LLF_COMPARE | flags;
9225
9226         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9227         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9228         return (retval);
9229 }
9230
9231 int
9232 ctl_verify(struct ctl_scsiio *ctsio)
9233 {
9234         struct ctl_lun *lun;
9235         struct ctl_lba_len_flags *lbalen;
9236         uint64_t lba;
9237         uint32_t num_blocks;
9238         int bytchk, flags;
9239         int retval;
9240
9241         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9242
9243         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9244
9245         bytchk = 0;
9246         flags = CTL_LLF_FUA;
9247         retval = CTL_RETVAL_COMPLETE;
9248
9249         switch (ctsio->cdb[0]) {
9250         case VERIFY_10: {
9251                 struct scsi_verify_10 *cdb;
9252
9253                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
9254                 if (cdb->byte2 & SVFY_BYTCHK)
9255                         bytchk = 1;
9256                 if (cdb->byte2 & SVFY_DPO)
9257                         flags |= CTL_LLF_DPO;
9258                 lba = scsi_4btoul(cdb->addr);
9259                 num_blocks = scsi_2btoul(cdb->length);
9260                 break;
9261         }
9262         case VERIFY_12: {
9263                 struct scsi_verify_12 *cdb;
9264
9265                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
9266                 if (cdb->byte2 & SVFY_BYTCHK)
9267                         bytchk = 1;
9268                 if (cdb->byte2 & SVFY_DPO)
9269                         flags |= CTL_LLF_DPO;
9270                 lba = scsi_4btoul(cdb->addr);
9271                 num_blocks = scsi_4btoul(cdb->length);
9272                 break;
9273         }
9274         case VERIFY_16: {
9275                 struct scsi_rw_16 *cdb;
9276
9277                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9278                 if (cdb->byte2 & SVFY_BYTCHK)
9279                         bytchk = 1;
9280                 if (cdb->byte2 & SVFY_DPO)
9281                         flags |= CTL_LLF_DPO;
9282                 lba = scsi_8btou64(cdb->addr);
9283                 num_blocks = scsi_4btoul(cdb->length);
9284                 break;
9285         }
9286         default:
9287                 /*
9288                  * We got a command we don't support.  This shouldn't
9289                  * happen, commands should be filtered out above us.
9290                  */
9291                 ctl_set_invalid_opcode(ctsio);
9292                 ctl_done((union ctl_io *)ctsio);
9293                 return (CTL_RETVAL_COMPLETE);
9294         }
9295
9296         /*
9297          * The first check is to make sure we're in bounds, the second
9298          * check is to catch wrap-around problems.  If the lba + num blocks
9299          * is less than the lba, then we've wrapped around and the block
9300          * range is invalid anyway.
9301          */
9302         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9303          || ((lba + num_blocks) < lba)) {
9304                 ctl_set_lba_out_of_range(ctsio);
9305                 ctl_done((union ctl_io *)ctsio);
9306                 return (CTL_RETVAL_COMPLETE);
9307         }
9308
9309         /*
9310          * According to SBC-3, a transfer length of 0 is not an error.
9311          */
9312         if (num_blocks == 0) {
9313                 ctl_set_success(ctsio);
9314                 ctl_done((union ctl_io *)ctsio);
9315                 return (CTL_RETVAL_COMPLETE);
9316         }
9317
9318         lbalen = (struct ctl_lba_len_flags *)
9319             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9320         lbalen->lba = lba;
9321         lbalen->len = num_blocks;
9322         if (bytchk) {
9323                 lbalen->flags = CTL_LLF_COMPARE | flags;
9324                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9325         } else {
9326                 lbalen->flags = CTL_LLF_VERIFY | flags;
9327                 ctsio->kern_total_len = 0;
9328         }
9329         ctsio->kern_rel_offset = 0;
9330
9331         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9332         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9333         return (retval);
9334 }
9335
9336 int
9337 ctl_report_luns(struct ctl_scsiio *ctsio)
9338 {
9339         struct ctl_softc *softc = control_softc;
9340         struct scsi_report_luns *cdb;
9341         struct scsi_report_luns_data *lun_data;
9342         struct ctl_lun *lun, *request_lun;
9343         struct ctl_port *port;
9344         int num_luns, retval;
9345         uint32_t alloc_len, lun_datalen;
9346         int num_filled, well_known;
9347         uint32_t initidx, targ_lun_id, lun_id;
9348
9349         retval = CTL_RETVAL_COMPLETE;
9350         well_known = 0;
9351
9352         cdb = (struct scsi_report_luns *)ctsio->cdb;
9353         port = ctl_io_port(&ctsio->io_hdr);
9354
9355         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9356
9357         mtx_lock(&softc->ctl_lock);
9358         num_luns = 0;
9359         for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
9360                 if (ctl_lun_map_from_port(port, targ_lun_id) < CTL_MAX_LUNS)
9361                         num_luns++;
9362         }
9363         mtx_unlock(&softc->ctl_lock);
9364
9365         switch (cdb->select_report) {
9366         case RPL_REPORT_DEFAULT:
9367         case RPL_REPORT_ALL:
9368                 break;
9369         case RPL_REPORT_WELLKNOWN:
9370                 well_known = 1;
9371                 num_luns = 0;
9372                 break;
9373         default:
9374                 ctl_set_invalid_field(ctsio,
9375                                       /*sks_valid*/ 1,
9376                                       /*command*/ 1,
9377                                       /*field*/ 2,
9378                                       /*bit_valid*/ 0,
9379                                       /*bit*/ 0);
9380                 ctl_done((union ctl_io *)ctsio);
9381                 return (retval);
9382                 break; /* NOTREACHED */
9383         }
9384
9385         alloc_len = scsi_4btoul(cdb->length);
9386         /*
9387          * The initiator has to allocate at least 16 bytes for this request,
9388          * so he can at least get the header and the first LUN.  Otherwise
9389          * we reject the request (per SPC-3 rev 14, section 6.21).
9390          */
9391         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9392             sizeof(struct scsi_report_luns_lundata))) {
9393                 ctl_set_invalid_field(ctsio,
9394                                       /*sks_valid*/ 1,
9395                                       /*command*/ 1,
9396                                       /*field*/ 6,
9397                                       /*bit_valid*/ 0,
9398                                       /*bit*/ 0);
9399                 ctl_done((union ctl_io *)ctsio);
9400                 return (retval);
9401         }
9402
9403         request_lun = (struct ctl_lun *)
9404                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9405
9406         lun_datalen = sizeof(*lun_data) +
9407                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9408
9409         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9410         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9411         ctsio->kern_sg_entries = 0;
9412
9413         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9414
9415         mtx_lock(&softc->ctl_lock);
9416         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9417                 lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9418                 if (lun_id >= CTL_MAX_LUNS)
9419                         continue;
9420                 lun = softc->ctl_luns[lun_id];
9421                 if (lun == NULL)
9422                         continue;
9423
9424                 if (targ_lun_id <= 0xff) {
9425                         /*
9426                          * Peripheral addressing method, bus number 0.
9427                          */
9428                         lun_data->luns[num_filled].lundata[0] =
9429                                 RPL_LUNDATA_ATYP_PERIPH;
9430                         lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9431                         num_filled++;
9432                 } else if (targ_lun_id <= 0x3fff) {
9433                         /*
9434                          * Flat addressing method.
9435                          */
9436                         lun_data->luns[num_filled].lundata[0] =
9437                                 RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9438                         lun_data->luns[num_filled].lundata[1] =
9439                                 (targ_lun_id & 0xff);
9440                         num_filled++;
9441                 } else if (targ_lun_id <= 0xffffff) {
9442                         /*
9443                          * Extended flat addressing method.
9444                          */
9445                         lun_data->luns[num_filled].lundata[0] =
9446                             RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9447                         scsi_ulto3b(targ_lun_id,
9448                             &lun_data->luns[num_filled].lundata[1]);
9449                         num_filled++;
9450                 } else {
9451                         printf("ctl_report_luns: bogus LUN number %jd, "
9452                                "skipping\n", (intmax_t)targ_lun_id);
9453                 }
9454                 /*
9455                  * According to SPC-3, rev 14 section 6.21:
9456                  *
9457                  * "The execution of a REPORT LUNS command to any valid and
9458                  * installed logical unit shall clear the REPORTED LUNS DATA
9459                  * HAS CHANGED unit attention condition for all logical
9460                  * units of that target with respect to the requesting
9461                  * initiator. A valid and installed logical unit is one
9462                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9463                  * INQUIRY data (see 6.4.2)."
9464                  *
9465                  * If request_lun is NULL, the LUN this report luns command
9466                  * was issued to is either disabled or doesn't exist. In that
9467                  * case, we shouldn't clear any pending lun change unit
9468                  * attention.
9469                  */
9470                 if (request_lun != NULL) {
9471                         mtx_lock(&lun->lun_lock);
9472                         ctl_clr_ua(lun, initidx, CTL_UA_RES_RELEASE);
9473                         mtx_unlock(&lun->lun_lock);
9474                 }
9475         }
9476         mtx_unlock(&softc->ctl_lock);
9477
9478         /*
9479          * It's quite possible that we've returned fewer LUNs than we allocated
9480          * space for.  Trim it.
9481          */
9482         lun_datalen = sizeof(*lun_data) +
9483                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9484
9485         if (lun_datalen < alloc_len) {
9486                 ctsio->residual = alloc_len - lun_datalen;
9487                 ctsio->kern_data_len = lun_datalen;
9488                 ctsio->kern_total_len = lun_datalen;
9489         } else {
9490                 ctsio->residual = 0;
9491                 ctsio->kern_data_len = alloc_len;
9492                 ctsio->kern_total_len = alloc_len;
9493         }
9494         ctsio->kern_data_resid = 0;
9495         ctsio->kern_rel_offset = 0;
9496         ctsio->kern_sg_entries = 0;
9497
9498         /*
9499          * We set this to the actual data length, regardless of how much
9500          * space we actually have to return results.  If the user looks at
9501          * this value, he'll know whether or not he allocated enough space
9502          * and reissue the command if necessary.  We don't support well
9503          * known logical units, so if the user asks for that, return none.
9504          */
9505         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9506
9507         /*
9508          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9509          * this request.
9510          */
9511         ctl_set_success(ctsio);
9512         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9513         ctsio->be_move_done = ctl_config_move_done;
9514         ctl_datamove((union ctl_io *)ctsio);
9515         return (retval);
9516 }
9517
9518 int
9519 ctl_request_sense(struct ctl_scsiio *ctsio)
9520 {
9521         struct scsi_request_sense *cdb;
9522         struct scsi_sense_data *sense_ptr;
9523         struct ctl_softc *ctl_softc;
9524         struct ctl_lun *lun;
9525         uint32_t initidx;
9526         int have_error;
9527         scsi_sense_data_type sense_format;
9528         ctl_ua_type ua_type;
9529
9530         cdb = (struct scsi_request_sense *)ctsio->cdb;
9531
9532         ctl_softc = control_softc;
9533         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9534
9535         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9536
9537         /*
9538          * Determine which sense format the user wants.
9539          */
9540         if (cdb->byte2 & SRS_DESC)
9541                 sense_format = SSD_TYPE_DESC;
9542         else
9543                 sense_format = SSD_TYPE_FIXED;
9544
9545         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9546         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9547         ctsio->kern_sg_entries = 0;
9548
9549         /*
9550          * struct scsi_sense_data, which is currently set to 256 bytes, is
9551          * larger than the largest allowed value for the length field in the
9552          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9553          */
9554         ctsio->residual = 0;
9555         ctsio->kern_data_len = cdb->length;
9556         ctsio->kern_total_len = cdb->length;
9557
9558         ctsio->kern_data_resid = 0;
9559         ctsio->kern_rel_offset = 0;
9560         ctsio->kern_sg_entries = 0;
9561
9562         /*
9563          * If we don't have a LUN, we don't have any pending sense.
9564          */
9565         if (lun == NULL)
9566                 goto no_sense;
9567
9568         have_error = 0;
9569         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9570         /*
9571          * Check for pending sense, and then for pending unit attentions.
9572          * Pending sense gets returned first, then pending unit attentions.
9573          */
9574         mtx_lock(&lun->lun_lock);
9575 #ifdef CTL_WITH_CA
9576         if (ctl_is_set(lun->have_ca, initidx)) {
9577                 scsi_sense_data_type stored_format;
9578
9579                 /*
9580                  * Check to see which sense format was used for the stored
9581                  * sense data.
9582                  */
9583                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9584
9585                 /*
9586                  * If the user requested a different sense format than the
9587                  * one we stored, then we need to convert it to the other
9588                  * format.  If we're going from descriptor to fixed format
9589                  * sense data, we may lose things in translation, depending
9590                  * on what options were used.
9591                  *
9592                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9593                  * for some reason we'll just copy it out as-is.
9594                  */
9595                 if ((stored_format == SSD_TYPE_FIXED)
9596                  && (sense_format == SSD_TYPE_DESC))
9597                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9598                             &lun->pending_sense[initidx],
9599                             (struct scsi_sense_data_desc *)sense_ptr);
9600                 else if ((stored_format == SSD_TYPE_DESC)
9601                       && (sense_format == SSD_TYPE_FIXED))
9602                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9603                             &lun->pending_sense[initidx],
9604                             (struct scsi_sense_data_fixed *)sense_ptr);
9605                 else
9606                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9607                                MIN(sizeof(*sense_ptr),
9608                                sizeof(lun->pending_sense[initidx])));
9609
9610                 ctl_clear_mask(lun->have_ca, initidx);
9611                 have_error = 1;
9612         } else
9613 #endif
9614         {
9615                 ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9616                 if (ua_type != CTL_UA_NONE)
9617                         have_error = 1;
9618                 if (ua_type == CTL_UA_LUN_CHANGE) {
9619                         mtx_unlock(&lun->lun_lock);
9620                         mtx_lock(&ctl_softc->ctl_lock);
9621                         ctl_clear_ua(ctl_softc, initidx, ua_type);
9622                         mtx_unlock(&ctl_softc->ctl_lock);
9623                         mtx_lock(&lun->lun_lock);
9624                 }
9625
9626         }
9627         mtx_unlock(&lun->lun_lock);
9628
9629         /*
9630          * We already have a pending error, return it.
9631          */
9632         if (have_error != 0) {
9633                 /*
9634                  * We report the SCSI status as OK, since the status of the
9635                  * request sense command itself is OK.
9636                  * We report 0 for the sense length, because we aren't doing
9637                  * autosense in this case.  We're reporting sense as
9638                  * parameter data.
9639                  */
9640                 ctl_set_success(ctsio);
9641                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9642                 ctsio->be_move_done = ctl_config_move_done;
9643                 ctl_datamove((union ctl_io *)ctsio);
9644                 return (CTL_RETVAL_COMPLETE);
9645         }
9646
9647 no_sense:
9648
9649         /*
9650          * No sense information to report, so we report that everything is
9651          * okay.
9652          */
9653         ctl_set_sense_data(sense_ptr,
9654                            lun,
9655                            sense_format,
9656                            /*current_error*/ 1,
9657                            /*sense_key*/ SSD_KEY_NO_SENSE,
9658                            /*asc*/ 0x00,
9659                            /*ascq*/ 0x00,
9660                            SSD_ELEM_NONE);
9661
9662         /*
9663          * We report 0 for the sense length, because we aren't doing
9664          * autosense in this case.  We're reporting sense as parameter data.
9665          */
9666         ctl_set_success(ctsio);
9667         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9668         ctsio->be_move_done = ctl_config_move_done;
9669         ctl_datamove((union ctl_io *)ctsio);
9670         return (CTL_RETVAL_COMPLETE);
9671 }
9672
9673 int
9674 ctl_tur(struct ctl_scsiio *ctsio)
9675 {
9676
9677         CTL_DEBUG_PRINT(("ctl_tur\n"));
9678
9679         ctl_set_success(ctsio);
9680         ctl_done((union ctl_io *)ctsio);
9681
9682         return (CTL_RETVAL_COMPLETE);
9683 }
9684
9685 #ifdef notyet
9686 static int
9687 ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9688 {
9689
9690 }
9691 #endif
9692
9693 /*
9694  * SCSI VPD page 0x00, the Supported VPD Pages page.
9695  */
9696 static int
9697 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9698 {
9699         struct scsi_vpd_supported_pages *pages;
9700         int sup_page_size;
9701         struct ctl_lun *lun;
9702         int p;
9703
9704         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9705
9706         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9707             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9708         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9709         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9710         ctsio->kern_sg_entries = 0;
9711
9712         if (sup_page_size < alloc_len) {
9713                 ctsio->residual = alloc_len - sup_page_size;
9714                 ctsio->kern_data_len = sup_page_size;
9715                 ctsio->kern_total_len = sup_page_size;
9716         } else {
9717                 ctsio->residual = 0;
9718                 ctsio->kern_data_len = alloc_len;
9719                 ctsio->kern_total_len = alloc_len;
9720         }
9721         ctsio->kern_data_resid = 0;
9722         ctsio->kern_rel_offset = 0;
9723         ctsio->kern_sg_entries = 0;
9724
9725         /*
9726          * The control device is always connected.  The disk device, on the
9727          * other hand, may not be online all the time.  Need to change this
9728          * to figure out whether the disk device is actually online or not.
9729          */
9730         if (lun != NULL)
9731                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9732                                 lun->be_lun->lun_type;
9733         else
9734                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9735
9736         p = 0;
9737         /* Supported VPD pages */
9738         pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9739         /* Serial Number */
9740         pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9741         /* Device Identification */
9742         pages->page_list[p++] = SVPD_DEVICE_ID;
9743         /* Extended INQUIRY Data */
9744         pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9745         /* Mode Page Policy */
9746         pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9747         /* SCSI Ports */
9748         pages->page_list[p++] = SVPD_SCSI_PORTS;
9749         /* Third-party Copy */
9750         pages->page_list[p++] = SVPD_SCSI_TPC;
9751         if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9752                 /* Block limits */
9753                 pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9754                 /* Block Device Characteristics */
9755                 pages->page_list[p++] = SVPD_BDC;
9756                 /* Logical Block Provisioning */
9757                 pages->page_list[p++] = SVPD_LBP;
9758         }
9759         pages->length = p;
9760
9761         ctl_set_success(ctsio);
9762         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9763         ctsio->be_move_done = ctl_config_move_done;
9764         ctl_datamove((union ctl_io *)ctsio);
9765         return (CTL_RETVAL_COMPLETE);
9766 }
9767
9768 /*
9769  * SCSI VPD page 0x80, the Unit Serial Number page.
9770  */
9771 static int
9772 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9773 {
9774         struct scsi_vpd_unit_serial_number *sn_ptr;
9775         struct ctl_lun *lun;
9776         int data_len;
9777
9778         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9779
9780         data_len = 4 + CTL_SN_LEN;
9781         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9782         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9783         if (data_len < alloc_len) {
9784                 ctsio->residual = alloc_len - data_len;
9785                 ctsio->kern_data_len = data_len;
9786                 ctsio->kern_total_len = data_len;
9787         } else {
9788                 ctsio->residual = 0;
9789                 ctsio->kern_data_len = alloc_len;
9790                 ctsio->kern_total_len = alloc_len;
9791         }
9792         ctsio->kern_data_resid = 0;
9793         ctsio->kern_rel_offset = 0;
9794         ctsio->kern_sg_entries = 0;
9795
9796         /*
9797          * The control device is always connected.  The disk device, on the
9798          * other hand, may not be online all the time.  Need to change this
9799          * to figure out whether the disk device is actually online or not.
9800          */
9801         if (lun != NULL)
9802                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9803                                   lun->be_lun->lun_type;
9804         else
9805                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9806
9807         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9808         sn_ptr->length = CTL_SN_LEN;
9809         /*
9810          * If we don't have a LUN, we just leave the serial number as
9811          * all spaces.
9812          */
9813         if (lun != NULL) {
9814                 strncpy((char *)sn_ptr->serial_num,
9815                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9816         } else
9817                 memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9818
9819         ctl_set_success(ctsio);
9820         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9821         ctsio->be_move_done = ctl_config_move_done;
9822         ctl_datamove((union ctl_io *)ctsio);
9823         return (CTL_RETVAL_COMPLETE);
9824 }
9825
9826
9827 /*
9828  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9829  */
9830 static int
9831 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9832 {
9833         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9834         struct ctl_lun *lun;
9835         int data_len;
9836
9837         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9838
9839         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9840         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9841         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9842         ctsio->kern_sg_entries = 0;
9843
9844         if (data_len < alloc_len) {
9845                 ctsio->residual = alloc_len - data_len;
9846                 ctsio->kern_data_len = data_len;
9847                 ctsio->kern_total_len = data_len;
9848         } else {
9849                 ctsio->residual = 0;
9850                 ctsio->kern_data_len = alloc_len;
9851                 ctsio->kern_total_len = alloc_len;
9852         }
9853         ctsio->kern_data_resid = 0;
9854         ctsio->kern_rel_offset = 0;
9855         ctsio->kern_sg_entries = 0;
9856
9857         /*
9858          * The control device is always connected.  The disk device, on the
9859          * other hand, may not be online all the time.
9860          */
9861         if (lun != NULL)
9862                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9863                                      lun->be_lun->lun_type;
9864         else
9865                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9866         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9867         scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9868         /*
9869          * We support head of queue, ordered and simple tags.
9870          */
9871         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9872         /*
9873          * Volatile cache supported.
9874          */
9875         eid_ptr->flags3 = SVPD_EID_V_SUP;
9876
9877         /*
9878          * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9879          * attention for a particular IT nexus on all LUNs once we report
9880          * it to that nexus once.  This bit is required as of SPC-4.
9881          */
9882         eid_ptr->flags4 = SVPD_EID_LUICLT;
9883
9884         /*
9885          * XXX KDM in order to correctly answer this, we would need
9886          * information from the SIM to determine how much sense data it
9887          * can send.  So this would really be a path inquiry field, most
9888          * likely.  This can be set to a maximum of 252 according to SPC-4,
9889          * but the hardware may or may not be able to support that much.
9890          * 0 just means that the maximum sense data length is not reported.
9891          */
9892         eid_ptr->max_sense_length = 0;
9893
9894         ctl_set_success(ctsio);
9895         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9896         ctsio->be_move_done = ctl_config_move_done;
9897         ctl_datamove((union ctl_io *)ctsio);
9898         return (CTL_RETVAL_COMPLETE);
9899 }
9900
9901 static int
9902 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9903 {
9904         struct scsi_vpd_mode_page_policy *mpp_ptr;
9905         struct ctl_lun *lun;
9906         int data_len;
9907
9908         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9909
9910         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9911             sizeof(struct scsi_vpd_mode_page_policy_descr);
9912
9913         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9914         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9915         ctsio->kern_sg_entries = 0;
9916
9917         if (data_len < alloc_len) {
9918                 ctsio->residual = alloc_len - data_len;
9919                 ctsio->kern_data_len = data_len;
9920                 ctsio->kern_total_len = data_len;
9921         } else {
9922                 ctsio->residual = 0;
9923                 ctsio->kern_data_len = alloc_len;
9924                 ctsio->kern_total_len = alloc_len;
9925         }
9926         ctsio->kern_data_resid = 0;
9927         ctsio->kern_rel_offset = 0;
9928         ctsio->kern_sg_entries = 0;
9929
9930         /*
9931          * The control device is always connected.  The disk device, on the
9932          * other hand, may not be online all the time.
9933          */
9934         if (lun != NULL)
9935                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9936                                      lun->be_lun->lun_type;
9937         else
9938                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9939         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9940         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9941         mpp_ptr->descr[0].page_code = 0x3f;
9942         mpp_ptr->descr[0].subpage_code = 0xff;
9943         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9944
9945         ctl_set_success(ctsio);
9946         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9947         ctsio->be_move_done = ctl_config_move_done;
9948         ctl_datamove((union ctl_io *)ctsio);
9949         return (CTL_RETVAL_COMPLETE);
9950 }
9951
9952 /*
9953  * SCSI VPD page 0x83, the Device Identification page.
9954  */
9955 static int
9956 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9957 {
9958         struct scsi_vpd_device_id *devid_ptr;
9959         struct scsi_vpd_id_descriptor *desc;
9960         struct ctl_softc *softc;
9961         struct ctl_lun *lun;
9962         struct ctl_port *port;
9963         int data_len;
9964         uint8_t proto;
9965
9966         softc = control_softc;
9967
9968         port = softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9969         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9970
9971         data_len = sizeof(struct scsi_vpd_device_id) +
9972             sizeof(struct scsi_vpd_id_descriptor) +
9973                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9974             sizeof(struct scsi_vpd_id_descriptor) +
9975                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9976         if (lun && lun->lun_devid)
9977                 data_len += lun->lun_devid->len;
9978         if (port->port_devid)
9979                 data_len += port->port_devid->len;
9980         if (port->target_devid)
9981                 data_len += port->target_devid->len;
9982
9983         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9984         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9985         ctsio->kern_sg_entries = 0;
9986
9987         if (data_len < alloc_len) {
9988                 ctsio->residual = alloc_len - data_len;
9989                 ctsio->kern_data_len = data_len;
9990                 ctsio->kern_total_len = data_len;
9991         } else {
9992                 ctsio->residual = 0;
9993                 ctsio->kern_data_len = alloc_len;
9994                 ctsio->kern_total_len = alloc_len;
9995         }
9996         ctsio->kern_data_resid = 0;
9997         ctsio->kern_rel_offset = 0;
9998         ctsio->kern_sg_entries = 0;
9999
10000         /*
10001          * The control device is always connected.  The disk device, on the
10002          * other hand, may not be online all the time.
10003          */
10004         if (lun != NULL)
10005                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10006                                      lun->be_lun->lun_type;
10007         else
10008                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10009         devid_ptr->page_code = SVPD_DEVICE_ID;
10010         scsi_ulto2b(data_len - 4, devid_ptr->length);
10011
10012         if (port->port_type == CTL_PORT_FC)
10013                 proto = SCSI_PROTO_FC << 4;
10014         else if (port->port_type == CTL_PORT_ISCSI)
10015                 proto = SCSI_PROTO_ISCSI << 4;
10016         else
10017                 proto = SCSI_PROTO_SPI << 4;
10018         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
10019
10020         /*
10021          * We're using a LUN association here.  i.e., this device ID is a
10022          * per-LUN identifier.
10023          */
10024         if (lun && lun->lun_devid) {
10025                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
10026                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10027                     lun->lun_devid->len);
10028         }
10029
10030         /*
10031          * This is for the WWPN which is a port association.
10032          */
10033         if (port->port_devid) {
10034                 memcpy(desc, port->port_devid->data, port->port_devid->len);
10035                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10036                     port->port_devid->len);
10037         }
10038
10039         /*
10040          * This is for the Relative Target Port(type 4h) identifier
10041          */
10042         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10043         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10044             SVPD_ID_TYPE_RELTARG;
10045         desc->length = 4;
10046         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
10047         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10048             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
10049
10050         /*
10051          * This is for the Target Port Group(type 5h) identifier
10052          */
10053         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10054         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10055             SVPD_ID_TYPE_TPORTGRP;
10056         desc->length = 4;
10057         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
10058             &desc->identifier[2]);
10059         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10060             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
10061
10062         /*
10063          * This is for the Target identifier
10064          */
10065         if (port->target_devid) {
10066                 memcpy(desc, port->target_devid->data, port->target_devid->len);
10067         }
10068
10069         ctl_set_success(ctsio);
10070         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10071         ctsio->be_move_done = ctl_config_move_done;
10072         ctl_datamove((union ctl_io *)ctsio);
10073         return (CTL_RETVAL_COMPLETE);
10074 }
10075
10076 static int
10077 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
10078 {
10079         struct ctl_softc *softc = control_softc;
10080         struct scsi_vpd_scsi_ports *sp;
10081         struct scsi_vpd_port_designation *pd;
10082         struct scsi_vpd_port_designation_cont *pdc;
10083         struct ctl_lun *lun;
10084         struct ctl_port *port;
10085         int data_len, num_target_ports, iid_len, id_len, g, pg, p;
10086         int num_target_port_groups;
10087
10088         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10089
10090         if (softc->is_single)
10091                 num_target_port_groups = 1;
10092         else
10093                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10094         num_target_ports = 0;
10095         iid_len = 0;
10096         id_len = 0;
10097         mtx_lock(&softc->ctl_lock);
10098         STAILQ_FOREACH(port, &softc->port_list, links) {
10099                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10100                         continue;
10101                 if (lun != NULL &&
10102                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
10103                         continue;
10104                 num_target_ports++;
10105                 if (port->init_devid)
10106                         iid_len += port->init_devid->len;
10107                 if (port->port_devid)
10108                         id_len += port->port_devid->len;
10109         }
10110         mtx_unlock(&softc->ctl_lock);
10111
10112         data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10113             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10114              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10115         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10116         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10117         ctsio->kern_sg_entries = 0;
10118
10119         if (data_len < alloc_len) {
10120                 ctsio->residual = alloc_len - data_len;
10121                 ctsio->kern_data_len = data_len;
10122                 ctsio->kern_total_len = data_len;
10123         } else {
10124                 ctsio->residual = 0;
10125                 ctsio->kern_data_len = alloc_len;
10126                 ctsio->kern_total_len = alloc_len;
10127         }
10128         ctsio->kern_data_resid = 0;
10129         ctsio->kern_rel_offset = 0;
10130         ctsio->kern_sg_entries = 0;
10131
10132         /*
10133          * The control device is always connected.  The disk device, on the
10134          * other hand, may not be online all the time.  Need to change this
10135          * to figure out whether the disk device is actually online or not.
10136          */
10137         if (lun != NULL)
10138                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10139                                   lun->be_lun->lun_type;
10140         else
10141                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10142
10143         sp->page_code = SVPD_SCSI_PORTS;
10144         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10145             sp->page_length);
10146         pd = &sp->design[0];
10147
10148         mtx_lock(&softc->ctl_lock);
10149         pg = softc->port_offset / CTL_MAX_PORTS;
10150         for (g = 0; g < num_target_port_groups; g++) {
10151                 STAILQ_FOREACH(port, &softc->port_list, links) {
10152                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10153                                 continue;
10154                         if (lun != NULL &&
10155                             ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
10156                                 continue;
10157                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10158                         scsi_ulto2b(p, pd->relative_port_id);
10159                         if (port->init_devid && g == pg) {
10160                                 iid_len = port->init_devid->len;
10161                                 memcpy(pd->initiator_transportid,
10162                                     port->init_devid->data, port->init_devid->len);
10163                         } else
10164                                 iid_len = 0;
10165                         scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10166                         pdc = (struct scsi_vpd_port_designation_cont *)
10167                             (&pd->initiator_transportid[iid_len]);
10168                         if (port->port_devid && g == pg) {
10169                                 id_len = port->port_devid->len;
10170                                 memcpy(pdc->target_port_descriptors,
10171                                     port->port_devid->data, port->port_devid->len);
10172                         } else
10173                                 id_len = 0;
10174                         scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10175                         pd = (struct scsi_vpd_port_designation *)
10176                             ((uint8_t *)pdc->target_port_descriptors + id_len);
10177                 }
10178         }
10179         mtx_unlock(&softc->ctl_lock);
10180
10181         ctl_set_success(ctsio);
10182         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10183         ctsio->be_move_done = ctl_config_move_done;
10184         ctl_datamove((union ctl_io *)ctsio);
10185         return (CTL_RETVAL_COMPLETE);
10186 }
10187
10188 static int
10189 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10190 {
10191         struct scsi_vpd_block_limits *bl_ptr;
10192         struct ctl_lun *lun;
10193         int bs;
10194
10195         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10196
10197         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10198         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10199         ctsio->kern_sg_entries = 0;
10200
10201         if (sizeof(*bl_ptr) < alloc_len) {
10202                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
10203                 ctsio->kern_data_len = sizeof(*bl_ptr);
10204                 ctsio->kern_total_len = sizeof(*bl_ptr);
10205         } else {
10206                 ctsio->residual = 0;
10207                 ctsio->kern_data_len = alloc_len;
10208                 ctsio->kern_total_len = alloc_len;
10209         }
10210         ctsio->kern_data_resid = 0;
10211         ctsio->kern_rel_offset = 0;
10212         ctsio->kern_sg_entries = 0;
10213
10214         /*
10215          * The control device is always connected.  The disk device, on the
10216          * other hand, may not be online all the time.  Need to change this
10217          * to figure out whether the disk device is actually online or not.
10218          */
10219         if (lun != NULL)
10220                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10221                                   lun->be_lun->lun_type;
10222         else
10223                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10224
10225         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10226         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10227         bl_ptr->max_cmp_write_len = 0xff;
10228         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10229         if (lun != NULL) {
10230                 bs = lun->be_lun->blocksize;
10231                 scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
10232                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10233                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10234                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10235                         if (lun->be_lun->ublockexp != 0) {
10236                                 scsi_ulto4b((1 << lun->be_lun->ublockexp),
10237                                     bl_ptr->opt_unmap_grain);
10238                                 scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
10239                                     bl_ptr->unmap_grain_align);
10240                         }
10241                 }
10242                 scsi_ulto4b(lun->be_lun->atomicblock,
10243                     bl_ptr->max_atomic_transfer_length);
10244                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
10245                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10246         }
10247         scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10248
10249         ctl_set_success(ctsio);
10250         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10251         ctsio->be_move_done = ctl_config_move_done;
10252         ctl_datamove((union ctl_io *)ctsio);
10253         return (CTL_RETVAL_COMPLETE);
10254 }
10255
10256 static int
10257 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10258 {
10259         struct scsi_vpd_block_device_characteristics *bdc_ptr;
10260         struct ctl_lun *lun;
10261         const char *value;
10262         u_int i;
10263
10264         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10265
10266         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10267         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10268         ctsio->kern_sg_entries = 0;
10269
10270         if (sizeof(*bdc_ptr) < alloc_len) {
10271                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10272                 ctsio->kern_data_len = sizeof(*bdc_ptr);
10273                 ctsio->kern_total_len = sizeof(*bdc_ptr);
10274         } else {
10275                 ctsio->residual = 0;
10276                 ctsio->kern_data_len = alloc_len;
10277                 ctsio->kern_total_len = alloc_len;
10278         }
10279         ctsio->kern_data_resid = 0;
10280         ctsio->kern_rel_offset = 0;
10281         ctsio->kern_sg_entries = 0;
10282
10283         /*
10284          * The control device is always connected.  The disk device, on the
10285          * other hand, may not be online all the time.  Need to change this
10286          * to figure out whether the disk device is actually online or not.
10287          */
10288         if (lun != NULL)
10289                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10290                                   lun->be_lun->lun_type;
10291         else
10292                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10293         bdc_ptr->page_code = SVPD_BDC;
10294         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10295         if (lun != NULL &&
10296             (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10297                 i = strtol(value, NULL, 0);
10298         else
10299                 i = CTL_DEFAULT_ROTATION_RATE;
10300         scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10301         if (lun != NULL &&
10302             (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10303                 i = strtol(value, NULL, 0);
10304         else
10305                 i = 0;
10306         bdc_ptr->wab_wac_ff = (i & 0x0f);
10307         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10308
10309         ctl_set_success(ctsio);
10310         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10311         ctsio->be_move_done = ctl_config_move_done;
10312         ctl_datamove((union ctl_io *)ctsio);
10313         return (CTL_RETVAL_COMPLETE);
10314 }
10315
10316 static int
10317 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10318 {
10319         struct scsi_vpd_logical_block_prov *lbp_ptr;
10320         struct ctl_lun *lun;
10321
10322         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10323
10324         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10325         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10326         ctsio->kern_sg_entries = 0;
10327
10328         if (sizeof(*lbp_ptr) < alloc_len) {
10329                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10330                 ctsio->kern_data_len = sizeof(*lbp_ptr);
10331                 ctsio->kern_total_len = sizeof(*lbp_ptr);
10332         } else {
10333                 ctsio->residual = 0;
10334                 ctsio->kern_data_len = alloc_len;
10335                 ctsio->kern_total_len = alloc_len;
10336         }
10337         ctsio->kern_data_resid = 0;
10338         ctsio->kern_rel_offset = 0;
10339         ctsio->kern_sg_entries = 0;
10340
10341         /*
10342          * The control device is always connected.  The disk device, on the
10343          * other hand, may not be online all the time.  Need to change this
10344          * to figure out whether the disk device is actually online or not.
10345          */
10346         if (lun != NULL)
10347                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10348                                   lun->be_lun->lun_type;
10349         else
10350                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10351
10352         lbp_ptr->page_code = SVPD_LBP;
10353         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10354         lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10355         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10356                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10357                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10358                 lbp_ptr->prov_type = SVPD_LBP_THIN;
10359         }
10360
10361         ctl_set_success(ctsio);
10362         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10363         ctsio->be_move_done = ctl_config_move_done;
10364         ctl_datamove((union ctl_io *)ctsio);
10365         return (CTL_RETVAL_COMPLETE);
10366 }
10367
10368 /*
10369  * INQUIRY with the EVPD bit set.
10370  */
10371 static int
10372 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10373 {
10374         struct ctl_lun *lun;
10375         struct scsi_inquiry *cdb;
10376         int alloc_len, retval;
10377
10378         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10379         cdb = (struct scsi_inquiry *)ctsio->cdb;
10380         alloc_len = scsi_2btoul(cdb->length);
10381
10382         switch (cdb->page_code) {
10383         case SVPD_SUPPORTED_PAGES:
10384                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10385                 break;
10386         case SVPD_UNIT_SERIAL_NUMBER:
10387                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10388                 break;
10389         case SVPD_DEVICE_ID:
10390                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10391                 break;
10392         case SVPD_EXTENDED_INQUIRY_DATA:
10393                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10394                 break;
10395         case SVPD_MODE_PAGE_POLICY:
10396                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10397                 break;
10398         case SVPD_SCSI_PORTS:
10399                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10400                 break;
10401         case SVPD_SCSI_TPC:
10402                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10403                 break;
10404         case SVPD_BLOCK_LIMITS:
10405                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10406                         goto err;
10407                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10408                 break;
10409         case SVPD_BDC:
10410                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10411                         goto err;
10412                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10413                 break;
10414         case SVPD_LBP:
10415                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10416                         goto err;
10417                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10418                 break;
10419         default:
10420 err:
10421                 ctl_set_invalid_field(ctsio,
10422                                       /*sks_valid*/ 1,
10423                                       /*command*/ 1,
10424                                       /*field*/ 2,
10425                                       /*bit_valid*/ 0,
10426                                       /*bit*/ 0);
10427                 ctl_done((union ctl_io *)ctsio);
10428                 retval = CTL_RETVAL_COMPLETE;
10429                 break;
10430         }
10431
10432         return (retval);
10433 }
10434
10435 /*
10436  * Standard INQUIRY data.
10437  */
10438 static int
10439 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10440 {
10441         struct scsi_inquiry_data *inq_ptr;
10442         struct scsi_inquiry *cdb;
10443         struct ctl_softc *softc;
10444         struct ctl_lun *lun;
10445         char *val;
10446         uint32_t alloc_len, data_len;
10447         ctl_port_type port_type;
10448
10449         softc = control_softc;
10450
10451         /*
10452          * Figure out whether we're talking to a Fibre Channel port or not.
10453          * We treat the ioctl front end, and any SCSI adapters, as packetized
10454          * SCSI front ends.
10455          */
10456         port_type = softc->ctl_ports[
10457             ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10458         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10459                 port_type = CTL_PORT_SCSI;
10460
10461         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10462         cdb = (struct scsi_inquiry *)ctsio->cdb;
10463         alloc_len = scsi_2btoul(cdb->length);
10464
10465         /*
10466          * We malloc the full inquiry data size here and fill it
10467          * in.  If the user only asks for less, we'll give him
10468          * that much.
10469          */
10470         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10471         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10472         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10473         ctsio->kern_sg_entries = 0;
10474         ctsio->kern_data_resid = 0;
10475         ctsio->kern_rel_offset = 0;
10476
10477         if (data_len < alloc_len) {
10478                 ctsio->residual = alloc_len - data_len;
10479                 ctsio->kern_data_len = data_len;
10480                 ctsio->kern_total_len = data_len;
10481         } else {
10482                 ctsio->residual = 0;
10483                 ctsio->kern_data_len = alloc_len;
10484                 ctsio->kern_total_len = alloc_len;
10485         }
10486
10487         /*
10488          * If we have a LUN configured, report it as connected.  Otherwise,
10489          * report that it is offline or no device is supported, depending 
10490          * on the value of inquiry_pq_no_lun.
10491          *
10492          * According to the spec (SPC-4 r34), the peripheral qualifier
10493          * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10494          *
10495          * "A peripheral device having the specified peripheral device type 
10496          * is not connected to this logical unit. However, the device
10497          * server is capable of supporting the specified peripheral device
10498          * type on this logical unit."
10499          *
10500          * According to the same spec, the peripheral qualifier
10501          * SID_QUAL_BAD_LU (011b) is used in this scenario:
10502          *
10503          * "The device server is not capable of supporting a peripheral
10504          * device on this logical unit. For this peripheral qualifier the
10505          * peripheral device type shall be set to 1Fh. All other peripheral
10506          * device type values are reserved for this peripheral qualifier."
10507          *
10508          * Given the text, it would seem that we probably want to report that
10509          * the LUN is offline here.  There is no LUN connected, but we can
10510          * support a LUN at the given LUN number.
10511          *
10512          * In the real world, though, it sounds like things are a little
10513          * different:
10514          *
10515          * - Linux, when presented with a LUN with the offline peripheral
10516          *   qualifier, will create an sg driver instance for it.  So when
10517          *   you attach it to CTL, you wind up with a ton of sg driver
10518          *   instances.  (One for every LUN that Linux bothered to probe.)
10519          *   Linux does this despite the fact that it issues a REPORT LUNs
10520          *   to LUN 0 to get the inventory of supported LUNs.
10521          *
10522          * - There is other anecdotal evidence (from Emulex folks) about
10523          *   arrays that use the offline peripheral qualifier for LUNs that
10524          *   are on the "passive" path in an active/passive array.
10525          *
10526          * So the solution is provide a hopefully reasonable default
10527          * (return bad/no LUN) and allow the user to change the behavior
10528          * with a tunable/sysctl variable.
10529          */
10530         if (lun != NULL)
10531                 inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10532                                   lun->be_lun->lun_type;
10533         else if (softc->inquiry_pq_no_lun == 0)
10534                 inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10535         else
10536                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10537
10538         /* RMB in byte 2 is 0 */
10539         inq_ptr->version = SCSI_REV_SPC4;
10540
10541         /*
10542          * According to SAM-3, even if a device only supports a single
10543          * level of LUN addressing, it should still set the HISUP bit:
10544          *
10545          * 4.9.1 Logical unit numbers overview
10546          *
10547          * All logical unit number formats described in this standard are
10548          * hierarchical in structure even when only a single level in that
10549          * hierarchy is used. The HISUP bit shall be set to one in the
10550          * standard INQUIRY data (see SPC-2) when any logical unit number
10551          * format described in this standard is used.  Non-hierarchical
10552          * formats are outside the scope of this standard.
10553          *
10554          * Therefore we set the HiSup bit here.
10555          *
10556          * The reponse format is 2, per SPC-3.
10557          */
10558         inq_ptr->response_format = SID_HiSup | 2;
10559
10560         inq_ptr->additional_length = data_len -
10561             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10562         CTL_DEBUG_PRINT(("additional_length = %d\n",
10563                          inq_ptr->additional_length));
10564
10565         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10566         /* 16 bit addressing */
10567         if (port_type == CTL_PORT_SCSI)
10568                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10569         /* XXX set the SID_MultiP bit here if we're actually going to
10570            respond on multiple ports */
10571         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10572
10573         /* 16 bit data bus, synchronous transfers */
10574         if (port_type == CTL_PORT_SCSI)
10575                 inq_ptr->flags = SID_WBus16 | SID_Sync;
10576         /*
10577          * XXX KDM do we want to support tagged queueing on the control
10578          * device at all?
10579          */
10580         if ((lun == NULL)
10581          || (lun->be_lun->lun_type != T_PROCESSOR))
10582                 inq_ptr->flags |= SID_CmdQue;
10583         /*
10584          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10585          * We have 8 bytes for the vendor name, and 16 bytes for the device
10586          * name and 4 bytes for the revision.
10587          */
10588         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10589             "vendor")) == NULL) {
10590                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10591         } else {
10592                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10593                 strncpy(inq_ptr->vendor, val,
10594                     min(sizeof(inq_ptr->vendor), strlen(val)));
10595         }
10596         if (lun == NULL) {
10597                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10598                     sizeof(inq_ptr->product));
10599         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10600                 switch (lun->be_lun->lun_type) {
10601                 case T_DIRECT:
10602                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10603                             sizeof(inq_ptr->product));
10604                         break;
10605                 case T_PROCESSOR:
10606                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10607                             sizeof(inq_ptr->product));
10608                         break;
10609                 default:
10610                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10611                             sizeof(inq_ptr->product));
10612                         break;
10613                 }
10614         } else {
10615                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10616                 strncpy(inq_ptr->product, val,
10617                     min(sizeof(inq_ptr->product), strlen(val)));
10618         }
10619
10620         /*
10621          * XXX make this a macro somewhere so it automatically gets
10622          * incremented when we make changes.
10623          */
10624         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10625             "revision")) == NULL) {
10626                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10627         } else {
10628                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10629                 strncpy(inq_ptr->revision, val,
10630                     min(sizeof(inq_ptr->revision), strlen(val)));
10631         }
10632
10633         /*
10634          * For parallel SCSI, we support double transition and single
10635          * transition clocking.  We also support QAS (Quick Arbitration
10636          * and Selection) and Information Unit transfers on both the
10637          * control and array devices.
10638          */
10639         if (port_type == CTL_PORT_SCSI)
10640                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10641                                     SID_SPI_IUS;
10642
10643         /* SAM-5 (no version claimed) */
10644         scsi_ulto2b(0x00A0, inq_ptr->version1);
10645         /* SPC-4 (no version claimed) */
10646         scsi_ulto2b(0x0460, inq_ptr->version2);
10647         if (port_type == CTL_PORT_FC) {
10648                 /* FCP-2 ANSI INCITS.350:2003 */
10649                 scsi_ulto2b(0x0917, inq_ptr->version3);
10650         } else if (port_type == CTL_PORT_SCSI) {
10651                 /* SPI-4 ANSI INCITS.362:200x */
10652                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10653         } else if (port_type == CTL_PORT_ISCSI) {
10654                 /* iSCSI (no version claimed) */
10655                 scsi_ulto2b(0x0960, inq_ptr->version3);
10656         } else if (port_type == CTL_PORT_SAS) {
10657                 /* SAS (no version claimed) */
10658                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10659         }
10660
10661         if (lun == NULL) {
10662                 /* SBC-4 (no version claimed) */
10663                 scsi_ulto2b(0x0600, inq_ptr->version4);
10664         } else {
10665                 switch (lun->be_lun->lun_type) {
10666                 case T_DIRECT:
10667                         /* SBC-4 (no version claimed) */
10668                         scsi_ulto2b(0x0600, inq_ptr->version4);
10669                         break;
10670                 case T_PROCESSOR:
10671                 default:
10672                         break;
10673                 }
10674         }
10675
10676         ctl_set_success(ctsio);
10677         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10678         ctsio->be_move_done = ctl_config_move_done;
10679         ctl_datamove((union ctl_io *)ctsio);
10680         return (CTL_RETVAL_COMPLETE);
10681 }
10682
10683 int
10684 ctl_inquiry(struct ctl_scsiio *ctsio)
10685 {
10686         struct scsi_inquiry *cdb;
10687         int retval;
10688
10689         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10690
10691         cdb = (struct scsi_inquiry *)ctsio->cdb;
10692         if (cdb->byte2 & SI_EVPD)
10693                 retval = ctl_inquiry_evpd(ctsio);
10694         else if (cdb->page_code == 0)
10695                 retval = ctl_inquiry_std(ctsio);
10696         else {
10697                 ctl_set_invalid_field(ctsio,
10698                                       /*sks_valid*/ 1,
10699                                       /*command*/ 1,
10700                                       /*field*/ 2,
10701                                       /*bit_valid*/ 0,
10702                                       /*bit*/ 0);
10703                 ctl_done((union ctl_io *)ctsio);
10704                 return (CTL_RETVAL_COMPLETE);
10705         }
10706
10707         return (retval);
10708 }
10709
10710 /*
10711  * For known CDB types, parse the LBA and length.
10712  */
10713 static int
10714 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10715 {
10716         if (io->io_hdr.io_type != CTL_IO_SCSI)
10717                 return (1);
10718
10719         switch (io->scsiio.cdb[0]) {
10720         case COMPARE_AND_WRITE: {
10721                 struct scsi_compare_and_write *cdb;
10722
10723                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10724
10725                 *lba = scsi_8btou64(cdb->addr);
10726                 *len = cdb->length;
10727                 break;
10728         }
10729         case READ_6:
10730         case WRITE_6: {
10731                 struct scsi_rw_6 *cdb;
10732
10733                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10734
10735                 *lba = scsi_3btoul(cdb->addr);
10736                 /* only 5 bits are valid in the most significant address byte */
10737                 *lba &= 0x1fffff;
10738                 *len = cdb->length;
10739                 break;
10740         }
10741         case READ_10:
10742         case WRITE_10: {
10743                 struct scsi_rw_10 *cdb;
10744
10745                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10746
10747                 *lba = scsi_4btoul(cdb->addr);
10748                 *len = scsi_2btoul(cdb->length);
10749                 break;
10750         }
10751         case WRITE_VERIFY_10: {
10752                 struct scsi_write_verify_10 *cdb;
10753
10754                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10755
10756                 *lba = scsi_4btoul(cdb->addr);
10757                 *len = scsi_2btoul(cdb->length);
10758                 break;
10759         }
10760         case READ_12:
10761         case WRITE_12: {
10762                 struct scsi_rw_12 *cdb;
10763
10764                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10765
10766                 *lba = scsi_4btoul(cdb->addr);
10767                 *len = scsi_4btoul(cdb->length);
10768                 break;
10769         }
10770         case WRITE_VERIFY_12: {
10771                 struct scsi_write_verify_12 *cdb;
10772
10773                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10774
10775                 *lba = scsi_4btoul(cdb->addr);
10776                 *len = scsi_4btoul(cdb->length);
10777                 break;
10778         }
10779         case READ_16:
10780         case WRITE_16:
10781         case WRITE_ATOMIC_16: {
10782                 struct scsi_rw_16 *cdb;
10783
10784                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10785
10786                 *lba = scsi_8btou64(cdb->addr);
10787                 *len = scsi_4btoul(cdb->length);
10788                 break;
10789         }
10790         case WRITE_VERIFY_16: {
10791                 struct scsi_write_verify_16 *cdb;
10792
10793                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10794
10795                 *lba = scsi_8btou64(cdb->addr);
10796                 *len = scsi_4btoul(cdb->length);
10797                 break;
10798         }
10799         case WRITE_SAME_10: {
10800                 struct scsi_write_same_10 *cdb;
10801
10802                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10803
10804                 *lba = scsi_4btoul(cdb->addr);
10805                 *len = scsi_2btoul(cdb->length);
10806                 break;
10807         }
10808         case WRITE_SAME_16: {
10809                 struct scsi_write_same_16 *cdb;
10810
10811                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10812
10813                 *lba = scsi_8btou64(cdb->addr);
10814                 *len = scsi_4btoul(cdb->length);
10815                 break;
10816         }
10817         case VERIFY_10: {
10818                 struct scsi_verify_10 *cdb;
10819
10820                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10821
10822                 *lba = scsi_4btoul(cdb->addr);
10823                 *len = scsi_2btoul(cdb->length);
10824                 break;
10825         }
10826         case VERIFY_12: {
10827                 struct scsi_verify_12 *cdb;
10828
10829                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10830
10831                 *lba = scsi_4btoul(cdb->addr);
10832                 *len = scsi_4btoul(cdb->length);
10833                 break;
10834         }
10835         case VERIFY_16: {
10836                 struct scsi_verify_16 *cdb;
10837
10838                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10839
10840                 *lba = scsi_8btou64(cdb->addr);
10841                 *len = scsi_4btoul(cdb->length);
10842                 break;
10843         }
10844         case UNMAP: {
10845                 *lba = 0;
10846                 *len = UINT64_MAX;
10847                 break;
10848         }
10849         case SERVICE_ACTION_IN: {       /* GET LBA STATUS */
10850                 struct scsi_get_lba_status *cdb;
10851
10852                 cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10853                 *lba = scsi_8btou64(cdb->addr);
10854                 *len = UINT32_MAX;
10855                 break;
10856         }
10857         default:
10858                 return (1);
10859                 break; /* NOTREACHED */
10860         }
10861
10862         return (0);
10863 }
10864
10865 static ctl_action
10866 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10867     bool seq)
10868 {
10869         uint64_t endlba1, endlba2;
10870
10871         endlba1 = lba1 + len1 - (seq ? 0 : 1);
10872         endlba2 = lba2 + len2 - 1;
10873
10874         if ((endlba1 < lba2) || (endlba2 < lba1))
10875                 return (CTL_ACTION_PASS);
10876         else
10877                 return (CTL_ACTION_BLOCK);
10878 }
10879
10880 static int
10881 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10882 {
10883         struct ctl_ptr_len_flags *ptrlen;
10884         struct scsi_unmap_desc *buf, *end, *range;
10885         uint64_t lba;
10886         uint32_t len;
10887
10888         /* If not UNMAP -- go other way. */
10889         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10890             io->scsiio.cdb[0] != UNMAP)
10891                 return (CTL_ACTION_ERROR);
10892
10893         /* If UNMAP without data -- block and wait for data. */
10894         ptrlen = (struct ctl_ptr_len_flags *)
10895             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10896         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10897             ptrlen->ptr == NULL)
10898                 return (CTL_ACTION_BLOCK);
10899
10900         /* UNMAP with data -- check for collision. */
10901         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10902         end = buf + ptrlen->len / sizeof(*buf);
10903         for (range = buf; range < end; range++) {
10904                 lba = scsi_8btou64(range->lba);
10905                 len = scsi_4btoul(range->length);
10906                 if ((lba < lba2 + len2) && (lba + len > lba2))
10907                         return (CTL_ACTION_BLOCK);
10908         }
10909         return (CTL_ACTION_PASS);
10910 }
10911
10912 static ctl_action
10913 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10914 {
10915         uint64_t lba1, lba2;
10916         uint64_t len1, len2;
10917         int retval;
10918
10919         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10920                 return (CTL_ACTION_ERROR);
10921
10922         retval = ctl_extent_check_unmap(io1, lba2, len2);
10923         if (retval != CTL_ACTION_ERROR)
10924                 return (retval);
10925
10926         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10927                 return (CTL_ACTION_ERROR);
10928
10929         return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10930 }
10931
10932 static ctl_action
10933 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10934 {
10935         uint64_t lba1, lba2;
10936         uint64_t len1, len2;
10937
10938         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10939                 return (CTL_ACTION_ERROR);
10940         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10941                 return (CTL_ACTION_ERROR);
10942
10943         if (lba1 + len1 == lba2)
10944                 return (CTL_ACTION_BLOCK);
10945         return (CTL_ACTION_PASS);
10946 }
10947
10948 static ctl_action
10949 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10950     union ctl_io *ooa_io)
10951 {
10952         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10953         ctl_serialize_action *serialize_row;
10954
10955         /*
10956          * The initiator attempted multiple untagged commands at the same
10957          * time.  Can't do that.
10958          */
10959         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10960          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10961          && ((pending_io->io_hdr.nexus.targ_port ==
10962               ooa_io->io_hdr.nexus.targ_port)
10963           && (pending_io->io_hdr.nexus.initid.id ==
10964               ooa_io->io_hdr.nexus.initid.id))
10965          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10966               CTL_FLAG_STATUS_SENT)) == 0))
10967                 return (CTL_ACTION_OVERLAP);
10968
10969         /*
10970          * The initiator attempted to send multiple tagged commands with
10971          * the same ID.  (It's fine if different initiators have the same
10972          * tag ID.)
10973          *
10974          * Even if all of those conditions are true, we don't kill the I/O
10975          * if the command ahead of us has been aborted.  We won't end up
10976          * sending it to the FETD, and it's perfectly legal to resend a
10977          * command with the same tag number as long as the previous
10978          * instance of this tag number has been aborted somehow.
10979          */
10980         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10981          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10982          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10983          && ((pending_io->io_hdr.nexus.targ_port ==
10984               ooa_io->io_hdr.nexus.targ_port)
10985           && (pending_io->io_hdr.nexus.initid.id ==
10986               ooa_io->io_hdr.nexus.initid.id))
10987          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10988               CTL_FLAG_STATUS_SENT)) == 0))
10989                 return (CTL_ACTION_OVERLAP_TAG);
10990
10991         /*
10992          * If we get a head of queue tag, SAM-3 says that we should
10993          * immediately execute it.
10994          *
10995          * What happens if this command would normally block for some other
10996          * reason?  e.g. a request sense with a head of queue tag
10997          * immediately after a write.  Normally that would block, but this
10998          * will result in its getting executed immediately...
10999          *
11000          * We currently return "pass" instead of "skip", so we'll end up
11001          * going through the rest of the queue to check for overlapped tags.
11002          *
11003          * XXX KDM check for other types of blockage first??
11004          */
11005         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11006                 return (CTL_ACTION_PASS);
11007
11008         /*
11009          * Ordered tags have to block until all items ahead of them
11010          * have completed.  If we get called with an ordered tag, we always
11011          * block, if something else is ahead of us in the queue.
11012          */
11013         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11014                 return (CTL_ACTION_BLOCK);
11015
11016         /*
11017          * Simple tags get blocked until all head of queue and ordered tags
11018          * ahead of them have completed.  I'm lumping untagged commands in
11019          * with simple tags here.  XXX KDM is that the right thing to do?
11020          */
11021         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11022           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11023          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11024           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11025                 return (CTL_ACTION_BLOCK);
11026
11027         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11028         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11029
11030         serialize_row = ctl_serialize_table[ooa_entry->seridx];
11031
11032         switch (serialize_row[pending_entry->seridx]) {
11033         case CTL_SER_BLOCK:
11034                 return (CTL_ACTION_BLOCK);
11035         case CTL_SER_EXTENT:
11036                 return (ctl_extent_check(ooa_io, pending_io,
11037                     (lun->serseq == CTL_LUN_SERSEQ_ON)));
11038         case CTL_SER_EXTENTOPT:
11039                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11040                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11041                         return (ctl_extent_check(ooa_io, pending_io,
11042                             (lun->serseq == CTL_LUN_SERSEQ_ON)));
11043                 return (CTL_ACTION_PASS);
11044         case CTL_SER_EXTENTSEQ:
11045                 if (lun->serseq != CTL_LUN_SERSEQ_OFF)
11046                         return (ctl_extent_check_seq(ooa_io, pending_io));
11047                 return (CTL_ACTION_PASS);
11048         case CTL_SER_PASS:
11049                 return (CTL_ACTION_PASS);
11050         case CTL_SER_BLOCKOPT:
11051                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11052                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11053                         return (CTL_ACTION_BLOCK);
11054                 return (CTL_ACTION_PASS);
11055         case CTL_SER_SKIP:
11056                 return (CTL_ACTION_SKIP);
11057         default:
11058                 panic("invalid serialization value %d",
11059                       serialize_row[pending_entry->seridx]);
11060         }
11061
11062         return (CTL_ACTION_ERROR);
11063 }
11064
11065 /*
11066  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11067  * Assumptions:
11068  * - pending_io is generally either incoming, or on the blocked queue
11069  * - starting I/O is the I/O we want to start the check with.
11070  */
11071 static ctl_action
11072 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11073               union ctl_io *starting_io)
11074 {
11075         union ctl_io *ooa_io;
11076         ctl_action action;
11077
11078         mtx_assert(&lun->lun_lock, MA_OWNED);
11079
11080         /*
11081          * Run back along the OOA queue, starting with the current
11082          * blocked I/O and going through every I/O before it on the
11083          * queue.  If starting_io is NULL, we'll just end up returning
11084          * CTL_ACTION_PASS.
11085          */
11086         for (ooa_io = starting_io; ooa_io != NULL;
11087              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11088              ooa_links)){
11089
11090                 /*
11091                  * This routine just checks to see whether
11092                  * cur_blocked is blocked by ooa_io, which is ahead
11093                  * of it in the queue.  It doesn't queue/dequeue
11094                  * cur_blocked.
11095                  */
11096                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11097                 switch (action) {
11098                 case CTL_ACTION_BLOCK:
11099                 case CTL_ACTION_OVERLAP:
11100                 case CTL_ACTION_OVERLAP_TAG:
11101                 case CTL_ACTION_SKIP:
11102                 case CTL_ACTION_ERROR:
11103                         return (action);
11104                         break; /* NOTREACHED */
11105                 case CTL_ACTION_PASS:
11106                         break;
11107                 default:
11108                         panic("invalid action %d", action);
11109                         break;  /* NOTREACHED */
11110                 }
11111         }
11112
11113         return (CTL_ACTION_PASS);
11114 }
11115
11116 /*
11117  * Assumptions:
11118  * - An I/O has just completed, and has been removed from the per-LUN OOA
11119  *   queue, so some items on the blocked queue may now be unblocked.
11120  */
11121 static int
11122 ctl_check_blocked(struct ctl_lun *lun)
11123 {
11124         union ctl_io *cur_blocked, *next_blocked;
11125
11126         mtx_assert(&lun->lun_lock, MA_OWNED);
11127
11128         /*
11129          * Run forward from the head of the blocked queue, checking each
11130          * entry against the I/Os prior to it on the OOA queue to see if
11131          * there is still any blockage.
11132          *
11133          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11134          * with our removing a variable on it while it is traversing the
11135          * list.
11136          */
11137         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11138              cur_blocked != NULL; cur_blocked = next_blocked) {
11139                 union ctl_io *prev_ooa;
11140                 ctl_action action;
11141
11142                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11143                                                           blocked_links);
11144
11145                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11146                                                       ctl_ooaq, ooa_links);
11147
11148                 /*
11149                  * If cur_blocked happens to be the first item in the OOA
11150                  * queue now, prev_ooa will be NULL, and the action
11151                  * returned will just be CTL_ACTION_PASS.
11152                  */
11153                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11154
11155                 switch (action) {
11156                 case CTL_ACTION_BLOCK:
11157                         /* Nothing to do here, still blocked */
11158                         break;
11159                 case CTL_ACTION_OVERLAP:
11160                 case CTL_ACTION_OVERLAP_TAG:
11161                         /*
11162                          * This shouldn't happen!  In theory we've already
11163                          * checked this command for overlap...
11164                          */
11165                         break;
11166                 case CTL_ACTION_PASS:
11167                 case CTL_ACTION_SKIP: {
11168                         const struct ctl_cmd_entry *entry;
11169                         int isc_retval;
11170
11171                         /*
11172                          * The skip case shouldn't happen, this transaction
11173                          * should have never made it onto the blocked queue.
11174                          */
11175                         /*
11176                          * This I/O is no longer blocked, we can remove it
11177                          * from the blocked queue.  Since this is a TAILQ
11178                          * (doubly linked list), we can do O(1) removals
11179                          * from any place on the list.
11180                          */
11181                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11182                                      blocked_links);
11183                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11184
11185                         if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11186                                 /*
11187                                  * Need to send IO back to original side to
11188                                  * run
11189                                  */
11190                                 union ctl_ha_msg msg_info;
11191
11192                                 msg_info.hdr.original_sc =
11193                                         cur_blocked->io_hdr.original_sc;
11194                                 msg_info.hdr.serializing_sc = cur_blocked;
11195                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
11196                                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11197                                      &msg_info, sizeof(msg_info), 0)) >
11198                                      CTL_HA_STATUS_SUCCESS) {
11199                                         printf("CTL:Check Blocked error from "
11200                                                "ctl_ha_msg_send %d\n",
11201                                                isc_retval);
11202                                 }
11203                                 break;
11204                         }
11205                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11206
11207                         /*
11208                          * Check this I/O for LUN state changes that may
11209                          * have happened while this command was blocked.
11210                          * The LUN state may have been changed by a command
11211                          * ahead of us in the queue, so we need to re-check
11212                          * for any states that can be caused by SCSI
11213                          * commands.
11214                          */
11215                         if (ctl_scsiio_lun_check(lun, entry,
11216                                                  &cur_blocked->scsiio) == 0) {
11217                                 cur_blocked->io_hdr.flags |=
11218                                                       CTL_FLAG_IS_WAS_ON_RTR;
11219                                 ctl_enqueue_rtr(cur_blocked);
11220                         } else
11221                                 ctl_done(cur_blocked);
11222                         break;
11223                 }
11224                 default:
11225                         /*
11226                          * This probably shouldn't happen -- we shouldn't
11227                          * get CTL_ACTION_ERROR, or anything else.
11228                          */
11229                         break;
11230                 }
11231         }
11232
11233         return (CTL_RETVAL_COMPLETE);
11234 }
11235
11236 /*
11237  * This routine (with one exception) checks LUN flags that can be set by
11238  * commands ahead of us in the OOA queue.  These flags have to be checked
11239  * when a command initially comes in, and when we pull a command off the
11240  * blocked queue and are preparing to execute it.  The reason we have to
11241  * check these flags for commands on the blocked queue is that the LUN
11242  * state may have been changed by a command ahead of us while we're on the
11243  * blocked queue.
11244  *
11245  * Ordering is somewhat important with these checks, so please pay
11246  * careful attention to the placement of any new checks.
11247  */
11248 static int
11249 ctl_scsiio_lun_check(struct ctl_lun *lun,
11250     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11251 {
11252         struct ctl_softc *softc = lun->ctl_softc;
11253         int retval;
11254         uint32_t residx;
11255
11256         retval = 0;
11257
11258         mtx_assert(&lun->lun_lock, MA_OWNED);
11259
11260         /*
11261          * If this shelf is a secondary shelf controller, we have to reject
11262          * any media access commands.
11263          */
11264         if ((softc->flags & CTL_FLAG_ACTIVE_SHELF) == 0 &&
11265             (entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0) {
11266                 ctl_set_lun_standby(ctsio);
11267                 retval = 1;
11268                 goto bailout;
11269         }
11270
11271         if (entry->pattern & CTL_LUN_PAT_WRITE) {
11272                 if (lun->flags & CTL_LUN_READONLY) {
11273                         ctl_set_sense(ctsio, /*current_error*/ 1,
11274                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11275                             /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11276                         retval = 1;
11277                         goto bailout;
11278                 }
11279                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11280                     .eca_and_aen & SCP_SWP) != 0) {
11281                         ctl_set_sense(ctsio, /*current_error*/ 1,
11282                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11283                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11284                         retval = 1;
11285                         goto bailout;
11286                 }
11287         }
11288
11289         /*
11290          * Check for a reservation conflict.  If this command isn't allowed
11291          * even on reserved LUNs, and if this initiator isn't the one who
11292          * reserved us, reject the command with a reservation conflict.
11293          */
11294         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11295         if ((lun->flags & CTL_LUN_RESERVED)
11296          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11297                 if (lun->res_idx != residx) {
11298                         ctl_set_reservation_conflict(ctsio);
11299                         retval = 1;
11300                         goto bailout;
11301                 }
11302         }
11303
11304         if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11305             (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11306                 /* No reservation or command is allowed. */;
11307         } else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11308             (lun->res_type == SPR_TYPE_WR_EX ||
11309              lun->res_type == SPR_TYPE_WR_EX_RO ||
11310              lun->res_type == SPR_TYPE_WR_EX_AR)) {
11311                 /* The command is allowed for Write Exclusive resv. */;
11312         } else {
11313                 /*
11314                  * if we aren't registered or it's a res holder type
11315                  * reservation and this isn't the res holder then set a
11316                  * conflict.
11317                  */
11318                 if (ctl_get_prkey(lun, residx) == 0
11319                  || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11320                         ctl_set_reservation_conflict(ctsio);
11321                         retval = 1;
11322                         goto bailout;
11323                 }
11324
11325         }
11326
11327         if ((lun->flags & CTL_LUN_OFFLINE)
11328          && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11329                 ctl_set_lun_not_ready(ctsio);
11330                 retval = 1;
11331                 goto bailout;
11332         }
11333
11334         /*
11335          * If the LUN is stopped, see if this particular command is allowed
11336          * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11337          */
11338         if ((lun->flags & CTL_LUN_STOPPED)
11339          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11340                 /* "Logical unit not ready, initializing cmd. required" */
11341                 ctl_set_lun_stopped(ctsio);
11342                 retval = 1;
11343                 goto bailout;
11344         }
11345
11346         if ((lun->flags & CTL_LUN_INOPERABLE)
11347          && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11348                 /* "Medium format corrupted" */
11349                 ctl_set_medium_format_corrupted(ctsio);
11350                 retval = 1;
11351                 goto bailout;
11352         }
11353
11354 bailout:
11355         return (retval);
11356
11357 }
11358
11359 static void
11360 ctl_failover_io(union ctl_io *io, int have_lock)
11361 {
11362         ctl_set_busy(&io->scsiio);
11363         ctl_done(io);
11364 }
11365
11366 static void
11367 ctl_failover(void)
11368 {
11369         struct ctl_lun *lun;
11370         struct ctl_softc *softc;
11371         union ctl_io *next_io, *pending_io;
11372         union ctl_io *io;
11373         int lun_idx;
11374
11375         softc = control_softc;
11376
11377         mtx_lock(&softc->ctl_lock);
11378         /*
11379          * Remove any cmds from the other SC from the rtr queue.  These
11380          * will obviously only be for LUNs for which we're the primary.
11381          * We can't send status or get/send data for these commands.
11382          * Since they haven't been executed yet, we can just remove them.
11383          * We'll either abort them or delete them below, depending on
11384          * which HA mode we're in.
11385          */
11386 #ifdef notyet
11387         mtx_lock(&softc->queue_lock);
11388         for (io = (union ctl_io *)STAILQ_FIRST(&softc->rtr_queue);
11389              io != NULL; io = next_io) {
11390                 next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11391                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11392                         STAILQ_REMOVE(&softc->rtr_queue, &io->io_hdr,
11393                                       ctl_io_hdr, links);
11394         }
11395         mtx_unlock(&softc->queue_lock);
11396 #endif
11397
11398         for (lun_idx=0; lun_idx < softc->num_luns; lun_idx++) {
11399                 lun = softc->ctl_luns[lun_idx];
11400                 if (lun==NULL)
11401                         continue;
11402
11403                 /*
11404                  * Processor LUNs are primary on both sides.
11405                  * XXX will this always be true?
11406                  */
11407                 if (lun->be_lun->lun_type == T_PROCESSOR)
11408                         continue;
11409
11410                 if ((lun->flags & CTL_LUN_PRIMARY_SC)
11411                  && (softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11412                         printf("FAILOVER: primary lun %d\n", lun_idx);
11413                         /*
11414                          * Remove all commands from the other SC. First from the
11415                          * blocked queue then from the ooa queue. Once we have
11416                          * removed them. Call ctl_check_blocked to see if there
11417                          * is anything that can run.
11418                          */
11419                         for (io = (union ctl_io *)TAILQ_FIRST(
11420                              &lun->blocked_queue); io != NULL; io = next_io) {
11421
11422                                 next_io = (union ctl_io *)TAILQ_NEXT(
11423                                     &io->io_hdr, blocked_links);
11424
11425                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11426                                         TAILQ_REMOVE(&lun->blocked_queue,
11427                                                      &io->io_hdr,blocked_links);
11428                                         io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11429                                         TAILQ_REMOVE(&lun->ooa_queue,
11430                                                      &io->io_hdr, ooa_links);
11431
11432                                         ctl_free_io(io);
11433                                 }
11434                         }
11435
11436                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11437                              io != NULL; io = next_io) {
11438
11439                                 next_io = (union ctl_io *)TAILQ_NEXT(
11440                                     &io->io_hdr, ooa_links);
11441
11442                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11443
11444                                         TAILQ_REMOVE(&lun->ooa_queue,
11445                                                 &io->io_hdr,
11446                                                 ooa_links);
11447
11448                                         ctl_free_io(io);
11449                                 }
11450                         }
11451                         ctl_check_blocked(lun);
11452                 } else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11453                         && (softc->ha_mode == CTL_HA_MODE_XFER)) {
11454
11455                         printf("FAILOVER: primary lun %d\n", lun_idx);
11456                         /*
11457                          * Abort all commands from the other SC.  We can't
11458                          * send status back for them now.  These should get
11459                          * cleaned up when they are completed or come out
11460                          * for a datamove operation.
11461                          */
11462                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11463                              io != NULL; io = next_io) {
11464                                 next_io = (union ctl_io *)TAILQ_NEXT(
11465                                         &io->io_hdr, ooa_links);
11466
11467                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11468                                         io->io_hdr.flags |= CTL_FLAG_ABORT;
11469                         }
11470                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11471                         && (softc->ha_mode == CTL_HA_MODE_XFER)) {
11472
11473                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11474
11475                         lun->flags |= CTL_LUN_PRIMARY_SC;
11476
11477                         /*
11478                          * We send all I/O that was sent to this controller
11479                          * and redirected to the other side back with
11480                          * busy status, and have the initiator retry it.
11481                          * Figuring out how much data has been transferred,
11482                          * etc. and picking up where we left off would be 
11483                          * very tricky.
11484                          *
11485                          * XXX KDM need to remove I/O from the blocked
11486                          * queue as well!
11487                          */
11488                         for (pending_io = (union ctl_io *)TAILQ_FIRST(
11489                              &lun->ooa_queue); pending_io != NULL;
11490                              pending_io = next_io) {
11491
11492                                 next_io =  (union ctl_io *)TAILQ_NEXT(
11493                                         &pending_io->io_hdr, ooa_links);
11494
11495                                 pending_io->io_hdr.flags &=
11496                                         ~CTL_FLAG_SENT_2OTHER_SC;
11497
11498                                 if (pending_io->io_hdr.flags &
11499                                     CTL_FLAG_IO_ACTIVE) {
11500                                         pending_io->io_hdr.flags |=
11501                                                 CTL_FLAG_FAILOVER;
11502                                 } else {
11503                                         ctl_set_busy(&pending_io->scsiio);
11504                                         ctl_done(pending_io);
11505                                 }
11506                         }
11507
11508                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11509                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11510                         && (softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11511                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11512                         /*
11513                          * if the first io on the OOA is not on the RtR queue
11514                          * add it.
11515                          */
11516                         lun->flags |= CTL_LUN_PRIMARY_SC;
11517
11518                         pending_io = (union ctl_io *)TAILQ_FIRST(
11519                             &lun->ooa_queue);
11520                         if (pending_io==NULL) {
11521                                 printf("Nothing on OOA queue\n");
11522                                 continue;
11523                         }
11524
11525                         pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11526                         if ((pending_io->io_hdr.flags &
11527                              CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11528                                 pending_io->io_hdr.flags |=
11529                                     CTL_FLAG_IS_WAS_ON_RTR;
11530                                 ctl_enqueue_rtr(pending_io);
11531                         }
11532 #if 0
11533                         else
11534                         {
11535                                 printf("Tag 0x%04x is running\n",
11536                                       pending_io->scsiio.tag_num);
11537                         }
11538 #endif
11539
11540                         next_io = (union ctl_io *)TAILQ_NEXT(
11541                             &pending_io->io_hdr, ooa_links);
11542                         for (pending_io=next_io; pending_io != NULL;
11543                              pending_io = next_io) {
11544                                 pending_io->io_hdr.flags &=
11545                                     ~CTL_FLAG_SENT_2OTHER_SC;
11546                                 next_io = (union ctl_io *)TAILQ_NEXT(
11547                                         &pending_io->io_hdr, ooa_links);
11548                                 if (pending_io->io_hdr.flags &
11549                                     CTL_FLAG_IS_WAS_ON_RTR) {
11550 #if 0
11551                                         printf("Tag 0x%04x is running\n",
11552                                                 pending_io->scsiio.tag_num);
11553 #endif
11554                                         continue;
11555                                 }
11556
11557                                 switch (ctl_check_ooa(lun, pending_io,
11558                                     (union ctl_io *)TAILQ_PREV(
11559                                     &pending_io->io_hdr, ctl_ooaq,
11560                                     ooa_links))) {
11561
11562                                 case CTL_ACTION_BLOCK:
11563                                         TAILQ_INSERT_TAIL(&lun->blocked_queue,
11564                                                           &pending_io->io_hdr,
11565                                                           blocked_links);
11566                                         pending_io->io_hdr.flags |=
11567                                             CTL_FLAG_BLOCKED;
11568                                         break;
11569                                 case CTL_ACTION_PASS:
11570                                 case CTL_ACTION_SKIP:
11571                                         pending_io->io_hdr.flags |=
11572                                             CTL_FLAG_IS_WAS_ON_RTR;
11573                                         ctl_enqueue_rtr(pending_io);
11574                                         break;
11575                                 case CTL_ACTION_OVERLAP:
11576                                         ctl_set_overlapped_cmd(
11577                                             (struct ctl_scsiio *)pending_io);
11578                                         ctl_done(pending_io);
11579                                         break;
11580                                 case CTL_ACTION_OVERLAP_TAG:
11581                                         ctl_set_overlapped_tag(
11582                                             (struct ctl_scsiio *)pending_io,
11583                                             pending_io->scsiio.tag_num & 0xff);
11584                                         ctl_done(pending_io);
11585                                         break;
11586                                 case CTL_ACTION_ERROR:
11587                                 default:
11588                                         ctl_set_internal_failure(
11589                                                 (struct ctl_scsiio *)pending_io,
11590                                                 0,  // sks_valid
11591                                                 0); //retry count
11592                                         ctl_done(pending_io);
11593                                         break;
11594                                 }
11595                         }
11596
11597                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11598                 } else {
11599                         panic("Unhandled HA mode failover, LUN flags = %#x, "
11600                               "ha_mode = #%x", lun->flags, softc->ha_mode);
11601                 }
11602         }
11603         ctl_pause_rtr = 0;
11604         mtx_unlock(&softc->ctl_lock);
11605 }
11606
11607 static void
11608 ctl_clear_ua(struct ctl_softc *ctl_softc, uint32_t initidx,
11609              ctl_ua_type ua_type)
11610 {
11611         struct ctl_lun *lun;
11612         ctl_ua_type *pu;
11613
11614         mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
11615
11616         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
11617                 mtx_lock(&lun->lun_lock);
11618                 pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
11619                 if (pu != NULL)
11620                         pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua_type;
11621                 mtx_unlock(&lun->lun_lock);
11622         }
11623 }
11624
11625 static int
11626 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11627 {
11628         struct ctl_lun *lun;
11629         const struct ctl_cmd_entry *entry;
11630         uint32_t initidx, targ_lun;
11631         int retval;
11632
11633         retval = 0;
11634
11635         lun = NULL;
11636
11637         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11638         if ((targ_lun < CTL_MAX_LUNS)
11639          && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11640                 /*
11641                  * If the LUN is invalid, pretend that it doesn't exist.
11642                  * It will go away as soon as all pending I/O has been
11643                  * completed.
11644                  */
11645                 mtx_lock(&lun->lun_lock);
11646                 if (lun->flags & CTL_LUN_DISABLED) {
11647                         mtx_unlock(&lun->lun_lock);
11648                         lun = NULL;
11649                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11650                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11651                 } else {
11652                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11653                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11654                                 lun->be_lun;
11655                         if (lun->be_lun->lun_type == T_PROCESSOR) {
11656                                 ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11657                         }
11658
11659                         /*
11660                          * Every I/O goes into the OOA queue for a
11661                          * particular LUN, and stays there until completion.
11662                          */
11663 #ifdef CTL_TIME_IO
11664                         if (TAILQ_EMPTY(&lun->ooa_queue)) {
11665                                 lun->idle_time += getsbinuptime() -
11666                                     lun->last_busy;
11667                         }
11668 #endif
11669                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11670                             ooa_links);
11671                 }
11672         } else {
11673                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11674                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11675         }
11676
11677         /* Get command entry and return error if it is unsuppotyed. */
11678         entry = ctl_validate_command(ctsio);
11679         if (entry == NULL) {
11680                 if (lun)
11681                         mtx_unlock(&lun->lun_lock);
11682                 return (retval);
11683         }
11684
11685         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11686         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11687
11688         /*
11689          * Check to see whether we can send this command to LUNs that don't
11690          * exist.  This should pretty much only be the case for inquiry
11691          * and request sense.  Further checks, below, really require having
11692          * a LUN, so we can't really check the command anymore.  Just put
11693          * it on the rtr queue.
11694          */
11695         if (lun == NULL) {
11696                 if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11697                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11698                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11699                         return (retval);
11700                 }
11701
11702                 ctl_set_unsupported_lun(ctsio);
11703                 ctl_done((union ctl_io *)ctsio);
11704                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11705                 return (retval);
11706         } else {
11707                 /*
11708                  * Make sure we support this particular command on this LUN.
11709                  * e.g., we don't support writes to the control LUN.
11710                  */
11711                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11712                         mtx_unlock(&lun->lun_lock);
11713                         ctl_set_invalid_opcode(ctsio);
11714                         ctl_done((union ctl_io *)ctsio);
11715                         return (retval);
11716                 }
11717         }
11718
11719         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11720
11721 #ifdef CTL_WITH_CA
11722         /*
11723          * If we've got a request sense, it'll clear the contingent
11724          * allegiance condition.  Otherwise, if we have a CA condition for
11725          * this initiator, clear it, because it sent down a command other
11726          * than request sense.
11727          */
11728         if ((ctsio->cdb[0] != REQUEST_SENSE)
11729          && (ctl_is_set(lun->have_ca, initidx)))
11730                 ctl_clear_mask(lun->have_ca, initidx);
11731 #endif
11732
11733         /*
11734          * If the command has this flag set, it handles its own unit
11735          * attention reporting, we shouldn't do anything.  Otherwise we
11736          * check for any pending unit attentions, and send them back to the
11737          * initiator.  We only do this when a command initially comes in,
11738          * not when we pull it off the blocked queue.
11739          *
11740          * According to SAM-3, section 5.3.2, the order that things get
11741          * presented back to the host is basically unit attentions caused
11742          * by some sort of reset event, busy status, reservation conflicts
11743          * or task set full, and finally any other status.
11744          *
11745          * One issue here is that some of the unit attentions we report
11746          * don't fall into the "reset" category (e.g. "reported luns data
11747          * has changed").  So reporting it here, before the reservation
11748          * check, may be technically wrong.  I guess the only thing to do
11749          * would be to check for and report the reset events here, and then
11750          * check for the other unit attention types after we check for a
11751          * reservation conflict.
11752          *
11753          * XXX KDM need to fix this
11754          */
11755         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11756                 ctl_ua_type ua_type;
11757                 scsi_sense_data_type sense_format;
11758
11759                 if (lun->flags & CTL_LUN_SENSE_DESC)
11760                         sense_format = SSD_TYPE_DESC;
11761                 else
11762                         sense_format = SSD_TYPE_FIXED;
11763
11764                 ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11765                     sense_format);
11766                 if (ua_type != CTL_UA_NONE) {
11767                         mtx_unlock(&lun->lun_lock);
11768                         ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11769                         ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11770                         ctsio->sense_len = SSD_FULL_SIZE;
11771                         ctl_done((union ctl_io *)ctsio);
11772                         return (retval);
11773                 }
11774         }
11775
11776
11777         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11778                 mtx_unlock(&lun->lun_lock);
11779                 ctl_done((union ctl_io *)ctsio);
11780                 return (retval);
11781         }
11782
11783         /*
11784          * XXX CHD this is where we want to send IO to other side if
11785          * this LUN is secondary on this SC. We will need to make a copy
11786          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11787          * the copy we send as FROM_OTHER.
11788          * We also need to stuff the address of the original IO so we can
11789          * find it easily. Something similar will need be done on the other
11790          * side so when we are done we can find the copy.
11791          */
11792         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11793                 union ctl_ha_msg msg_info;
11794                 int isc_retval;
11795
11796                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11797
11798                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11799                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11800 #if 0
11801                 printf("1. ctsio %p\n", ctsio);
11802 #endif
11803                 msg_info.hdr.serializing_sc = NULL;
11804                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11805                 msg_info.scsi.tag_num = ctsio->tag_num;
11806                 msg_info.scsi.tag_type = ctsio->tag_type;
11807                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11808
11809                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11810
11811                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11812                     (void *)&msg_info, sizeof(msg_info), 0)) >
11813                     CTL_HA_STATUS_SUCCESS) {
11814                         printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11815                                isc_retval);
11816                         printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11817                 } else {
11818 #if 0
11819                         printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11820 #endif
11821                 }
11822
11823                 /*
11824                  * XXX KDM this I/O is off the incoming queue, but hasn't
11825                  * been inserted on any other queue.  We may need to come
11826                  * up with a holding queue while we wait for serialization
11827                  * so that we have an idea of what we're waiting for from
11828                  * the other side.
11829                  */
11830                 mtx_unlock(&lun->lun_lock);
11831                 return (retval);
11832         }
11833
11834         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11835                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11836                               ctl_ooaq, ooa_links))) {
11837         case CTL_ACTION_BLOCK:
11838                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11839                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11840                                   blocked_links);
11841                 mtx_unlock(&lun->lun_lock);
11842                 return (retval);
11843         case CTL_ACTION_PASS:
11844         case CTL_ACTION_SKIP:
11845                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11846                 mtx_unlock(&lun->lun_lock);
11847                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11848                 break;
11849         case CTL_ACTION_OVERLAP:
11850                 mtx_unlock(&lun->lun_lock);
11851                 ctl_set_overlapped_cmd(ctsio);
11852                 ctl_done((union ctl_io *)ctsio);
11853                 break;
11854         case CTL_ACTION_OVERLAP_TAG:
11855                 mtx_unlock(&lun->lun_lock);
11856                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11857                 ctl_done((union ctl_io *)ctsio);
11858                 break;
11859         case CTL_ACTION_ERROR:
11860         default:
11861                 mtx_unlock(&lun->lun_lock);
11862                 ctl_set_internal_failure(ctsio,
11863                                          /*sks_valid*/ 0,
11864                                          /*retry_count*/ 0);
11865                 ctl_done((union ctl_io *)ctsio);
11866                 break;
11867         }
11868         return (retval);
11869 }
11870
11871 const struct ctl_cmd_entry *
11872 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11873 {
11874         const struct ctl_cmd_entry *entry;
11875         int service_action;
11876
11877         entry = &ctl_cmd_table[ctsio->cdb[0]];
11878         if (sa)
11879                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11880         if (entry->flags & CTL_CMD_FLAG_SA5) {
11881                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11882                 entry = &((const struct ctl_cmd_entry *)
11883                     entry->execute)[service_action];
11884         }
11885         return (entry);
11886 }
11887
11888 const struct ctl_cmd_entry *
11889 ctl_validate_command(struct ctl_scsiio *ctsio)
11890 {
11891         const struct ctl_cmd_entry *entry;
11892         int i, sa;
11893         uint8_t diff;
11894
11895         entry = ctl_get_cmd_entry(ctsio, &sa);
11896         if (entry->execute == NULL) {
11897                 if (sa)
11898                         ctl_set_invalid_field(ctsio,
11899                                               /*sks_valid*/ 1,
11900                                               /*command*/ 1,
11901                                               /*field*/ 1,
11902                                               /*bit_valid*/ 1,
11903                                               /*bit*/ 4);
11904                 else
11905                         ctl_set_invalid_opcode(ctsio);
11906                 ctl_done((union ctl_io *)ctsio);
11907                 return (NULL);
11908         }
11909         KASSERT(entry->length > 0,
11910             ("Not defined length for command 0x%02x/0x%02x",
11911              ctsio->cdb[0], ctsio->cdb[1]));
11912         for (i = 1; i < entry->length; i++) {
11913                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11914                 if (diff == 0)
11915                         continue;
11916                 ctl_set_invalid_field(ctsio,
11917                                       /*sks_valid*/ 1,
11918                                       /*command*/ 1,
11919                                       /*field*/ i,
11920                                       /*bit_valid*/ 1,
11921                                       /*bit*/ fls(diff) - 1);
11922                 ctl_done((union ctl_io *)ctsio);
11923                 return (NULL);
11924         }
11925         return (entry);
11926 }
11927
11928 static int
11929 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11930 {
11931
11932         switch (lun_type) {
11933         case T_PROCESSOR:
11934                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11935                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11936                         return (0);
11937                 break;
11938         case T_DIRECT:
11939                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11940                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11941                         return (0);
11942                 break;
11943         default:
11944                 return (0);
11945         }
11946         return (1);
11947 }
11948
11949 static int
11950 ctl_scsiio(struct ctl_scsiio *ctsio)
11951 {
11952         int retval;
11953         const struct ctl_cmd_entry *entry;
11954
11955         retval = CTL_RETVAL_COMPLETE;
11956
11957         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11958
11959         entry = ctl_get_cmd_entry(ctsio, NULL);
11960
11961         /*
11962          * If this I/O has been aborted, just send it straight to
11963          * ctl_done() without executing it.
11964          */
11965         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11966                 ctl_done((union ctl_io *)ctsio);
11967                 goto bailout;
11968         }
11969
11970         /*
11971          * All the checks should have been handled by ctl_scsiio_precheck().
11972          * We should be clear now to just execute the I/O.
11973          */
11974         retval = entry->execute(ctsio);
11975
11976 bailout:
11977         return (retval);
11978 }
11979
11980 /*
11981  * Since we only implement one target right now, a bus reset simply resets
11982  * our single target.
11983  */
11984 static int
11985 ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11986 {
11987         return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11988 }
11989
11990 static int
11991 ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11992                  ctl_ua_type ua_type)
11993 {
11994         struct ctl_lun *lun;
11995         int retval;
11996
11997         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11998                 union ctl_ha_msg msg_info;
11999
12000                 io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
12001                 msg_info.hdr.nexus = io->io_hdr.nexus;
12002                 if (ua_type==CTL_UA_TARG_RESET)
12003                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
12004                 else
12005                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
12006                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12007                 msg_info.hdr.original_sc = NULL;
12008                 msg_info.hdr.serializing_sc = NULL;
12009                 if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12010                     (void *)&msg_info, sizeof(msg_info), 0)) {
12011                 }
12012         }
12013         retval = 0;
12014
12015         mtx_lock(&softc->ctl_lock);
12016         STAILQ_FOREACH(lun, &softc->lun_list, links)
12017                 retval += ctl_lun_reset(lun, io, ua_type);
12018         mtx_unlock(&softc->ctl_lock);
12019
12020         return (retval);
12021 }
12022
12023 /*
12024  * The LUN should always be set.  The I/O is optional, and is used to
12025  * distinguish between I/Os sent by this initiator, and by other
12026  * initiators.  We set unit attention for initiators other than this one.
12027  * SAM-3 is vague on this point.  It does say that a unit attention should
12028  * be established for other initiators when a LUN is reset (see section
12029  * 5.7.3), but it doesn't specifically say that the unit attention should
12030  * be established for this particular initiator when a LUN is reset.  Here
12031  * is the relevant text, from SAM-3 rev 8:
12032  *
12033  * 5.7.2 When a SCSI initiator port aborts its own tasks
12034  *
12035  * When a SCSI initiator port causes its own task(s) to be aborted, no
12036  * notification that the task(s) have been aborted shall be returned to
12037  * the SCSI initiator port other than the completion response for the
12038  * command or task management function action that caused the task(s) to
12039  * be aborted and notification(s) associated with related effects of the
12040  * action (e.g., a reset unit attention condition).
12041  *
12042  * XXX KDM for now, we're setting unit attention for all initiators.
12043  */
12044 static int
12045 ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
12046 {
12047         union ctl_io *xio;
12048 #if 0
12049         uint32_t initidx;
12050 #endif
12051 #ifdef CTL_WITH_CA
12052         int i;
12053 #endif
12054
12055         mtx_lock(&lun->lun_lock);
12056         /*
12057          * Run through the OOA queue and abort each I/O.
12058          */
12059         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12060              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12061                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
12062         }
12063
12064         /*
12065          * This version sets unit attention for every
12066          */
12067 #if 0
12068         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12069         ctl_est_ua_all(lun, initidx, ua_type);
12070 #else
12071         ctl_est_ua_all(lun, -1, ua_type);
12072 #endif
12073
12074         /*
12075          * A reset (any kind, really) clears reservations established with
12076          * RESERVE/RELEASE.  It does not clear reservations established
12077          * with PERSISTENT RESERVE OUT, but we don't support that at the
12078          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
12079          * reservations made with the RESERVE/RELEASE commands, because
12080          * those commands are obsolete in SPC-3.
12081          */
12082         lun->flags &= ~CTL_LUN_RESERVED;
12083
12084 #ifdef CTL_WITH_CA
12085         for (i = 0; i < CTL_MAX_INITIATORS; i++)
12086                 ctl_clear_mask(lun->have_ca, i);
12087 #endif
12088         mtx_unlock(&lun->lun_lock);
12089
12090         return (0);
12091 }
12092
12093 static void
12094 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
12095     int other_sc)
12096 {
12097         union ctl_io *xio;
12098
12099         mtx_assert(&lun->lun_lock, MA_OWNED);
12100
12101         /*
12102          * Run through the OOA queue and attempt to find the given I/O.
12103          * The target port, initiator ID, tag type and tag number have to
12104          * match the values that we got from the initiator.  If we have an
12105          * untagged command to abort, simply abort the first untagged command
12106          * we come to.  We only allow one untagged command at a time of course.
12107          */
12108         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12109              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12110
12111                 if ((targ_port == UINT32_MAX ||
12112                      targ_port == xio->io_hdr.nexus.targ_port) &&
12113                     (init_id == UINT32_MAX ||
12114                      init_id == xio->io_hdr.nexus.initid.id)) {
12115                         if (targ_port != xio->io_hdr.nexus.targ_port ||
12116                             init_id != xio->io_hdr.nexus.initid.id)
12117                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12118                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12119                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12120                                 union ctl_ha_msg msg_info;
12121
12122                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
12123                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12124                                 msg_info.task.tag_num = xio->scsiio.tag_num;
12125                                 msg_info.task.tag_type = xio->scsiio.tag_type;
12126                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12127                                 msg_info.hdr.original_sc = NULL;
12128                                 msg_info.hdr.serializing_sc = NULL;
12129                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12130                                     (void *)&msg_info, sizeof(msg_info), 0);
12131                         }
12132                 }
12133         }
12134 }
12135
12136 static int
12137 ctl_abort_task_set(union ctl_io *io)
12138 {
12139         struct ctl_softc *softc = control_softc;
12140         struct ctl_lun *lun;
12141         uint32_t targ_lun;
12142
12143         /*
12144          * Look up the LUN.
12145          */
12146         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12147         mtx_lock(&softc->ctl_lock);
12148         if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
12149                 lun = softc->ctl_luns[targ_lun];
12150         else {
12151                 mtx_unlock(&softc->ctl_lock);
12152                 return (1);
12153         }
12154
12155         mtx_lock(&lun->lun_lock);
12156         mtx_unlock(&softc->ctl_lock);
12157         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12158                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12159                     io->io_hdr.nexus.initid.id,
12160                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12161         } else { /* CTL_TASK_CLEAR_TASK_SET */
12162                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12163                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12164         }
12165         mtx_unlock(&lun->lun_lock);
12166         return (0);
12167 }
12168
12169 static int
12170 ctl_i_t_nexus_reset(union ctl_io *io)
12171 {
12172         struct ctl_softc *softc = control_softc;
12173         struct ctl_lun *lun;
12174         uint32_t initidx, residx;
12175
12176         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12177         residx = ctl_get_resindex(&io->io_hdr.nexus);
12178         mtx_lock(&softc->ctl_lock);
12179         STAILQ_FOREACH(lun, &softc->lun_list, links) {
12180                 mtx_lock(&lun->lun_lock);
12181                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12182                     io->io_hdr.nexus.initid.id,
12183                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12184 #ifdef CTL_WITH_CA
12185                 ctl_clear_mask(lun->have_ca, initidx);
12186 #endif
12187                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
12188                         lun->flags &= ~CTL_LUN_RESERVED;
12189                 ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12190                 mtx_unlock(&lun->lun_lock);
12191         }
12192         mtx_unlock(&softc->ctl_lock);
12193         return (0);
12194 }
12195
12196 static int
12197 ctl_abort_task(union ctl_io *io)
12198 {
12199         union ctl_io *xio;
12200         struct ctl_lun *lun;
12201         struct ctl_softc *softc;
12202 #if 0
12203         struct sbuf sb;
12204         char printbuf[128];
12205 #endif
12206         int found;
12207         uint32_t targ_lun;
12208
12209         softc = control_softc;
12210         found = 0;
12211
12212         /*
12213          * Look up the LUN.
12214          */
12215         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12216         mtx_lock(&softc->ctl_lock);
12217         if ((targ_lun < CTL_MAX_LUNS)
12218          && (softc->ctl_luns[targ_lun] != NULL))
12219                 lun = softc->ctl_luns[targ_lun];
12220         else {
12221                 mtx_unlock(&softc->ctl_lock);
12222                 return (1);
12223         }
12224
12225 #if 0
12226         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12227                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12228 #endif
12229
12230         mtx_lock(&lun->lun_lock);
12231         mtx_unlock(&softc->ctl_lock);
12232         /*
12233          * Run through the OOA queue and attempt to find the given I/O.
12234          * The target port, initiator ID, tag type and tag number have to
12235          * match the values that we got from the initiator.  If we have an
12236          * untagged command to abort, simply abort the first untagged command
12237          * we come to.  We only allow one untagged command at a time of course.
12238          */
12239         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12240              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12241 #if 0
12242                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12243
12244                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12245                             lun->lun, xio->scsiio.tag_num,
12246                             xio->scsiio.tag_type,
12247                             (xio->io_hdr.blocked_links.tqe_prev
12248                             == NULL) ? "" : " BLOCKED",
12249                             (xio->io_hdr.flags &
12250                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12251                             (xio->io_hdr.flags &
12252                             CTL_FLAG_ABORT) ? " ABORT" : "",
12253                             (xio->io_hdr.flags &
12254                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12255                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12256                 sbuf_finish(&sb);
12257                 printf("%s\n", sbuf_data(&sb));
12258 #endif
12259
12260                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12261                  || (xio->io_hdr.nexus.initid.id != io->io_hdr.nexus.initid.id)
12262                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12263                         continue;
12264
12265                 /*
12266                  * If the abort says that the task is untagged, the
12267                  * task in the queue must be untagged.  Otherwise,
12268                  * we just check to see whether the tag numbers
12269                  * match.  This is because the QLogic firmware
12270                  * doesn't pass back the tag type in an abort
12271                  * request.
12272                  */
12273 #if 0
12274                 if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12275                   && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12276                  || (xio->scsiio.tag_num == io->taskio.tag_num))
12277 #endif
12278                 /*
12279                  * XXX KDM we've got problems with FC, because it
12280                  * doesn't send down a tag type with aborts.  So we
12281                  * can only really go by the tag number...
12282                  * This may cause problems with parallel SCSI.
12283                  * Need to figure that out!!
12284                  */
12285                 if (xio->scsiio.tag_num == io->taskio.tag_num) {
12286                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12287                         found = 1;
12288                         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12289                             !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12290                                 union ctl_ha_msg msg_info;
12291
12292                                 io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
12293                                 msg_info.hdr.nexus = io->io_hdr.nexus;
12294                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12295                                 msg_info.task.tag_num = io->taskio.tag_num;
12296                                 msg_info.task.tag_type = io->taskio.tag_type;
12297                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12298                                 msg_info.hdr.original_sc = NULL;
12299                                 msg_info.hdr.serializing_sc = NULL;
12300 #if 0
12301                                 printf("Sent Abort to other side\n");
12302 #endif
12303                                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12304                                     (void *)&msg_info, sizeof(msg_info), 0) !=
12305                                     CTL_HA_STATUS_SUCCESS) {
12306                                 }
12307                         }
12308 #if 0
12309                         printf("ctl_abort_task: found I/O to abort\n");
12310 #endif
12311                 }
12312         }
12313         mtx_unlock(&lun->lun_lock);
12314
12315         if (found == 0) {
12316                 /*
12317                  * This isn't really an error.  It's entirely possible for
12318                  * the abort and command completion to cross on the wire.
12319                  * This is more of an informative/diagnostic error.
12320                  */
12321 #if 0
12322                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12323                        "%d:%d:%d:%d tag %d type %d\n",
12324                        io->io_hdr.nexus.initid.id,
12325                        io->io_hdr.nexus.targ_port,
12326                        io->io_hdr.nexus.targ_target.id,
12327                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12328                        io->taskio.tag_type);
12329 #endif
12330         }
12331         return (0);
12332 }
12333
12334 static void
12335 ctl_run_task(union ctl_io *io)
12336 {
12337         struct ctl_softc *softc = control_softc;
12338         int retval = 1;
12339         const char *task_desc;
12340
12341         CTL_DEBUG_PRINT(("ctl_run_task\n"));
12342
12343         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12344             ("ctl_run_task: Unextected io_type %d\n",
12345              io->io_hdr.io_type));
12346
12347         task_desc = ctl_scsi_task_string(&io->taskio);
12348         if (task_desc != NULL) {
12349 #ifdef NEEDTOPORT
12350                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12351                             CTL_TASK_REPORT,
12352                             csevent_LogType_Trace,
12353                             csevent_Severity_Information,
12354                             csevent_AlertLevel_Green,
12355                             csevent_FRU_Firmware,
12356                             csevent_FRU_Unknown,
12357                             "CTL: received task: %s",task_desc);
12358 #endif
12359         } else {
12360 #ifdef NEEDTOPORT
12361                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12362                             CTL_TASK_REPORT,
12363                             csevent_LogType_Trace,
12364                             csevent_Severity_Information,
12365                             csevent_AlertLevel_Green,
12366                             csevent_FRU_Firmware,
12367                             csevent_FRU_Unknown,
12368                             "CTL: received unknown task "
12369                             "type: %d (%#x)",
12370                             io->taskio.task_action,
12371                             io->taskio.task_action);
12372 #endif
12373         }
12374         switch (io->taskio.task_action) {
12375         case CTL_TASK_ABORT_TASK:
12376                 retval = ctl_abort_task(io);
12377                 break;
12378         case CTL_TASK_ABORT_TASK_SET:
12379         case CTL_TASK_CLEAR_TASK_SET:
12380                 retval = ctl_abort_task_set(io);
12381                 break;
12382         case CTL_TASK_CLEAR_ACA:
12383                 break;
12384         case CTL_TASK_I_T_NEXUS_RESET:
12385                 retval = ctl_i_t_nexus_reset(io);
12386                 break;
12387         case CTL_TASK_LUN_RESET: {
12388                 struct ctl_lun *lun;
12389                 uint32_t targ_lun;
12390
12391                 targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12392                 mtx_lock(&softc->ctl_lock);
12393                 if ((targ_lun < CTL_MAX_LUNS)
12394                  && (softc->ctl_luns[targ_lun] != NULL))
12395                         lun = softc->ctl_luns[targ_lun];
12396                 else {
12397                         mtx_unlock(&softc->ctl_lock);
12398                         retval = 1;
12399                         break;
12400                 }
12401
12402                 if (!(io->io_hdr.flags &
12403                     CTL_FLAG_FROM_OTHER_SC)) {
12404                         union ctl_ha_msg msg_info;
12405
12406                         io->io_hdr.flags |=
12407                                 CTL_FLAG_SENT_2OTHER_SC;
12408                         msg_info.hdr.msg_type =
12409                                 CTL_MSG_MANAGE_TASKS;
12410                         msg_info.hdr.nexus = io->io_hdr.nexus;
12411                         msg_info.task.task_action =
12412                                 CTL_TASK_LUN_RESET;
12413                         msg_info.hdr.original_sc = NULL;
12414                         msg_info.hdr.serializing_sc = NULL;
12415                         if (CTL_HA_STATUS_SUCCESS !=
12416                             ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12417                             (void *)&msg_info,
12418                             sizeof(msg_info), 0)) {
12419                         }
12420                 }
12421
12422                 retval = ctl_lun_reset(lun, io,
12423                                        CTL_UA_LUN_RESET);
12424                 mtx_unlock(&softc->ctl_lock);
12425                 break;
12426         }
12427         case CTL_TASK_TARGET_RESET:
12428                 retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12429                 break;
12430         case CTL_TASK_BUS_RESET:
12431                 retval = ctl_bus_reset(softc, io);
12432                 break;
12433         case CTL_TASK_PORT_LOGIN:
12434                 break;
12435         case CTL_TASK_PORT_LOGOUT:
12436                 break;
12437         default:
12438                 printf("ctl_run_task: got unknown task management event %d\n",
12439                        io->taskio.task_action);
12440                 break;
12441         }
12442         if (retval == 0)
12443                 io->io_hdr.status = CTL_SUCCESS;
12444         else
12445                 io->io_hdr.status = CTL_ERROR;
12446         ctl_done(io);
12447 }
12448
12449 /*
12450  * For HA operation.  Handle commands that come in from the other
12451  * controller.
12452  */
12453 static void
12454 ctl_handle_isc(union ctl_io *io)
12455 {
12456         int free_io;
12457         struct ctl_lun *lun;
12458         struct ctl_softc *softc;
12459         uint32_t targ_lun;
12460
12461         softc = control_softc;
12462
12463         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12464         lun = softc->ctl_luns[targ_lun];
12465
12466         switch (io->io_hdr.msg_type) {
12467         case CTL_MSG_SERIALIZE:
12468                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12469                 break;
12470         case CTL_MSG_R2R: {
12471                 const struct ctl_cmd_entry *entry;
12472
12473                 /*
12474                  * This is only used in SER_ONLY mode.
12475                  */
12476                 free_io = 0;
12477                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12478                 mtx_lock(&lun->lun_lock);
12479                 if (ctl_scsiio_lun_check(lun,
12480                     entry, (struct ctl_scsiio *)io) != 0) {
12481                         mtx_unlock(&lun->lun_lock);
12482                         ctl_done(io);
12483                         break;
12484                 }
12485                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12486                 mtx_unlock(&lun->lun_lock);
12487                 ctl_enqueue_rtr(io);
12488                 break;
12489         }
12490         case CTL_MSG_FINISH_IO:
12491                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
12492                         free_io = 0;
12493                         ctl_done(io);
12494                 } else {
12495                         free_io = 1;
12496                         mtx_lock(&lun->lun_lock);
12497                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12498                                      ooa_links);
12499                         ctl_check_blocked(lun);
12500                         mtx_unlock(&lun->lun_lock);
12501                 }
12502                 break;
12503         case CTL_MSG_PERS_ACTION:
12504                 ctl_hndl_per_res_out_on_other_sc(
12505                         (union ctl_ha_msg *)&io->presio.pr_msg);
12506                 free_io = 1;
12507                 break;
12508         case CTL_MSG_BAD_JUJU:
12509                 free_io = 0;
12510                 ctl_done(io);
12511                 break;
12512         case CTL_MSG_DATAMOVE:
12513                 /* Only used in XFER mode */
12514                 free_io = 0;
12515                 ctl_datamove_remote(io);
12516                 break;
12517         case CTL_MSG_DATAMOVE_DONE:
12518                 /* Only used in XFER mode */
12519                 free_io = 0;
12520                 io->scsiio.be_move_done(io);
12521                 break;
12522         default:
12523                 free_io = 1;
12524                 printf("%s: Invalid message type %d\n",
12525                        __func__, io->io_hdr.msg_type);
12526                 break;
12527         }
12528         if (free_io)
12529                 ctl_free_io(io);
12530
12531 }
12532
12533
12534 /*
12535  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12536  * there is no match.
12537  */
12538 static ctl_lun_error_pattern
12539 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12540 {
12541         const struct ctl_cmd_entry *entry;
12542         ctl_lun_error_pattern filtered_pattern, pattern;
12543
12544         pattern = desc->error_pattern;
12545
12546         /*
12547          * XXX KDM we need more data passed into this function to match a
12548          * custom pattern, and we actually need to implement custom pattern
12549          * matching.
12550          */
12551         if (pattern & CTL_LUN_PAT_CMD)
12552                 return (CTL_LUN_PAT_CMD);
12553
12554         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12555                 return (CTL_LUN_PAT_ANY);
12556
12557         entry = ctl_get_cmd_entry(ctsio, NULL);
12558
12559         filtered_pattern = entry->pattern & pattern;
12560
12561         /*
12562          * If the user requested specific flags in the pattern (e.g.
12563          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12564          * flags.
12565          *
12566          * If the user did not specify any flags, it doesn't matter whether
12567          * or not the command supports the flags.
12568          */
12569         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12570              (pattern & ~CTL_LUN_PAT_MASK))
12571                 return (CTL_LUN_PAT_NONE);
12572
12573         /*
12574          * If the user asked for a range check, see if the requested LBA
12575          * range overlaps with this command's LBA range.
12576          */
12577         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12578                 uint64_t lba1;
12579                 uint64_t len1;
12580                 ctl_action action;
12581                 int retval;
12582
12583                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12584                 if (retval != 0)
12585                         return (CTL_LUN_PAT_NONE);
12586
12587                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12588                                               desc->lba_range.len, FALSE);
12589                 /*
12590                  * A "pass" means that the LBA ranges don't overlap, so
12591                  * this doesn't match the user's range criteria.
12592                  */
12593                 if (action == CTL_ACTION_PASS)
12594                         return (CTL_LUN_PAT_NONE);
12595         }
12596
12597         return (filtered_pattern);
12598 }
12599
12600 static void
12601 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12602 {
12603         struct ctl_error_desc *desc, *desc2;
12604
12605         mtx_assert(&lun->lun_lock, MA_OWNED);
12606
12607         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12608                 ctl_lun_error_pattern pattern;
12609                 /*
12610                  * Check to see whether this particular command matches
12611                  * the pattern in the descriptor.
12612                  */
12613                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12614                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12615                         continue;
12616
12617                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12618                 case CTL_LUN_INJ_ABORTED:
12619                         ctl_set_aborted(&io->scsiio);
12620                         break;
12621                 case CTL_LUN_INJ_MEDIUM_ERR:
12622                         ctl_set_medium_error(&io->scsiio);
12623                         break;
12624                 case CTL_LUN_INJ_UA:
12625                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12626                          * OCCURRED */
12627                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12628                         break;
12629                 case CTL_LUN_INJ_CUSTOM:
12630                         /*
12631                          * We're assuming the user knows what he is doing.
12632                          * Just copy the sense information without doing
12633                          * checks.
12634                          */
12635                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12636                               MIN(sizeof(desc->custom_sense),
12637                                   sizeof(io->scsiio.sense_data)));
12638                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12639                         io->scsiio.sense_len = SSD_FULL_SIZE;
12640                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12641                         break;
12642                 case CTL_LUN_INJ_NONE:
12643                 default:
12644                         /*
12645                          * If this is an error injection type we don't know
12646                          * about, clear the continuous flag (if it is set)
12647                          * so it will get deleted below.
12648                          */
12649                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12650                         break;
12651                 }
12652                 /*
12653                  * By default, each error injection action is a one-shot
12654                  */
12655                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12656                         continue;
12657
12658                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12659
12660                 free(desc, M_CTL);
12661         }
12662 }
12663
12664 #ifdef CTL_IO_DELAY
12665 static void
12666 ctl_datamove_timer_wakeup(void *arg)
12667 {
12668         union ctl_io *io;
12669
12670         io = (union ctl_io *)arg;
12671
12672         ctl_datamove(io);
12673 }
12674 #endif /* CTL_IO_DELAY */
12675
12676 void
12677 ctl_datamove(union ctl_io *io)
12678 {
12679         void (*fe_datamove)(union ctl_io *io);
12680
12681         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12682
12683         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12684
12685 #ifdef CTL_TIME_IO
12686         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12687                 char str[256];
12688                 char path_str[64];
12689                 struct sbuf sb;
12690
12691                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12692                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12693
12694                 sbuf_cat(&sb, path_str);
12695                 switch (io->io_hdr.io_type) {
12696                 case CTL_IO_SCSI:
12697                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12698                         sbuf_printf(&sb, "\n");
12699                         sbuf_cat(&sb, path_str);
12700                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12701                                     io->scsiio.tag_num, io->scsiio.tag_type);
12702                         break;
12703                 case CTL_IO_TASK:
12704                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12705                                     "Tag Type: %d\n", io->taskio.task_action,
12706                                     io->taskio.tag_num, io->taskio.tag_type);
12707                         break;
12708                 default:
12709                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12710                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12711                         break;
12712                 }
12713                 sbuf_cat(&sb, path_str);
12714                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12715                             (intmax_t)time_uptime - io->io_hdr.start_time);
12716                 sbuf_finish(&sb);
12717                 printf("%s", sbuf_data(&sb));
12718         }
12719 #endif /* CTL_TIME_IO */
12720
12721 #ifdef CTL_IO_DELAY
12722         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12723                 struct ctl_lun *lun;
12724
12725                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12726
12727                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12728         } else {
12729                 struct ctl_lun *lun;
12730
12731                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12732                 if ((lun != NULL)
12733                  && (lun->delay_info.datamove_delay > 0)) {
12734                         struct callout *callout;
12735
12736                         callout = (struct callout *)&io->io_hdr.timer_bytes;
12737                         callout_init(callout, /*mpsafe*/ 1);
12738                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12739                         callout_reset(callout,
12740                                       lun->delay_info.datamove_delay * hz,
12741                                       ctl_datamove_timer_wakeup, io);
12742                         if (lun->delay_info.datamove_type ==
12743                             CTL_DELAY_TYPE_ONESHOT)
12744                                 lun->delay_info.datamove_delay = 0;
12745                         return;
12746                 }
12747         }
12748 #endif
12749
12750         /*
12751          * This command has been aborted.  Set the port status, so we fail
12752          * the data move.
12753          */
12754         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12755                 printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12756                        io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12757                        io->io_hdr.nexus.targ_port,
12758                        (uintmax_t)io->io_hdr.nexus.targ_target.id,
12759                        io->io_hdr.nexus.targ_lun);
12760                 io->io_hdr.port_status = 31337;
12761                 /*
12762                  * Note that the backend, in this case, will get the
12763                  * callback in its context.  In other cases it may get
12764                  * called in the frontend's interrupt thread context.
12765                  */
12766                 io->scsiio.be_move_done(io);
12767                 return;
12768         }
12769
12770         /* Don't confuse frontend with zero length data move. */
12771         if (io->scsiio.kern_data_len == 0) {
12772                 io->scsiio.be_move_done(io);
12773                 return;
12774         }
12775
12776         /*
12777          * If we're in XFER mode and this I/O is from the other shelf
12778          * controller, we need to send the DMA to the other side to
12779          * actually transfer the data to/from the host.  In serialize only
12780          * mode the transfer happens below CTL and ctl_datamove() is only
12781          * called on the machine that originally received the I/O.
12782          */
12783         if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12784          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12785                 union ctl_ha_msg msg;
12786                 uint32_t sg_entries_sent;
12787                 int do_sg_copy;
12788                 int i;
12789
12790                 memset(&msg, 0, sizeof(msg));
12791                 msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12792                 msg.hdr.original_sc = io->io_hdr.original_sc;
12793                 msg.hdr.serializing_sc = io;
12794                 msg.hdr.nexus = io->io_hdr.nexus;
12795                 msg.dt.flags = io->io_hdr.flags;
12796                 /*
12797                  * We convert everything into a S/G list here.  We can't
12798                  * pass by reference, only by value between controllers.
12799                  * So we can't pass a pointer to the S/G list, only as many
12800                  * S/G entries as we can fit in here.  If it's possible for
12801                  * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12802                  * then we need to break this up into multiple transfers.
12803                  */
12804                 if (io->scsiio.kern_sg_entries == 0) {
12805                         msg.dt.kern_sg_entries = 1;
12806                         /*
12807                          * If this is in cached memory, flush the cache
12808                          * before we send the DMA request to the other
12809                          * controller.  We want to do this in either the
12810                          * read or the write case.  The read case is
12811                          * straightforward.  In the write case, we want to
12812                          * make sure nothing is in the local cache that
12813                          * could overwrite the DMAed data.
12814                          */
12815                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12816                                 /*
12817                                  * XXX KDM use bus_dmamap_sync() here.
12818                                  */
12819                         }
12820
12821                         /*
12822                          * Convert to a physical address if this is a
12823                          * virtual address.
12824                          */
12825                         if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12826                                 msg.dt.sg_list[0].addr =
12827                                         io->scsiio.kern_data_ptr;
12828                         } else {
12829                                 /*
12830                                  * XXX KDM use busdma here!
12831                                  */
12832 #if 0
12833                                 msg.dt.sg_list[0].addr = (void *)
12834                                         vtophys(io->scsiio.kern_data_ptr);
12835 #endif
12836                         }
12837
12838                         msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12839                         do_sg_copy = 0;
12840                 } else {
12841                         struct ctl_sg_entry *sgl;
12842
12843                         do_sg_copy = 1;
12844                         msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12845                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12846                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12847                                 /*
12848                                  * XXX KDM use bus_dmamap_sync() here.
12849                                  */
12850                         }
12851                 }
12852
12853                 msg.dt.kern_data_len = io->scsiio.kern_data_len;
12854                 msg.dt.kern_total_len = io->scsiio.kern_total_len;
12855                 msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12856                 msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12857                 msg.dt.sg_sequence = 0;
12858
12859                 /*
12860                  * Loop until we've sent all of the S/G entries.  On the
12861                  * other end, we'll recompose these S/G entries into one
12862                  * contiguous list before passing it to the
12863                  */
12864                 for (sg_entries_sent = 0; sg_entries_sent <
12865                      msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12866                         msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list)/
12867                                 sizeof(msg.dt.sg_list[0])),
12868                                 msg.dt.kern_sg_entries - sg_entries_sent);
12869
12870                         if (do_sg_copy != 0) {
12871                                 struct ctl_sg_entry *sgl;
12872                                 int j;
12873
12874                                 sgl = (struct ctl_sg_entry *)
12875                                         io->scsiio.kern_data_ptr;
12876                                 /*
12877                                  * If this is in cached memory, flush the cache
12878                                  * before we send the DMA request to the other
12879                                  * controller.  We want to do this in either
12880                                  * the * read or the write case.  The read
12881                                  * case is straightforward.  In the write
12882                                  * case, we want to make sure nothing is
12883                                  * in the local cache that could overwrite
12884                                  * the DMAed data.
12885                                  */
12886
12887                                 for (i = sg_entries_sent, j = 0;
12888                                      i < msg.dt.cur_sg_entries; i++, j++) {
12889                                         if ((io->io_hdr.flags &
12890                                              CTL_FLAG_NO_DATASYNC) == 0) {
12891                                                 /*
12892                                                  * XXX KDM use bus_dmamap_sync()
12893                                                  */
12894                                         }
12895                                         if ((io->io_hdr.flags &
12896                                              CTL_FLAG_BUS_ADDR) == 0) {
12897                                                 /*
12898                                                  * XXX KDM use busdma.
12899                                                  */
12900 #if 0
12901                                                 msg.dt.sg_list[j].addr =(void *)
12902                                                        vtophys(sgl[i].addr);
12903 #endif
12904                                         } else {
12905                                                 msg.dt.sg_list[j].addr =
12906                                                         sgl[i].addr;
12907                                         }
12908                                         msg.dt.sg_list[j].len = sgl[i].len;
12909                                 }
12910                         }
12911
12912                         sg_entries_sent += msg.dt.cur_sg_entries;
12913                         if (sg_entries_sent >= msg.dt.kern_sg_entries)
12914                                 msg.dt.sg_last = 1;
12915                         else
12916                                 msg.dt.sg_last = 0;
12917
12918                         /*
12919                          * XXX KDM drop and reacquire the lock here?
12920                          */
12921                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12922                             sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12923                                 /*
12924                                  * XXX do something here.
12925                                  */
12926                         }
12927
12928                         msg.dt.sent_sg_entries = sg_entries_sent;
12929                 }
12930                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12931                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12932                         ctl_failover_io(io, /*have_lock*/ 0);
12933
12934         } else {
12935
12936                 /*
12937                  * Lookup the fe_datamove() function for this particular
12938                  * front end.
12939                  */
12940                 fe_datamove =
12941                     control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12942
12943                 fe_datamove(io);
12944         }
12945 }
12946
12947 static void
12948 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12949 {
12950         union ctl_ha_msg msg;
12951         int isc_status;
12952
12953         memset(&msg, 0, sizeof(msg));
12954
12955         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12956         msg.hdr.original_sc = io;
12957         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12958         msg.hdr.nexus = io->io_hdr.nexus;
12959         msg.hdr.status = io->io_hdr.status;
12960         msg.scsi.tag_num = io->scsiio.tag_num;
12961         msg.scsi.tag_type = io->scsiio.tag_type;
12962         msg.scsi.scsi_status = io->scsiio.scsi_status;
12963         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12964                sizeof(io->scsiio.sense_data));
12965         msg.scsi.sense_len = io->scsiio.sense_len;
12966         msg.scsi.sense_residual = io->scsiio.sense_residual;
12967         msg.scsi.fetd_status = io->io_hdr.port_status;
12968         msg.scsi.residual = io->scsiio.residual;
12969         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12970
12971         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12972                 ctl_failover_io(io, /*have_lock*/ have_lock);
12973                 return;
12974         }
12975
12976         isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12977         if (isc_status > CTL_HA_STATUS_SUCCESS) {
12978                 /* XXX do something if this fails */
12979         }
12980
12981 }
12982
12983 /*
12984  * The DMA to the remote side is done, now we need to tell the other side
12985  * we're done so it can continue with its data movement.
12986  */
12987 static void
12988 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12989 {
12990         union ctl_io *io;
12991
12992         io = rq->context;
12993
12994         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12995                 printf("%s: ISC DMA write failed with error %d", __func__,
12996                        rq->ret);
12997                 ctl_set_internal_failure(&io->scsiio,
12998                                          /*sks_valid*/ 1,
12999                                          /*retry_count*/ rq->ret);
13000         }
13001
13002         ctl_dt_req_free(rq);
13003
13004         /*
13005          * In this case, we had to malloc the memory locally.  Free it.
13006          */
13007         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13008                 int i;
13009                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13010                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13011         }
13012         /*
13013          * The data is in local and remote memory, so now we need to send
13014          * status (good or back) back to the other side.
13015          */
13016         ctl_send_datamove_done(io, /*have_lock*/ 0);
13017 }
13018
13019 /*
13020  * We've moved the data from the host/controller into local memory.  Now we
13021  * need to push it over to the remote controller's memory.
13022  */
13023 static int
13024 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
13025 {
13026         int retval;
13027
13028         retval = 0;
13029
13030         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
13031                                           ctl_datamove_remote_write_cb);
13032
13033         return (retval);
13034 }
13035
13036 static void
13037 ctl_datamove_remote_write(union ctl_io *io)
13038 {
13039         int retval;
13040         void (*fe_datamove)(union ctl_io *io);
13041
13042         /*
13043          * - Get the data from the host/HBA into local memory.
13044          * - DMA memory from the local controller to the remote controller.
13045          * - Send status back to the remote controller.
13046          */
13047
13048         retval = ctl_datamove_remote_sgl_setup(io);
13049         if (retval != 0)
13050                 return;
13051
13052         /* Switch the pointer over so the FETD knows what to do */
13053         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13054
13055         /*
13056          * Use a custom move done callback, since we need to send completion
13057          * back to the other controller, not to the backend on this side.
13058          */
13059         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
13060
13061         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13062
13063         fe_datamove(io);
13064
13065         return;
13066
13067 }
13068
13069 static int
13070 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
13071 {
13072 #if 0
13073         char str[256];
13074         char path_str[64];
13075         struct sbuf sb;
13076 #endif
13077
13078         /*
13079          * In this case, we had to malloc the memory locally.  Free it.
13080          */
13081         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13082                 int i;
13083                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13084                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13085         }
13086
13087 #if 0
13088         scsi_path_string(io, path_str, sizeof(path_str));
13089         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13090         sbuf_cat(&sb, path_str);
13091         scsi_command_string(&io->scsiio, NULL, &sb);
13092         sbuf_printf(&sb, "\n");
13093         sbuf_cat(&sb, path_str);
13094         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13095                     io->scsiio.tag_num, io->scsiio.tag_type);
13096         sbuf_cat(&sb, path_str);
13097         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
13098                     io->io_hdr.flags, io->io_hdr.status);
13099         sbuf_finish(&sb);
13100         printk("%s", sbuf_data(&sb));
13101 #endif
13102
13103
13104         /*
13105          * The read is done, now we need to send status (good or bad) back
13106          * to the other side.
13107          */
13108         ctl_send_datamove_done(io, /*have_lock*/ 0);
13109
13110         return (0);
13111 }
13112
13113 static void
13114 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
13115 {
13116         union ctl_io *io;
13117         void (*fe_datamove)(union ctl_io *io);
13118
13119         io = rq->context;
13120
13121         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13122                 printf("%s: ISC DMA read failed with error %d", __func__,
13123                        rq->ret);
13124                 ctl_set_internal_failure(&io->scsiio,
13125                                          /*sks_valid*/ 1,
13126                                          /*retry_count*/ rq->ret);
13127         }
13128
13129         ctl_dt_req_free(rq);
13130
13131         /* Switch the pointer over so the FETD knows what to do */
13132         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13133
13134         /*
13135          * Use a custom move done callback, since we need to send completion
13136          * back to the other controller, not to the backend on this side.
13137          */
13138         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13139
13140         /* XXX KDM add checks like the ones in ctl_datamove? */
13141
13142         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13143
13144         fe_datamove(io);
13145 }
13146
13147 static int
13148 ctl_datamove_remote_sgl_setup(union ctl_io *io)
13149 {
13150         struct ctl_sg_entry *local_sglist, *remote_sglist;
13151         struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13152         struct ctl_softc *softc;
13153         int retval;
13154         int i;
13155
13156         retval = 0;
13157         softc = control_softc;
13158
13159         local_sglist = io->io_hdr.local_sglist;
13160         local_dma_sglist = io->io_hdr.local_dma_sglist;
13161         remote_sglist = io->io_hdr.remote_sglist;
13162         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13163
13164         if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13165                 for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13166                         local_sglist[i].len = remote_sglist[i].len;
13167
13168                         /*
13169                          * XXX Detect the situation where the RS-level I/O
13170                          * redirector on the other side has already read the
13171                          * data off of the AOR RS on this side, and
13172                          * transferred it to remote (mirror) memory on the
13173                          * other side.  Since we already have the data in
13174                          * memory here, we just need to use it.
13175                          *
13176                          * XXX KDM this can probably be removed once we
13177                          * get the cache device code in and take the
13178                          * current AOR implementation out.
13179                          */
13180 #ifdef NEEDTOPORT
13181                         if ((remote_sglist[i].addr >=
13182                              (void *)vtophys(softc->mirr->addr))
13183                          && (remote_sglist[i].addr <
13184                              ((void *)vtophys(softc->mirr->addr) +
13185                              CacheMirrorOffset))) {
13186                                 local_sglist[i].addr = remote_sglist[i].addr -
13187                                         CacheMirrorOffset;
13188                                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13189                                      CTL_FLAG_DATA_IN)
13190                                         io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13191                         } else {
13192                                 local_sglist[i].addr = remote_sglist[i].addr +
13193                                         CacheMirrorOffset;
13194                         }
13195 #endif
13196 #if 0
13197                         printf("%s: local %p, remote %p, len %d\n",
13198                                __func__, local_sglist[i].addr,
13199                                remote_sglist[i].addr, local_sglist[i].len);
13200 #endif
13201                 }
13202         } else {
13203                 uint32_t len_to_go;
13204
13205                 /*
13206                  * In this case, we don't have automatically allocated
13207                  * memory for this I/O on this controller.  This typically
13208                  * happens with internal CTL I/O -- e.g. inquiry, mode
13209                  * sense, etc.  Anything coming from RAIDCore will have
13210                  * a mirror area available.
13211                  */
13212                 len_to_go = io->scsiio.kern_data_len;
13213
13214                 /*
13215                  * Clear the no datasync flag, we have to use malloced
13216                  * buffers.
13217                  */
13218                 io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13219
13220                 /*
13221                  * The difficult thing here is that the size of the various
13222                  * S/G segments may be different than the size from the
13223                  * remote controller.  That'll make it harder when DMAing
13224                  * the data back to the other side.
13225                  */
13226                 for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13227                      sizeof(io->io_hdr.remote_sglist[0])) &&
13228                      (len_to_go > 0); i++) {
13229                         local_sglist[i].len = MIN(len_to_go, 131072);
13230                         CTL_SIZE_8B(local_dma_sglist[i].len,
13231                                     local_sglist[i].len);
13232                         local_sglist[i].addr =
13233                                 malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13234
13235                         local_dma_sglist[i].addr = local_sglist[i].addr;
13236
13237                         if (local_sglist[i].addr == NULL) {
13238                                 int j;
13239
13240                                 printf("malloc failed for %zd bytes!",
13241                                        local_dma_sglist[i].len);
13242                                 for (j = 0; j < i; j++) {
13243                                         free(local_sglist[j].addr, M_CTL);
13244                                 }
13245                                 ctl_set_internal_failure(&io->scsiio,
13246                                                          /*sks_valid*/ 1,
13247                                                          /*retry_count*/ 4857);
13248                                 retval = 1;
13249                                 goto bailout_error;
13250                                 
13251                         }
13252                         /* XXX KDM do we need a sync here? */
13253
13254                         len_to_go -= local_sglist[i].len;
13255                 }
13256                 /*
13257                  * Reset the number of S/G entries accordingly.  The
13258                  * original number of S/G entries is available in
13259                  * rem_sg_entries.
13260                  */
13261                 io->scsiio.kern_sg_entries = i;
13262
13263 #if 0
13264                 printf("%s: kern_sg_entries = %d\n", __func__,
13265                        io->scsiio.kern_sg_entries);
13266                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13267                         printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13268                                local_sglist[i].addr, local_sglist[i].len,
13269                                local_dma_sglist[i].len);
13270 #endif
13271         }
13272
13273
13274         return (retval);
13275
13276 bailout_error:
13277
13278         ctl_send_datamove_done(io, /*have_lock*/ 0);
13279
13280         return (retval);
13281 }
13282
13283 static int
13284 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13285                          ctl_ha_dt_cb callback)
13286 {
13287         struct ctl_ha_dt_req *rq;
13288         struct ctl_sg_entry *remote_sglist, *local_sglist;
13289         struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13290         uint32_t local_used, remote_used, total_used;
13291         int retval;
13292         int i, j;
13293
13294         retval = 0;
13295
13296         rq = ctl_dt_req_alloc();
13297
13298         /*
13299          * If we failed to allocate the request, and if the DMA didn't fail
13300          * anyway, set busy status.  This is just a resource allocation
13301          * failure.
13302          */
13303         if ((rq == NULL)
13304          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13305                 ctl_set_busy(&io->scsiio);
13306
13307         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13308
13309                 if (rq != NULL)
13310                         ctl_dt_req_free(rq);
13311
13312                 /*
13313                  * The data move failed.  We need to return status back
13314                  * to the other controller.  No point in trying to DMA
13315                  * data to the remote controller.
13316                  */
13317
13318                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13319
13320                 retval = 1;
13321
13322                 goto bailout;
13323         }
13324
13325         local_sglist = io->io_hdr.local_sglist;
13326         local_dma_sglist = io->io_hdr.local_dma_sglist;
13327         remote_sglist = io->io_hdr.remote_sglist;
13328         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13329         local_used = 0;
13330         remote_used = 0;
13331         total_used = 0;
13332
13333         if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13334                 rq->ret = CTL_HA_STATUS_SUCCESS;
13335                 rq->context = io;
13336                 callback(rq);
13337                 goto bailout;
13338         }
13339
13340         /*
13341          * Pull/push the data over the wire from/to the other controller.
13342          * This takes into account the possibility that the local and
13343          * remote sglists may not be identical in terms of the size of
13344          * the elements and the number of elements.
13345          *
13346          * One fundamental assumption here is that the length allocated for
13347          * both the local and remote sglists is identical.  Otherwise, we've
13348          * essentially got a coding error of some sort.
13349          */
13350         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13351                 int isc_ret;
13352                 uint32_t cur_len, dma_length;
13353                 uint8_t *tmp_ptr;
13354
13355                 rq->id = CTL_HA_DATA_CTL;
13356                 rq->command = command;
13357                 rq->context = io;
13358
13359                 /*
13360                  * Both pointers should be aligned.  But it is possible
13361                  * that the allocation length is not.  They should both
13362                  * also have enough slack left over at the end, though,
13363                  * to round up to the next 8 byte boundary.
13364                  */
13365                 cur_len = MIN(local_sglist[i].len - local_used,
13366                               remote_sglist[j].len - remote_used);
13367
13368                 /*
13369                  * In this case, we have a size issue and need to decrease
13370                  * the size, except in the case where we actually have less
13371                  * than 8 bytes left.  In that case, we need to increase
13372                  * the DMA length to get the last bit.
13373                  */
13374                 if ((cur_len & 0x7) != 0) {
13375                         if (cur_len > 0x7) {
13376                                 cur_len = cur_len - (cur_len & 0x7);
13377                                 dma_length = cur_len;
13378                         } else {
13379                                 CTL_SIZE_8B(dma_length, cur_len);
13380                         }
13381
13382                 } else
13383                         dma_length = cur_len;
13384
13385                 /*
13386                  * If we had to allocate memory for this I/O, instead of using
13387                  * the non-cached mirror memory, we'll need to flush the cache
13388                  * before trying to DMA to the other controller.
13389                  *
13390                  * We could end up doing this multiple times for the same
13391                  * segment if we have a larger local segment than remote
13392                  * segment.  That shouldn't be an issue.
13393                  */
13394                 if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13395                         /*
13396                          * XXX KDM use bus_dmamap_sync() here.
13397                          */
13398                 }
13399
13400                 rq->size = dma_length;
13401
13402                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
13403                 tmp_ptr += local_used;
13404
13405                 /* Use physical addresses when talking to ISC hardware */
13406                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13407                         /* XXX KDM use busdma */
13408 #if 0
13409                         rq->local = vtophys(tmp_ptr);
13410 #endif
13411                 } else
13412                         rq->local = tmp_ptr;
13413
13414                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13415                 tmp_ptr += remote_used;
13416                 rq->remote = tmp_ptr;
13417
13418                 rq->callback = NULL;
13419
13420                 local_used += cur_len;
13421                 if (local_used >= local_sglist[i].len) {
13422                         i++;
13423                         local_used = 0;
13424                 }
13425
13426                 remote_used += cur_len;
13427                 if (remote_used >= remote_sglist[j].len) {
13428                         j++;
13429                         remote_used = 0;
13430                 }
13431                 total_used += cur_len;
13432
13433                 if (total_used >= io->scsiio.kern_data_len)
13434                         rq->callback = callback;
13435
13436                 if ((rq->size & 0x7) != 0) {
13437                         printf("%s: warning: size %d is not on 8b boundary\n",
13438                                __func__, rq->size);
13439                 }
13440                 if (((uintptr_t)rq->local & 0x7) != 0) {
13441                         printf("%s: warning: local %p not on 8b boundary\n",
13442                                __func__, rq->local);
13443                 }
13444                 if (((uintptr_t)rq->remote & 0x7) != 0) {
13445                         printf("%s: warning: remote %p not on 8b boundary\n",
13446                                __func__, rq->local);
13447                 }
13448 #if 0
13449                 printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13450                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13451                        rq->local, rq->remote, rq->size);
13452 #endif
13453
13454                 isc_ret = ctl_dt_single(rq);
13455                 if (isc_ret == CTL_HA_STATUS_WAIT)
13456                         continue;
13457
13458                 if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13459                         rq->ret = CTL_HA_STATUS_SUCCESS;
13460                 } else {
13461                         rq->ret = isc_ret;
13462                 }
13463                 callback(rq);
13464                 goto bailout;
13465         }
13466
13467 bailout:
13468         return (retval);
13469
13470 }
13471
13472 static void
13473 ctl_datamove_remote_read(union ctl_io *io)
13474 {
13475         int retval;
13476         int i;
13477
13478         /*
13479          * This will send an error to the other controller in the case of a
13480          * failure.
13481          */
13482         retval = ctl_datamove_remote_sgl_setup(io);
13483         if (retval != 0)
13484                 return;
13485
13486         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13487                                           ctl_datamove_remote_read_cb);
13488         if ((retval != 0)
13489          && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13490                 /*
13491                  * Make sure we free memory if there was an error..  The
13492                  * ctl_datamove_remote_xfer() function will send the
13493                  * datamove done message, or call the callback with an
13494                  * error if there is a problem.
13495                  */
13496                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13497                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13498         }
13499
13500         return;
13501 }
13502
13503 /*
13504  * Process a datamove request from the other controller.  This is used for
13505  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13506  * first.  Once that is complete, the data gets DMAed into the remote
13507  * controller's memory.  For reads, we DMA from the remote controller's
13508  * memory into our memory first, and then move it out to the FETD.
13509  */
13510 static void
13511 ctl_datamove_remote(union ctl_io *io)
13512 {
13513         struct ctl_softc *softc;
13514
13515         softc = control_softc;
13516
13517         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13518
13519         /*
13520          * Note that we look for an aborted I/O here, but don't do some of
13521          * the other checks that ctl_datamove() normally does.
13522          * We don't need to run the datamove delay code, since that should
13523          * have been done if need be on the other controller.
13524          */
13525         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13526                 printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13527                        io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13528                        io->io_hdr.nexus.targ_port,
13529                        io->io_hdr.nexus.targ_target.id,
13530                        io->io_hdr.nexus.targ_lun);
13531                 io->io_hdr.port_status = 31338;
13532                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13533                 return;
13534         }
13535
13536         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13537                 ctl_datamove_remote_write(io);
13538         } else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13539                 ctl_datamove_remote_read(io);
13540         } else {
13541                 union ctl_ha_msg msg;
13542                 struct scsi_sense_data *sense;
13543                 uint8_t sks[3];
13544                 int retry_count;
13545
13546                 memset(&msg, 0, sizeof(msg));
13547
13548                 msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13549                 msg.hdr.status = CTL_SCSI_ERROR;
13550                 msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13551
13552                 retry_count = 4243;
13553
13554                 sense = &msg.scsi.sense_data;
13555                 sks[0] = SSD_SCS_VALID;
13556                 sks[1] = (retry_count >> 8) & 0xff;
13557                 sks[2] = retry_count & 0xff;
13558
13559                 /* "Internal target failure" */
13560                 scsi_set_sense_data(sense,
13561                                     /*sense_format*/ SSD_TYPE_NONE,
13562                                     /*current_error*/ 1,
13563                                     /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13564                                     /*asc*/ 0x44,
13565                                     /*ascq*/ 0x00,
13566                                     /*type*/ SSD_ELEM_SKS,
13567                                     /*size*/ sizeof(sks),
13568                                     /*data*/ sks,
13569                                     SSD_ELEM_NONE);
13570
13571                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13572                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13573                         ctl_failover_io(io, /*have_lock*/ 1);
13574                         return;
13575                 }
13576
13577                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13578                     CTL_HA_STATUS_SUCCESS) {
13579                         /* XXX KDM what to do if this fails? */
13580                 }
13581                 return;
13582         }
13583         
13584 }
13585
13586 static int
13587 ctl_process_done(union ctl_io *io)
13588 {
13589         struct ctl_lun *lun;
13590         struct ctl_softc *softc = control_softc;
13591         void (*fe_done)(union ctl_io *io);
13592         uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13593
13594         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13595
13596         fe_done = softc->ctl_ports[targ_port]->fe_done;
13597
13598 #ifdef CTL_TIME_IO
13599         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13600                 char str[256];
13601                 char path_str[64];
13602                 struct sbuf sb;
13603
13604                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13605                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13606
13607                 sbuf_cat(&sb, path_str);
13608                 switch (io->io_hdr.io_type) {
13609                 case CTL_IO_SCSI:
13610                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13611                         sbuf_printf(&sb, "\n");
13612                         sbuf_cat(&sb, path_str);
13613                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13614                                     io->scsiio.tag_num, io->scsiio.tag_type);
13615                         break;
13616                 case CTL_IO_TASK:
13617                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13618                                     "Tag Type: %d\n", io->taskio.task_action,
13619                                     io->taskio.tag_num, io->taskio.tag_type);
13620                         break;
13621                 default:
13622                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13623                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13624                         break;
13625                 }
13626                 sbuf_cat(&sb, path_str);
13627                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13628                             (intmax_t)time_uptime - io->io_hdr.start_time);
13629                 sbuf_finish(&sb);
13630                 printf("%s", sbuf_data(&sb));
13631         }
13632 #endif /* CTL_TIME_IO */
13633
13634         switch (io->io_hdr.io_type) {
13635         case CTL_IO_SCSI:
13636                 break;
13637         case CTL_IO_TASK:
13638                 if (bootverbose || (ctl_debug & CTL_DEBUG_INFO))
13639                         ctl_io_error_print(io, NULL);
13640                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13641                         ctl_free_io(io);
13642                 else
13643                         fe_done(io);
13644                 return (CTL_RETVAL_COMPLETE);
13645         default:
13646                 panic("ctl_process_done: invalid io type %d\n",
13647                       io->io_hdr.io_type);
13648                 break; /* NOTREACHED */
13649         }
13650
13651         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13652         if (lun == NULL) {
13653                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13654                                  io->io_hdr.nexus.targ_mapped_lun));
13655                 goto bailout;
13656         }
13657
13658         mtx_lock(&lun->lun_lock);
13659
13660         /*
13661          * Check to see if we have any errors to inject here.  We only
13662          * inject errors for commands that don't already have errors set.
13663          */
13664         if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13665             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13666             ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13667                 ctl_inject_error(lun, io);
13668
13669         /*
13670          * XXX KDM how do we treat commands that aren't completed
13671          * successfully?
13672          *
13673          * XXX KDM should we also track I/O latency?
13674          */
13675         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13676             io->io_hdr.io_type == CTL_IO_SCSI) {
13677 #ifdef CTL_TIME_IO
13678                 struct bintime cur_bt;
13679 #endif
13680                 int type;
13681
13682                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13683                     CTL_FLAG_DATA_IN)
13684                         type = CTL_STATS_READ;
13685                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13686                     CTL_FLAG_DATA_OUT)
13687                         type = CTL_STATS_WRITE;
13688                 else
13689                         type = CTL_STATS_NO_IO;
13690
13691                 lun->stats.ports[targ_port].bytes[type] +=
13692                     io->scsiio.kern_total_len;
13693                 lun->stats.ports[targ_port].operations[type]++;
13694 #ifdef CTL_TIME_IO
13695                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13696                    &io->io_hdr.dma_bt);
13697                 lun->stats.ports[targ_port].num_dmas[type] +=
13698                     io->io_hdr.num_dmas;
13699                 getbintime(&cur_bt);
13700                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13701                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13702 #endif
13703         }
13704
13705         /*
13706          * Remove this from the OOA queue.
13707          */
13708         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13709 #ifdef CTL_TIME_IO
13710         if (TAILQ_EMPTY(&lun->ooa_queue))
13711                 lun->last_busy = getsbinuptime();
13712 #endif
13713
13714         /*
13715          * Run through the blocked queue on this LUN and see if anything
13716          * has become unblocked, now that this transaction is done.
13717          */
13718         ctl_check_blocked(lun);
13719
13720         /*
13721          * If the LUN has been invalidated, free it if there is nothing
13722          * left on its OOA queue.
13723          */
13724         if ((lun->flags & CTL_LUN_INVALID)
13725          && TAILQ_EMPTY(&lun->ooa_queue)) {
13726                 mtx_unlock(&lun->lun_lock);
13727                 mtx_lock(&softc->ctl_lock);
13728                 ctl_free_lun(lun);
13729                 mtx_unlock(&softc->ctl_lock);
13730         } else
13731                 mtx_unlock(&lun->lun_lock);
13732
13733 bailout:
13734
13735         /*
13736          * If this command has been aborted, make sure we set the status
13737          * properly.  The FETD is responsible for freeing the I/O and doing
13738          * whatever it needs to do to clean up its state.
13739          */
13740         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13741                 ctl_set_task_aborted(&io->scsiio);
13742
13743         /*
13744          * If enabled, print command error status.
13745          * We don't print UAs unless debugging was enabled explicitly.
13746          */
13747         do {
13748                 if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)
13749                         break;
13750                 if (!bootverbose && (ctl_debug & CTL_DEBUG_INFO) == 0)
13751                         break;
13752                 if ((ctl_debug & CTL_DEBUG_INFO) == 0 &&
13753                     ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR) &&
13754                      (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13755                         int error_code, sense_key, asc, ascq;
13756
13757                         scsi_extract_sense_len(&io->scsiio.sense_data,
13758                             io->scsiio.sense_len, &error_code, &sense_key,
13759                             &asc, &ascq, /*show_errors*/ 0);
13760                         if (sense_key == SSD_KEY_UNIT_ATTENTION)
13761                                 break;
13762                 }
13763
13764                 ctl_io_error_print(io, NULL);
13765         } while (0);
13766
13767         /*
13768          * Tell the FETD or the other shelf controller we're done with this
13769          * command.  Note that only SCSI commands get to this point.  Task
13770          * management commands are completed above.
13771          *
13772          * We only send status to the other controller if we're in XFER
13773          * mode.  In SER_ONLY mode, the I/O is done on the controller that
13774          * received the I/O (from CTL's perspective), and so the status is
13775          * generated there.
13776          * 
13777          * XXX KDM if we hold the lock here, we could cause a deadlock
13778          * if the frontend comes back in in this context to queue
13779          * something.
13780          */
13781         if ((softc->ha_mode == CTL_HA_MODE_XFER)
13782          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13783                 union ctl_ha_msg msg;
13784
13785                 memset(&msg, 0, sizeof(msg));
13786                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13787                 msg.hdr.original_sc = io->io_hdr.original_sc;
13788                 msg.hdr.nexus = io->io_hdr.nexus;
13789                 msg.hdr.status = io->io_hdr.status;
13790                 msg.scsi.scsi_status = io->scsiio.scsi_status;
13791                 msg.scsi.tag_num = io->scsiio.tag_num;
13792                 msg.scsi.tag_type = io->scsiio.tag_type;
13793                 msg.scsi.sense_len = io->scsiio.sense_len;
13794                 msg.scsi.sense_residual = io->scsiio.sense_residual;
13795                 msg.scsi.residual = io->scsiio.residual;
13796                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13797                        sizeof(io->scsiio.sense_data));
13798                 /*
13799                  * We copy this whether or not this is an I/O-related
13800                  * command.  Otherwise, we'd have to go and check to see
13801                  * whether it's a read/write command, and it really isn't
13802                  * worth it.
13803                  */
13804                 memcpy(&msg.scsi.lbalen,
13805                        &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13806                        sizeof(msg.scsi.lbalen));
13807
13808                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13809                                 sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13810                         /* XXX do something here */
13811                 }
13812
13813                 ctl_free_io(io);
13814         } else 
13815                 fe_done(io);
13816
13817         return (CTL_RETVAL_COMPLETE);
13818 }
13819
13820 #ifdef CTL_WITH_CA
13821 /*
13822  * Front end should call this if it doesn't do autosense.  When the request
13823  * sense comes back in from the initiator, we'll dequeue this and send it.
13824  */
13825 int
13826 ctl_queue_sense(union ctl_io *io)
13827 {
13828         struct ctl_lun *lun;
13829         struct ctl_port *port;
13830         struct ctl_softc *softc;
13831         uint32_t initidx, targ_lun;
13832
13833         softc = control_softc;
13834
13835         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13836
13837         /*
13838          * LUN lookup will likely move to the ctl_work_thread() once we
13839          * have our new queueing infrastructure (that doesn't put things on
13840          * a per-LUN queue initially).  That is so that we can handle
13841          * things like an INQUIRY to a LUN that we don't have enabled.  We
13842          * can't deal with that right now.
13843          */
13844         mtx_lock(&softc->ctl_lock);
13845
13846         /*
13847          * If we don't have a LUN for this, just toss the sense
13848          * information.
13849          */
13850         port = ctl_io_port(&ctsio->io_hdr);
13851         targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13852         if ((targ_lun < CTL_MAX_LUNS)
13853          && (softc->ctl_luns[targ_lun] != NULL))
13854                 lun = softc->ctl_luns[targ_lun];
13855         else
13856                 goto bailout;
13857
13858         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13859
13860         mtx_lock(&lun->lun_lock);
13861         /*
13862          * Already have CA set for this LUN...toss the sense information.
13863          */
13864         if (ctl_is_set(lun->have_ca, initidx)) {
13865                 mtx_unlock(&lun->lun_lock);
13866                 goto bailout;
13867         }
13868
13869         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13870                MIN(sizeof(lun->pending_sense[initidx]),
13871                sizeof(io->scsiio.sense_data)));
13872         ctl_set_mask(lun->have_ca, initidx);
13873         mtx_unlock(&lun->lun_lock);
13874
13875 bailout:
13876         mtx_unlock(&softc->ctl_lock);
13877
13878         ctl_free_io(io);
13879
13880         return (CTL_RETVAL_COMPLETE);
13881 }
13882 #endif
13883
13884 /*
13885  * Primary command inlet from frontend ports.  All SCSI and task I/O
13886  * requests must go through this function.
13887  */
13888 int
13889 ctl_queue(union ctl_io *io)
13890 {
13891         struct ctl_port *port;
13892
13893         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13894
13895 #ifdef CTL_TIME_IO
13896         io->io_hdr.start_time = time_uptime;
13897         getbintime(&io->io_hdr.start_bt);
13898 #endif /* CTL_TIME_IO */
13899
13900         /* Map FE-specific LUN ID into global one. */
13901         port = ctl_io_port(&io->io_hdr);
13902         io->io_hdr.nexus.targ_mapped_lun =
13903             ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13904
13905         switch (io->io_hdr.io_type) {
13906         case CTL_IO_SCSI:
13907         case CTL_IO_TASK:
13908                 if (ctl_debug & CTL_DEBUG_CDB)
13909                         ctl_io_print(io);
13910                 ctl_enqueue_incoming(io);
13911                 break;
13912         default:
13913                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13914                 return (EINVAL);
13915         }
13916
13917         return (CTL_RETVAL_COMPLETE);
13918 }
13919
13920 #ifdef CTL_IO_DELAY
13921 static void
13922 ctl_done_timer_wakeup(void *arg)
13923 {
13924         union ctl_io *io;
13925
13926         io = (union ctl_io *)arg;
13927         ctl_done(io);
13928 }
13929 #endif /* CTL_IO_DELAY */
13930
13931 void
13932 ctl_done(union ctl_io *io)
13933 {
13934
13935         /*
13936          * Enable this to catch duplicate completion issues.
13937          */
13938 #if 0
13939         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13940                 printf("%s: type %d msg %d cdb %x iptl: "
13941                        "%d:%d:%d:%d tag 0x%04x "
13942                        "flag %#x status %x\n",
13943                         __func__,
13944                         io->io_hdr.io_type,
13945                         io->io_hdr.msg_type,
13946                         io->scsiio.cdb[0],
13947                         io->io_hdr.nexus.initid.id,
13948                         io->io_hdr.nexus.targ_port,
13949                         io->io_hdr.nexus.targ_target.id,
13950                         io->io_hdr.nexus.targ_lun,
13951                         (io->io_hdr.io_type ==
13952                         CTL_IO_TASK) ?
13953                         io->taskio.tag_num :
13954                         io->scsiio.tag_num,
13955                         io->io_hdr.flags,
13956                         io->io_hdr.status);
13957         } else
13958                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13959 #endif
13960
13961         /*
13962          * This is an internal copy of an I/O, and should not go through
13963          * the normal done processing logic.
13964          */
13965         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13966                 return;
13967
13968         /*
13969          * We need to send a msg to the serializing shelf to finish the IO
13970          * as well.  We don't send a finish message to the other shelf if
13971          * this is a task management command.  Task management commands
13972          * aren't serialized in the OOA queue, but rather just executed on
13973          * both shelf controllers for commands that originated on that
13974          * controller.
13975          */
13976         if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13977          && (io->io_hdr.io_type != CTL_IO_TASK)) {
13978                 union ctl_ha_msg msg_io;
13979
13980                 msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13981                 msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13982                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13983                     sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13984                 }
13985                 /* continue on to finish IO */
13986         }
13987 #ifdef CTL_IO_DELAY
13988         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13989                 struct ctl_lun *lun;
13990
13991                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13992
13993                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13994         } else {
13995                 struct ctl_lun *lun;
13996
13997                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13998
13999                 if ((lun != NULL)
14000                  && (lun->delay_info.done_delay > 0)) {
14001                         struct callout *callout;
14002
14003                         callout = (struct callout *)&io->io_hdr.timer_bytes;
14004                         callout_init(callout, /*mpsafe*/ 1);
14005                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
14006                         callout_reset(callout,
14007                                       lun->delay_info.done_delay * hz,
14008                                       ctl_done_timer_wakeup, io);
14009                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
14010                                 lun->delay_info.done_delay = 0;
14011                         return;
14012                 }
14013         }
14014 #endif /* CTL_IO_DELAY */
14015
14016         ctl_enqueue_done(io);
14017 }
14018
14019 int
14020 ctl_isc(struct ctl_scsiio *ctsio)
14021 {
14022         struct ctl_lun *lun;
14023         int retval;
14024
14025         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14026
14027         CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
14028
14029         CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
14030
14031         retval = lun->backend->data_submit((union ctl_io *)ctsio);
14032
14033         return (retval);
14034 }
14035
14036
14037 static void
14038 ctl_work_thread(void *arg)
14039 {
14040         struct ctl_thread *thr = (struct ctl_thread *)arg;
14041         struct ctl_softc *softc = thr->ctl_softc;
14042         union ctl_io *io;
14043         int retval;
14044
14045         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
14046
14047         for (;;) {
14048                 retval = 0;
14049
14050                 /*
14051                  * We handle the queues in this order:
14052                  * - ISC
14053                  * - done queue (to free up resources, unblock other commands)
14054                  * - RtR queue
14055                  * - incoming queue
14056                  *
14057                  * If those queues are empty, we break out of the loop and
14058                  * go to sleep.
14059                  */
14060                 mtx_lock(&thr->queue_lock);
14061                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
14062                 if (io != NULL) {
14063                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
14064                         mtx_unlock(&thr->queue_lock);
14065                         ctl_handle_isc(io);
14066                         continue;
14067                 }
14068                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
14069                 if (io != NULL) {
14070                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
14071                         /* clear any blocked commands, call fe_done */
14072                         mtx_unlock(&thr->queue_lock);
14073                         retval = ctl_process_done(io);
14074                         continue;
14075                 }
14076                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
14077                 if (io != NULL) {
14078                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
14079                         mtx_unlock(&thr->queue_lock);
14080                         if (io->io_hdr.io_type == CTL_IO_TASK)
14081                                 ctl_run_task(io);
14082                         else
14083                                 ctl_scsiio_precheck(softc, &io->scsiio);
14084                         continue;
14085                 }
14086                 if (!ctl_pause_rtr) {
14087                         io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
14088                         if (io != NULL) {
14089                                 STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
14090                                 mtx_unlock(&thr->queue_lock);
14091                                 retval = ctl_scsiio(&io->scsiio);
14092                                 if (retval != CTL_RETVAL_COMPLETE)
14093                                         CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
14094                                 continue;
14095                         }
14096                 }
14097
14098                 /* Sleep until we have something to do. */
14099                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
14100         }
14101 }
14102
14103 static void
14104 ctl_lun_thread(void *arg)
14105 {
14106         struct ctl_softc *softc = (struct ctl_softc *)arg;
14107         struct ctl_be_lun *be_lun;
14108         int retval;
14109
14110         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
14111
14112         for (;;) {
14113                 retval = 0;
14114                 mtx_lock(&softc->ctl_lock);
14115                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
14116                 if (be_lun != NULL) {
14117                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
14118                         mtx_unlock(&softc->ctl_lock);
14119                         ctl_create_lun(be_lun);
14120                         continue;
14121                 }
14122
14123                 /* Sleep until we have something to do. */
14124                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
14125                     PDROP | PRIBIO, "-", 0);
14126         }
14127 }
14128
14129 static void
14130 ctl_thresh_thread(void *arg)
14131 {
14132         struct ctl_softc *softc = (struct ctl_softc *)arg;
14133         struct ctl_lun *lun;
14134         struct ctl_be_lun *be_lun;
14135         struct scsi_da_rw_recovery_page *rwpage;
14136         struct ctl_logical_block_provisioning_page *page;
14137         const char *attr;
14138         uint64_t thres, val;
14139         int i, e;
14140
14141         CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
14142
14143         for (;;) {
14144                 mtx_lock(&softc->ctl_lock);
14145                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
14146                         be_lun = lun->be_lun;
14147                         if ((lun->flags & CTL_LUN_DISABLED) ||
14148                             (lun->flags & CTL_LUN_OFFLINE) ||
14149                             lun->backend->lun_attr == NULL)
14150                                 continue;
14151                         rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
14152                         if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
14153                                 continue;
14154                         e = 0;
14155                         page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
14156                         for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
14157                                 if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
14158                                         continue;
14159                                 thres = scsi_4btoul(page->descr[i].count);
14160                                 thres <<= CTL_LBP_EXPONENT;
14161                                 switch (page->descr[i].resource) {
14162                                 case 0x01:
14163                                         attr = "blocksavail";
14164                                         break;
14165                                 case 0x02:
14166                                         attr = "blocksused";
14167                                         break;
14168                                 case 0xf1:
14169                                         attr = "poolblocksavail";
14170                                         break;
14171                                 case 0xf2:
14172                                         attr = "poolblocksused";
14173                                         break;
14174                                 default:
14175                                         continue;
14176                                 }
14177                                 mtx_unlock(&softc->ctl_lock); // XXX
14178                                 val = lun->backend->lun_attr(
14179                                     lun->be_lun->be_lun, attr);
14180                                 mtx_lock(&softc->ctl_lock);
14181                                 if (val == UINT64_MAX)
14182                                         continue;
14183                                 if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
14184                                     == SLBPPD_ARMING_INC)
14185                                         e |= (val >= thres);
14186                                 else
14187                                         e |= (val <= thres);
14188                         }
14189                         mtx_lock(&lun->lun_lock);
14190                         if (e) {
14191                                 if (lun->lasttpt == 0 ||
14192                                     time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
14193                                         lun->lasttpt = time_uptime;
14194                                         ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14195                                 }
14196                         } else {
14197                                 lun->lasttpt = 0;
14198                                 ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14199                         }
14200                         mtx_unlock(&lun->lun_lock);
14201                 }
14202                 mtx_unlock(&softc->ctl_lock);
14203                 pause("-", CTL_LBP_PERIOD * hz);
14204         }
14205 }
14206
14207 static void
14208 ctl_enqueue_incoming(union ctl_io *io)
14209 {
14210         struct ctl_softc *softc = control_softc;
14211         struct ctl_thread *thr;
14212         u_int idx;
14213
14214         idx = (io->io_hdr.nexus.targ_port * 127 +
14215                io->io_hdr.nexus.initid.id) % worker_threads;
14216         thr = &softc->threads[idx];
14217         mtx_lock(&thr->queue_lock);
14218         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14219         mtx_unlock(&thr->queue_lock);
14220         wakeup(thr);
14221 }
14222
14223 static void
14224 ctl_enqueue_rtr(union ctl_io *io)
14225 {
14226         struct ctl_softc *softc = control_softc;
14227         struct ctl_thread *thr;
14228
14229         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14230         mtx_lock(&thr->queue_lock);
14231         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14232         mtx_unlock(&thr->queue_lock);
14233         wakeup(thr);
14234 }
14235
14236 static void
14237 ctl_enqueue_done(union ctl_io *io)
14238 {
14239         struct ctl_softc *softc = control_softc;
14240         struct ctl_thread *thr;
14241
14242         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14243         mtx_lock(&thr->queue_lock);
14244         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14245         mtx_unlock(&thr->queue_lock);
14246         wakeup(thr);
14247 }
14248
14249 static void
14250 ctl_enqueue_isc(union ctl_io *io)
14251 {
14252         struct ctl_softc *softc = control_softc;
14253         struct ctl_thread *thr;
14254
14255         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14256         mtx_lock(&thr->queue_lock);
14257         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14258         mtx_unlock(&thr->queue_lock);
14259         wakeup(thr);
14260 }
14261
14262 /* Initialization and failover */
14263
14264 void
14265 ctl_init_isc_msg(void)
14266 {
14267         printf("CTL: Still calling this thing\n");
14268 }
14269
14270 /*
14271  * Init component
14272  *      Initializes component into configuration defined by bootMode
14273  *      (see hasc-sv.c)
14274  *      returns hasc_Status:
14275  *              OK
14276  *              ERROR - fatal error
14277  */
14278 static ctl_ha_comp_status
14279 ctl_isc_init(struct ctl_ha_component *c)
14280 {
14281         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14282
14283         c->status = ret;
14284         return ret;
14285 }
14286
14287 /* Start component
14288  *      Starts component in state requested. If component starts successfully,
14289  *      it must set its own state to the requestrd state
14290  *      When requested state is HASC_STATE_HA, the component may refine it
14291  *      by adding _SLAVE or _MASTER flags.
14292  *      Currently allowed state transitions are:
14293  *      UNKNOWN->HA             - initial startup
14294  *      UNKNOWN->SINGLE - initial startup when no parter detected
14295  *      HA->SINGLE              - failover
14296  * returns ctl_ha_comp_status:
14297  *              OK      - component successfully started in requested state
14298  *              FAILED  - could not start the requested state, failover may
14299  *                        be possible
14300  *              ERROR   - fatal error detected, no future startup possible
14301  */
14302 static ctl_ha_comp_status
14303 ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14304 {
14305         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14306
14307         printf("%s: go\n", __func__);
14308
14309         // UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14310         if (c->state == CTL_HA_STATE_UNKNOWN ) {
14311                 control_softc->is_single = 0;
14312                 if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14313                     != CTL_HA_STATUS_SUCCESS) {
14314                         printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14315                         ret = CTL_HA_COMP_STATUS_ERROR;
14316                 }
14317         } else if (CTL_HA_STATE_IS_HA(c->state)
14318                 && CTL_HA_STATE_IS_SINGLE(state)){
14319                 // HA->SINGLE transition
14320                 ctl_failover();
14321                 control_softc->is_single = 1;
14322         } else {
14323                 printf("ctl_isc_start:Invalid state transition %X->%X\n",
14324                        c->state, state);
14325                 ret = CTL_HA_COMP_STATUS_ERROR;
14326         }
14327         if (CTL_HA_STATE_IS_SINGLE(state))
14328                 control_softc->is_single = 1;
14329
14330         c->state = state;
14331         c->status = ret;
14332         return ret;
14333 }
14334
14335 /*
14336  * Quiesce component
14337  * The component must clear any error conditions (set status to OK) and
14338  * prepare itself to another Start call
14339  * returns ctl_ha_comp_status:
14340  *      OK
14341  *      ERROR
14342  */
14343 static ctl_ha_comp_status
14344 ctl_isc_quiesce(struct ctl_ha_component *c)
14345 {
14346         int ret = CTL_HA_COMP_STATUS_OK;
14347
14348         ctl_pause_rtr = 1;
14349         c->status = ret;
14350         return ret;
14351 }
14352
14353 struct ctl_ha_component ctl_ha_component_ctlisc =
14354 {
14355         .name = "CTL ISC",
14356         .state = CTL_HA_STATE_UNKNOWN,
14357         .init = ctl_isc_init,
14358         .start = ctl_isc_start,
14359         .quiesce = ctl_isc_quiesce
14360 };
14361
14362 /*
14363  *  vim: ts=8
14364  */