]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/ctl.c
MFC r275405: Convert persis_offset from global variable to softc field.
[FreeBSD/stable/10.git] / sys / cam / ctl / ctl.c
1 /*-
2  * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3  * Copyright (c) 2012 The FreeBSD Foundation
4  * All rights reserved.
5  *
6  * Portions of this software were developed by Edward Tomasz Napierala
7  * under sponsorship from the FreeBSD Foundation.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions, and the following disclaimer,
14  *    without modification.
15  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
16  *    substantially similar to the "NO WARRANTY" disclaimer below
17  *    ("Disclaimer") and any redistribution must be conditioned upon
18  *    including a substantially similar Disclaimer requirement for further
19  *    binary redistribution.
20  *
21  * NO WARRANTY
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
25  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
31  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGES.
33  *
34  * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/ctl.c#8 $
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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
330         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
331         /*subpage_code*/0x02,
332         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
333         /*flags*/0,
334         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
335         /*descr*/{}},
336         {{/*flags*/0,
337           /*resource*/0,
338           /*reserved*/{0, 0},
339           /*count*/{0, 0, 0, 0}},
340          {/*flags*/0,
341           /*resource*/0,
342           /*reserved*/{0, 0},
343           /*count*/{0, 0, 0, 0}},
344          {/*flags*/0,
345           /*resource*/0,
346           /*reserved*/{0, 0},
347           /*count*/{0, 0, 0, 0}},
348          {/*flags*/0,
349           /*resource*/0,
350           /*reserved*/{0, 0},
351           /*count*/{0, 0, 0, 0}}
352         }
353 };
354
355 /*
356  * XXX KDM move these into the softc.
357  */
358 static int rcv_sync_msg;
359 static uint8_t ctl_pause_rtr;
360
361 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
362 static int worker_threads = -1;
363 TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
364 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
365     &worker_threads, 1, "Number of worker threads");
366 static int ctl_debug = CTL_DEBUG_NONE;
367 TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
368 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
369     &ctl_debug, 0, "Enabled debug flags");
370
371 /*
372  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
373  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
374  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
375  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
376  */
377 #define SCSI_EVPD_NUM_SUPPORTED_PAGES   10
378
379 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
380                                   int param);
381 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
382 static int ctl_init(void);
383 void ctl_shutdown(void);
384 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
385 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
386 static void ctl_ioctl_online(void *arg);
387 static void ctl_ioctl_offline(void *arg);
388 static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
389 static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
390 static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
391 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
392 static int ctl_ioctl_submit_wait(union ctl_io *io);
393 static void ctl_ioctl_datamove(union ctl_io *io);
394 static void ctl_ioctl_done(union ctl_io *io);
395 static void ctl_ioctl_hard_startstop_callback(void *arg,
396                                               struct cfi_metatask *metatask);
397 static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
398 static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
399                               struct ctl_ooa *ooa_hdr,
400                               struct ctl_ooa_entry *kern_entries);
401 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
402                      struct thread *td);
403 static uint32_t ctl_map_lun(int port_num, uint32_t lun);
404 static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
405 #ifdef unused
406 static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
407                                    uint32_t targ_target, uint32_t targ_lun,
408                                    int can_wait);
409 static void ctl_kfree_io(union ctl_io *io);
410 #endif /* unused */
411 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
412                          struct ctl_be_lun *be_lun, struct ctl_id target_id);
413 static int ctl_free_lun(struct ctl_lun *lun);
414 static void ctl_create_lun(struct ctl_be_lun *be_lun);
415 /**
416 static void ctl_failover_change_pages(struct ctl_softc *softc,
417                                       struct ctl_scsiio *ctsio, int master);
418 **/
419
420 static int ctl_do_mode_select(union ctl_io *io);
421 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
422                            uint64_t res_key, uint64_t sa_res_key,
423                            uint8_t type, uint32_t residx,
424                            struct ctl_scsiio *ctsio,
425                            struct scsi_per_res_out *cdb,
426                            struct scsi_per_res_out_parms* param);
427 static void ctl_pro_preempt_other(struct ctl_lun *lun,
428                                   union ctl_ha_msg *msg);
429 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
430 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
431 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
432 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
433 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
434 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
435 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
436                                          int alloc_len);
437 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
438                                          int alloc_len);
439 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
440 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
441 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
442 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
443 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
444 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
445 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
446     union ctl_io *pending_io, union ctl_io *ooa_io);
447 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
448                                 union ctl_io *starting_io);
449 static int ctl_check_blocked(struct ctl_lun *lun);
450 static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
451                                 struct ctl_lun *lun,
452                                 const struct ctl_cmd_entry *entry,
453                                 struct ctl_scsiio *ctsio);
454 //static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
455 static void ctl_failover(void);
456 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
457                                struct ctl_scsiio *ctsio);
458 static int ctl_scsiio(struct ctl_scsiio *ctsio);
459
460 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
461 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
462                             ctl_ua_type ua_type);
463 static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
464                          ctl_ua_type ua_type);
465 static int ctl_abort_task(union ctl_io *io);
466 static int ctl_abort_task_set(union ctl_io *io);
467 static int ctl_i_t_nexus_reset(union ctl_io *io);
468 static void ctl_run_task(union ctl_io *io);
469 #ifdef CTL_IO_DELAY
470 static void ctl_datamove_timer_wakeup(void *arg);
471 static void ctl_done_timer_wakeup(void *arg);
472 #endif /* CTL_IO_DELAY */
473
474 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
475 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
476 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
477 static void ctl_datamove_remote_write(union ctl_io *io);
478 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
479 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
480 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
481 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
482                                     ctl_ha_dt_cb callback);
483 static void ctl_datamove_remote_read(union ctl_io *io);
484 static void ctl_datamove_remote(union ctl_io *io);
485 static int ctl_process_done(union ctl_io *io);
486 static void ctl_lun_thread(void *arg);
487 static void ctl_thresh_thread(void *arg);
488 static void ctl_work_thread(void *arg);
489 static void ctl_enqueue_incoming(union ctl_io *io);
490 static void ctl_enqueue_rtr(union ctl_io *io);
491 static void ctl_enqueue_done(union ctl_io *io);
492 static void ctl_enqueue_isc(union ctl_io *io);
493 static const struct ctl_cmd_entry *
494     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
495 static const struct ctl_cmd_entry *
496     ctl_validate_command(struct ctl_scsiio *ctsio);
497 static int ctl_cmd_applicable(uint8_t lun_type,
498     const struct ctl_cmd_entry *entry);
499
500 /*
501  * Load the serialization table.  This isn't very pretty, but is probably
502  * the easiest way to do it.
503  */
504 #include "ctl_ser_table.c"
505
506 /*
507  * We only need to define open, close and ioctl routines for this driver.
508  */
509 static struct cdevsw ctl_cdevsw = {
510         .d_version =    D_VERSION,
511         .d_flags =      0,
512         .d_open =       ctl_open,
513         .d_close =      ctl_close,
514         .d_ioctl =      ctl_ioctl,
515         .d_name =       "ctl",
516 };
517
518
519 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
520 MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
521
522 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
523
524 static moduledata_t ctl_moduledata = {
525         "ctl",
526         ctl_module_event_handler,
527         NULL
528 };
529
530 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
531 MODULE_VERSION(ctl, 1);
532
533 static struct ctl_frontend ioctl_frontend =
534 {
535         .name = "ioctl",
536 };
537
538 static void
539 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
540                             union ctl_ha_msg *msg_info)
541 {
542         struct ctl_scsiio *ctsio;
543
544         if (msg_info->hdr.original_sc == NULL) {
545                 printf("%s: original_sc == NULL!\n", __func__);
546                 /* XXX KDM now what? */
547                 return;
548         }
549
550         ctsio = &msg_info->hdr.original_sc->scsiio;
551         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
552         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
553         ctsio->io_hdr.status = msg_info->hdr.status;
554         ctsio->scsi_status = msg_info->scsi.scsi_status;
555         ctsio->sense_len = msg_info->scsi.sense_len;
556         ctsio->sense_residual = msg_info->scsi.sense_residual;
557         ctsio->residual = msg_info->scsi.residual;
558         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
559                sizeof(ctsio->sense_data));
560         memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
561                &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
562         ctl_enqueue_isc((union ctl_io *)ctsio);
563 }
564
565 static void
566 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
567                                 union ctl_ha_msg *msg_info)
568 {
569         struct ctl_scsiio *ctsio;
570
571         if (msg_info->hdr.serializing_sc == NULL) {
572                 printf("%s: serializing_sc == NULL!\n", __func__);
573                 /* XXX KDM now what? */
574                 return;
575         }
576
577         ctsio = &msg_info->hdr.serializing_sc->scsiio;
578 #if 0
579         /*
580          * Attempt to catch the situation where an I/O has
581          * been freed, and we're using it again.
582          */
583         if (ctsio->io_hdr.io_type == 0xff) {
584                 union ctl_io *tmp_io;
585                 tmp_io = (union ctl_io *)ctsio;
586                 printf("%s: %p use after free!\n", __func__,
587                        ctsio);
588                 printf("%s: type %d msg %d cdb %x iptl: "
589                        "%d:%d:%d:%d tag 0x%04x "
590                        "flag %#x status %x\n",
591                         __func__,
592                         tmp_io->io_hdr.io_type,
593                         tmp_io->io_hdr.msg_type,
594                         tmp_io->scsiio.cdb[0],
595                         tmp_io->io_hdr.nexus.initid.id,
596                         tmp_io->io_hdr.nexus.targ_port,
597                         tmp_io->io_hdr.nexus.targ_target.id,
598                         tmp_io->io_hdr.nexus.targ_lun,
599                         (tmp_io->io_hdr.io_type ==
600                         CTL_IO_TASK) ?
601                         tmp_io->taskio.tag_num :
602                         tmp_io->scsiio.tag_num,
603                         tmp_io->io_hdr.flags,
604                         tmp_io->io_hdr.status);
605         }
606 #endif
607         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
608         ctl_enqueue_isc((union ctl_io *)ctsio);
609 }
610
611 /*
612  * ISC (Inter Shelf Communication) event handler.  Events from the HA
613  * subsystem come in here.
614  */
615 static void
616 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
617 {
618         struct ctl_softc *ctl_softc;
619         union ctl_io *io;
620         struct ctl_prio *presio;
621         ctl_ha_status isc_status;
622
623         ctl_softc = control_softc;
624         io = NULL;
625
626
627 #if 0
628         printf("CTL: Isc Msg event %d\n", event);
629 #endif
630         if (event == CTL_HA_EVT_MSG_RECV) {
631                 union ctl_ha_msg msg_info;
632
633                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
634                                              sizeof(msg_info), /*wait*/ 0);
635 #if 0
636                 printf("CTL: msg_type %d\n", msg_info.msg_type);
637 #endif
638                 if (isc_status != 0) {
639                         printf("Error receiving message, status = %d\n",
640                                isc_status);
641                         return;
642                 }
643
644                 switch (msg_info.hdr.msg_type) {
645                 case CTL_MSG_SERIALIZE:
646 #if 0
647                         printf("Serialize\n");
648 #endif
649                         io = ctl_alloc_io_nowait(ctl_softc->othersc_pool);
650                         if (io == NULL) {
651                                 printf("ctl_isc_event_handler: can't allocate "
652                                        "ctl_io!\n");
653                                 /* Bad Juju */
654                                 /* Need to set busy and send msg back */
655                                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
656                                 msg_info.hdr.status = CTL_SCSI_ERROR;
657                                 msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
658                                 msg_info.scsi.sense_len = 0;
659                                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
660                                     sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
661                                 }
662                                 goto bailout;
663                         }
664                         ctl_zero_io(io);
665                         // populate ctsio from msg_info
666                         io->io_hdr.io_type = CTL_IO_SCSI;
667                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
668                         io->io_hdr.original_sc = msg_info.hdr.original_sc;
669 #if 0
670                         printf("pOrig %x\n", (int)msg_info.original_sc);
671 #endif
672                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
673                                             CTL_FLAG_IO_ACTIVE;
674                         /*
675                          * If we're in serialization-only mode, we don't
676                          * want to go through full done processing.  Thus
677                          * the COPY flag.
678                          *
679                          * XXX KDM add another flag that is more specific.
680                          */
681                         if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
682                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
683                         io->io_hdr.nexus = msg_info.hdr.nexus;
684 #if 0
685                         printf("targ %d, port %d, iid %d, lun %d\n",
686                                io->io_hdr.nexus.targ_target.id,
687                                io->io_hdr.nexus.targ_port,
688                                io->io_hdr.nexus.initid.id,
689                                io->io_hdr.nexus.targ_lun);
690 #endif
691                         io->scsiio.tag_num = msg_info.scsi.tag_num;
692                         io->scsiio.tag_type = msg_info.scsi.tag_type;
693                         memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
694                                CTL_MAX_CDBLEN);
695                         if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
696                                 const struct ctl_cmd_entry *entry;
697
698                                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
699                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
700                                 io->io_hdr.flags |=
701                                         entry->flags & CTL_FLAG_DATA_MASK;
702                         }
703                         ctl_enqueue_isc(io);
704                         break;
705
706                 /* Performed on the Originating SC, XFER mode only */
707                 case CTL_MSG_DATAMOVE: {
708                         struct ctl_sg_entry *sgl;
709                         int i, j;
710
711                         io = msg_info.hdr.original_sc;
712                         if (io == NULL) {
713                                 printf("%s: original_sc == NULL!\n", __func__);
714                                 /* XXX KDM do something here */
715                                 break;
716                         }
717                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
718                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
719                         /*
720                          * Keep track of this, we need to send it back over
721                          * when the datamove is complete.
722                          */
723                         io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
724
725                         if (msg_info.dt.sg_sequence == 0) {
726                                 /*
727                                  * XXX KDM we use the preallocated S/G list
728                                  * here, but we'll need to change this to
729                                  * dynamic allocation if we need larger S/G
730                                  * lists.
731                                  */
732                                 if (msg_info.dt.kern_sg_entries >
733                                     sizeof(io->io_hdr.remote_sglist) /
734                                     sizeof(io->io_hdr.remote_sglist[0])) {
735                                         printf("%s: number of S/G entries "
736                                             "needed %u > allocated num %zd\n",
737                                             __func__,
738                                             msg_info.dt.kern_sg_entries,
739                                             sizeof(io->io_hdr.remote_sglist)/
740                                             sizeof(io->io_hdr.remote_sglist[0]));
741                                 
742                                         /*
743                                          * XXX KDM send a message back to
744                                          * the other side to shut down the
745                                          * DMA.  The error will come back
746                                          * through via the normal channel.
747                                          */
748                                         break;
749                                 }
750                                 sgl = io->io_hdr.remote_sglist;
751                                 memset(sgl, 0,
752                                        sizeof(io->io_hdr.remote_sglist));
753
754                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
755
756                                 io->scsiio.kern_sg_entries =
757                                         msg_info.dt.kern_sg_entries;
758                                 io->scsiio.rem_sg_entries =
759                                         msg_info.dt.kern_sg_entries;
760                                 io->scsiio.kern_data_len =
761                                         msg_info.dt.kern_data_len;
762                                 io->scsiio.kern_total_len =
763                                         msg_info.dt.kern_total_len;
764                                 io->scsiio.kern_data_resid =
765                                         msg_info.dt.kern_data_resid;
766                                 io->scsiio.kern_rel_offset =
767                                         msg_info.dt.kern_rel_offset;
768                                 /*
769                                  * Clear out per-DMA flags.
770                                  */
771                                 io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
772                                 /*
773                                  * Add per-DMA flags that are set for this
774                                  * particular DMA request.
775                                  */
776                                 io->io_hdr.flags |= msg_info.dt.flags &
777                                                     CTL_FLAG_RDMA_MASK;
778                         } else
779                                 sgl = (struct ctl_sg_entry *)
780                                         io->scsiio.kern_data_ptr;
781
782                         for (i = msg_info.dt.sent_sg_entries, j = 0;
783                              i < (msg_info.dt.sent_sg_entries +
784                              msg_info.dt.cur_sg_entries); i++, j++) {
785                                 sgl[i].addr = msg_info.dt.sg_list[j].addr;
786                                 sgl[i].len = msg_info.dt.sg_list[j].len;
787
788 #if 0
789                                 printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
790                                        __func__,
791                                        msg_info.dt.sg_list[j].addr,
792                                        msg_info.dt.sg_list[j].len,
793                                        sgl[i].addr, sgl[i].len, j, i);
794 #endif
795                         }
796 #if 0
797                         memcpy(&sgl[msg_info.dt.sent_sg_entries],
798                                msg_info.dt.sg_list,
799                                sizeof(*sgl) * msg_info.dt.cur_sg_entries);
800 #endif
801
802                         /*
803                          * If this is the last piece of the I/O, we've got
804                          * the full S/G list.  Queue processing in the thread.
805                          * Otherwise wait for the next piece.
806                          */
807                         if (msg_info.dt.sg_last != 0)
808                                 ctl_enqueue_isc(io);
809                         break;
810                 }
811                 /* Performed on the Serializing (primary) SC, XFER mode only */
812                 case CTL_MSG_DATAMOVE_DONE: {
813                         if (msg_info.hdr.serializing_sc == NULL) {
814                                 printf("%s: serializing_sc == NULL!\n",
815                                        __func__);
816                                 /* XXX KDM now what? */
817                                 break;
818                         }
819                         /*
820                          * We grab the sense information here in case
821                          * there was a failure, so we can return status
822                          * back to the initiator.
823                          */
824                         io = msg_info.hdr.serializing_sc;
825                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
826                         io->io_hdr.status = msg_info.hdr.status;
827                         io->scsiio.scsi_status = msg_info.scsi.scsi_status;
828                         io->scsiio.sense_len = msg_info.scsi.sense_len;
829                         io->scsiio.sense_residual =msg_info.scsi.sense_residual;
830                         io->io_hdr.port_status = msg_info.scsi.fetd_status;
831                         io->scsiio.residual = msg_info.scsi.residual;
832                         memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
833                                sizeof(io->scsiio.sense_data));
834                         ctl_enqueue_isc(io);
835                         break;
836                 }
837
838                 /* Preformed on Originating SC, SER_ONLY mode */
839                 case CTL_MSG_R2R:
840                         io = msg_info.hdr.original_sc;
841                         if (io == NULL) {
842                                 printf("%s: Major Bummer\n", __func__);
843                                 return;
844                         } else {
845 #if 0
846                                 printf("pOrig %x\n",(int) ctsio);
847 #endif
848                         }
849                         io->io_hdr.msg_type = CTL_MSG_R2R;
850                         io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
851                         ctl_enqueue_isc(io);
852                         break;
853
854                 /*
855                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
856                  * mode.
857                  * Performed on the Originating (i.e. secondary) SC in XFER
858                  * mode
859                  */
860                 case CTL_MSG_FINISH_IO:
861                         if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
862                                 ctl_isc_handler_finish_xfer(ctl_softc,
863                                                             &msg_info);
864                         else
865                                 ctl_isc_handler_finish_ser_only(ctl_softc,
866                                                                 &msg_info);
867                         break;
868
869                 /* Preformed on Originating SC */
870                 case CTL_MSG_BAD_JUJU:
871                         io = msg_info.hdr.original_sc;
872                         if (io == NULL) {
873                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
874                                        __func__);
875                                 break;
876                         }
877                         ctl_copy_sense_data(&msg_info, io);
878                         /*
879                          * IO should have already been cleaned up on other
880                          * SC so clear this flag so we won't send a message
881                          * back to finish the IO there.
882                          */
883                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
884                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
885
886                         /* io = msg_info.hdr.serializing_sc; */
887                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
888                         ctl_enqueue_isc(io);
889                         break;
890
891                 /* Handle resets sent from the other side */
892                 case CTL_MSG_MANAGE_TASKS: {
893                         struct ctl_taskio *taskio;
894                         taskio = (struct ctl_taskio *)ctl_alloc_io_nowait(
895                             ctl_softc->othersc_pool);
896                         if (taskio == NULL) {
897                                 printf("ctl_isc_event_handler: can't allocate "
898                                        "ctl_io!\n");
899                                 /* Bad Juju */
900                                 /* should I just call the proper reset func
901                                    here??? */
902                                 goto bailout;
903                         }
904                         ctl_zero_io((union ctl_io *)taskio);
905                         taskio->io_hdr.io_type = CTL_IO_TASK;
906                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
907                         taskio->io_hdr.nexus = msg_info.hdr.nexus;
908                         taskio->task_action = msg_info.task.task_action;
909                         taskio->tag_num = msg_info.task.tag_num;
910                         taskio->tag_type = msg_info.task.tag_type;
911 #ifdef CTL_TIME_IO
912                         taskio->io_hdr.start_time = time_uptime;
913                         getbintime(&taskio->io_hdr.start_bt);
914 #if 0
915                         cs_prof_gettime(&taskio->io_hdr.start_ticks);
916 #endif
917 #endif /* CTL_TIME_IO */
918                         ctl_run_task((union ctl_io *)taskio);
919                         break;
920                 }
921                 /* Persistent Reserve action which needs attention */
922                 case CTL_MSG_PERS_ACTION:
923                         presio = (struct ctl_prio *)ctl_alloc_io_nowait(
924                             ctl_softc->othersc_pool);
925                         if (presio == NULL) {
926                                 printf("ctl_isc_event_handler: can't allocate "
927                                        "ctl_io!\n");
928                                 /* Bad Juju */
929                                 /* Need to set busy and send msg back */
930                                 goto bailout;
931                         }
932                         ctl_zero_io((union ctl_io *)presio);
933                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
934                         presio->pr_msg = msg_info.pr;
935                         ctl_enqueue_isc((union ctl_io *)presio);
936                         break;
937                 case CTL_MSG_SYNC_FE:
938                         rcv_sync_msg = 1;
939                         break;
940                 default:
941                         printf("How did I get here?\n");
942                 }
943         } else if (event == CTL_HA_EVT_MSG_SENT) {
944                 if (param != CTL_HA_STATUS_SUCCESS) {
945                         printf("Bad status from ctl_ha_msg_send status %d\n",
946                                param);
947                 }
948                 return;
949         } else if (event == CTL_HA_EVT_DISCONNECT) {
950                 printf("CTL: Got a disconnect from Isc\n");
951                 return;
952         } else {
953                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
954                 return;
955         }
956
957 bailout:
958         return;
959 }
960
961 static void
962 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
963 {
964         struct scsi_sense_data *sense;
965
966         sense = &dest->scsiio.sense_data;
967         bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
968         dest->scsiio.scsi_status = src->scsi.scsi_status;
969         dest->scsiio.sense_len = src->scsi.sense_len;
970         dest->io_hdr.status = src->hdr.status;
971 }
972
973 static int
974 ctl_ha_state_sysctl(SYSCTL_HANDLER_ARGS)
975 {
976         struct ctl_softc *softc = (struct ctl_softc *)arg1;
977         struct ctl_lun *lun;
978         int error, value, i;
979
980         if (softc->flags & CTL_FLAG_ACTIVE_SHELF)
981                 value = 0;
982         else
983                 value = 1;
984
985         error = sysctl_handle_int(oidp, &value, 0, req);
986         if ((error != 0) || (req->newptr == NULL))
987                 return (error);
988
989         mtx_lock(&softc->ctl_lock);
990         if (value == 0)
991                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
992         else
993                 softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
994         STAILQ_FOREACH(lun, &softc->lun_list, links) {
995                 mtx_lock(&lun->lun_lock);
996                 for (i = 0; i < CTL_MAX_INITIATORS; i++)
997                         lun->pending_ua[i] |= CTL_UA_ASYM_ACC_CHANGE;
998                 mtx_unlock(&lun->lun_lock);
999         }
1000         mtx_unlock(&softc->ctl_lock);
1001         return (0);
1002 }
1003
1004 static int
1005 ctl_init(void)
1006 {
1007         struct ctl_softc *softc;
1008         void *other_pool;
1009         struct ctl_port *port;
1010         int i, error, retval;
1011         //int isc_retval;
1012
1013         retval = 0;
1014         ctl_pause_rtr = 0;
1015         rcv_sync_msg = 0;
1016
1017         control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1018                                M_WAITOK | M_ZERO);
1019         softc = control_softc;
1020
1021         softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1022                               "cam/ctl");
1023
1024         softc->dev->si_drv1 = softc;
1025
1026         /*
1027          * By default, return a "bad LUN" peripheral qualifier for unknown
1028          * LUNs.  The user can override this default using the tunable or
1029          * sysctl.  See the comment in ctl_inquiry_std() for more details.
1030          */
1031         softc->inquiry_pq_no_lun = 1;
1032         TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
1033                           &softc->inquiry_pq_no_lun);
1034         sysctl_ctx_init(&softc->sysctl_ctx);
1035         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1036                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1037                 CTLFLAG_RD, 0, "CAM Target Layer");
1038
1039         if (softc->sysctl_tree == NULL) {
1040                 printf("%s: unable to allocate sysctl tree\n", __func__);
1041                 destroy_dev(softc->dev);
1042                 free(control_softc, M_DEVBUF);
1043                 control_softc = NULL;
1044                 return (ENOMEM);
1045         }
1046
1047         SYSCTL_ADD_INT(&softc->sysctl_ctx,
1048                        SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1049                        "inquiry_pq_no_lun", CTLFLAG_RW,
1050                        &softc->inquiry_pq_no_lun, 0,
1051                        "Report no lun possible for invalid LUNs");
1052
1053         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1054         softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1055             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1056         softc->open_count = 0;
1057
1058         /*
1059          * Default to actually sending a SYNCHRONIZE CACHE command down to
1060          * the drive.
1061          */
1062         softc->flags = CTL_FLAG_REAL_SYNC;
1063
1064         /*
1065          * In Copan's HA scheme, the "master" and "slave" roles are
1066          * figured out through the slot the controller is in.  Although it
1067          * is an active/active system, someone has to be in charge.
1068          */
1069         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1070             OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1071             "HA head ID (0 - no HA)");
1072         if (softc->ha_id == 0) {
1073                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1074                 softc->is_single = 1;
1075                 softc->port_offset = 0;
1076         } else
1077                 softc->port_offset = (softc->ha_id - 1) * CTL_MAX_PORTS;
1078         softc->persis_offset = softc->port_offset * CTL_MAX_INIT_PER_PORT;
1079
1080         /*
1081          * XXX KDM need to figure out where we want to get our target ID
1082          * and WWID.  Is it different on each port?
1083          */
1084         softc->target.id = 0;
1085         softc->target.wwid[0] = 0x12345678;
1086         softc->target.wwid[1] = 0x87654321;
1087         STAILQ_INIT(&softc->lun_list);
1088         STAILQ_INIT(&softc->pending_lun_queue);
1089         STAILQ_INIT(&softc->fe_list);
1090         STAILQ_INIT(&softc->port_list);
1091         STAILQ_INIT(&softc->be_list);
1092         ctl_tpc_init(softc);
1093
1094         if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1095                             &other_pool) != 0)
1096         {
1097                 printf("ctl: can't allocate %d entry other SC pool, "
1098                        "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1099                 return (ENOMEM);
1100         }
1101         softc->othersc_pool = other_pool;
1102
1103         if (worker_threads <= 0)
1104                 worker_threads = max(1, mp_ncpus / 4);
1105         if (worker_threads > CTL_MAX_THREADS)
1106                 worker_threads = CTL_MAX_THREADS;
1107
1108         for (i = 0; i < worker_threads; i++) {
1109                 struct ctl_thread *thr = &softc->threads[i];
1110
1111                 mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1112                 thr->ctl_softc = softc;
1113                 STAILQ_INIT(&thr->incoming_queue);
1114                 STAILQ_INIT(&thr->rtr_queue);
1115                 STAILQ_INIT(&thr->done_queue);
1116                 STAILQ_INIT(&thr->isc_queue);
1117
1118                 error = kproc_kthread_add(ctl_work_thread, thr,
1119                     &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1120                 if (error != 0) {
1121                         printf("error creating CTL work thread!\n");
1122                         ctl_pool_free(other_pool);
1123                         return (error);
1124                 }
1125         }
1126         error = kproc_kthread_add(ctl_lun_thread, softc,
1127             &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1128         if (error != 0) {
1129                 printf("error creating CTL lun thread!\n");
1130                 ctl_pool_free(other_pool);
1131                 return (error);
1132         }
1133         error = kproc_kthread_add(ctl_thresh_thread, softc,
1134             &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1135         if (error != 0) {
1136                 printf("error creating CTL threshold thread!\n");
1137                 ctl_pool_free(other_pool);
1138                 return (error);
1139         }
1140         if (bootverbose)
1141                 printf("ctl: CAM Target Layer loaded\n");
1142
1143         /*
1144          * Initialize the ioctl front end.
1145          */
1146         ctl_frontend_register(&ioctl_frontend);
1147         port = &softc->ioctl_info.port;
1148         port->frontend = &ioctl_frontend;
1149         sprintf(softc->ioctl_info.port_name, "ioctl");
1150         port->port_type = CTL_PORT_IOCTL;
1151         port->num_requested_ctl_io = 100;
1152         port->port_name = softc->ioctl_info.port_name;
1153         port->port_online = ctl_ioctl_online;
1154         port->port_offline = ctl_ioctl_offline;
1155         port->onoff_arg = &softc->ioctl_info;
1156         port->lun_enable = ctl_ioctl_lun_enable;
1157         port->lun_disable = ctl_ioctl_lun_disable;
1158         port->targ_lun_arg = &softc->ioctl_info;
1159         port->fe_datamove = ctl_ioctl_datamove;
1160         port->fe_done = ctl_ioctl_done;
1161         port->max_targets = 15;
1162         port->max_target_id = 15;
1163
1164         if (ctl_port_register(&softc->ioctl_info.port) != 0) {
1165                 printf("ctl: ioctl front end registration failed, will "
1166                        "continue anyway\n");
1167         }
1168
1169         SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1170             OID_AUTO, "ha_state", CTLTYPE_INT | CTLFLAG_RWTUN,
1171             softc, 0, ctl_ha_state_sysctl, "I", "HA state for this head");
1172
1173 #ifdef CTL_IO_DELAY
1174         if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1175                 printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1176                        sizeof(struct callout), CTL_TIMER_BYTES);
1177                 return (EINVAL);
1178         }
1179 #endif /* CTL_IO_DELAY */
1180
1181         return (0);
1182 }
1183
1184 void
1185 ctl_shutdown(void)
1186 {
1187         struct ctl_softc *softc;
1188         struct ctl_lun *lun, *next_lun;
1189
1190         softc = (struct ctl_softc *)control_softc;
1191
1192         if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1193                 printf("ctl: ioctl front end deregistration failed\n");
1194
1195         mtx_lock(&softc->ctl_lock);
1196
1197         /*
1198          * Free up each LUN.
1199          */
1200         for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1201                 next_lun = STAILQ_NEXT(lun, links);
1202                 ctl_free_lun(lun);
1203         }
1204
1205         mtx_unlock(&softc->ctl_lock);
1206
1207         ctl_frontend_deregister(&ioctl_frontend);
1208
1209 #if 0
1210         ctl_shutdown_thread(softc->work_thread);
1211         mtx_destroy(&softc->queue_lock);
1212 #endif
1213
1214         ctl_tpc_shutdown(softc);
1215         uma_zdestroy(softc->io_zone);
1216         mtx_destroy(&softc->ctl_lock);
1217
1218         destroy_dev(softc->dev);
1219
1220         sysctl_ctx_free(&softc->sysctl_ctx);
1221
1222         free(control_softc, M_DEVBUF);
1223         control_softc = NULL;
1224
1225         if (bootverbose)
1226                 printf("ctl: CAM Target Layer unloaded\n");
1227 }
1228
1229 static int
1230 ctl_module_event_handler(module_t mod, int what, void *arg)
1231 {
1232
1233         switch (what) {
1234         case MOD_LOAD:
1235                 return (ctl_init());
1236         case MOD_UNLOAD:
1237                 return (EBUSY);
1238         default:
1239                 return (EOPNOTSUPP);
1240         }
1241 }
1242
1243 /*
1244  * XXX KDM should we do some access checks here?  Bump a reference count to
1245  * prevent a CTL module from being unloaded while someone has it open?
1246  */
1247 static int
1248 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1249 {
1250         return (0);
1251 }
1252
1253 static int
1254 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1255 {
1256         return (0);
1257 }
1258
1259 int
1260 ctl_port_enable(ctl_port_type port_type)
1261 {
1262         struct ctl_softc *softc = control_softc;
1263         struct ctl_port *port;
1264
1265         if (softc->is_single == 0) {
1266                 union ctl_ha_msg msg_info;
1267                 int isc_retval;
1268
1269 #if 0
1270                 printf("%s: HA mode, synchronizing frontend enable\n",
1271                         __func__);
1272 #endif
1273                 msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1274                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1275                         sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1276                         printf("Sync msg send error retval %d\n", isc_retval);
1277                 }
1278                 if (!rcv_sync_msg) {
1279                         isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1280                                 sizeof(msg_info), 1);
1281                 }
1282 #if 0
1283                 printf("CTL:Frontend Enable\n");
1284         } else {
1285                 printf("%s: single mode, skipping frontend synchronization\n",
1286                         __func__);
1287 #endif
1288         }
1289
1290         STAILQ_FOREACH(port, &softc->port_list, links) {
1291                 if (port_type & port->port_type)
1292                 {
1293 #if 0
1294                         printf("port %d\n", port->targ_port);
1295 #endif
1296                         ctl_port_online(port);
1297                 }
1298         }
1299
1300         return (0);
1301 }
1302
1303 int
1304 ctl_port_disable(ctl_port_type port_type)
1305 {
1306         struct ctl_softc *softc;
1307         struct ctl_port *port;
1308
1309         softc = control_softc;
1310
1311         STAILQ_FOREACH(port, &softc->port_list, links) {
1312                 if (port_type & port->port_type)
1313                         ctl_port_offline(port);
1314         }
1315
1316         return (0);
1317 }
1318
1319 /*
1320  * Returns 0 for success, 1 for failure.
1321  * Currently the only failure mode is if there aren't enough entries
1322  * allocated.  So, in case of a failure, look at num_entries_dropped,
1323  * reallocate and try again.
1324  */
1325 int
1326 ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1327               int *num_entries_filled, int *num_entries_dropped,
1328               ctl_port_type port_type, int no_virtual)
1329 {
1330         struct ctl_softc *softc;
1331         struct ctl_port *port;
1332         int entries_dropped, entries_filled;
1333         int retval;
1334         int i;
1335
1336         softc = control_softc;
1337
1338         retval = 0;
1339         entries_filled = 0;
1340         entries_dropped = 0;
1341
1342         i = 0;
1343         mtx_lock(&softc->ctl_lock);
1344         STAILQ_FOREACH(port, &softc->port_list, links) {
1345                 struct ctl_port_entry *entry;
1346
1347                 if ((port->port_type & port_type) == 0)
1348                         continue;
1349
1350                 if ((no_virtual != 0)
1351                  && (port->virtual_port != 0))
1352                         continue;
1353
1354                 if (entries_filled >= num_entries_alloced) {
1355                         entries_dropped++;
1356                         continue;
1357                 }
1358                 entry = &entries[i];
1359
1360                 entry->port_type = port->port_type;
1361                 strlcpy(entry->port_name, port->port_name,
1362                         sizeof(entry->port_name));
1363                 entry->physical_port = port->physical_port;
1364                 entry->virtual_port = port->virtual_port;
1365                 entry->wwnn = port->wwnn;
1366                 entry->wwpn = port->wwpn;
1367
1368                 i++;
1369                 entries_filled++;
1370         }
1371
1372         mtx_unlock(&softc->ctl_lock);
1373
1374         if (entries_dropped > 0)
1375                 retval = 1;
1376
1377         *num_entries_dropped = entries_dropped;
1378         *num_entries_filled = entries_filled;
1379
1380         return (retval);
1381 }
1382
1383 static void
1384 ctl_ioctl_online(void *arg)
1385 {
1386         struct ctl_ioctl_info *ioctl_info;
1387
1388         ioctl_info = (struct ctl_ioctl_info *)arg;
1389
1390         ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1391 }
1392
1393 static void
1394 ctl_ioctl_offline(void *arg)
1395 {
1396         struct ctl_ioctl_info *ioctl_info;
1397
1398         ioctl_info = (struct ctl_ioctl_info *)arg;
1399
1400         ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1401 }
1402
1403 /*
1404  * Remove an initiator by port number and initiator ID.
1405  * Returns 0 for success, -1 for failure.
1406  */
1407 int
1408 ctl_remove_initiator(struct ctl_port *port, int iid)
1409 {
1410         struct ctl_softc *softc = control_softc;
1411
1412         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1413
1414         if (iid > CTL_MAX_INIT_PER_PORT) {
1415                 printf("%s: initiator ID %u > maximun %u!\n",
1416                        __func__, iid, CTL_MAX_INIT_PER_PORT);
1417                 return (-1);
1418         }
1419
1420         mtx_lock(&softc->ctl_lock);
1421         port->wwpn_iid[iid].in_use--;
1422         port->wwpn_iid[iid].last_use = time_uptime;
1423         mtx_unlock(&softc->ctl_lock);
1424
1425         return (0);
1426 }
1427
1428 /*
1429  * Add an initiator to the initiator map.
1430  * Returns iid for success, < 0 for failure.
1431  */
1432 int
1433 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1434 {
1435         struct ctl_softc *softc = control_softc;
1436         time_t best_time;
1437         int i, best;
1438
1439         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1440
1441         if (iid >= CTL_MAX_INIT_PER_PORT) {
1442                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1443                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1444                 free(name, M_CTL);
1445                 return (-1);
1446         }
1447
1448         mtx_lock(&softc->ctl_lock);
1449
1450         if (iid < 0 && (wwpn != 0 || name != NULL)) {
1451                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1452                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1453                                 iid = i;
1454                                 break;
1455                         }
1456                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
1457                             strcmp(name, port->wwpn_iid[i].name) == 0) {
1458                                 iid = i;
1459                                 break;
1460                         }
1461                 }
1462         }
1463
1464         if (iid < 0) {
1465                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1466                         if (port->wwpn_iid[i].in_use == 0 &&
1467                             port->wwpn_iid[i].wwpn == 0 &&
1468                             port->wwpn_iid[i].name == NULL) {
1469                                 iid = i;
1470                                 break;
1471                         }
1472                 }
1473         }
1474
1475         if (iid < 0) {
1476                 best = -1;
1477                 best_time = INT32_MAX;
1478                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1479                         if (port->wwpn_iid[i].in_use == 0) {
1480                                 if (port->wwpn_iid[i].last_use < best_time) {
1481                                         best = i;
1482                                         best_time = port->wwpn_iid[i].last_use;
1483                                 }
1484                         }
1485                 }
1486                 iid = best;
1487         }
1488
1489         if (iid < 0) {
1490                 mtx_unlock(&softc->ctl_lock);
1491                 free(name, M_CTL);
1492                 return (-2);
1493         }
1494
1495         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1496                 /*
1497                  * This is not an error yet.
1498                  */
1499                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1500 #if 0
1501                         printf("%s: port %d iid %u WWPN %#jx arrived"
1502                             " again\n", __func__, port->targ_port,
1503                             iid, (uintmax_t)wwpn);
1504 #endif
1505                         goto take;
1506                 }
1507                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1508                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
1509 #if 0
1510                         printf("%s: port %d iid %u name '%s' arrived"
1511                             " again\n", __func__, port->targ_port,
1512                             iid, name);
1513 #endif
1514                         goto take;
1515                 }
1516
1517                 /*
1518                  * This is an error, but what do we do about it?  The
1519                  * driver is telling us we have a new WWPN for this
1520                  * initiator ID, so we pretty much need to use it.
1521                  */
1522                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1523                     " but WWPN %#jx '%s' is still at that address\n",
1524                     __func__, port->targ_port, iid, wwpn, name,
1525                     (uintmax_t)port->wwpn_iid[iid].wwpn,
1526                     port->wwpn_iid[iid].name);
1527
1528                 /*
1529                  * XXX KDM clear have_ca and ua_pending on each LUN for
1530                  * this initiator.
1531                  */
1532         }
1533 take:
1534         free(port->wwpn_iid[iid].name, M_CTL);
1535         port->wwpn_iid[iid].name = name;
1536         port->wwpn_iid[iid].wwpn = wwpn;
1537         port->wwpn_iid[iid].in_use++;
1538         mtx_unlock(&softc->ctl_lock);
1539
1540         return (iid);
1541 }
1542
1543 static int
1544 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1545 {
1546         int len;
1547
1548         switch (port->port_type) {
1549         case CTL_PORT_FC:
1550         {
1551                 struct scsi_transportid_fcp *id =
1552                     (struct scsi_transportid_fcp *)buf;
1553                 if (port->wwpn_iid[iid].wwpn == 0)
1554                         return (0);
1555                 memset(id, 0, sizeof(*id));
1556                 id->format_protocol = SCSI_PROTO_FC;
1557                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1558                 return (sizeof(*id));
1559         }
1560         case CTL_PORT_ISCSI:
1561         {
1562                 struct scsi_transportid_iscsi_port *id =
1563                     (struct scsi_transportid_iscsi_port *)buf;
1564                 if (port->wwpn_iid[iid].name == NULL)
1565                         return (0);
1566                 memset(id, 0, 256);
1567                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1568                     SCSI_PROTO_ISCSI;
1569                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1570                 len = roundup2(min(len, 252), 4);
1571                 scsi_ulto2b(len, id->additional_length);
1572                 return (sizeof(*id) + len);
1573         }
1574         case CTL_PORT_SAS:
1575         {
1576                 struct scsi_transportid_sas *id =
1577                     (struct scsi_transportid_sas *)buf;
1578                 if (port->wwpn_iid[iid].wwpn == 0)
1579                         return (0);
1580                 memset(id, 0, sizeof(*id));
1581                 id->format_protocol = SCSI_PROTO_SAS;
1582                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1583                 return (sizeof(*id));
1584         }
1585         default:
1586         {
1587                 struct scsi_transportid_spi *id =
1588                     (struct scsi_transportid_spi *)buf;
1589                 memset(id, 0, sizeof(*id));
1590                 id->format_protocol = SCSI_PROTO_SPI;
1591                 scsi_ulto2b(iid, id->scsi_addr);
1592                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1593                 return (sizeof(*id));
1594         }
1595         }
1596 }
1597
1598 static int
1599 ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1600 {
1601         return (0);
1602 }
1603
1604 static int
1605 ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1606 {
1607         return (0);
1608 }
1609
1610 /*
1611  * Data movement routine for the CTL ioctl frontend port.
1612  */
1613 static int
1614 ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1615 {
1616         struct ctl_sg_entry *ext_sglist, *kern_sglist;
1617         struct ctl_sg_entry ext_entry, kern_entry;
1618         int ext_sglen, ext_sg_entries, kern_sg_entries;
1619         int ext_sg_start, ext_offset;
1620         int len_to_copy, len_copied;
1621         int kern_watermark, ext_watermark;
1622         int ext_sglist_malloced;
1623         int i, j;
1624
1625         ext_sglist_malloced = 0;
1626         ext_sg_start = 0;
1627         ext_offset = 0;
1628
1629         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1630
1631         /*
1632          * If this flag is set, fake the data transfer.
1633          */
1634         if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1635                 ctsio->ext_data_filled = ctsio->ext_data_len;
1636                 goto bailout;
1637         }
1638
1639         /*
1640          * To simplify things here, if we have a single buffer, stick it in
1641          * a S/G entry and just make it a single entry S/G list.
1642          */
1643         if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1644                 int len_seen;
1645
1646                 ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1647
1648                 ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1649                                                            M_WAITOK);
1650                 ext_sglist_malloced = 1;
1651                 if (copyin(ctsio->ext_data_ptr, ext_sglist,
1652                                    ext_sglen) != 0) {
1653                         ctl_set_internal_failure(ctsio,
1654                                                  /*sks_valid*/ 0,
1655                                                  /*retry_count*/ 0);
1656                         goto bailout;
1657                 }
1658                 ext_sg_entries = ctsio->ext_sg_entries;
1659                 len_seen = 0;
1660                 for (i = 0; i < ext_sg_entries; i++) {
1661                         if ((len_seen + ext_sglist[i].len) >=
1662                              ctsio->ext_data_filled) {
1663                                 ext_sg_start = i;
1664                                 ext_offset = ctsio->ext_data_filled - len_seen;
1665                                 break;
1666                         }
1667                         len_seen += ext_sglist[i].len;
1668                 }
1669         } else {
1670                 ext_sglist = &ext_entry;
1671                 ext_sglist->addr = ctsio->ext_data_ptr;
1672                 ext_sglist->len = ctsio->ext_data_len;
1673                 ext_sg_entries = 1;
1674                 ext_sg_start = 0;
1675                 ext_offset = ctsio->ext_data_filled;
1676         }
1677
1678         if (ctsio->kern_sg_entries > 0) {
1679                 kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1680                 kern_sg_entries = ctsio->kern_sg_entries;
1681         } else {
1682                 kern_sglist = &kern_entry;
1683                 kern_sglist->addr = ctsio->kern_data_ptr;
1684                 kern_sglist->len = ctsio->kern_data_len;
1685                 kern_sg_entries = 1;
1686         }
1687
1688
1689         kern_watermark = 0;
1690         ext_watermark = ext_offset;
1691         len_copied = 0;
1692         for (i = ext_sg_start, j = 0;
1693              i < ext_sg_entries && j < kern_sg_entries;) {
1694                 uint8_t *ext_ptr, *kern_ptr;
1695
1696                 len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1697                                       kern_sglist[j].len - kern_watermark);
1698
1699                 ext_ptr = (uint8_t *)ext_sglist[i].addr;
1700                 ext_ptr = ext_ptr + ext_watermark;
1701                 if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1702                         /*
1703                          * XXX KDM fix this!
1704                          */
1705                         panic("need to implement bus address support");
1706 #if 0
1707                         kern_ptr = bus_to_virt(kern_sglist[j].addr);
1708 #endif
1709                 } else
1710                         kern_ptr = (uint8_t *)kern_sglist[j].addr;
1711                 kern_ptr = kern_ptr + kern_watermark;
1712
1713                 kern_watermark += len_to_copy;
1714                 ext_watermark += len_to_copy;
1715
1716                 if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1717                      CTL_FLAG_DATA_IN) {
1718                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1719                                          "bytes to user\n", len_to_copy));
1720                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1721                                          "to %p\n", kern_ptr, ext_ptr));
1722                         if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1723                                 ctl_set_internal_failure(ctsio,
1724                                                          /*sks_valid*/ 0,
1725                                                          /*retry_count*/ 0);
1726                                 goto bailout;
1727                         }
1728                 } else {
1729                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1730                                          "bytes from user\n", len_to_copy));
1731                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1732                                          "to %p\n", ext_ptr, kern_ptr));
1733                         if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1734                                 ctl_set_internal_failure(ctsio,
1735                                                          /*sks_valid*/ 0,
1736                                                          /*retry_count*/0);
1737                                 goto bailout;
1738                         }
1739                 }
1740
1741                 len_copied += len_to_copy;
1742
1743                 if (ext_sglist[i].len == ext_watermark) {
1744                         i++;
1745                         ext_watermark = 0;
1746                 }
1747
1748                 if (kern_sglist[j].len == kern_watermark) {
1749                         j++;
1750                         kern_watermark = 0;
1751                 }
1752         }
1753
1754         ctsio->ext_data_filled += len_copied;
1755
1756         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1757                          "kern_sg_entries: %d\n", ext_sg_entries,
1758                          kern_sg_entries));
1759         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1760                          "kern_data_len = %d\n", ctsio->ext_data_len,
1761                          ctsio->kern_data_len));
1762
1763
1764         /* XXX KDM set residual?? */
1765 bailout:
1766
1767         if (ext_sglist_malloced != 0)
1768                 free(ext_sglist, M_CTL);
1769
1770         return (CTL_RETVAL_COMPLETE);
1771 }
1772
1773 /*
1774  * Serialize a command that went down the "wrong" side, and so was sent to
1775  * this controller for execution.  The logic is a little different than the
1776  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1777  * sent back to the other side, but in the success case, we execute the
1778  * command on this side (XFER mode) or tell the other side to execute it
1779  * (SER_ONLY mode).
1780  */
1781 static int
1782 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1783 {
1784         struct ctl_softc *ctl_softc;
1785         union ctl_ha_msg msg_info;
1786         struct ctl_lun *lun;
1787         int retval = 0;
1788         uint32_t targ_lun;
1789
1790         ctl_softc = control_softc;
1791
1792         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1793         lun = ctl_softc->ctl_luns[targ_lun];
1794         if (lun==NULL)
1795         {
1796                 /*
1797                  * Why isn't LUN defined? The other side wouldn't
1798                  * send a cmd if the LUN is undefined.
1799                  */
1800                 printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1801
1802                 /* "Logical unit not supported" */
1803                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1804                                    lun,
1805                                    /*sense_format*/SSD_TYPE_NONE,
1806                                    /*current_error*/ 1,
1807                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1808                                    /*asc*/ 0x25,
1809                                    /*ascq*/ 0x00,
1810                                    SSD_ELEM_NONE);
1811
1812                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1813                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1814                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1815                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1816                 msg_info.hdr.serializing_sc = NULL;
1817                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1818                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1819                                 sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1820                 }
1821                 return(1);
1822
1823         }
1824
1825         mtx_lock(&lun->lun_lock);
1826         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1827
1828         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1829                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1830                  ooa_links))) {
1831         case CTL_ACTION_BLOCK:
1832                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1833                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1834                                   blocked_links);
1835                 break;
1836         case CTL_ACTION_PASS:
1837         case CTL_ACTION_SKIP:
1838                 if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1839                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1840                         ctl_enqueue_rtr((union ctl_io *)ctsio);
1841                 } else {
1842
1843                         /* send msg back to other side */
1844                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1845                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1846                         msg_info.hdr.msg_type = CTL_MSG_R2R;
1847 #if 0
1848                         printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1849 #endif
1850                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1851                             sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1852                         }
1853                 }
1854                 break;
1855         case CTL_ACTION_OVERLAP:
1856                 /* OVERLAPPED COMMANDS ATTEMPTED */
1857                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1858                                    lun,
1859                                    /*sense_format*/SSD_TYPE_NONE,
1860                                    /*current_error*/ 1,
1861                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1862                                    /*asc*/ 0x4E,
1863                                    /*ascq*/ 0x00,
1864                                    SSD_ELEM_NONE);
1865
1866                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1867                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1868                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1869                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1870                 msg_info.hdr.serializing_sc = NULL;
1871                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1872 #if 0
1873                 printf("BAD JUJU:Major Bummer Overlap\n");
1874 #endif
1875                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1876                 retval = 1;
1877                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1878                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1879                 }
1880                 break;
1881         case CTL_ACTION_OVERLAP_TAG:
1882                 /* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1883                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1884                                    lun,
1885                                    /*sense_format*/SSD_TYPE_NONE,
1886                                    /*current_error*/ 1,
1887                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1888                                    /*asc*/ 0x4D,
1889                                    /*ascq*/ ctsio->tag_num & 0xff,
1890                                    SSD_ELEM_NONE);
1891
1892                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1893                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1894                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1895                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1896                 msg_info.hdr.serializing_sc = NULL;
1897                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1898 #if 0
1899                 printf("BAD JUJU:Major Bummer Overlap Tag\n");
1900 #endif
1901                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1902                 retval = 1;
1903                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1904                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1905                 }
1906                 break;
1907         case CTL_ACTION_ERROR:
1908         default:
1909                 /* "Internal target failure" */
1910                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1911                                    lun,
1912                                    /*sense_format*/SSD_TYPE_NONE,
1913                                    /*current_error*/ 1,
1914                                    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1915                                    /*asc*/ 0x44,
1916                                    /*ascq*/ 0x00,
1917                                    SSD_ELEM_NONE);
1918
1919                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1920                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1921                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1922                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1923                 msg_info.hdr.serializing_sc = NULL;
1924                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1925 #if 0
1926                 printf("BAD JUJU:Major Bummer HW Error\n");
1927 #endif
1928                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1929                 retval = 1;
1930                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1931                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1932                 }
1933                 break;
1934         }
1935         mtx_unlock(&lun->lun_lock);
1936         return (retval);
1937 }
1938
1939 static int
1940 ctl_ioctl_submit_wait(union ctl_io *io)
1941 {
1942         struct ctl_fe_ioctl_params params;
1943         ctl_fe_ioctl_state last_state;
1944         int done, retval;
1945
1946         retval = 0;
1947
1948         bzero(&params, sizeof(params));
1949
1950         mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1951         cv_init(&params.sem, "ctlioccv");
1952         params.state = CTL_IOCTL_INPROG;
1953         last_state = params.state;
1954
1955         io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1956
1957         CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1958
1959         /* This shouldn't happen */
1960         if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1961                 return (retval);
1962
1963         done = 0;
1964
1965         do {
1966                 mtx_lock(&params.ioctl_mtx);
1967                 /*
1968                  * Check the state here, and don't sleep if the state has
1969                  * already changed (i.e. wakeup has already occured, but we
1970                  * weren't waiting yet).
1971                  */
1972                 if (params.state == last_state) {
1973                         /* XXX KDM cv_wait_sig instead? */
1974                         cv_wait(&params.sem, &params.ioctl_mtx);
1975                 }
1976                 last_state = params.state;
1977
1978                 switch (params.state) {
1979                 case CTL_IOCTL_INPROG:
1980                         /* Why did we wake up? */
1981                         /* XXX KDM error here? */
1982                         mtx_unlock(&params.ioctl_mtx);
1983                         break;
1984                 case CTL_IOCTL_DATAMOVE:
1985                         CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1986
1987                         /*
1988                          * change last_state back to INPROG to avoid
1989                          * deadlock on subsequent data moves.
1990                          */
1991                         params.state = last_state = CTL_IOCTL_INPROG;
1992
1993                         mtx_unlock(&params.ioctl_mtx);
1994                         ctl_ioctl_do_datamove(&io->scsiio);
1995                         /*
1996                          * Note that in some cases, most notably writes,
1997                          * this will queue the I/O and call us back later.
1998                          * In other cases, generally reads, this routine
1999                          * will immediately call back and wake us up,
2000                          * probably using our own context.
2001                          */
2002                         io->scsiio.be_move_done(io);
2003                         break;
2004                 case CTL_IOCTL_DONE:
2005                         mtx_unlock(&params.ioctl_mtx);
2006                         CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
2007                         done = 1;
2008                         break;
2009                 default:
2010                         mtx_unlock(&params.ioctl_mtx);
2011                         /* XXX KDM error here? */
2012                         break;
2013                 }
2014         } while (done == 0);
2015
2016         mtx_destroy(&params.ioctl_mtx);
2017         cv_destroy(&params.sem);
2018
2019         return (CTL_RETVAL_COMPLETE);
2020 }
2021
2022 static void
2023 ctl_ioctl_datamove(union ctl_io *io)
2024 {
2025         struct ctl_fe_ioctl_params *params;
2026
2027         params = (struct ctl_fe_ioctl_params *)
2028                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2029
2030         mtx_lock(&params->ioctl_mtx);
2031         params->state = CTL_IOCTL_DATAMOVE;
2032         cv_broadcast(&params->sem);
2033         mtx_unlock(&params->ioctl_mtx);
2034 }
2035
2036 static void
2037 ctl_ioctl_done(union ctl_io *io)
2038 {
2039         struct ctl_fe_ioctl_params *params;
2040
2041         params = (struct ctl_fe_ioctl_params *)
2042                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2043
2044         mtx_lock(&params->ioctl_mtx);
2045         params->state = CTL_IOCTL_DONE;
2046         cv_broadcast(&params->sem);
2047         mtx_unlock(&params->ioctl_mtx);
2048 }
2049
2050 static void
2051 ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2052 {
2053         struct ctl_fe_ioctl_startstop_info *sd_info;
2054
2055         sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2056
2057         sd_info->hs_info.status = metatask->status;
2058         sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2059         sd_info->hs_info.luns_complete =
2060                 metatask->taskinfo.startstop.luns_complete;
2061         sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2062
2063         cv_broadcast(&sd_info->sem);
2064 }
2065
2066 static void
2067 ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2068 {
2069         struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2070
2071         fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2072
2073         mtx_lock(fe_bbr_info->lock);
2074         fe_bbr_info->bbr_info->status = metatask->status;
2075         fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2076         fe_bbr_info->wakeup_done = 1;
2077         mtx_unlock(fe_bbr_info->lock);
2078
2079         cv_broadcast(&fe_bbr_info->sem);
2080 }
2081
2082 /*
2083  * Returns 0 for success, errno for failure.
2084  */
2085 static int
2086 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2087                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2088 {
2089         union ctl_io *io;
2090         int retval;
2091
2092         retval = 0;
2093
2094         mtx_lock(&lun->lun_lock);
2095         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2096              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2097              ooa_links)) {
2098                 struct ctl_ooa_entry *entry;
2099
2100                 /*
2101                  * If we've got more than we can fit, just count the
2102                  * remaining entries.
2103                  */
2104                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2105                         continue;
2106
2107                 entry = &kern_entries[*cur_fill_num];
2108
2109                 entry->tag_num = io->scsiio.tag_num;
2110                 entry->lun_num = lun->lun;
2111 #ifdef CTL_TIME_IO
2112                 entry->start_bt = io->io_hdr.start_bt;
2113 #endif
2114                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2115                 entry->cdb_len = io->scsiio.cdb_len;
2116                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2117                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2118
2119                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2120                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2121
2122                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2123                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2124
2125                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2126                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2127
2128                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2129                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2130         }
2131         mtx_unlock(&lun->lun_lock);
2132
2133         return (retval);
2134 }
2135
2136 static void *
2137 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2138                  size_t error_str_len)
2139 {
2140         void *kptr;
2141
2142         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2143
2144         if (copyin(user_addr, kptr, len) != 0) {
2145                 snprintf(error_str, error_str_len, "Error copying %d bytes "
2146                          "from user address %p to kernel address %p", len,
2147                          user_addr, kptr);
2148                 free(kptr, M_CTL);
2149                 return (NULL);
2150         }
2151
2152         return (kptr);
2153 }
2154
2155 static void
2156 ctl_free_args(int num_args, struct ctl_be_arg *args)
2157 {
2158         int i;
2159
2160         if (args == NULL)
2161                 return;
2162
2163         for (i = 0; i < num_args; i++) {
2164                 free(args[i].kname, M_CTL);
2165                 free(args[i].kvalue, M_CTL);
2166         }
2167
2168         free(args, M_CTL);
2169 }
2170
2171 static struct ctl_be_arg *
2172 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2173                 char *error_str, size_t error_str_len)
2174 {
2175         struct ctl_be_arg *args;
2176         int i;
2177
2178         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2179                                 error_str, error_str_len);
2180
2181         if (args == NULL)
2182                 goto bailout;
2183
2184         for (i = 0; i < num_args; i++) {
2185                 args[i].kname = NULL;
2186                 args[i].kvalue = NULL;
2187         }
2188
2189         for (i = 0; i < num_args; i++) {
2190                 uint8_t *tmpptr;
2191
2192                 args[i].kname = ctl_copyin_alloc(args[i].name,
2193                         args[i].namelen, error_str, error_str_len);
2194                 if (args[i].kname == NULL)
2195                         goto bailout;
2196
2197                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2198                         snprintf(error_str, error_str_len, "Argument %d "
2199                                  "name is not NUL-terminated", i);
2200                         goto bailout;
2201                 }
2202
2203                 if (args[i].flags & CTL_BEARG_RD) {
2204                         tmpptr = ctl_copyin_alloc(args[i].value,
2205                                 args[i].vallen, error_str, error_str_len);
2206                         if (tmpptr == NULL)
2207                                 goto bailout;
2208                         if ((args[i].flags & CTL_BEARG_ASCII)
2209                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2210                                 snprintf(error_str, error_str_len, "Argument "
2211                                     "%d value is not NUL-terminated", i);
2212                                 goto bailout;
2213                         }
2214                         args[i].kvalue = tmpptr;
2215                 } else {
2216                         args[i].kvalue = malloc(args[i].vallen,
2217                             M_CTL, M_WAITOK | M_ZERO);
2218                 }
2219         }
2220
2221         return (args);
2222 bailout:
2223
2224         ctl_free_args(num_args, args);
2225
2226         return (NULL);
2227 }
2228
2229 static void
2230 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2231 {
2232         int i;
2233
2234         for (i = 0; i < num_args; i++) {
2235                 if (args[i].flags & CTL_BEARG_WR)
2236                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2237         }
2238 }
2239
2240 /*
2241  * Escape characters that are illegal or not recommended in XML.
2242  */
2243 int
2244 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2245 {
2246         char *end = str + size;
2247         int retval;
2248
2249         retval = 0;
2250
2251         for (; *str && str < end; str++) {
2252                 switch (*str) {
2253                 case '&':
2254                         retval = sbuf_printf(sb, "&amp;");
2255                         break;
2256                 case '>':
2257                         retval = sbuf_printf(sb, "&gt;");
2258                         break;
2259                 case '<':
2260                         retval = sbuf_printf(sb, "&lt;");
2261                         break;
2262                 default:
2263                         retval = sbuf_putc(sb, *str);
2264                         break;
2265                 }
2266
2267                 if (retval != 0)
2268                         break;
2269
2270         }
2271
2272         return (retval);
2273 }
2274
2275 static void
2276 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2277 {
2278         struct scsi_vpd_id_descriptor *desc;
2279         int i;
2280
2281         if (id == NULL || id->len < 4)
2282                 return;
2283         desc = (struct scsi_vpd_id_descriptor *)id->data;
2284         switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2285         case SVPD_ID_TYPE_T10:
2286                 sbuf_printf(sb, "t10.");
2287                 break;
2288         case SVPD_ID_TYPE_EUI64:
2289                 sbuf_printf(sb, "eui.");
2290                 break;
2291         case SVPD_ID_TYPE_NAA:
2292                 sbuf_printf(sb, "naa.");
2293                 break;
2294         case SVPD_ID_TYPE_SCSI_NAME:
2295                 break;
2296         }
2297         switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2298         case SVPD_ID_CODESET_BINARY:
2299                 for (i = 0; i < desc->length; i++)
2300                         sbuf_printf(sb, "%02x", desc->identifier[i]);
2301                 break;
2302         case SVPD_ID_CODESET_ASCII:
2303                 sbuf_printf(sb, "%.*s", (int)desc->length,
2304                     (char *)desc->identifier);
2305                 break;
2306         case SVPD_ID_CODESET_UTF8:
2307                 sbuf_printf(sb, "%s", (char *)desc->identifier);
2308                 break;
2309         }
2310 }
2311
2312 static int
2313 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2314           struct thread *td)
2315 {
2316         struct ctl_softc *softc;
2317         int retval;
2318
2319         softc = control_softc;
2320
2321         retval = 0;
2322
2323         switch (cmd) {
2324         case CTL_IO: {
2325                 union ctl_io *io;
2326                 void *pool_tmp;
2327
2328                 /*
2329                  * If we haven't been "enabled", don't allow any SCSI I/O
2330                  * to this FETD.
2331                  */
2332                 if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2333                         retval = EPERM;
2334                         break;
2335                 }
2336
2337                 io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2338
2339                 /*
2340                  * Need to save the pool reference so it doesn't get
2341                  * spammed by the user's ctl_io.
2342                  */
2343                 pool_tmp = io->io_hdr.pool;
2344                 memcpy(io, (void *)addr, sizeof(*io));
2345                 io->io_hdr.pool = pool_tmp;
2346
2347                 /*
2348                  * No status yet, so make sure the status is set properly.
2349                  */
2350                 io->io_hdr.status = CTL_STATUS_NONE;
2351
2352                 /*
2353                  * The user sets the initiator ID, target and LUN IDs.
2354                  */
2355                 io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2356                 io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2357                 if ((io->io_hdr.io_type == CTL_IO_SCSI)
2358                  && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2359                         io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2360
2361                 retval = ctl_ioctl_submit_wait(io);
2362
2363                 if (retval != 0) {
2364                         ctl_free_io(io);
2365                         break;
2366                 }
2367
2368                 memcpy((void *)addr, io, sizeof(*io));
2369
2370                 /* return this to our pool */
2371                 ctl_free_io(io);
2372
2373                 break;
2374         }
2375         case CTL_ENABLE_PORT:
2376         case CTL_DISABLE_PORT:
2377         case CTL_SET_PORT_WWNS: {
2378                 struct ctl_port *port;
2379                 struct ctl_port_entry *entry;
2380
2381                 entry = (struct ctl_port_entry *)addr;
2382                 
2383                 mtx_lock(&softc->ctl_lock);
2384                 STAILQ_FOREACH(port, &softc->port_list, links) {
2385                         int action, done;
2386
2387                         action = 0;
2388                         done = 0;
2389
2390                         if ((entry->port_type == CTL_PORT_NONE)
2391                          && (entry->targ_port == port->targ_port)) {
2392                                 /*
2393                                  * If the user only wants to enable or
2394                                  * disable or set WWNs on a specific port,
2395                                  * do the operation and we're done.
2396                                  */
2397                                 action = 1;
2398                                 done = 1;
2399                         } else if (entry->port_type & port->port_type) {
2400                                 /*
2401                                  * Compare the user's type mask with the
2402                                  * particular frontend type to see if we
2403                                  * have a match.
2404                                  */
2405                                 action = 1;
2406                                 done = 0;
2407
2408                                 /*
2409                                  * Make sure the user isn't trying to set
2410                                  * WWNs on multiple ports at the same time.
2411                                  */
2412                                 if (cmd == CTL_SET_PORT_WWNS) {
2413                                         printf("%s: Can't set WWNs on "
2414                                                "multiple ports\n", __func__);
2415                                         retval = EINVAL;
2416                                         break;
2417                                 }
2418                         }
2419                         if (action != 0) {
2420                                 /*
2421                                  * XXX KDM we have to drop the lock here,
2422                                  * because the online/offline operations
2423                                  * can potentially block.  We need to
2424                                  * reference count the frontends so they
2425                                  * can't go away,
2426                                  */
2427                                 mtx_unlock(&softc->ctl_lock);
2428
2429                                 if (cmd == CTL_ENABLE_PORT) {
2430                                         struct ctl_lun *lun;
2431
2432                                         STAILQ_FOREACH(lun, &softc->lun_list,
2433                                                        links) {
2434                                                 port->lun_enable(port->targ_lun_arg,
2435                                                     lun->target,
2436                                                     lun->lun);
2437                                         }
2438
2439                                         ctl_port_online(port);
2440                                 } else if (cmd == CTL_DISABLE_PORT) {
2441                                         struct ctl_lun *lun;
2442
2443                                         ctl_port_offline(port);
2444
2445                                         STAILQ_FOREACH(lun, &softc->lun_list,
2446                                                        links) {
2447                                                 port->lun_disable(
2448                                                     port->targ_lun_arg,
2449                                                     lun->target,
2450                                                     lun->lun);
2451                                         }
2452                                 }
2453
2454                                 mtx_lock(&softc->ctl_lock);
2455
2456                                 if (cmd == CTL_SET_PORT_WWNS)
2457                                         ctl_port_set_wwns(port,
2458                                             (entry->flags & CTL_PORT_WWNN_VALID) ?
2459                                             1 : 0, entry->wwnn,
2460                                             (entry->flags & CTL_PORT_WWPN_VALID) ?
2461                                             1 : 0, entry->wwpn);
2462                         }
2463                         if (done != 0)
2464                                 break;
2465                 }
2466                 mtx_unlock(&softc->ctl_lock);
2467                 break;
2468         }
2469         case CTL_GET_PORT_LIST: {
2470                 struct ctl_port *port;
2471                 struct ctl_port_list *list;
2472                 int i;
2473
2474                 list = (struct ctl_port_list *)addr;
2475
2476                 if (list->alloc_len != (list->alloc_num *
2477                     sizeof(struct ctl_port_entry))) {
2478                         printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2479                                "alloc_num %u * sizeof(struct ctl_port_entry) "
2480                                "%zu\n", __func__, list->alloc_len,
2481                                list->alloc_num, sizeof(struct ctl_port_entry));
2482                         retval = EINVAL;
2483                         break;
2484                 }
2485                 list->fill_len = 0;
2486                 list->fill_num = 0;
2487                 list->dropped_num = 0;
2488                 i = 0;
2489                 mtx_lock(&softc->ctl_lock);
2490                 STAILQ_FOREACH(port, &softc->port_list, links) {
2491                         struct ctl_port_entry entry, *list_entry;
2492
2493                         if (list->fill_num >= list->alloc_num) {
2494                                 list->dropped_num++;
2495                                 continue;
2496                         }
2497
2498                         entry.port_type = port->port_type;
2499                         strlcpy(entry.port_name, port->port_name,
2500                                 sizeof(entry.port_name));
2501                         entry.targ_port = port->targ_port;
2502                         entry.physical_port = port->physical_port;
2503                         entry.virtual_port = port->virtual_port;
2504                         entry.wwnn = port->wwnn;
2505                         entry.wwpn = port->wwpn;
2506                         if (port->status & CTL_PORT_STATUS_ONLINE)
2507                                 entry.online = 1;
2508                         else
2509                                 entry.online = 0;
2510
2511                         list_entry = &list->entries[i];
2512
2513                         retval = copyout(&entry, list_entry, sizeof(entry));
2514                         if (retval != 0) {
2515                                 printf("%s: CTL_GET_PORT_LIST: copyout "
2516                                        "returned %d\n", __func__, retval);
2517                                 break;
2518                         }
2519                         i++;
2520                         list->fill_num++;
2521                         list->fill_len += sizeof(entry);
2522                 }
2523                 mtx_unlock(&softc->ctl_lock);
2524
2525                 /*
2526                  * If this is non-zero, we had a copyout fault, so there's
2527                  * probably no point in attempting to set the status inside
2528                  * the structure.
2529                  */
2530                 if (retval != 0)
2531                         break;
2532
2533                 if (list->dropped_num > 0)
2534                         list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2535                 else
2536                         list->status = CTL_PORT_LIST_OK;
2537                 break;
2538         }
2539         case CTL_DUMP_OOA: {
2540                 struct ctl_lun *lun;
2541                 union ctl_io *io;
2542                 char printbuf[128];
2543                 struct sbuf sb;
2544
2545                 mtx_lock(&softc->ctl_lock);
2546                 printf("Dumping OOA queues:\n");
2547                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2548                         mtx_lock(&lun->lun_lock);
2549                         for (io = (union ctl_io *)TAILQ_FIRST(
2550                              &lun->ooa_queue); io != NULL;
2551                              io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2552                              ooa_links)) {
2553                                 sbuf_new(&sb, printbuf, sizeof(printbuf),
2554                                          SBUF_FIXEDLEN);
2555                                 sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2556                                             (intmax_t)lun->lun,
2557                                             io->scsiio.tag_num,
2558                                             (io->io_hdr.flags &
2559                                             CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2560                                             (io->io_hdr.flags &
2561                                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2562                                             (io->io_hdr.flags &
2563                                             CTL_FLAG_ABORT) ? " ABORT" : "",
2564                                             (io->io_hdr.flags &
2565                                         CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2566                                 ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2567                                 sbuf_finish(&sb);
2568                                 printf("%s\n", sbuf_data(&sb));
2569                         }
2570                         mtx_unlock(&lun->lun_lock);
2571                 }
2572                 printf("OOA queues dump done\n");
2573                 mtx_unlock(&softc->ctl_lock);
2574                 break;
2575         }
2576         case CTL_GET_OOA: {
2577                 struct ctl_lun *lun;
2578                 struct ctl_ooa *ooa_hdr;
2579                 struct ctl_ooa_entry *entries;
2580                 uint32_t cur_fill_num;
2581
2582                 ooa_hdr = (struct ctl_ooa *)addr;
2583
2584                 if ((ooa_hdr->alloc_len == 0)
2585                  || (ooa_hdr->alloc_num == 0)) {
2586                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2587                                "must be non-zero\n", __func__,
2588                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2589                         retval = EINVAL;
2590                         break;
2591                 }
2592
2593                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2594                     sizeof(struct ctl_ooa_entry))) {
2595                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2596                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2597                                __func__, ooa_hdr->alloc_len,
2598                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2599                         retval = EINVAL;
2600                         break;
2601                 }
2602
2603                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2604                 if (entries == NULL) {
2605                         printf("%s: could not allocate %d bytes for OOA "
2606                                "dump\n", __func__, ooa_hdr->alloc_len);
2607                         retval = ENOMEM;
2608                         break;
2609                 }
2610
2611                 mtx_lock(&softc->ctl_lock);
2612                 if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2613                  && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2614                   || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2615                         mtx_unlock(&softc->ctl_lock);
2616                         free(entries, M_CTL);
2617                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2618                                __func__, (uintmax_t)ooa_hdr->lun_num);
2619                         retval = EINVAL;
2620                         break;
2621                 }
2622
2623                 cur_fill_num = 0;
2624
2625                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2626                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2627                                 retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2628                                         ooa_hdr, entries);
2629                                 if (retval != 0)
2630                                         break;
2631                         }
2632                         if (retval != 0) {
2633                                 mtx_unlock(&softc->ctl_lock);
2634                                 free(entries, M_CTL);
2635                                 break;
2636                         }
2637                 } else {
2638                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2639
2640                         retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2641                                                     entries);
2642                 }
2643                 mtx_unlock(&softc->ctl_lock);
2644
2645                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2646                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2647                         sizeof(struct ctl_ooa_entry);
2648                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2649                 if (retval != 0) {
2650                         printf("%s: error copying out %d bytes for OOA dump\n", 
2651                                __func__, ooa_hdr->fill_len);
2652                 }
2653
2654                 getbintime(&ooa_hdr->cur_bt);
2655
2656                 if (cur_fill_num > ooa_hdr->alloc_num) {
2657                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2658                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2659                 } else {
2660                         ooa_hdr->dropped_num = 0;
2661                         ooa_hdr->status = CTL_OOA_OK;
2662                 }
2663
2664                 free(entries, M_CTL);
2665                 break;
2666         }
2667         case CTL_CHECK_OOA: {
2668                 union ctl_io *io;
2669                 struct ctl_lun *lun;
2670                 struct ctl_ooa_info *ooa_info;
2671
2672
2673                 ooa_info = (struct ctl_ooa_info *)addr;
2674
2675                 if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2676                         ooa_info->status = CTL_OOA_INVALID_LUN;
2677                         break;
2678                 }
2679                 mtx_lock(&softc->ctl_lock);
2680                 lun = softc->ctl_luns[ooa_info->lun_id];
2681                 if (lun == NULL) {
2682                         mtx_unlock(&softc->ctl_lock);
2683                         ooa_info->status = CTL_OOA_INVALID_LUN;
2684                         break;
2685                 }
2686                 mtx_lock(&lun->lun_lock);
2687                 mtx_unlock(&softc->ctl_lock);
2688                 ooa_info->num_entries = 0;
2689                 for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2690                      io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2691                      &io->io_hdr, ooa_links)) {
2692                         ooa_info->num_entries++;
2693                 }
2694                 mtx_unlock(&lun->lun_lock);
2695
2696                 ooa_info->status = CTL_OOA_SUCCESS;
2697
2698                 break;
2699         }
2700         case CTL_HARD_START:
2701         case CTL_HARD_STOP: {
2702                 struct ctl_fe_ioctl_startstop_info ss_info;
2703                 struct cfi_metatask *metatask;
2704                 struct mtx hs_mtx;
2705
2706                 mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2707
2708                 cv_init(&ss_info.sem, "hard start/stop cv" );
2709
2710                 metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2711                 if (metatask == NULL) {
2712                         retval = ENOMEM;
2713                         mtx_destroy(&hs_mtx);
2714                         break;
2715                 }
2716
2717                 if (cmd == CTL_HARD_START)
2718                         metatask->tasktype = CFI_TASK_STARTUP;
2719                 else
2720                         metatask->tasktype = CFI_TASK_SHUTDOWN;
2721
2722                 metatask->callback = ctl_ioctl_hard_startstop_callback;
2723                 metatask->callback_arg = &ss_info;
2724
2725                 cfi_action(metatask);
2726
2727                 /* Wait for the callback */
2728                 mtx_lock(&hs_mtx);
2729                 cv_wait_sig(&ss_info.sem, &hs_mtx);
2730                 mtx_unlock(&hs_mtx);
2731
2732                 /*
2733                  * All information has been copied from the metatask by the
2734                  * time cv_broadcast() is called, so we free the metatask here.
2735                  */
2736                 cfi_free_metatask(metatask);
2737
2738                 memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2739
2740                 mtx_destroy(&hs_mtx);
2741                 break;
2742         }
2743         case CTL_BBRREAD: {
2744                 struct ctl_bbrread_info *bbr_info;
2745                 struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2746                 struct mtx bbr_mtx;
2747                 struct cfi_metatask *metatask;
2748
2749                 bbr_info = (struct ctl_bbrread_info *)addr;
2750
2751                 bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2752
2753                 bzero(&bbr_mtx, sizeof(bbr_mtx));
2754                 mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2755
2756                 fe_bbr_info.bbr_info = bbr_info;
2757                 fe_bbr_info.lock = &bbr_mtx;
2758
2759                 cv_init(&fe_bbr_info.sem, "BBR read cv");
2760                 metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2761
2762                 if (metatask == NULL) {
2763                         mtx_destroy(&bbr_mtx);
2764                         cv_destroy(&fe_bbr_info.sem);
2765                         retval = ENOMEM;
2766                         break;
2767                 }
2768                 metatask->tasktype = CFI_TASK_BBRREAD;
2769                 metatask->callback = ctl_ioctl_bbrread_callback;
2770                 metatask->callback_arg = &fe_bbr_info;
2771                 metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2772                 metatask->taskinfo.bbrread.lba = bbr_info->lba;
2773                 metatask->taskinfo.bbrread.len = bbr_info->len;
2774
2775                 cfi_action(metatask);
2776
2777                 mtx_lock(&bbr_mtx);
2778                 while (fe_bbr_info.wakeup_done == 0)
2779                         cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2780                 mtx_unlock(&bbr_mtx);
2781
2782                 bbr_info->status = metatask->status;
2783                 bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2784                 bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2785                 memcpy(&bbr_info->sense_data,
2786                        &metatask->taskinfo.bbrread.sense_data,
2787                        ctl_min(sizeof(bbr_info->sense_data),
2788                                sizeof(metatask->taskinfo.bbrread.sense_data)));
2789
2790                 cfi_free_metatask(metatask);
2791
2792                 mtx_destroy(&bbr_mtx);
2793                 cv_destroy(&fe_bbr_info.sem);
2794
2795                 break;
2796         }
2797         case CTL_DELAY_IO: {
2798                 struct ctl_io_delay_info *delay_info;
2799 #ifdef CTL_IO_DELAY
2800                 struct ctl_lun *lun;
2801 #endif /* CTL_IO_DELAY */
2802
2803                 delay_info = (struct ctl_io_delay_info *)addr;
2804
2805 #ifdef CTL_IO_DELAY
2806                 mtx_lock(&softc->ctl_lock);
2807
2808                 if ((delay_info->lun_id >= CTL_MAX_LUNS)
2809                  || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2810                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2811                 } else {
2812                         lun = softc->ctl_luns[delay_info->lun_id];
2813                         mtx_lock(&lun->lun_lock);
2814
2815                         delay_info->status = CTL_DELAY_STATUS_OK;
2816
2817                         switch (delay_info->delay_type) {
2818                         case CTL_DELAY_TYPE_CONT:
2819                                 break;
2820                         case CTL_DELAY_TYPE_ONESHOT:
2821                                 break;
2822                         default:
2823                                 delay_info->status =
2824                                         CTL_DELAY_STATUS_INVALID_TYPE;
2825                                 break;
2826                         }
2827
2828                         switch (delay_info->delay_loc) {
2829                         case CTL_DELAY_LOC_DATAMOVE:
2830                                 lun->delay_info.datamove_type =
2831                                         delay_info->delay_type;
2832                                 lun->delay_info.datamove_delay =
2833                                         delay_info->delay_secs;
2834                                 break;
2835                         case CTL_DELAY_LOC_DONE:
2836                                 lun->delay_info.done_type =
2837                                         delay_info->delay_type;
2838                                 lun->delay_info.done_delay =
2839                                         delay_info->delay_secs;
2840                                 break;
2841                         default:
2842                                 delay_info->status =
2843                                         CTL_DELAY_STATUS_INVALID_LOC;
2844                                 break;
2845                         }
2846                         mtx_unlock(&lun->lun_lock);
2847                 }
2848
2849                 mtx_unlock(&softc->ctl_lock);
2850 #else
2851                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2852 #endif /* CTL_IO_DELAY */
2853                 break;
2854         }
2855         case CTL_REALSYNC_SET: {
2856                 int *syncstate;
2857
2858                 syncstate = (int *)addr;
2859
2860                 mtx_lock(&softc->ctl_lock);
2861                 switch (*syncstate) {
2862                 case 0:
2863                         softc->flags &= ~CTL_FLAG_REAL_SYNC;
2864                         break;
2865                 case 1:
2866                         softc->flags |= CTL_FLAG_REAL_SYNC;
2867                         break;
2868                 default:
2869                         retval = EINVAL;
2870                         break;
2871                 }
2872                 mtx_unlock(&softc->ctl_lock);
2873                 break;
2874         }
2875         case CTL_REALSYNC_GET: {
2876                 int *syncstate;
2877
2878                 syncstate = (int*)addr;
2879
2880                 mtx_lock(&softc->ctl_lock);
2881                 if (softc->flags & CTL_FLAG_REAL_SYNC)
2882                         *syncstate = 1;
2883                 else
2884                         *syncstate = 0;
2885                 mtx_unlock(&softc->ctl_lock);
2886
2887                 break;
2888         }
2889         case CTL_SETSYNC:
2890         case CTL_GETSYNC: {
2891                 struct ctl_sync_info *sync_info;
2892                 struct ctl_lun *lun;
2893
2894                 sync_info = (struct ctl_sync_info *)addr;
2895
2896                 mtx_lock(&softc->ctl_lock);
2897                 lun = softc->ctl_luns[sync_info->lun_id];
2898                 if (lun == NULL) {
2899                         mtx_unlock(&softc->ctl_lock);
2900                         sync_info->status = CTL_GS_SYNC_NO_LUN;
2901                 }
2902                 /*
2903                  * Get or set the sync interval.  We're not bounds checking
2904                  * in the set case, hopefully the user won't do something
2905                  * silly.
2906                  */
2907                 mtx_lock(&lun->lun_lock);
2908                 mtx_unlock(&softc->ctl_lock);
2909                 if (cmd == CTL_GETSYNC)
2910                         sync_info->sync_interval = lun->sync_interval;
2911                 else
2912                         lun->sync_interval = sync_info->sync_interval;
2913                 mtx_unlock(&lun->lun_lock);
2914
2915                 sync_info->status = CTL_GS_SYNC_OK;
2916
2917                 break;
2918         }
2919         case CTL_GETSTATS: {
2920                 struct ctl_stats *stats;
2921                 struct ctl_lun *lun;
2922                 int i;
2923
2924                 stats = (struct ctl_stats *)addr;
2925
2926                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2927                      stats->alloc_len) {
2928                         stats->status = CTL_SS_NEED_MORE_SPACE;
2929                         stats->num_luns = softc->num_luns;
2930                         break;
2931                 }
2932                 /*
2933                  * XXX KDM no locking here.  If the LUN list changes,
2934                  * things can blow up.
2935                  */
2936                 for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2937                      i++, lun = STAILQ_NEXT(lun, links)) {
2938                         retval = copyout(&lun->stats, &stats->lun_stats[i],
2939                                          sizeof(lun->stats));
2940                         if (retval != 0)
2941                                 break;
2942                 }
2943                 stats->num_luns = softc->num_luns;
2944                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2945                                  softc->num_luns;
2946                 stats->status = CTL_SS_OK;
2947 #ifdef CTL_TIME_IO
2948                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
2949 #else
2950                 stats->flags = CTL_STATS_FLAG_NONE;
2951 #endif
2952                 getnanouptime(&stats->timestamp);
2953                 break;
2954         }
2955         case CTL_ERROR_INJECT: {
2956                 struct ctl_error_desc *err_desc, *new_err_desc;
2957                 struct ctl_lun *lun;
2958
2959                 err_desc = (struct ctl_error_desc *)addr;
2960
2961                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2962                                       M_WAITOK | M_ZERO);
2963                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2964
2965                 mtx_lock(&softc->ctl_lock);
2966                 lun = softc->ctl_luns[err_desc->lun_id];
2967                 if (lun == NULL) {
2968                         mtx_unlock(&softc->ctl_lock);
2969                         free(new_err_desc, M_CTL);
2970                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2971                                __func__, (uintmax_t)err_desc->lun_id);
2972                         retval = EINVAL;
2973                         break;
2974                 }
2975                 mtx_lock(&lun->lun_lock);
2976                 mtx_unlock(&softc->ctl_lock);
2977
2978                 /*
2979                  * We could do some checking here to verify the validity
2980                  * of the request, but given the complexity of error
2981                  * injection requests, the checking logic would be fairly
2982                  * complex.
2983                  *
2984                  * For now, if the request is invalid, it just won't get
2985                  * executed and might get deleted.
2986                  */
2987                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2988
2989                 /*
2990                  * XXX KDM check to make sure the serial number is unique,
2991                  * in case we somehow manage to wrap.  That shouldn't
2992                  * happen for a very long time, but it's the right thing to
2993                  * do.
2994                  */
2995                 new_err_desc->serial = lun->error_serial;
2996                 err_desc->serial = lun->error_serial;
2997                 lun->error_serial++;
2998
2999                 mtx_unlock(&lun->lun_lock);
3000                 break;
3001         }
3002         case CTL_ERROR_INJECT_DELETE: {
3003                 struct ctl_error_desc *delete_desc, *desc, *desc2;
3004                 struct ctl_lun *lun;
3005                 int delete_done;
3006
3007                 delete_desc = (struct ctl_error_desc *)addr;
3008                 delete_done = 0;
3009
3010                 mtx_lock(&softc->ctl_lock);
3011                 lun = softc->ctl_luns[delete_desc->lun_id];
3012                 if (lun == NULL) {
3013                         mtx_unlock(&softc->ctl_lock);
3014                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
3015                                __func__, (uintmax_t)delete_desc->lun_id);
3016                         retval = EINVAL;
3017                         break;
3018                 }
3019                 mtx_lock(&lun->lun_lock);
3020                 mtx_unlock(&softc->ctl_lock);
3021                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
3022                         if (desc->serial != delete_desc->serial)
3023                                 continue;
3024
3025                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
3026                                       links);
3027                         free(desc, M_CTL);
3028                         delete_done = 1;
3029                 }
3030                 mtx_unlock(&lun->lun_lock);
3031                 if (delete_done == 0) {
3032                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
3033                                "error serial %ju on LUN %u\n", __func__, 
3034                                delete_desc->serial, delete_desc->lun_id);
3035                         retval = EINVAL;
3036                         break;
3037                 }
3038                 break;
3039         }
3040         case CTL_DUMP_STRUCTS: {
3041                 int i, j, k, idx;
3042                 struct ctl_port *port;
3043                 struct ctl_frontend *fe;
3044
3045                 mtx_lock(&softc->ctl_lock);
3046                 printf("CTL Persistent Reservation information start:\n");
3047                 for (i = 0; i < CTL_MAX_LUNS; i++) {
3048                         struct ctl_lun *lun;
3049
3050                         lun = softc->ctl_luns[i];
3051
3052                         if ((lun == NULL)
3053                          || ((lun->flags & CTL_LUN_DISABLED) != 0))
3054                                 continue;
3055
3056                         for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
3057                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3058                                         idx = j * CTL_MAX_INIT_PER_PORT + k;
3059                                         if (lun->pr_keys[idx] == 0)
3060                                                 continue;
3061                                         printf("  LUN %d port %d iid %d key "
3062                                                "%#jx\n", i, j, k,
3063                                                (uintmax_t)lun->pr_keys[idx]);
3064                                 }
3065                         }
3066                 }
3067                 printf("CTL Persistent Reservation information end\n");
3068                 printf("CTL Ports:\n");
3069                 STAILQ_FOREACH(port, &softc->port_list, links) {
3070                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3071                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3072                                port->frontend->name, port->port_type,
3073                                port->physical_port, port->virtual_port,
3074                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3075                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3076                                 if (port->wwpn_iid[j].in_use == 0 &&
3077                                     port->wwpn_iid[j].wwpn == 0 &&
3078                                     port->wwpn_iid[j].name == NULL)
3079                                         continue;
3080
3081                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
3082                                     j, port->wwpn_iid[j].in_use,
3083                                     (uintmax_t)port->wwpn_iid[j].wwpn,
3084                                     port->wwpn_iid[j].name);
3085                         }
3086                 }
3087                 printf("CTL Port information end\n");
3088                 mtx_unlock(&softc->ctl_lock);
3089                 /*
3090                  * XXX KDM calling this without a lock.  We'd likely want
3091                  * to drop the lock before calling the frontend's dump
3092                  * routine anyway.
3093                  */
3094                 printf("CTL Frontends:\n");
3095                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
3096                         printf("  Frontend '%s'\n", fe->name);
3097                         if (fe->fe_dump != NULL)
3098                                 fe->fe_dump();
3099                 }
3100                 printf("CTL Frontend information end\n");
3101                 break;
3102         }
3103         case CTL_LUN_REQ: {
3104                 struct ctl_lun_req *lun_req;
3105                 struct ctl_backend_driver *backend;
3106
3107                 lun_req = (struct ctl_lun_req *)addr;
3108
3109                 backend = ctl_backend_find(lun_req->backend);
3110                 if (backend == NULL) {
3111                         lun_req->status = CTL_LUN_ERROR;
3112                         snprintf(lun_req->error_str,
3113                                  sizeof(lun_req->error_str),
3114                                  "Backend \"%s\" not found.",
3115                                  lun_req->backend);
3116                         break;
3117                 }
3118                 if (lun_req->num_be_args > 0) {
3119                         lun_req->kern_be_args = ctl_copyin_args(
3120                                 lun_req->num_be_args,
3121                                 lun_req->be_args,
3122                                 lun_req->error_str,
3123                                 sizeof(lun_req->error_str));
3124                         if (lun_req->kern_be_args == NULL) {
3125                                 lun_req->status = CTL_LUN_ERROR;
3126                                 break;
3127                         }
3128                 }
3129
3130                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3131
3132                 if (lun_req->num_be_args > 0) {
3133                         ctl_copyout_args(lun_req->num_be_args,
3134                                       lun_req->kern_be_args);
3135                         ctl_free_args(lun_req->num_be_args,
3136                                       lun_req->kern_be_args);
3137                 }
3138                 break;
3139         }
3140         case CTL_LUN_LIST: {
3141                 struct sbuf *sb;
3142                 struct ctl_lun *lun;
3143                 struct ctl_lun_list *list;
3144                 struct ctl_option *opt;
3145
3146                 list = (struct ctl_lun_list *)addr;
3147
3148                 /*
3149                  * Allocate a fixed length sbuf here, based on the length
3150                  * of the user's buffer.  We could allocate an auto-extending
3151                  * buffer, and then tell the user how much larger our
3152                  * amount of data is than his buffer, but that presents
3153                  * some problems:
3154                  *
3155                  * 1.  The sbuf(9) routines use a blocking malloc, and so
3156                  *     we can't hold a lock while calling them with an
3157                  *     auto-extending buffer.
3158                  *
3159                  * 2.  There is not currently a LUN reference counting
3160                  *     mechanism, outside of outstanding transactions on
3161                  *     the LUN's OOA queue.  So a LUN could go away on us
3162                  *     while we're getting the LUN number, backend-specific
3163                  *     information, etc.  Thus, given the way things
3164                  *     currently work, we need to hold the CTL lock while
3165                  *     grabbing LUN information.
3166                  *
3167                  * So, from the user's standpoint, the best thing to do is
3168                  * allocate what he thinks is a reasonable buffer length,
3169                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3170                  * double the buffer length and try again.  (And repeat
3171                  * that until he succeeds.)
3172                  */
3173                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3174                 if (sb == NULL) {
3175                         list->status = CTL_LUN_LIST_ERROR;
3176                         snprintf(list->error_str, sizeof(list->error_str),
3177                                  "Unable to allocate %d bytes for LUN list",
3178                                  list->alloc_len);
3179                         break;
3180                 }
3181
3182                 sbuf_printf(sb, "<ctllunlist>\n");
3183
3184                 mtx_lock(&softc->ctl_lock);
3185                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3186                         mtx_lock(&lun->lun_lock);
3187                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3188                                              (uintmax_t)lun->lun);
3189
3190                         /*
3191                          * Bail out as soon as we see that we've overfilled
3192                          * the buffer.
3193                          */
3194                         if (retval != 0)
3195                                 break;
3196
3197                         retval = sbuf_printf(sb, "\t<backend_type>%s"
3198                                              "</backend_type>\n",
3199                                              (lun->backend == NULL) ?  "none" :
3200                                              lun->backend->name);
3201
3202                         if (retval != 0)
3203                                 break;
3204
3205                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3206                                              lun->be_lun->lun_type);
3207
3208                         if (retval != 0)
3209                                 break;
3210
3211                         if (lun->backend == NULL) {
3212                                 retval = sbuf_printf(sb, "</lun>\n");
3213                                 if (retval != 0)
3214                                         break;
3215                                 continue;
3216                         }
3217
3218                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3219                                              (lun->be_lun->maxlba > 0) ?
3220                                              lun->be_lun->maxlba + 1 : 0);
3221
3222                         if (retval != 0)
3223                                 break;
3224
3225                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3226                                              lun->be_lun->blocksize);
3227
3228                         if (retval != 0)
3229                                 break;
3230
3231                         retval = sbuf_printf(sb, "\t<serial_number>");
3232
3233                         if (retval != 0)
3234                                 break;
3235
3236                         retval = ctl_sbuf_printf_esc(sb,
3237                             lun->be_lun->serial_num,
3238                             sizeof(lun->be_lun->serial_num));
3239
3240                         if (retval != 0)
3241                                 break;
3242
3243                         retval = sbuf_printf(sb, "</serial_number>\n");
3244                 
3245                         if (retval != 0)
3246                                 break;
3247
3248                         retval = sbuf_printf(sb, "\t<device_id>");
3249
3250                         if (retval != 0)
3251                                 break;
3252
3253                         retval = ctl_sbuf_printf_esc(sb,
3254                             lun->be_lun->device_id,
3255                             sizeof(lun->be_lun->device_id));
3256
3257                         if (retval != 0)
3258                                 break;
3259
3260                         retval = sbuf_printf(sb, "</device_id>\n");
3261
3262                         if (retval != 0)
3263                                 break;
3264
3265                         if (lun->backend->lun_info != NULL) {
3266                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3267                                 if (retval != 0)
3268                                         break;
3269                         }
3270                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3271                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3272                                     opt->name, opt->value, opt->name);
3273                                 if (retval != 0)
3274                                         break;
3275                         }
3276
3277                         retval = sbuf_printf(sb, "</lun>\n");
3278
3279                         if (retval != 0)
3280                                 break;
3281                         mtx_unlock(&lun->lun_lock);
3282                 }
3283                 if (lun != NULL)
3284                         mtx_unlock(&lun->lun_lock);
3285                 mtx_unlock(&softc->ctl_lock);
3286
3287                 if ((retval != 0)
3288                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3289                         retval = 0;
3290                         sbuf_delete(sb);
3291                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3292                         snprintf(list->error_str, sizeof(list->error_str),
3293                                  "Out of space, %d bytes is too small",
3294                                  list->alloc_len);
3295                         break;
3296                 }
3297
3298                 sbuf_finish(sb);
3299
3300                 retval = copyout(sbuf_data(sb), list->lun_xml,
3301                                  sbuf_len(sb) + 1);
3302
3303                 list->fill_len = sbuf_len(sb) + 1;
3304                 list->status = CTL_LUN_LIST_OK;
3305                 sbuf_delete(sb);
3306                 break;
3307         }
3308         case CTL_ISCSI: {
3309                 struct ctl_iscsi *ci;
3310                 struct ctl_frontend *fe;
3311
3312                 ci = (struct ctl_iscsi *)addr;
3313
3314                 fe = ctl_frontend_find("iscsi");
3315                 if (fe == NULL) {
3316                         ci->status = CTL_ISCSI_ERROR;
3317                         snprintf(ci->error_str, sizeof(ci->error_str),
3318                             "Frontend \"iscsi\" not found.");
3319                         break;
3320                 }
3321
3322                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3323                 break;
3324         }
3325         case CTL_PORT_REQ: {
3326                 struct ctl_req *req;
3327                 struct ctl_frontend *fe;
3328
3329                 req = (struct ctl_req *)addr;
3330
3331                 fe = ctl_frontend_find(req->driver);
3332                 if (fe == NULL) {
3333                         req->status = CTL_LUN_ERROR;
3334                         snprintf(req->error_str, sizeof(req->error_str),
3335                             "Frontend \"%s\" not found.", req->driver);
3336                         break;
3337                 }
3338                 if (req->num_args > 0) {
3339                         req->kern_args = ctl_copyin_args(req->num_args,
3340                             req->args, req->error_str, sizeof(req->error_str));
3341                         if (req->kern_args == NULL) {
3342                                 req->status = CTL_LUN_ERROR;
3343                                 break;
3344                         }
3345                 }
3346
3347                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3348
3349                 if (req->num_args > 0) {
3350                         ctl_copyout_args(req->num_args, req->kern_args);
3351                         ctl_free_args(req->num_args, req->kern_args);
3352                 }
3353                 break;
3354         }
3355         case CTL_PORT_LIST: {
3356                 struct sbuf *sb;
3357                 struct ctl_port *port;
3358                 struct ctl_lun_list *list;
3359                 struct ctl_option *opt;
3360                 int j;
3361
3362                 list = (struct ctl_lun_list *)addr;
3363
3364                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3365                 if (sb == NULL) {
3366                         list->status = CTL_LUN_LIST_ERROR;
3367                         snprintf(list->error_str, sizeof(list->error_str),
3368                                  "Unable to allocate %d bytes for LUN list",
3369                                  list->alloc_len);
3370                         break;
3371                 }
3372
3373                 sbuf_printf(sb, "<ctlportlist>\n");
3374
3375                 mtx_lock(&softc->ctl_lock);
3376                 STAILQ_FOREACH(port, &softc->port_list, links) {
3377                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3378                                              (uintmax_t)port->targ_port);
3379
3380                         /*
3381                          * Bail out as soon as we see that we've overfilled
3382                          * the buffer.
3383                          */
3384                         if (retval != 0)
3385                                 break;
3386
3387                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3388                             "</frontend_type>\n", port->frontend->name);
3389                         if (retval != 0)
3390                                 break;
3391
3392                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3393                                              port->port_type);
3394                         if (retval != 0)
3395                                 break;
3396
3397                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3398                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3399                         if (retval != 0)
3400                                 break;
3401
3402                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3403                             port->port_name);
3404                         if (retval != 0)
3405                                 break;
3406
3407                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3408                             port->physical_port);
3409                         if (retval != 0)
3410                                 break;
3411
3412                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3413                             port->virtual_port);
3414                         if (retval != 0)
3415                                 break;
3416
3417                         if (port->target_devid != NULL) {
3418                                 sbuf_printf(sb, "\t<target>");
3419                                 ctl_id_sbuf(port->target_devid, sb);
3420                                 sbuf_printf(sb, "</target>\n");
3421                         }
3422
3423                         if (port->port_devid != NULL) {
3424                                 sbuf_printf(sb, "\t<port>");
3425                                 ctl_id_sbuf(port->port_devid, sb);
3426                                 sbuf_printf(sb, "</port>\n");
3427                         }
3428
3429                         if (port->port_info != NULL) {
3430                                 retval = port->port_info(port->onoff_arg, sb);
3431                                 if (retval != 0)
3432                                         break;
3433                         }
3434                         STAILQ_FOREACH(opt, &port->options, links) {
3435                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3436                                     opt->name, opt->value, opt->name);
3437                                 if (retval != 0)
3438                                         break;
3439                         }
3440
3441                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3442                                 if (port->wwpn_iid[j].in_use == 0 ||
3443                                     (port->wwpn_iid[j].wwpn == 0 &&
3444                                      port->wwpn_iid[j].name == NULL))
3445                                         continue;
3446
3447                                 if (port->wwpn_iid[j].name != NULL)
3448                                         retval = sbuf_printf(sb,
3449                                             "\t<initiator>%u %s</initiator>\n",
3450                                             j, port->wwpn_iid[j].name);
3451                                 else
3452                                         retval = sbuf_printf(sb,
3453                                             "\t<initiator>%u naa.%08jx</initiator>\n",
3454                                             j, port->wwpn_iid[j].wwpn);
3455                                 if (retval != 0)
3456                                         break;
3457                         }
3458                         if (retval != 0)
3459                                 break;
3460
3461                         retval = sbuf_printf(sb, "</targ_port>\n");
3462                         if (retval != 0)
3463                                 break;
3464                 }
3465                 mtx_unlock(&softc->ctl_lock);
3466
3467                 if ((retval != 0)
3468                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3469                         retval = 0;
3470                         sbuf_delete(sb);
3471                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3472                         snprintf(list->error_str, sizeof(list->error_str),
3473                                  "Out of space, %d bytes is too small",
3474                                  list->alloc_len);
3475                         break;
3476                 }
3477
3478                 sbuf_finish(sb);
3479
3480                 retval = copyout(sbuf_data(sb), list->lun_xml,
3481                                  sbuf_len(sb) + 1);
3482
3483                 list->fill_len = sbuf_len(sb) + 1;
3484                 list->status = CTL_LUN_LIST_OK;
3485                 sbuf_delete(sb);
3486                 break;
3487         }
3488         default: {
3489                 /* XXX KDM should we fix this? */
3490 #if 0
3491                 struct ctl_backend_driver *backend;
3492                 unsigned int type;
3493                 int found;
3494
3495                 found = 0;
3496
3497                 /*
3498                  * We encode the backend type as the ioctl type for backend
3499                  * ioctls.  So parse it out here, and then search for a
3500                  * backend of this type.
3501                  */
3502                 type = _IOC_TYPE(cmd);
3503
3504                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3505                         if (backend->type == type) {
3506                                 found = 1;
3507                                 break;
3508                         }
3509                 }
3510                 if (found == 0) {
3511                         printf("ctl: unknown ioctl command %#lx or backend "
3512                                "%d\n", cmd, type);
3513                         retval = EINVAL;
3514                         break;
3515                 }
3516                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3517 #endif
3518                 retval = ENOTTY;
3519                 break;
3520         }
3521         }
3522         return (retval);
3523 }
3524
3525 uint32_t
3526 ctl_get_initindex(struct ctl_nexus *nexus)
3527 {
3528         if (nexus->targ_port < CTL_MAX_PORTS)
3529                 return (nexus->initid.id +
3530                         (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3531         else
3532                 return (nexus->initid.id +
3533                        ((nexus->targ_port - CTL_MAX_PORTS) *
3534                         CTL_MAX_INIT_PER_PORT));
3535 }
3536
3537 uint32_t
3538 ctl_get_resindex(struct ctl_nexus *nexus)
3539 {
3540         return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3541 }
3542
3543 uint32_t
3544 ctl_port_idx(int port_num)
3545 {
3546         if (port_num < CTL_MAX_PORTS)
3547                 return(port_num);
3548         else
3549                 return(port_num - CTL_MAX_PORTS);
3550 }
3551
3552 static uint32_t
3553 ctl_map_lun(int port_num, uint32_t lun_id)
3554 {
3555         struct ctl_port *port;
3556
3557         port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3558         if (port == NULL)
3559                 return (UINT32_MAX);
3560         if (port->lun_map == NULL)
3561                 return (lun_id);
3562         return (port->lun_map(port->targ_lun_arg, lun_id));
3563 }
3564
3565 static uint32_t
3566 ctl_map_lun_back(int port_num, uint32_t lun_id)
3567 {
3568         struct ctl_port *port;
3569         uint32_t i;
3570
3571         port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3572         if (port->lun_map == NULL)
3573                 return (lun_id);
3574         for (i = 0; i < CTL_MAX_LUNS; i++) {
3575                 if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3576                         return (i);
3577         }
3578         return (UINT32_MAX);
3579 }
3580
3581 /*
3582  * Note:  This only works for bitmask sizes that are at least 32 bits, and
3583  * that are a power of 2.
3584  */
3585 int
3586 ctl_ffz(uint32_t *mask, uint32_t size)
3587 {
3588         uint32_t num_chunks, num_pieces;
3589         int i, j;
3590
3591         num_chunks = (size >> 5);
3592         if (num_chunks == 0)
3593                 num_chunks++;
3594         num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3595
3596         for (i = 0; i < num_chunks; i++) {
3597                 for (j = 0; j < num_pieces; j++) {
3598                         if ((mask[i] & (1 << j)) == 0)
3599                                 return ((i << 5) + j);
3600                 }
3601         }
3602
3603         return (-1);
3604 }
3605
3606 int
3607 ctl_set_mask(uint32_t *mask, uint32_t bit)
3608 {
3609         uint32_t chunk, piece;
3610
3611         chunk = bit >> 5;
3612         piece = bit % (sizeof(uint32_t) * 8);
3613
3614         if ((mask[chunk] & (1 << piece)) != 0)
3615                 return (-1);
3616         else
3617                 mask[chunk] |= (1 << piece);
3618
3619         return (0);
3620 }
3621
3622 int
3623 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3624 {
3625         uint32_t chunk, piece;
3626
3627         chunk = bit >> 5;
3628         piece = bit % (sizeof(uint32_t) * 8);
3629
3630         if ((mask[chunk] & (1 << piece)) == 0)
3631                 return (-1);
3632         else
3633                 mask[chunk] &= ~(1 << piece);
3634
3635         return (0);
3636 }
3637
3638 int
3639 ctl_is_set(uint32_t *mask, uint32_t bit)
3640 {
3641         uint32_t chunk, piece;
3642
3643         chunk = bit >> 5;
3644         piece = bit % (sizeof(uint32_t) * 8);
3645
3646         if ((mask[chunk] & (1 << piece)) == 0)
3647                 return (0);
3648         else
3649                 return (1);
3650 }
3651
3652 #ifdef unused
3653 /*
3654  * The bus, target and lun are optional, they can be filled in later.
3655  * can_wait is used to determine whether we can wait on the malloc or not.
3656  */
3657 union ctl_io*
3658 ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3659               uint32_t targ_lun, int can_wait)
3660 {
3661         union ctl_io *io;
3662
3663         if (can_wait)
3664                 io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3665         else
3666                 io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3667
3668         if (io != NULL) {
3669                 io->io_hdr.io_type = io_type;
3670                 io->io_hdr.targ_port = targ_port;
3671                 /*
3672                  * XXX KDM this needs to change/go away.  We need to move
3673                  * to a preallocated pool of ctl_scsiio structures.
3674                  */
3675                 io->io_hdr.nexus.targ_target.id = targ_target;
3676                 io->io_hdr.nexus.targ_lun = targ_lun;
3677         }
3678
3679         return (io);
3680 }
3681
3682 void
3683 ctl_kfree_io(union ctl_io *io)
3684 {
3685         free(io, M_CTL);
3686 }
3687 #endif /* unused */
3688
3689 /*
3690  * ctl_softc, pool_name, total_ctl_io are passed in.
3691  * npool is passed out.
3692  */
3693 int
3694 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3695                 uint32_t total_ctl_io, void **npool)
3696 {
3697 #ifdef IO_POOLS
3698         struct ctl_io_pool *pool;
3699
3700         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3701                                             M_NOWAIT | M_ZERO);
3702         if (pool == NULL)
3703                 return (ENOMEM);
3704
3705         snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3706         pool->ctl_softc = ctl_softc;
3707         pool->zone = uma_zsecond_create(pool->name, NULL,
3708             NULL, NULL, NULL, ctl_softc->io_zone);
3709         /* uma_prealloc(pool->zone, total_ctl_io); */
3710
3711         *npool = pool;
3712 #else
3713         *npool = ctl_softc->io_zone;
3714 #endif
3715         return (0);
3716 }
3717
3718 void
3719 ctl_pool_free(struct ctl_io_pool *pool)
3720 {
3721
3722         if (pool == NULL)
3723                 return;
3724
3725 #ifdef IO_POOLS
3726         uma_zdestroy(pool->zone);
3727         free(pool, M_CTL);
3728 #endif
3729 }
3730
3731 union ctl_io *
3732 ctl_alloc_io(void *pool_ref)
3733 {
3734         union ctl_io *io;
3735 #ifdef IO_POOLS
3736         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3737
3738         io = uma_zalloc(pool->zone, M_WAITOK);
3739 #else
3740         io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3741 #endif
3742         if (io != NULL)
3743                 io->io_hdr.pool = pool_ref;
3744         return (io);
3745 }
3746
3747 union ctl_io *
3748 ctl_alloc_io_nowait(void *pool_ref)
3749 {
3750         union ctl_io *io;
3751 #ifdef IO_POOLS
3752         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3753
3754         io = uma_zalloc(pool->zone, M_NOWAIT);
3755 #else
3756         io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3757 #endif
3758         if (io != NULL)
3759                 io->io_hdr.pool = pool_ref;
3760         return (io);
3761 }
3762
3763 void
3764 ctl_free_io(union ctl_io *io)
3765 {
3766 #ifdef IO_POOLS
3767         struct ctl_io_pool *pool;
3768 #endif
3769
3770         if (io == NULL)
3771                 return;
3772
3773 #ifdef IO_POOLS
3774         pool = (struct ctl_io_pool *)io->io_hdr.pool;
3775         uma_zfree(pool->zone, io);
3776 #else
3777         uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3778 #endif
3779 }
3780
3781 void
3782 ctl_zero_io(union ctl_io *io)
3783 {
3784         void *pool_ref;
3785
3786         if (io == NULL)
3787                 return;
3788
3789         /*
3790          * May need to preserve linked list pointers at some point too.
3791          */
3792         pool_ref = io->io_hdr.pool;
3793         memset(io, 0, sizeof(*io));
3794         io->io_hdr.pool = pool_ref;
3795 }
3796
3797 /*
3798  * This routine is currently used for internal copies of ctl_ios that need
3799  * to persist for some reason after we've already returned status to the
3800  * FETD.  (Thus the flag set.)
3801  *
3802  * XXX XXX
3803  * Note that this makes a blind copy of all fields in the ctl_io, except
3804  * for the pool reference.  This includes any memory that has been
3805  * allocated!  That memory will no longer be valid after done has been
3806  * called, so this would be VERY DANGEROUS for command that actually does
3807  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3808  * start and stop commands, which don't transfer any data, so this is not a
3809  * problem.  If it is used for anything else, the caller would also need to
3810  * allocate data buffer space and this routine would need to be modified to
3811  * copy the data buffer(s) as well.
3812  */
3813 void
3814 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3815 {
3816         void *pool_ref;
3817
3818         if ((src == NULL)
3819          || (dest == NULL))
3820                 return;
3821
3822         /*
3823          * May need to preserve linked list pointers at some point too.
3824          */
3825         pool_ref = dest->io_hdr.pool;
3826
3827         memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3828
3829         dest->io_hdr.pool = pool_ref;
3830         /*
3831          * We need to know that this is an internal copy, and doesn't need
3832          * to get passed back to the FETD that allocated it.
3833          */
3834         dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3835 }
3836
3837 static int
3838 ctl_expand_number(const char *buf, uint64_t *num)
3839 {
3840         char *endptr;
3841         uint64_t number;
3842         unsigned shift;
3843
3844         number = strtoq(buf, &endptr, 0);
3845
3846         switch (tolower((unsigned char)*endptr)) {
3847         case 'e':
3848                 shift = 60;
3849                 break;
3850         case 'p':
3851                 shift = 50;
3852                 break;
3853         case 't':
3854                 shift = 40;
3855                 break;
3856         case 'g':
3857                 shift = 30;
3858                 break;
3859         case 'm':
3860                 shift = 20;
3861                 break;
3862         case 'k':
3863                 shift = 10;
3864                 break;
3865         case 'b':
3866         case '\0': /* No unit. */
3867                 *num = number;
3868                 return (0);
3869         default:
3870                 /* Unrecognized unit. */
3871                 return (-1);
3872         }
3873
3874         if ((number << shift) >> shift != number) {
3875                 /* Overflow */
3876                 return (-1);
3877         }
3878         *num = number << shift;
3879         return (0);
3880 }
3881
3882
3883 /*
3884  * This routine could be used in the future to load default and/or saved
3885  * mode page parameters for a particuar lun.
3886  */
3887 static int
3888 ctl_init_page_index(struct ctl_lun *lun)
3889 {
3890         int i;
3891         struct ctl_page_index *page_index;
3892         const char *value;
3893         uint64_t ival;
3894
3895         memcpy(&lun->mode_pages.index, page_index_template,
3896                sizeof(page_index_template));
3897
3898         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3899
3900                 page_index = &lun->mode_pages.index[i];
3901                 /*
3902                  * If this is a disk-only mode page, there's no point in
3903                  * setting it up.  For some pages, we have to have some
3904                  * basic information about the disk in order to calculate the
3905                  * mode page data.
3906                  */
3907                 if ((lun->be_lun->lun_type != T_DIRECT)
3908                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3909                         continue;
3910
3911                 switch (page_index->page_code & SMPH_PC_MASK) {
3912                 case SMS_RW_ERROR_RECOVERY_PAGE: {
3913                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3914                                 panic("subpage is incorrect!");
3915                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3916                                &rw_er_page_default,
3917                                sizeof(rw_er_page_default));
3918                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3919                                &rw_er_page_changeable,
3920                                sizeof(rw_er_page_changeable));
3921                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3922                                &rw_er_page_default,
3923                                sizeof(rw_er_page_default));
3924                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3925                                &rw_er_page_default,
3926                                sizeof(rw_er_page_default));
3927                         page_index->page_data =
3928                                 (uint8_t *)lun->mode_pages.rw_er_page;
3929                         break;
3930                 }
3931                 case SMS_FORMAT_DEVICE_PAGE: {
3932                         struct scsi_format_page *format_page;
3933
3934                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3935                                 panic("subpage is incorrect!");
3936
3937                         /*
3938                          * Sectors per track are set above.  Bytes per
3939                          * sector need to be set here on a per-LUN basis.
3940                          */
3941                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3942                                &format_page_default,
3943                                sizeof(format_page_default));
3944                         memcpy(&lun->mode_pages.format_page[
3945                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
3946                                sizeof(format_page_changeable));
3947                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3948                                &format_page_default,
3949                                sizeof(format_page_default));
3950                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3951                                &format_page_default,
3952                                sizeof(format_page_default));
3953
3954                         format_page = &lun->mode_pages.format_page[
3955                                 CTL_PAGE_CURRENT];
3956                         scsi_ulto2b(lun->be_lun->blocksize,
3957                                     format_page->bytes_per_sector);
3958
3959                         format_page = &lun->mode_pages.format_page[
3960                                 CTL_PAGE_DEFAULT];
3961                         scsi_ulto2b(lun->be_lun->blocksize,
3962                                     format_page->bytes_per_sector);
3963
3964                         format_page = &lun->mode_pages.format_page[
3965                                 CTL_PAGE_SAVED];
3966                         scsi_ulto2b(lun->be_lun->blocksize,
3967                                     format_page->bytes_per_sector);
3968
3969                         page_index->page_data =
3970                                 (uint8_t *)lun->mode_pages.format_page;
3971                         break;
3972                 }
3973                 case SMS_RIGID_DISK_PAGE: {
3974                         struct scsi_rigid_disk_page *rigid_disk_page;
3975                         uint32_t sectors_per_cylinder;
3976                         uint64_t cylinders;
3977 #ifndef __XSCALE__
3978                         int shift;
3979 #endif /* !__XSCALE__ */
3980
3981                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3982                                 panic("invalid subpage value %d",
3983                                       page_index->subpage);
3984
3985                         /*
3986                          * Rotation rate and sectors per track are set
3987                          * above.  We calculate the cylinders here based on
3988                          * capacity.  Due to the number of heads and
3989                          * sectors per track we're using, smaller arrays
3990                          * may turn out to have 0 cylinders.  Linux and
3991                          * FreeBSD don't pay attention to these mode pages
3992                          * to figure out capacity, but Solaris does.  It
3993                          * seems to deal with 0 cylinders just fine, and
3994                          * works out a fake geometry based on the capacity.
3995                          */
3996                         memcpy(&lun->mode_pages.rigid_disk_page[
3997                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3998                                sizeof(rigid_disk_page_default));
3999                         memcpy(&lun->mode_pages.rigid_disk_page[
4000                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4001                                sizeof(rigid_disk_page_changeable));
4002
4003                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4004                                 CTL_DEFAULT_HEADS;
4005
4006                         /*
4007                          * The divide method here will be more accurate,
4008                          * probably, but results in floating point being
4009                          * used in the kernel on i386 (__udivdi3()).  On the
4010                          * XScale, though, __udivdi3() is implemented in
4011                          * software.
4012                          *
4013                          * The shift method for cylinder calculation is
4014                          * accurate if sectors_per_cylinder is a power of
4015                          * 2.  Otherwise it might be slightly off -- you
4016                          * might have a bit of a truncation problem.
4017                          */
4018 #ifdef  __XSCALE__
4019                         cylinders = (lun->be_lun->maxlba + 1) /
4020                                 sectors_per_cylinder;
4021 #else
4022                         for (shift = 31; shift > 0; shift--) {
4023                                 if (sectors_per_cylinder & (1 << shift))
4024                                         break;
4025                         }
4026                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
4027 #endif
4028
4029                         /*
4030                          * We've basically got 3 bytes, or 24 bits for the
4031                          * cylinder size in the mode page.  If we're over,
4032                          * just round down to 2^24.
4033                          */
4034                         if (cylinders > 0xffffff)
4035                                 cylinders = 0xffffff;
4036
4037                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4038                                 CTL_PAGE_DEFAULT];
4039                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4040
4041                         if ((value = ctl_get_opt(&lun->be_lun->options,
4042                             "rpm")) != NULL) {
4043                                 scsi_ulto2b(strtol(value, NULL, 0),
4044                                      rigid_disk_page->rotation_rate);
4045                         }
4046
4047                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4048                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4049                                sizeof(rigid_disk_page_default));
4050                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4051                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4052                                sizeof(rigid_disk_page_default));
4053
4054                         page_index->page_data =
4055                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
4056                         break;
4057                 }
4058                 case SMS_CACHING_PAGE: {
4059                         struct scsi_caching_page *caching_page;
4060
4061                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4062                                 panic("invalid subpage value %d",
4063                                       page_index->subpage);
4064                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4065                                &caching_page_default,
4066                                sizeof(caching_page_default));
4067                         memcpy(&lun->mode_pages.caching_page[
4068                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4069                                sizeof(caching_page_changeable));
4070                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4071                                &caching_page_default,
4072                                sizeof(caching_page_default));
4073                         caching_page = &lun->mode_pages.caching_page[
4074                             CTL_PAGE_SAVED];
4075                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
4076                         if (value != NULL && strcmp(value, "off") == 0)
4077                                 caching_page->flags1 &= ~SCP_WCE;
4078                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
4079                         if (value != NULL && strcmp(value, "off") == 0)
4080                                 caching_page->flags1 |= SCP_RCD;
4081                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4082                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4083                                sizeof(caching_page_default));
4084                         page_index->page_data =
4085                                 (uint8_t *)lun->mode_pages.caching_page;
4086                         break;
4087                 }
4088                 case SMS_CONTROL_MODE_PAGE: {
4089                         struct scsi_control_page *control_page;
4090
4091                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4092                                 panic("invalid subpage value %d",
4093                                       page_index->subpage);
4094
4095                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4096                                &control_page_default,
4097                                sizeof(control_page_default));
4098                         memcpy(&lun->mode_pages.control_page[
4099                                CTL_PAGE_CHANGEABLE], &control_page_changeable,
4100                                sizeof(control_page_changeable));
4101                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4102                                &control_page_default,
4103                                sizeof(control_page_default));
4104                         control_page = &lun->mode_pages.control_page[
4105                             CTL_PAGE_SAVED];
4106                         value = ctl_get_opt(&lun->be_lun->options, "reordering");
4107                         if (value != NULL && strcmp(value, "unrestricted") == 0) {
4108                                 control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4109                                 control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4110                         }
4111                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4112                                &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4113                                sizeof(control_page_default));
4114                         page_index->page_data =
4115                                 (uint8_t *)lun->mode_pages.control_page;
4116                         break;
4117
4118                 }
4119                 case SMS_INFO_EXCEPTIONS_PAGE: {
4120                         switch (page_index->subpage) {
4121                         case SMS_SUBPAGE_PAGE_0:
4122                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4123                                        &ie_page_default,
4124                                        sizeof(ie_page_default));
4125                                 memcpy(&lun->mode_pages.ie_page[
4126                                        CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4127                                        sizeof(ie_page_changeable));
4128                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4129                                        &ie_page_default,
4130                                        sizeof(ie_page_default));
4131                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4132                                        &ie_page_default,
4133                                        sizeof(ie_page_default));
4134                                 page_index->page_data =
4135                                         (uint8_t *)lun->mode_pages.ie_page;
4136                                 break;
4137                         case 0x02: {
4138                                 struct ctl_logical_block_provisioning_page *page;
4139
4140                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4141                                        &lbp_page_default,
4142                                        sizeof(lbp_page_default));
4143                                 memcpy(&lun->mode_pages.lbp_page[
4144                                        CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4145                                        sizeof(lbp_page_changeable));
4146                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4147                                        &lbp_page_default,
4148                                        sizeof(lbp_page_default));
4149                                 page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4150                                 value = ctl_get_opt(&lun->be_lun->options,
4151                                     "avail-threshold");
4152                                 if (value != NULL &&
4153                                     ctl_expand_number(value, &ival) == 0) {
4154                                         page->descr[0].flags |= SLBPPD_ENABLED |
4155                                             SLBPPD_ARMING_DEC;
4156                                         if (lun->be_lun->blocksize)
4157                                                 ival /= lun->be_lun->blocksize;
4158                                         else
4159                                                 ival /= 512;
4160                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4161                                             page->descr[0].count);
4162                                 }
4163                                 value = ctl_get_opt(&lun->be_lun->options,
4164                                     "used-threshold");
4165                                 if (value != NULL &&
4166                                     ctl_expand_number(value, &ival) == 0) {
4167                                         page->descr[1].flags |= SLBPPD_ENABLED |
4168                                             SLBPPD_ARMING_INC;
4169                                         if (lun->be_lun->blocksize)
4170                                                 ival /= lun->be_lun->blocksize;
4171                                         else
4172                                                 ival /= 512;
4173                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4174                                             page->descr[1].count);
4175                                 }
4176                                 value = ctl_get_opt(&lun->be_lun->options,
4177                                     "pool-avail-threshold");
4178                                 if (value != NULL &&
4179                                     ctl_expand_number(value, &ival) == 0) {
4180                                         page->descr[2].flags |= SLBPPD_ENABLED |
4181                                             SLBPPD_ARMING_DEC;
4182                                         if (lun->be_lun->blocksize)
4183                                                 ival /= lun->be_lun->blocksize;
4184                                         else
4185                                                 ival /= 512;
4186                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4187                                             page->descr[2].count);
4188                                 }
4189                                 value = ctl_get_opt(&lun->be_lun->options,
4190                                     "pool-used-threshold");
4191                                 if (value != NULL &&
4192                                     ctl_expand_number(value, &ival) == 0) {
4193                                         page->descr[3].flags |= SLBPPD_ENABLED |
4194                                             SLBPPD_ARMING_INC;
4195                                         if (lun->be_lun->blocksize)
4196                                                 ival /= lun->be_lun->blocksize;
4197                                         else
4198                                                 ival /= 512;
4199                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4200                                             page->descr[3].count);
4201                                 }
4202                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4203                                        &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4204                                        sizeof(lbp_page_default));
4205                                 page_index->page_data =
4206                                         (uint8_t *)lun->mode_pages.lbp_page;
4207                         }}
4208                         break;
4209                 }
4210                 case SMS_VENDOR_SPECIFIC_PAGE:{
4211                         switch (page_index->subpage) {
4212                         case DBGCNF_SUBPAGE_CODE: {
4213                                 struct copan_debugconf_subpage *current_page,
4214                                                                *saved_page;
4215
4216                                 memcpy(&lun->mode_pages.debugconf_subpage[
4217                                        CTL_PAGE_CURRENT],
4218                                        &debugconf_page_default,
4219                                        sizeof(debugconf_page_default));
4220                                 memcpy(&lun->mode_pages.debugconf_subpage[
4221                                        CTL_PAGE_CHANGEABLE],
4222                                        &debugconf_page_changeable,
4223                                        sizeof(debugconf_page_changeable));
4224                                 memcpy(&lun->mode_pages.debugconf_subpage[
4225                                        CTL_PAGE_DEFAULT],
4226                                        &debugconf_page_default,
4227                                        sizeof(debugconf_page_default));
4228                                 memcpy(&lun->mode_pages.debugconf_subpage[
4229                                        CTL_PAGE_SAVED],
4230                                        &debugconf_page_default,
4231                                        sizeof(debugconf_page_default));
4232                                 page_index->page_data =
4233                                         (uint8_t *)lun->mode_pages.debugconf_subpage;
4234
4235                                 current_page = (struct copan_debugconf_subpage *)
4236                                         (page_index->page_data +
4237                                          (page_index->page_len *
4238                                           CTL_PAGE_CURRENT));
4239                                 saved_page = (struct copan_debugconf_subpage *)
4240                                         (page_index->page_data +
4241                                          (page_index->page_len *
4242                                           CTL_PAGE_SAVED));
4243                                 break;
4244                         }
4245                         default:
4246                                 panic("invalid subpage value %d",
4247                                       page_index->subpage);
4248                                 break;
4249                         }
4250                         break;
4251                 }
4252                 default:
4253                         panic("invalid page value %d",
4254                               page_index->page_code & SMPH_PC_MASK);
4255                         break;
4256         }
4257         }
4258
4259         return (CTL_RETVAL_COMPLETE);
4260 }
4261
4262 static int
4263 ctl_init_log_page_index(struct ctl_lun *lun)
4264 {
4265         struct ctl_page_index *page_index;
4266         int i, j, k, prev;
4267
4268         memcpy(&lun->log_pages.index, log_page_index_template,
4269                sizeof(log_page_index_template));
4270
4271         prev = -1;
4272         for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4273
4274                 page_index = &lun->log_pages.index[i];
4275                 /*
4276                  * If this is a disk-only mode page, there's no point in
4277                  * setting it up.  For some pages, we have to have some
4278                  * basic information about the disk in order to calculate the
4279                  * mode page data.
4280                  */
4281                 if ((lun->be_lun->lun_type != T_DIRECT)
4282                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4283                         continue;
4284
4285                 if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4286                     ((lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) == 0 ||
4287                      lun->backend->lun_attr == NULL))
4288                         continue;
4289
4290                 if (page_index->page_code != prev) {
4291                         lun->log_pages.pages_page[j] = page_index->page_code;
4292                         prev = page_index->page_code;
4293                         j++;
4294                 }
4295                 lun->log_pages.subpages_page[k*2] = page_index->page_code;
4296                 lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4297                 k++;
4298         }
4299         lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4300         lun->log_pages.index[0].page_len = j;
4301         lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4302         lun->log_pages.index[1].page_len = k * 2;
4303         lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4304         lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4305
4306         return (CTL_RETVAL_COMPLETE);
4307 }
4308
4309 static int
4310 hex2bin(const char *str, uint8_t *buf, int buf_size)
4311 {
4312         int i;
4313         u_char c;
4314
4315         memset(buf, 0, buf_size);
4316         while (isspace(str[0]))
4317                 str++;
4318         if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4319                 str += 2;
4320         buf_size *= 2;
4321         for (i = 0; str[i] != 0 && i < buf_size; i++) {
4322                 c = str[i];
4323                 if (isdigit(c))
4324                         c -= '0';
4325                 else if (isalpha(c))
4326                         c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4327                 else
4328                         break;
4329                 if (c >= 16)
4330                         break;
4331                 if ((i & 1) == 0)
4332                         buf[i / 2] |= (c << 4);
4333                 else
4334                         buf[i / 2] |= c;
4335         }
4336         return ((i + 1) / 2);
4337 }
4338
4339 /*
4340  * LUN allocation.
4341  *
4342  * Requirements:
4343  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4344  *   wants us to allocate the LUN and he can block.
4345  * - ctl_softc is always set
4346  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4347  *
4348  * Returns 0 for success, non-zero (errno) for failure.
4349  */
4350 static int
4351 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4352               struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4353 {
4354         struct ctl_lun *nlun, *lun;
4355         struct ctl_port *port;
4356         struct scsi_vpd_id_descriptor *desc;
4357         struct scsi_vpd_id_t10 *t10id;
4358         const char *eui, *naa, *scsiname, *vendor, *value;
4359         int lun_number, i, lun_malloced;
4360         int devidlen, idlen1, idlen2 = 0, len;
4361
4362         if (be_lun == NULL)
4363                 return (EINVAL);
4364
4365         /*
4366          * We currently only support Direct Access or Processor LUN types.
4367          */
4368         switch (be_lun->lun_type) {
4369         case T_DIRECT:
4370                 break;
4371         case T_PROCESSOR:
4372                 break;
4373         case T_SEQUENTIAL:
4374         case T_CHANGER:
4375         default:
4376                 be_lun->lun_config_status(be_lun->be_lun,
4377                                           CTL_LUN_CONFIG_FAILURE);
4378                 break;
4379         }
4380         if (ctl_lun == NULL) {
4381                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4382                 lun_malloced = 1;
4383         } else {
4384                 lun_malloced = 0;
4385                 lun = ctl_lun;
4386         }
4387
4388         memset(lun, 0, sizeof(*lun));
4389         if (lun_malloced)
4390                 lun->flags = CTL_LUN_MALLOCED;
4391
4392         /* Generate LUN ID. */
4393         devidlen = max(CTL_DEVID_MIN_LEN,
4394             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4395         idlen1 = sizeof(*t10id) + devidlen;
4396         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4397         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4398         if (scsiname != NULL) {
4399                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4400                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4401         }
4402         eui = ctl_get_opt(&be_lun->options, "eui");
4403         if (eui != NULL) {
4404                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4405         }
4406         naa = ctl_get_opt(&be_lun->options, "naa");
4407         if (naa != NULL) {
4408                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4409         }
4410         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4411             M_CTL, M_WAITOK | M_ZERO);
4412         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4413         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4414         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4415         desc->length = idlen1;
4416         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4417         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4418         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4419                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4420         } else {
4421                 strncpy(t10id->vendor, vendor,
4422                     min(sizeof(t10id->vendor), strlen(vendor)));
4423         }
4424         strncpy((char *)t10id->vendor_spec_id,
4425             (char *)be_lun->device_id, devidlen);
4426         if (scsiname != NULL) {
4427                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4428                     desc->length);
4429                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4430                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4431                     SVPD_ID_TYPE_SCSI_NAME;
4432                 desc->length = idlen2;
4433                 strlcpy(desc->identifier, scsiname, idlen2);
4434         }
4435         if (eui != NULL) {
4436                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4437                     desc->length);
4438                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4439                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4440                     SVPD_ID_TYPE_EUI64;
4441                 desc->length = hex2bin(eui, desc->identifier, 16);
4442                 desc->length = desc->length > 12 ? 16 :
4443                     (desc->length > 8 ? 12 : 8);
4444                 len -= 16 - desc->length;
4445         }
4446         if (naa != NULL) {
4447                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4448                     desc->length);
4449                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4450                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4451                     SVPD_ID_TYPE_NAA;
4452                 desc->length = hex2bin(naa, desc->identifier, 16);
4453                 desc->length = desc->length > 8 ? 16 : 8;
4454                 len -= 16 - desc->length;
4455         }
4456         lun->lun_devid->len = len;
4457
4458         mtx_lock(&ctl_softc->ctl_lock);
4459         /*
4460          * See if the caller requested a particular LUN number.  If so, see
4461          * if it is available.  Otherwise, allocate the first available LUN.
4462          */
4463         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4464                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4465                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4466                         mtx_unlock(&ctl_softc->ctl_lock);
4467                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4468                                 printf("ctl: requested LUN ID %d is higher "
4469                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4470                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4471                         } else {
4472                                 /*
4473                                  * XXX KDM return an error, or just assign
4474                                  * another LUN ID in this case??
4475                                  */
4476                                 printf("ctl: requested LUN ID %d is already "
4477                                        "in use\n", be_lun->req_lun_id);
4478                         }
4479                         if (lun->flags & CTL_LUN_MALLOCED)
4480                                 free(lun, M_CTL);
4481                         be_lun->lun_config_status(be_lun->be_lun,
4482                                                   CTL_LUN_CONFIG_FAILURE);
4483                         return (ENOSPC);
4484                 }
4485                 lun_number = be_lun->req_lun_id;
4486         } else {
4487                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4488                 if (lun_number == -1) {
4489                         mtx_unlock(&ctl_softc->ctl_lock);
4490                         printf("ctl: can't allocate LUN on target %ju, out of "
4491                                "LUNs\n", (uintmax_t)target_id.id);
4492                         if (lun->flags & CTL_LUN_MALLOCED)
4493                                 free(lun, M_CTL);
4494                         be_lun->lun_config_status(be_lun->be_lun,
4495                                                   CTL_LUN_CONFIG_FAILURE);
4496                         return (ENOSPC);
4497                 }
4498         }
4499         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4500
4501         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4502         lun->target = target_id;
4503         lun->lun = lun_number;
4504         lun->be_lun = be_lun;
4505         /*
4506          * The processor LUN is always enabled.  Disk LUNs come on line
4507          * disabled, and must be enabled by the backend.
4508          */
4509         lun->flags |= CTL_LUN_DISABLED;
4510         lun->backend = be_lun->be;
4511         be_lun->ctl_lun = lun;
4512         be_lun->lun_id = lun_number;
4513         atomic_add_int(&be_lun->be->num_luns, 1);
4514         if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4515                 lun->flags |= CTL_LUN_OFFLINE;
4516
4517         if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4518                 lun->flags |= CTL_LUN_STOPPED;
4519
4520         if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4521                 lun->flags |= CTL_LUN_INOPERABLE;
4522
4523         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4524                 lun->flags |= CTL_LUN_PRIMARY_SC;
4525
4526         value = ctl_get_opt(&be_lun->options, "readonly");
4527         if (value != NULL && strcmp(value, "on") == 0)
4528                 lun->flags |= CTL_LUN_READONLY;
4529
4530         lun->ctl_softc = ctl_softc;
4531         TAILQ_INIT(&lun->ooa_queue);
4532         TAILQ_INIT(&lun->blocked_queue);
4533         STAILQ_INIT(&lun->error_list);
4534         ctl_tpc_lun_init(lun);
4535
4536         /*
4537          * Initialize the mode and log page index.
4538          */
4539         ctl_init_page_index(lun);
4540         ctl_init_log_page_index(lun);
4541
4542         /*
4543          * Set the poweron UA for all initiators on this LUN only.
4544          */
4545         for (i = 0; i < CTL_MAX_INITIATORS; i++)
4546                 lun->pending_ua[i] = CTL_UA_POWERON;
4547
4548         /*
4549          * Now, before we insert this lun on the lun list, set the lun
4550          * inventory changed UA for all other luns.
4551          */
4552         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4553                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4554                         nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4555                 }
4556         }
4557
4558         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4559
4560         ctl_softc->ctl_luns[lun_number] = lun;
4561
4562         ctl_softc->num_luns++;
4563
4564         /* Setup statistics gathering */
4565         lun->stats.device_type = be_lun->lun_type;
4566         lun->stats.lun_number = lun_number;
4567         if (lun->stats.device_type == T_DIRECT)
4568                 lun->stats.blocksize = be_lun->blocksize;
4569         else
4570                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4571         for (i = 0;i < CTL_MAX_PORTS;i++)
4572                 lun->stats.ports[i].targ_port = i;
4573
4574         mtx_unlock(&ctl_softc->ctl_lock);
4575
4576         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4577
4578         /*
4579          * Run through each registered FETD and bring it online if it isn't
4580          * already.  Enable the target ID if it hasn't been enabled, and
4581          * enable this particular LUN.
4582          */
4583         STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4584                 int retval;
4585
4586                 retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4587                 if (retval != 0) {
4588                         printf("ctl_alloc_lun: FETD %s port %d returned error "
4589                                "%d for lun_enable on target %ju lun %d\n",
4590                                port->port_name, port->targ_port, retval,
4591                                (uintmax_t)target_id.id, lun_number);
4592                 } else
4593                         port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4594         }
4595         return (0);
4596 }
4597
4598 /*
4599  * Delete a LUN.
4600  * Assumptions:
4601  * - LUN has already been marked invalid and any pending I/O has been taken
4602  *   care of.
4603  */
4604 static int
4605 ctl_free_lun(struct ctl_lun *lun)
4606 {
4607         struct ctl_softc *softc;
4608 #if 0
4609         struct ctl_port *port;
4610 #endif
4611         struct ctl_lun *nlun;
4612         int i;
4613
4614         softc = lun->ctl_softc;
4615
4616         mtx_assert(&softc->ctl_lock, MA_OWNED);
4617
4618         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4619
4620         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4621
4622         softc->ctl_luns[lun->lun] = NULL;
4623
4624         if (!TAILQ_EMPTY(&lun->ooa_queue))
4625                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4626
4627         softc->num_luns--;
4628
4629         /*
4630          * XXX KDM this scheme only works for a single target/multiple LUN
4631          * setup.  It needs to be revamped for a multiple target scheme.
4632          *
4633          * XXX KDM this results in port->lun_disable() getting called twice,
4634          * once when ctl_disable_lun() is called, and a second time here.
4635          * We really need to re-think the LUN disable semantics.  There
4636          * should probably be several steps/levels to LUN removal:
4637          *  - disable
4638          *  - invalidate
4639          *  - free
4640          *
4641          * Right now we only have a disable method when communicating to
4642          * the front end ports, at least for individual LUNs.
4643          */
4644 #if 0
4645         STAILQ_FOREACH(port, &softc->port_list, links) {
4646                 int retval;
4647
4648                 retval = port->lun_disable(port->targ_lun_arg, lun->target,
4649                                          lun->lun);
4650                 if (retval != 0) {
4651                         printf("ctl_free_lun: FETD %s port %d returned error "
4652                                "%d for lun_disable on target %ju lun %jd\n",
4653                                port->port_name, port->targ_port, retval,
4654                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4655                 }
4656
4657                 if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4658                         port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4659
4660                         retval = port->targ_disable(port->targ_lun_arg,lun->target);
4661                         if (retval != 0) {
4662                                 printf("ctl_free_lun: FETD %s port %d "
4663                                        "returned error %d for targ_disable on "
4664                                        "target %ju\n", port->port_name,
4665                                        port->targ_port, retval,
4666                                        (uintmax_t)lun->target.id);
4667                         } else
4668                                 port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4669
4670                         if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4671                                 continue;
4672
4673 #if 0
4674                         port->port_offline(port->onoff_arg);
4675                         port->status &= ~CTL_PORT_STATUS_ONLINE;
4676 #endif
4677                 }
4678         }
4679 #endif
4680
4681         /*
4682          * Tell the backend to free resources, if this LUN has a backend.
4683          */
4684         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4685         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4686
4687         ctl_tpc_lun_shutdown(lun);
4688         mtx_destroy(&lun->lun_lock);
4689         free(lun->lun_devid, M_CTL);
4690         free(lun->write_buffer, M_CTL);
4691         if (lun->flags & CTL_LUN_MALLOCED)
4692                 free(lun, M_CTL);
4693
4694         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4695                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4696                         nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4697                 }
4698         }
4699
4700         return (0);
4701 }
4702
4703 static void
4704 ctl_create_lun(struct ctl_be_lun *be_lun)
4705 {
4706         struct ctl_softc *ctl_softc;
4707
4708         ctl_softc = control_softc;
4709
4710         /*
4711          * ctl_alloc_lun() should handle all potential failure cases.
4712          */
4713         ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4714 }
4715
4716 int
4717 ctl_add_lun(struct ctl_be_lun *be_lun)
4718 {
4719         struct ctl_softc *ctl_softc = control_softc;
4720
4721         mtx_lock(&ctl_softc->ctl_lock);
4722         STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4723         mtx_unlock(&ctl_softc->ctl_lock);
4724         wakeup(&ctl_softc->pending_lun_queue);
4725
4726         return (0);
4727 }
4728
4729 int
4730 ctl_enable_lun(struct ctl_be_lun *be_lun)
4731 {
4732         struct ctl_softc *ctl_softc;
4733         struct ctl_port *port, *nport;
4734         struct ctl_lun *lun;
4735         int retval;
4736
4737         ctl_softc = control_softc;
4738
4739         lun = (struct ctl_lun *)be_lun->ctl_lun;
4740
4741         mtx_lock(&ctl_softc->ctl_lock);
4742         mtx_lock(&lun->lun_lock);
4743         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4744                 /*
4745                  * eh?  Why did we get called if the LUN is already
4746                  * enabled?
4747                  */
4748                 mtx_unlock(&lun->lun_lock);
4749                 mtx_unlock(&ctl_softc->ctl_lock);
4750                 return (0);
4751         }
4752         lun->flags &= ~CTL_LUN_DISABLED;
4753         mtx_unlock(&lun->lun_lock);
4754
4755         for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4756                 nport = STAILQ_NEXT(port, links);
4757
4758                 /*
4759                  * Drop the lock while we call the FETD's enable routine.
4760                  * This can lead to a callback into CTL (at least in the
4761                  * case of the internal initiator frontend.
4762                  */
4763                 mtx_unlock(&ctl_softc->ctl_lock);
4764                 retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4765                 mtx_lock(&ctl_softc->ctl_lock);
4766                 if (retval != 0) {
4767                         printf("%s: FETD %s port %d returned error "
4768                                "%d for lun_enable on target %ju lun %jd\n",
4769                                __func__, port->port_name, port->targ_port, retval,
4770                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4771                 }
4772 #if 0
4773                  else {
4774             /* NOTE:  TODO:  why does lun enable affect port status? */
4775                         port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4776                 }
4777 #endif
4778         }
4779
4780         mtx_unlock(&ctl_softc->ctl_lock);
4781
4782         return (0);
4783 }
4784
4785 int
4786 ctl_disable_lun(struct ctl_be_lun *be_lun)
4787 {
4788         struct ctl_softc *ctl_softc;
4789         struct ctl_port *port;
4790         struct ctl_lun *lun;
4791         int retval;
4792
4793         ctl_softc = control_softc;
4794
4795         lun = (struct ctl_lun *)be_lun->ctl_lun;
4796
4797         mtx_lock(&ctl_softc->ctl_lock);
4798         mtx_lock(&lun->lun_lock);
4799         if (lun->flags & CTL_LUN_DISABLED) {
4800                 mtx_unlock(&lun->lun_lock);
4801                 mtx_unlock(&ctl_softc->ctl_lock);
4802                 return (0);
4803         }
4804         lun->flags |= CTL_LUN_DISABLED;
4805         mtx_unlock(&lun->lun_lock);
4806
4807         STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4808                 mtx_unlock(&ctl_softc->ctl_lock);
4809                 /*
4810                  * Drop the lock before we call the frontend's disable
4811                  * routine, to avoid lock order reversals.
4812                  *
4813                  * XXX KDM what happens if the frontend list changes while
4814                  * we're traversing it?  It's unlikely, but should be handled.
4815                  */
4816                 retval = port->lun_disable(port->targ_lun_arg, lun->target,
4817                                          lun->lun);
4818                 mtx_lock(&ctl_softc->ctl_lock);
4819                 if (retval != 0) {
4820                         printf("ctl_alloc_lun: FETD %s port %d returned error "
4821                                "%d for lun_disable on target %ju lun %jd\n",
4822                                port->port_name, port->targ_port, retval,
4823                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4824                 }
4825         }
4826
4827         mtx_unlock(&ctl_softc->ctl_lock);
4828
4829         return (0);
4830 }
4831
4832 int
4833 ctl_start_lun(struct ctl_be_lun *be_lun)
4834 {
4835         struct ctl_softc *ctl_softc;
4836         struct ctl_lun *lun;
4837
4838         ctl_softc = control_softc;
4839
4840         lun = (struct ctl_lun *)be_lun->ctl_lun;
4841
4842         mtx_lock(&lun->lun_lock);
4843         lun->flags &= ~CTL_LUN_STOPPED;
4844         mtx_unlock(&lun->lun_lock);
4845
4846         return (0);
4847 }
4848
4849 int
4850 ctl_stop_lun(struct ctl_be_lun *be_lun)
4851 {
4852         struct ctl_softc *ctl_softc;
4853         struct ctl_lun *lun;
4854
4855         ctl_softc = control_softc;
4856
4857         lun = (struct ctl_lun *)be_lun->ctl_lun;
4858
4859         mtx_lock(&lun->lun_lock);
4860         lun->flags |= CTL_LUN_STOPPED;
4861         mtx_unlock(&lun->lun_lock);
4862
4863         return (0);
4864 }
4865
4866 int
4867 ctl_lun_offline(struct ctl_be_lun *be_lun)
4868 {
4869         struct ctl_softc *ctl_softc;
4870         struct ctl_lun *lun;
4871
4872         ctl_softc = control_softc;
4873
4874         lun = (struct ctl_lun *)be_lun->ctl_lun;
4875
4876         mtx_lock(&lun->lun_lock);
4877         lun->flags |= CTL_LUN_OFFLINE;
4878         mtx_unlock(&lun->lun_lock);
4879
4880         return (0);
4881 }
4882
4883 int
4884 ctl_lun_online(struct ctl_be_lun *be_lun)
4885 {
4886         struct ctl_softc *ctl_softc;
4887         struct ctl_lun *lun;
4888
4889         ctl_softc = control_softc;
4890
4891         lun = (struct ctl_lun *)be_lun->ctl_lun;
4892
4893         mtx_lock(&lun->lun_lock);
4894         lun->flags &= ~CTL_LUN_OFFLINE;
4895         mtx_unlock(&lun->lun_lock);
4896
4897         return (0);
4898 }
4899
4900 int
4901 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4902 {
4903         struct ctl_softc *ctl_softc;
4904         struct ctl_lun *lun;
4905
4906         ctl_softc = control_softc;
4907
4908         lun = (struct ctl_lun *)be_lun->ctl_lun;
4909
4910         mtx_lock(&lun->lun_lock);
4911
4912         /*
4913          * The LUN needs to be disabled before it can be marked invalid.
4914          */
4915         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4916                 mtx_unlock(&lun->lun_lock);
4917                 return (-1);
4918         }
4919         /*
4920          * Mark the LUN invalid.
4921          */
4922         lun->flags |= CTL_LUN_INVALID;
4923
4924         /*
4925          * If there is nothing in the OOA queue, go ahead and free the LUN.
4926          * If we have something in the OOA queue, we'll free it when the
4927          * last I/O completes.
4928          */
4929         if (TAILQ_EMPTY(&lun->ooa_queue)) {
4930                 mtx_unlock(&lun->lun_lock);
4931                 mtx_lock(&ctl_softc->ctl_lock);
4932                 ctl_free_lun(lun);
4933                 mtx_unlock(&ctl_softc->ctl_lock);
4934         } else
4935                 mtx_unlock(&lun->lun_lock);
4936
4937         return (0);
4938 }
4939
4940 int
4941 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4942 {
4943         struct ctl_softc *ctl_softc;
4944         struct ctl_lun *lun;
4945
4946         ctl_softc = control_softc;
4947         lun = (struct ctl_lun *)be_lun->ctl_lun;
4948
4949         mtx_lock(&lun->lun_lock);
4950         lun->flags |= CTL_LUN_INOPERABLE;
4951         mtx_unlock(&lun->lun_lock);
4952
4953         return (0);
4954 }
4955
4956 int
4957 ctl_lun_operable(struct ctl_be_lun *be_lun)
4958 {
4959         struct ctl_softc *ctl_softc;
4960         struct ctl_lun *lun;
4961
4962         ctl_softc = control_softc;
4963         lun = (struct ctl_lun *)be_lun->ctl_lun;
4964
4965         mtx_lock(&lun->lun_lock);
4966         lun->flags &= ~CTL_LUN_INOPERABLE;
4967         mtx_unlock(&lun->lun_lock);
4968
4969         return (0);
4970 }
4971
4972 void
4973 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4974 {
4975         struct ctl_lun *lun;
4976         struct ctl_softc *softc;
4977         int i;
4978
4979         softc = control_softc;
4980
4981         lun = (struct ctl_lun *)be_lun->ctl_lun;
4982
4983         mtx_lock(&lun->lun_lock);
4984
4985         for (i = 0; i < CTL_MAX_INITIATORS; i++) 
4986                 lun->pending_ua[i] |= CTL_UA_CAPACITY_CHANGED;
4987
4988         mtx_unlock(&lun->lun_lock);
4989 }
4990
4991 /*
4992  * Backend "memory move is complete" callback for requests that never
4993  * make it down to say RAIDCore's configuration code.
4994  */
4995 int
4996 ctl_config_move_done(union ctl_io *io)
4997 {
4998         int retval;
4999
5000         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5001         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5002             ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5003
5004         if ((io->io_hdr.port_status != 0) &&
5005             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5006              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5007                 /*
5008                  * For hardware error sense keys, the sense key
5009                  * specific value is defined to be a retry count,
5010                  * but we use it to pass back an internal FETD
5011                  * error code.  XXX KDM  Hopefully the FETD is only
5012                  * using 16 bits for an error code, since that's
5013                  * all the space we have in the sks field.
5014                  */
5015                 ctl_set_internal_failure(&io->scsiio,
5016                                          /*sks_valid*/ 1,
5017                                          /*retry_count*/
5018                                          io->io_hdr.port_status);
5019         }
5020
5021         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5022             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5023              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5024             ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5025                 /*
5026                  * XXX KDM just assuming a single pointer here, and not a
5027                  * S/G list.  If we start using S/G lists for config data,
5028                  * we'll need to know how to clean them up here as well.
5029                  */
5030                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5031                         free(io->scsiio.kern_data_ptr, M_CTL);
5032                 ctl_done(io);
5033                 retval = CTL_RETVAL_COMPLETE;
5034         } else {
5035                 /*
5036                  * XXX KDM now we need to continue data movement.  Some
5037                  * options:
5038                  * - call ctl_scsiio() again?  We don't do this for data
5039                  *   writes, because for those at least we know ahead of
5040                  *   time where the write will go and how long it is.  For
5041                  *   config writes, though, that information is largely
5042                  *   contained within the write itself, thus we need to
5043                  *   parse out the data again.
5044                  *
5045                  * - Call some other function once the data is in?
5046                  */
5047                 if (ctl_debug & CTL_DEBUG_CDB_DATA)
5048                         ctl_data_print(io);
5049
5050                 /*
5051                  * XXX KDM call ctl_scsiio() again for now, and check flag
5052                  * bits to see whether we're allocated or not.
5053                  */
5054                 retval = ctl_scsiio(&io->scsiio);
5055         }
5056         return (retval);
5057 }
5058
5059 /*
5060  * This gets called by a backend driver when it is done with a
5061  * data_submit method.
5062  */
5063 void
5064 ctl_data_submit_done(union ctl_io *io)
5065 {
5066         /*
5067          * If the IO_CONT flag is set, we need to call the supplied
5068          * function to continue processing the I/O, instead of completing
5069          * the I/O just yet.
5070          *
5071          * If there is an error, though, we don't want to keep processing.
5072          * Instead, just send status back to the initiator.
5073          */
5074         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5075             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5076             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5077              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5078                 io->scsiio.io_cont(io);
5079                 return;
5080         }
5081         ctl_done(io);
5082 }
5083
5084 /*
5085  * This gets called by a backend driver when it is done with a
5086  * configuration write.
5087  */
5088 void
5089 ctl_config_write_done(union ctl_io *io)
5090 {
5091         uint8_t *buf;
5092
5093         /*
5094          * If the IO_CONT flag is set, we need to call the supplied
5095          * function to continue processing the I/O, instead of completing
5096          * the I/O just yet.
5097          *
5098          * If there is an error, though, we don't want to keep processing.
5099          * Instead, just send status back to the initiator.
5100          */
5101         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5102             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5103             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5104              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5105                 io->scsiio.io_cont(io);
5106                 return;
5107         }
5108         /*
5109          * Since a configuration write can be done for commands that actually
5110          * have data allocated, like write buffer, and commands that have
5111          * no data, like start/stop unit, we need to check here.
5112          */
5113         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5114                 buf = io->scsiio.kern_data_ptr;
5115         else
5116                 buf = NULL;
5117         ctl_done(io);
5118         if (buf)
5119                 free(buf, M_CTL);
5120 }
5121
5122 /*
5123  * SCSI release command.
5124  */
5125 int
5126 ctl_scsi_release(struct ctl_scsiio *ctsio)
5127 {
5128         int length, longid, thirdparty_id, resv_id;
5129         struct ctl_softc *ctl_softc;
5130         struct ctl_lun *lun;
5131         uint32_t residx;
5132
5133         length = 0;
5134         resv_id = 0;
5135
5136         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5137
5138         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5139         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5140         ctl_softc = control_softc;
5141
5142         switch (ctsio->cdb[0]) {
5143         case RELEASE_10: {
5144                 struct scsi_release_10 *cdb;
5145
5146                 cdb = (struct scsi_release_10 *)ctsio->cdb;
5147
5148                 if (cdb->byte2 & SR10_LONGID)
5149                         longid = 1;
5150                 else
5151                         thirdparty_id = cdb->thirdparty_id;
5152
5153                 resv_id = cdb->resv_id;
5154                 length = scsi_2btoul(cdb->length);
5155                 break;
5156         }
5157         }
5158
5159
5160         /*
5161          * XXX KDM right now, we only support LUN reservation.  We don't
5162          * support 3rd party reservations, or extent reservations, which
5163          * might actually need the parameter list.  If we've gotten this
5164          * far, we've got a LUN reservation.  Anything else got kicked out
5165          * above.  So, according to SPC, ignore the length.
5166          */
5167         length = 0;
5168
5169         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5170          && (length > 0)) {
5171                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5172                 ctsio->kern_data_len = length;
5173                 ctsio->kern_total_len = length;
5174                 ctsio->kern_data_resid = 0;
5175                 ctsio->kern_rel_offset = 0;
5176                 ctsio->kern_sg_entries = 0;
5177                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5178                 ctsio->be_move_done = ctl_config_move_done;
5179                 ctl_datamove((union ctl_io *)ctsio);
5180
5181                 return (CTL_RETVAL_COMPLETE);
5182         }
5183
5184         if (length > 0)
5185                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5186
5187         mtx_lock(&lun->lun_lock);
5188
5189         /*
5190          * According to SPC, it is not an error for an intiator to attempt
5191          * to release a reservation on a LUN that isn't reserved, or that
5192          * is reserved by another initiator.  The reservation can only be
5193          * released, though, by the initiator who made it or by one of
5194          * several reset type events.
5195          */
5196         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5197                         lun->flags &= ~CTL_LUN_RESERVED;
5198
5199         mtx_unlock(&lun->lun_lock);
5200
5201         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5202                 free(ctsio->kern_data_ptr, M_CTL);
5203                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5204         }
5205
5206         ctl_set_success(ctsio);
5207         ctl_done((union ctl_io *)ctsio);
5208         return (CTL_RETVAL_COMPLETE);
5209 }
5210
5211 int
5212 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5213 {
5214         int extent, thirdparty, longid;
5215         int resv_id, length;
5216         uint64_t thirdparty_id;
5217         struct ctl_softc *ctl_softc;
5218         struct ctl_lun *lun;
5219         uint32_t residx;
5220
5221         extent = 0;
5222         thirdparty = 0;
5223         longid = 0;
5224         resv_id = 0;
5225         length = 0;
5226         thirdparty_id = 0;
5227
5228         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5229
5230         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5231         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5232         ctl_softc = control_softc;
5233
5234         switch (ctsio->cdb[0]) {
5235         case RESERVE_10: {
5236                 struct scsi_reserve_10 *cdb;
5237
5238                 cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5239
5240                 if (cdb->byte2 & SR10_LONGID)
5241                         longid = 1;
5242                 else
5243                         thirdparty_id = cdb->thirdparty_id;
5244
5245                 resv_id = cdb->resv_id;
5246                 length = scsi_2btoul(cdb->length);
5247                 break;
5248         }
5249         }
5250
5251         /*
5252          * XXX KDM right now, we only support LUN reservation.  We don't
5253          * support 3rd party reservations, or extent reservations, which
5254          * might actually need the parameter list.  If we've gotten this
5255          * far, we've got a LUN reservation.  Anything else got kicked out
5256          * above.  So, according to SPC, ignore the length.
5257          */
5258         length = 0;
5259
5260         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5261          && (length > 0)) {
5262                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5263                 ctsio->kern_data_len = length;
5264                 ctsio->kern_total_len = length;
5265                 ctsio->kern_data_resid = 0;
5266                 ctsio->kern_rel_offset = 0;
5267                 ctsio->kern_sg_entries = 0;
5268                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5269                 ctsio->be_move_done = ctl_config_move_done;
5270                 ctl_datamove((union ctl_io *)ctsio);
5271
5272                 return (CTL_RETVAL_COMPLETE);
5273         }
5274
5275         if (length > 0)
5276                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5277
5278         mtx_lock(&lun->lun_lock);
5279         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5280                 ctl_set_reservation_conflict(ctsio);
5281                 goto bailout;
5282         }
5283
5284         lun->flags |= CTL_LUN_RESERVED;
5285         lun->res_idx = residx;
5286
5287         ctl_set_success(ctsio);
5288
5289 bailout:
5290         mtx_unlock(&lun->lun_lock);
5291
5292         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5293                 free(ctsio->kern_data_ptr, M_CTL);
5294                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5295         }
5296
5297         ctl_done((union ctl_io *)ctsio);
5298         return (CTL_RETVAL_COMPLETE);
5299 }
5300
5301 int
5302 ctl_start_stop(struct ctl_scsiio *ctsio)
5303 {
5304         struct scsi_start_stop_unit *cdb;
5305         struct ctl_lun *lun;
5306         struct ctl_softc *ctl_softc;
5307         int retval;
5308
5309         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5310
5311         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5312         ctl_softc = control_softc;
5313         retval = 0;
5314
5315         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5316
5317         /*
5318          * XXX KDM
5319          * We don't support the immediate bit on a stop unit.  In order to
5320          * do that, we would need to code up a way to know that a stop is
5321          * pending, and hold off any new commands until it completes, one
5322          * way or another.  Then we could accept or reject those commands
5323          * depending on its status.  We would almost need to do the reverse
5324          * of what we do below for an immediate start -- return the copy of
5325          * the ctl_io to the FETD with status to send to the host (and to
5326          * free the copy!) and then free the original I/O once the stop
5327          * actually completes.  That way, the OOA queue mechanism can work
5328          * to block commands that shouldn't proceed.  Another alternative
5329          * would be to put the copy in the queue in place of the original,
5330          * and return the original back to the caller.  That could be
5331          * slightly safer..
5332          */
5333         if ((cdb->byte2 & SSS_IMMED)
5334          && ((cdb->how & SSS_START) == 0)) {
5335                 ctl_set_invalid_field(ctsio,
5336                                       /*sks_valid*/ 1,
5337                                       /*command*/ 1,
5338                                       /*field*/ 1,
5339                                       /*bit_valid*/ 1,
5340                                       /*bit*/ 0);
5341                 ctl_done((union ctl_io *)ctsio);
5342                 return (CTL_RETVAL_COMPLETE);
5343         }
5344
5345         if ((lun->flags & CTL_LUN_PR_RESERVED)
5346          && ((cdb->how & SSS_START)==0)) {
5347                 uint32_t residx;
5348
5349                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5350                 if (lun->pr_keys[residx] == 0
5351                  || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5352
5353                         ctl_set_reservation_conflict(ctsio);
5354                         ctl_done((union ctl_io *)ctsio);
5355                         return (CTL_RETVAL_COMPLETE);
5356                 }
5357         }
5358
5359         /*
5360          * If there is no backend on this device, we can't start or stop
5361          * it.  In theory we shouldn't get any start/stop commands in the
5362          * first place at this level if the LUN doesn't have a backend.
5363          * That should get stopped by the command decode code.
5364          */
5365         if (lun->backend == NULL) {
5366                 ctl_set_invalid_opcode(ctsio);
5367                 ctl_done((union ctl_io *)ctsio);
5368                 return (CTL_RETVAL_COMPLETE);
5369         }
5370
5371         /*
5372          * XXX KDM Copan-specific offline behavior.
5373          * Figure out a reasonable way to port this?
5374          */
5375 #ifdef NEEDTOPORT
5376         mtx_lock(&lun->lun_lock);
5377
5378         if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5379          && (lun->flags & CTL_LUN_OFFLINE)) {
5380                 /*
5381                  * If the LUN is offline, and the on/offline bit isn't set,
5382                  * reject the start or stop.  Otherwise, let it through.
5383                  */
5384                 mtx_unlock(&lun->lun_lock);
5385                 ctl_set_lun_not_ready(ctsio);
5386                 ctl_done((union ctl_io *)ctsio);
5387         } else {
5388                 mtx_unlock(&lun->lun_lock);
5389 #endif /* NEEDTOPORT */
5390                 /*
5391                  * This could be a start or a stop when we're online,
5392                  * or a stop/offline or start/online.  A start or stop when
5393                  * we're offline is covered in the case above.
5394                  */
5395                 /*
5396                  * In the non-immediate case, we send the request to
5397                  * the backend and return status to the user when
5398                  * it is done.
5399                  *
5400                  * In the immediate case, we allocate a new ctl_io
5401                  * to hold a copy of the request, and send that to
5402                  * the backend.  We then set good status on the
5403                  * user's request and return it immediately.
5404                  */
5405                 if (cdb->byte2 & SSS_IMMED) {
5406                         union ctl_io *new_io;
5407
5408                         new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5409                         ctl_copy_io((union ctl_io *)ctsio, new_io);
5410                         retval = lun->backend->config_write(new_io);
5411                         ctl_set_success(ctsio);
5412                         ctl_done((union ctl_io *)ctsio);
5413                 } else {
5414                         retval = lun->backend->config_write(
5415                                 (union ctl_io *)ctsio);
5416                 }
5417 #ifdef NEEDTOPORT
5418         }
5419 #endif
5420         return (retval);
5421 }
5422
5423 /*
5424  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5425  * we don't really do anything with the LBA and length fields if the user
5426  * passes them in.  Instead we'll just flush out the cache for the entire
5427  * LUN.
5428  */
5429 int
5430 ctl_sync_cache(struct ctl_scsiio *ctsio)
5431 {
5432         struct ctl_lun *lun;
5433         struct ctl_softc *ctl_softc;
5434         uint64_t starting_lba;
5435         uint32_t block_count;
5436         int retval;
5437
5438         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5439
5440         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5441         ctl_softc = control_softc;
5442         retval = 0;
5443
5444         switch (ctsio->cdb[0]) {
5445         case SYNCHRONIZE_CACHE: {
5446                 struct scsi_sync_cache *cdb;
5447                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5448
5449                 starting_lba = scsi_4btoul(cdb->begin_lba);
5450                 block_count = scsi_2btoul(cdb->lb_count);
5451                 break;
5452         }
5453         case SYNCHRONIZE_CACHE_16: {
5454                 struct scsi_sync_cache_16 *cdb;
5455                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5456
5457                 starting_lba = scsi_8btou64(cdb->begin_lba);
5458                 block_count = scsi_4btoul(cdb->lb_count);
5459                 break;
5460         }
5461         default:
5462                 ctl_set_invalid_opcode(ctsio);
5463                 ctl_done((union ctl_io *)ctsio);
5464                 goto bailout;
5465                 break; /* NOTREACHED */
5466         }
5467
5468         /*
5469          * We check the LBA and length, but don't do anything with them.
5470          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5471          * get flushed.  This check will just help satisfy anyone who wants
5472          * to see an error for an out of range LBA.
5473          */
5474         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5475                 ctl_set_lba_out_of_range(ctsio);
5476                 ctl_done((union ctl_io *)ctsio);
5477                 goto bailout;
5478         }
5479
5480         /*
5481          * If this LUN has no backend, we can't flush the cache anyway.
5482          */
5483         if (lun->backend == NULL) {
5484                 ctl_set_invalid_opcode(ctsio);
5485                 ctl_done((union ctl_io *)ctsio);
5486                 goto bailout;
5487         }
5488
5489         /*
5490          * Check to see whether we're configured to send the SYNCHRONIZE
5491          * CACHE command directly to the back end.
5492          */
5493         mtx_lock(&lun->lun_lock);
5494         if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5495          && (++(lun->sync_count) >= lun->sync_interval)) {
5496                 lun->sync_count = 0;
5497                 mtx_unlock(&lun->lun_lock);
5498                 retval = lun->backend->config_write((union ctl_io *)ctsio);
5499         } else {
5500                 mtx_unlock(&lun->lun_lock);
5501                 ctl_set_success(ctsio);
5502                 ctl_done((union ctl_io *)ctsio);
5503         }
5504
5505 bailout:
5506
5507         return (retval);
5508 }
5509
5510 int
5511 ctl_format(struct ctl_scsiio *ctsio)
5512 {
5513         struct scsi_format *cdb;
5514         struct ctl_lun *lun;
5515         struct ctl_softc *ctl_softc;
5516         int length, defect_list_len;
5517
5518         CTL_DEBUG_PRINT(("ctl_format\n"));
5519
5520         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5521         ctl_softc = control_softc;
5522
5523         cdb = (struct scsi_format *)ctsio->cdb;
5524
5525         length = 0;
5526         if (cdb->byte2 & SF_FMTDATA) {
5527                 if (cdb->byte2 & SF_LONGLIST)
5528                         length = sizeof(struct scsi_format_header_long);
5529                 else
5530                         length = sizeof(struct scsi_format_header_short);
5531         }
5532
5533         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5534          && (length > 0)) {
5535                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5536                 ctsio->kern_data_len = length;
5537                 ctsio->kern_total_len = length;
5538                 ctsio->kern_data_resid = 0;
5539                 ctsio->kern_rel_offset = 0;
5540                 ctsio->kern_sg_entries = 0;
5541                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5542                 ctsio->be_move_done = ctl_config_move_done;
5543                 ctl_datamove((union ctl_io *)ctsio);
5544
5545                 return (CTL_RETVAL_COMPLETE);
5546         }
5547
5548         defect_list_len = 0;
5549
5550         if (cdb->byte2 & SF_FMTDATA) {
5551                 if (cdb->byte2 & SF_LONGLIST) {
5552                         struct scsi_format_header_long *header;
5553
5554                         header = (struct scsi_format_header_long *)
5555                                 ctsio->kern_data_ptr;
5556
5557                         defect_list_len = scsi_4btoul(header->defect_list_len);
5558                         if (defect_list_len != 0) {
5559                                 ctl_set_invalid_field(ctsio,
5560                                                       /*sks_valid*/ 1,
5561                                                       /*command*/ 0,
5562                                                       /*field*/ 2,
5563                                                       /*bit_valid*/ 0,
5564                                                       /*bit*/ 0);
5565                                 goto bailout;
5566                         }
5567                 } else {
5568                         struct scsi_format_header_short *header;
5569
5570                         header = (struct scsi_format_header_short *)
5571                                 ctsio->kern_data_ptr;
5572
5573                         defect_list_len = scsi_2btoul(header->defect_list_len);
5574                         if (defect_list_len != 0) {
5575                                 ctl_set_invalid_field(ctsio,
5576                                                       /*sks_valid*/ 1,
5577                                                       /*command*/ 0,
5578                                                       /*field*/ 2,
5579                                                       /*bit_valid*/ 0,
5580                                                       /*bit*/ 0);
5581                                 goto bailout;
5582                         }
5583                 }
5584         }
5585
5586         /*
5587          * The format command will clear out the "Medium format corrupted"
5588          * status if set by the configuration code.  That status is really
5589          * just a way to notify the host that we have lost the media, and
5590          * get them to issue a command that will basically make them think
5591          * they're blowing away the media.
5592          */
5593         mtx_lock(&lun->lun_lock);
5594         lun->flags &= ~CTL_LUN_INOPERABLE;
5595         mtx_unlock(&lun->lun_lock);
5596
5597         ctl_set_success(ctsio);
5598 bailout:
5599
5600         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5601                 free(ctsio->kern_data_ptr, M_CTL);
5602                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5603         }
5604
5605         ctl_done((union ctl_io *)ctsio);
5606         return (CTL_RETVAL_COMPLETE);
5607 }
5608
5609 int
5610 ctl_read_buffer(struct ctl_scsiio *ctsio)
5611 {
5612         struct scsi_read_buffer *cdb;
5613         struct ctl_lun *lun;
5614         int buffer_offset, len;
5615         static uint8_t descr[4];
5616         static uint8_t echo_descr[4] = { 0 };
5617
5618         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5619
5620         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5621         cdb = (struct scsi_read_buffer *)ctsio->cdb;
5622
5623         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5624             (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5625             (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5626                 ctl_set_invalid_field(ctsio,
5627                                       /*sks_valid*/ 1,
5628                                       /*command*/ 1,
5629                                       /*field*/ 1,
5630                                       /*bit_valid*/ 1,
5631                                       /*bit*/ 4);
5632                 ctl_done((union ctl_io *)ctsio);
5633                 return (CTL_RETVAL_COMPLETE);
5634         }
5635
5636         len = scsi_3btoul(cdb->length);
5637         buffer_offset = scsi_3btoul(cdb->offset);
5638
5639         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5640                 ctl_set_invalid_field(ctsio,
5641                                       /*sks_valid*/ 1,
5642                                       /*command*/ 1,
5643                                       /*field*/ 6,
5644                                       /*bit_valid*/ 0,
5645                                       /*bit*/ 0);
5646                 ctl_done((union ctl_io *)ctsio);
5647                 return (CTL_RETVAL_COMPLETE);
5648         }
5649
5650         if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5651                 descr[0] = 0;
5652                 scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5653                 ctsio->kern_data_ptr = descr;
5654                 len = min(len, sizeof(descr));
5655         } else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5656                 ctsio->kern_data_ptr = echo_descr;
5657                 len = min(len, sizeof(echo_descr));
5658         } else {
5659                 if (lun->write_buffer == NULL) {
5660                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5661                             M_CTL, M_WAITOK);
5662                 }
5663                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5664         }
5665         ctsio->kern_data_len = len;
5666         ctsio->kern_total_len = len;
5667         ctsio->kern_data_resid = 0;
5668         ctsio->kern_rel_offset = 0;
5669         ctsio->kern_sg_entries = 0;
5670         ctl_set_success(ctsio);
5671         ctsio->be_move_done = ctl_config_move_done;
5672         ctl_datamove((union ctl_io *)ctsio);
5673         return (CTL_RETVAL_COMPLETE);
5674 }
5675
5676 int
5677 ctl_write_buffer(struct ctl_scsiio *ctsio)
5678 {
5679         struct scsi_write_buffer *cdb;
5680         struct ctl_lun *lun;
5681         int buffer_offset, len;
5682
5683         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5684
5685         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5686         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5687
5688         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5689                 ctl_set_invalid_field(ctsio,
5690                                       /*sks_valid*/ 1,
5691                                       /*command*/ 1,
5692                                       /*field*/ 1,
5693                                       /*bit_valid*/ 1,
5694                                       /*bit*/ 4);
5695                 ctl_done((union ctl_io *)ctsio);
5696                 return (CTL_RETVAL_COMPLETE);
5697         }
5698
5699         len = scsi_3btoul(cdb->length);
5700         buffer_offset = scsi_3btoul(cdb->offset);
5701
5702         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5703                 ctl_set_invalid_field(ctsio,
5704                                       /*sks_valid*/ 1,
5705                                       /*command*/ 1,
5706                                       /*field*/ 6,
5707                                       /*bit_valid*/ 0,
5708                                       /*bit*/ 0);
5709                 ctl_done((union ctl_io *)ctsio);
5710                 return (CTL_RETVAL_COMPLETE);
5711         }
5712
5713         /*
5714          * If we've got a kernel request that hasn't been malloced yet,
5715          * malloc it and tell the caller the data buffer is here.
5716          */
5717         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5718                 if (lun->write_buffer == NULL) {
5719                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5720                             M_CTL, M_WAITOK);
5721                 }
5722                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5723                 ctsio->kern_data_len = len;
5724                 ctsio->kern_total_len = len;
5725                 ctsio->kern_data_resid = 0;
5726                 ctsio->kern_rel_offset = 0;
5727                 ctsio->kern_sg_entries = 0;
5728                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5729                 ctsio->be_move_done = ctl_config_move_done;
5730                 ctl_datamove((union ctl_io *)ctsio);
5731
5732                 return (CTL_RETVAL_COMPLETE);
5733         }
5734
5735         ctl_set_success(ctsio);
5736         ctl_done((union ctl_io *)ctsio);
5737         return (CTL_RETVAL_COMPLETE);
5738 }
5739
5740 int
5741 ctl_write_same(struct ctl_scsiio *ctsio)
5742 {
5743         struct ctl_lun *lun;
5744         struct ctl_lba_len_flags *lbalen;
5745         uint64_t lba;
5746         uint32_t num_blocks;
5747         int len, retval;
5748         uint8_t byte2;
5749
5750         retval = CTL_RETVAL_COMPLETE;
5751
5752         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5753
5754         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5755
5756         switch (ctsio->cdb[0]) {
5757         case WRITE_SAME_10: {
5758                 struct scsi_write_same_10 *cdb;
5759
5760                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5761
5762                 lba = scsi_4btoul(cdb->addr);
5763                 num_blocks = scsi_2btoul(cdb->length);
5764                 byte2 = cdb->byte2;
5765                 break;
5766         }
5767         case WRITE_SAME_16: {
5768                 struct scsi_write_same_16 *cdb;
5769
5770                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5771
5772                 lba = scsi_8btou64(cdb->addr);
5773                 num_blocks = scsi_4btoul(cdb->length);
5774                 byte2 = cdb->byte2;
5775                 break;
5776         }
5777         default:
5778                 /*
5779                  * We got a command we don't support.  This shouldn't
5780                  * happen, commands should be filtered out above us.
5781                  */
5782                 ctl_set_invalid_opcode(ctsio);
5783                 ctl_done((union ctl_io *)ctsio);
5784
5785                 return (CTL_RETVAL_COMPLETE);
5786                 break; /* NOTREACHED */
5787         }
5788
5789         /* NDOB and ANCHOR flags can be used only together with UNMAP */
5790         if ((byte2 & SWS_UNMAP) == 0 &&
5791             (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5792                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5793                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5794                 ctl_done((union ctl_io *)ctsio);
5795                 return (CTL_RETVAL_COMPLETE);
5796         }
5797
5798         /*
5799          * The first check is to make sure we're in bounds, the second
5800          * check is to catch wrap-around problems.  If the lba + num blocks
5801          * is less than the lba, then we've wrapped around and the block
5802          * range is invalid anyway.
5803          */
5804         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5805          || ((lba + num_blocks) < lba)) {
5806                 ctl_set_lba_out_of_range(ctsio);
5807                 ctl_done((union ctl_io *)ctsio);
5808                 return (CTL_RETVAL_COMPLETE);
5809         }
5810
5811         /* Zero number of blocks means "to the last logical block" */
5812         if (num_blocks == 0) {
5813                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5814                         ctl_set_invalid_field(ctsio,
5815                                               /*sks_valid*/ 0,
5816                                               /*command*/ 1,
5817                                               /*field*/ 0,
5818                                               /*bit_valid*/ 0,
5819                                               /*bit*/ 0);
5820                         ctl_done((union ctl_io *)ctsio);
5821                         return (CTL_RETVAL_COMPLETE);
5822                 }
5823                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
5824         }
5825
5826         len = lun->be_lun->blocksize;
5827
5828         /*
5829          * If we've got a kernel request that hasn't been malloced yet,
5830          * malloc it and tell the caller the data buffer is here.
5831          */
5832         if ((byte2 & SWS_NDOB) == 0 &&
5833             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5834                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5835                 ctsio->kern_data_len = len;
5836                 ctsio->kern_total_len = len;
5837                 ctsio->kern_data_resid = 0;
5838                 ctsio->kern_rel_offset = 0;
5839                 ctsio->kern_sg_entries = 0;
5840                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5841                 ctsio->be_move_done = ctl_config_move_done;
5842                 ctl_datamove((union ctl_io *)ctsio);
5843
5844                 return (CTL_RETVAL_COMPLETE);
5845         }
5846
5847         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5848         lbalen->lba = lba;
5849         lbalen->len = num_blocks;
5850         lbalen->flags = byte2;
5851         retval = lun->backend->config_write((union ctl_io *)ctsio);
5852
5853         return (retval);
5854 }
5855
5856 int
5857 ctl_unmap(struct ctl_scsiio *ctsio)
5858 {
5859         struct ctl_lun *lun;
5860         struct scsi_unmap *cdb;
5861         struct ctl_ptr_len_flags *ptrlen;
5862         struct scsi_unmap_header *hdr;
5863         struct scsi_unmap_desc *buf, *end, *endnz, *range;
5864         uint64_t lba;
5865         uint32_t num_blocks;
5866         int len, retval;
5867         uint8_t byte2;
5868
5869         retval = CTL_RETVAL_COMPLETE;
5870
5871         CTL_DEBUG_PRINT(("ctl_unmap\n"));
5872
5873         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5874         cdb = (struct scsi_unmap *)ctsio->cdb;
5875
5876         len = scsi_2btoul(cdb->length);
5877         byte2 = cdb->byte2;
5878
5879         /*
5880          * If we've got a kernel request that hasn't been malloced yet,
5881          * malloc it and tell the caller the data buffer is here.
5882          */
5883         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5884                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5885                 ctsio->kern_data_len = len;
5886                 ctsio->kern_total_len = len;
5887                 ctsio->kern_data_resid = 0;
5888                 ctsio->kern_rel_offset = 0;
5889                 ctsio->kern_sg_entries = 0;
5890                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5891                 ctsio->be_move_done = ctl_config_move_done;
5892                 ctl_datamove((union ctl_io *)ctsio);
5893
5894                 return (CTL_RETVAL_COMPLETE);
5895         }
5896
5897         len = ctsio->kern_total_len - ctsio->kern_data_resid;
5898         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5899         if (len < sizeof (*hdr) ||
5900             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5901             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5902             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5903                 ctl_set_invalid_field(ctsio,
5904                                       /*sks_valid*/ 0,
5905                                       /*command*/ 0,
5906                                       /*field*/ 0,
5907                                       /*bit_valid*/ 0,
5908                                       /*bit*/ 0);
5909                 goto done;
5910         }
5911         len = scsi_2btoul(hdr->desc_length);
5912         buf = (struct scsi_unmap_desc *)(hdr + 1);
5913         end = buf + len / sizeof(*buf);
5914
5915         endnz = buf;
5916         for (range = buf; range < end; range++) {
5917                 lba = scsi_8btou64(range->lba);
5918                 num_blocks = scsi_4btoul(range->length);
5919                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5920                  || ((lba + num_blocks) < lba)) {
5921                         ctl_set_lba_out_of_range(ctsio);
5922                         ctl_done((union ctl_io *)ctsio);
5923                         return (CTL_RETVAL_COMPLETE);
5924                 }
5925                 if (num_blocks != 0)
5926                         endnz = range + 1;
5927         }
5928
5929         /*
5930          * Block backend can not handle zero last range.
5931          * Filter it out and return if there is nothing left.
5932          */
5933         len = (uint8_t *)endnz - (uint8_t *)buf;
5934         if (len == 0) {
5935                 ctl_set_success(ctsio);
5936                 goto done;
5937         }
5938
5939         mtx_lock(&lun->lun_lock);
5940         ptrlen = (struct ctl_ptr_len_flags *)
5941             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5942         ptrlen->ptr = (void *)buf;
5943         ptrlen->len = len;
5944         ptrlen->flags = byte2;
5945         ctl_check_blocked(lun);
5946         mtx_unlock(&lun->lun_lock);
5947
5948         retval = lun->backend->config_write((union ctl_io *)ctsio);
5949         return (retval);
5950
5951 done:
5952         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5953                 free(ctsio->kern_data_ptr, M_CTL);
5954                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5955         }
5956         ctl_done((union ctl_io *)ctsio);
5957         return (CTL_RETVAL_COMPLETE);
5958 }
5959
5960 /*
5961  * Note that this function currently doesn't actually do anything inside
5962  * CTL to enforce things if the DQue bit is turned on.
5963  *
5964  * Also note that this function can't be used in the default case, because
5965  * the DQue bit isn't set in the changeable mask for the control mode page
5966  * anyway.  This is just here as an example for how to implement a page
5967  * handler, and a placeholder in case we want to allow the user to turn
5968  * tagged queueing on and off.
5969  *
5970  * The D_SENSE bit handling is functional, however, and will turn
5971  * descriptor sense on and off for a given LUN.
5972  */
5973 int
5974 ctl_control_page_handler(struct ctl_scsiio *ctsio,
5975                          struct ctl_page_index *page_index, uint8_t *page_ptr)
5976 {
5977         struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5978         struct ctl_lun *lun;
5979         struct ctl_softc *softc;
5980         int set_ua;
5981         uint32_t initidx;
5982
5983         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5984         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5985         set_ua = 0;
5986
5987         user_cp = (struct scsi_control_page *)page_ptr;
5988         current_cp = (struct scsi_control_page *)
5989                 (page_index->page_data + (page_index->page_len *
5990                 CTL_PAGE_CURRENT));
5991         saved_cp = (struct scsi_control_page *)
5992                 (page_index->page_data + (page_index->page_len *
5993                 CTL_PAGE_SAVED));
5994
5995         softc = control_softc;
5996
5997         mtx_lock(&lun->lun_lock);
5998         if (((current_cp->rlec & SCP_DSENSE) == 0)
5999          && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6000                 /*
6001                  * Descriptor sense is currently turned off and the user
6002                  * wants to turn it on.
6003                  */
6004                 current_cp->rlec |= SCP_DSENSE;
6005                 saved_cp->rlec |= SCP_DSENSE;
6006                 lun->flags |= CTL_LUN_SENSE_DESC;
6007                 set_ua = 1;
6008         } else if (((current_cp->rlec & SCP_DSENSE) != 0)
6009                 && ((user_cp->rlec & SCP_DSENSE) == 0)) {
6010                 /*
6011                  * Descriptor sense is currently turned on, and the user
6012                  * wants to turn it off.
6013                  */
6014                 current_cp->rlec &= ~SCP_DSENSE;
6015                 saved_cp->rlec &= ~SCP_DSENSE;
6016                 lun->flags &= ~CTL_LUN_SENSE_DESC;
6017                 set_ua = 1;
6018         }
6019         if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6020             (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6021                 current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6022                 current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6023                 saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6024                 saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6025                 set_ua = 1;
6026         }
6027         if ((current_cp->eca_and_aen & SCP_SWP) !=
6028             (user_cp->eca_and_aen & SCP_SWP)) {
6029                 current_cp->eca_and_aen &= ~SCP_SWP;
6030                 current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6031                 saved_cp->eca_and_aen &= ~SCP_SWP;
6032                 saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6033                 set_ua = 1;
6034         }
6035         if (set_ua != 0) {
6036                 int i;
6037                 /*
6038                  * Let other initiators know that the mode
6039                  * parameters for this LUN have changed.
6040                  */
6041                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6042                         if (i == initidx)
6043                                 continue;
6044
6045                         lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6046                 }
6047         }
6048         mtx_unlock(&lun->lun_lock);
6049
6050         return (0);
6051 }
6052
6053 int
6054 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6055                      struct ctl_page_index *page_index, uint8_t *page_ptr)
6056 {
6057         struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6058         struct ctl_lun *lun;
6059         int set_ua;
6060         uint32_t initidx;
6061
6062         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6063         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6064         set_ua = 0;
6065
6066         user_cp = (struct scsi_caching_page *)page_ptr;
6067         current_cp = (struct scsi_caching_page *)
6068                 (page_index->page_data + (page_index->page_len *
6069                 CTL_PAGE_CURRENT));
6070         saved_cp = (struct scsi_caching_page *)
6071                 (page_index->page_data + (page_index->page_len *
6072                 CTL_PAGE_SAVED));
6073
6074         mtx_lock(&lun->lun_lock);
6075         if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6076             (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6077                 current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6078                 current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6079                 saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6080                 saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6081                 set_ua = 1;
6082         }
6083         if (set_ua != 0) {
6084                 int i;
6085                 /*
6086                  * Let other initiators know that the mode
6087                  * parameters for this LUN have changed.
6088                  */
6089                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6090                         if (i == initidx)
6091                                 continue;
6092
6093                         lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6094                 }
6095         }
6096         mtx_unlock(&lun->lun_lock);
6097
6098         return (0);
6099 }
6100
6101 int
6102 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6103                                 struct ctl_page_index *page_index,
6104                                 uint8_t *page_ptr)
6105 {
6106         uint8_t *c;
6107         int i;
6108
6109         c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6110         ctl_time_io_secs =
6111                 (c[0] << 8) |
6112                 (c[1] << 0) |
6113                 0;
6114         CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6115         printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6116         printf("page data:");
6117         for (i=0; i<8; i++)
6118                 printf(" %.2x",page_ptr[i]);
6119         printf("\n");
6120         return (0);
6121 }
6122
6123 int
6124 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6125                                struct ctl_page_index *page_index,
6126                                int pc)
6127 {
6128         struct copan_debugconf_subpage *page;
6129
6130         page = (struct copan_debugconf_subpage *)page_index->page_data +
6131                 (page_index->page_len * pc);
6132
6133         switch (pc) {
6134         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6135         case SMS_PAGE_CTRL_DEFAULT >> 6:
6136         case SMS_PAGE_CTRL_SAVED >> 6:
6137                 /*
6138                  * We don't update the changable or default bits for this page.
6139                  */
6140                 break;
6141         case SMS_PAGE_CTRL_CURRENT >> 6:
6142                 page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6143                 page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6144                 break;
6145         default:
6146 #ifdef NEEDTOPORT
6147                 EPRINT(0, "Invalid PC %d!!", pc);
6148 #endif /* NEEDTOPORT */
6149                 break;
6150         }
6151         return (0);
6152 }
6153
6154
6155 static int
6156 ctl_do_mode_select(union ctl_io *io)
6157 {
6158         struct scsi_mode_page_header *page_header;
6159         struct ctl_page_index *page_index;
6160         struct ctl_scsiio *ctsio;
6161         int control_dev, page_len;
6162         int page_len_offset, page_len_size;
6163         union ctl_modepage_info *modepage_info;
6164         struct ctl_lun *lun;
6165         int *len_left, *len_used;
6166         int retval, i;
6167
6168         ctsio = &io->scsiio;
6169         page_index = NULL;
6170         page_len = 0;
6171         retval = CTL_RETVAL_COMPLETE;
6172
6173         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6174
6175         if (lun->be_lun->lun_type != T_DIRECT)
6176                 control_dev = 1;
6177         else
6178                 control_dev = 0;
6179
6180         modepage_info = (union ctl_modepage_info *)
6181                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6182         len_left = &modepage_info->header.len_left;
6183         len_used = &modepage_info->header.len_used;
6184
6185 do_next_page:
6186
6187         page_header = (struct scsi_mode_page_header *)
6188                 (ctsio->kern_data_ptr + *len_used);
6189
6190         if (*len_left == 0) {
6191                 free(ctsio->kern_data_ptr, M_CTL);
6192                 ctl_set_success(ctsio);
6193                 ctl_done((union ctl_io *)ctsio);
6194                 return (CTL_RETVAL_COMPLETE);
6195         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6196
6197                 free(ctsio->kern_data_ptr, M_CTL);
6198                 ctl_set_param_len_error(ctsio);
6199                 ctl_done((union ctl_io *)ctsio);
6200                 return (CTL_RETVAL_COMPLETE);
6201
6202         } else if ((page_header->page_code & SMPH_SPF)
6203                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6204
6205                 free(ctsio->kern_data_ptr, M_CTL);
6206                 ctl_set_param_len_error(ctsio);
6207                 ctl_done((union ctl_io *)ctsio);
6208                 return (CTL_RETVAL_COMPLETE);
6209         }
6210
6211
6212         /*
6213          * XXX KDM should we do something with the block descriptor?
6214          */
6215         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6216
6217                 if ((control_dev != 0)
6218                  && (lun->mode_pages.index[i].page_flags &
6219                      CTL_PAGE_FLAG_DISK_ONLY))
6220                         continue;
6221
6222                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6223                     (page_header->page_code & SMPH_PC_MASK))
6224                         continue;
6225
6226                 /*
6227                  * If neither page has a subpage code, then we've got a
6228                  * match.
6229                  */
6230                 if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6231                  && ((page_header->page_code & SMPH_SPF) == 0)) {
6232                         page_index = &lun->mode_pages.index[i];
6233                         page_len = page_header->page_length;
6234                         break;
6235                 }
6236
6237                 /*
6238                  * If both pages have subpages, then the subpage numbers
6239                  * have to match.
6240                  */
6241                 if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6242                   && (page_header->page_code & SMPH_SPF)) {
6243                         struct scsi_mode_page_header_sp *sph;
6244
6245                         sph = (struct scsi_mode_page_header_sp *)page_header;
6246
6247                         if (lun->mode_pages.index[i].subpage ==
6248                             sph->subpage) {
6249                                 page_index = &lun->mode_pages.index[i];
6250                                 page_len = scsi_2btoul(sph->page_length);
6251                                 break;
6252                         }
6253                 }
6254         }
6255
6256         /*
6257          * If we couldn't find the page, or if we don't have a mode select
6258          * handler for it, send back an error to the user.
6259          */
6260         if ((page_index == NULL)
6261          || (page_index->select_handler == NULL)) {
6262                 ctl_set_invalid_field(ctsio,
6263                                       /*sks_valid*/ 1,
6264                                       /*command*/ 0,
6265                                       /*field*/ *len_used,
6266                                       /*bit_valid*/ 0,
6267                                       /*bit*/ 0);
6268                 free(ctsio->kern_data_ptr, M_CTL);
6269                 ctl_done((union ctl_io *)ctsio);
6270                 return (CTL_RETVAL_COMPLETE);
6271         }
6272
6273         if (page_index->page_code & SMPH_SPF) {
6274                 page_len_offset = 2;
6275                 page_len_size = 2;
6276         } else {
6277                 page_len_size = 1;
6278                 page_len_offset = 1;
6279         }
6280
6281         /*
6282          * If the length the initiator gives us isn't the one we specify in
6283          * the mode page header, or if they didn't specify enough data in
6284          * the CDB to avoid truncating this page, kick out the request.
6285          */
6286         if ((page_len != (page_index->page_len - page_len_offset -
6287                           page_len_size))
6288          || (*len_left < page_index->page_len)) {
6289
6290
6291                 ctl_set_invalid_field(ctsio,
6292                                       /*sks_valid*/ 1,
6293                                       /*command*/ 0,
6294                                       /*field*/ *len_used + page_len_offset,
6295                                       /*bit_valid*/ 0,
6296                                       /*bit*/ 0);
6297                 free(ctsio->kern_data_ptr, M_CTL);
6298                 ctl_done((union ctl_io *)ctsio);
6299                 return (CTL_RETVAL_COMPLETE);
6300         }
6301
6302         /*
6303          * Run through the mode page, checking to make sure that the bits
6304          * the user changed are actually legal for him to change.
6305          */
6306         for (i = 0; i < page_index->page_len; i++) {
6307                 uint8_t *user_byte, *change_mask, *current_byte;
6308                 int bad_bit;
6309                 int j;
6310
6311                 user_byte = (uint8_t *)page_header + i;
6312                 change_mask = page_index->page_data +
6313                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6314                 current_byte = page_index->page_data +
6315                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6316
6317                 /*
6318                  * Check to see whether the user set any bits in this byte
6319                  * that he is not allowed to set.
6320                  */
6321                 if ((*user_byte & ~(*change_mask)) ==
6322                     (*current_byte & ~(*change_mask)))
6323                         continue;
6324
6325                 /*
6326                  * Go through bit by bit to determine which one is illegal.
6327                  */
6328                 bad_bit = 0;
6329                 for (j = 7; j >= 0; j--) {
6330                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6331                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6332                                 bad_bit = i;
6333                                 break;
6334                         }
6335                 }
6336                 ctl_set_invalid_field(ctsio,
6337                                       /*sks_valid*/ 1,
6338                                       /*command*/ 0,
6339                                       /*field*/ *len_used + i,
6340                                       /*bit_valid*/ 1,
6341                                       /*bit*/ bad_bit);
6342                 free(ctsio->kern_data_ptr, M_CTL);
6343                 ctl_done((union ctl_io *)ctsio);
6344                 return (CTL_RETVAL_COMPLETE);
6345         }
6346
6347         /*
6348          * Decrement these before we call the page handler, since we may
6349          * end up getting called back one way or another before the handler
6350          * returns to this context.
6351          */
6352         *len_left -= page_index->page_len;
6353         *len_used += page_index->page_len;
6354
6355         retval = page_index->select_handler(ctsio, page_index,
6356                                             (uint8_t *)page_header);
6357
6358         /*
6359          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6360          * wait until this queued command completes to finish processing
6361          * the mode page.  If it returns anything other than
6362          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6363          * already set the sense information, freed the data pointer, and
6364          * completed the io for us.
6365          */
6366         if (retval != CTL_RETVAL_COMPLETE)
6367                 goto bailout_no_done;
6368
6369         /*
6370          * If the initiator sent us more than one page, parse the next one.
6371          */
6372         if (*len_left > 0)
6373                 goto do_next_page;
6374
6375         ctl_set_success(ctsio);
6376         free(ctsio->kern_data_ptr, M_CTL);
6377         ctl_done((union ctl_io *)ctsio);
6378
6379 bailout_no_done:
6380
6381         return (CTL_RETVAL_COMPLETE);
6382
6383 }
6384
6385 int
6386 ctl_mode_select(struct ctl_scsiio *ctsio)
6387 {
6388         int param_len, pf, sp;
6389         int header_size, bd_len;
6390         int len_left, len_used;
6391         struct ctl_page_index *page_index;
6392         struct ctl_lun *lun;
6393         int control_dev, page_len;
6394         union ctl_modepage_info *modepage_info;
6395         int retval;
6396
6397         pf = 0;
6398         sp = 0;
6399         page_len = 0;
6400         len_used = 0;
6401         len_left = 0;
6402         retval = 0;
6403         bd_len = 0;
6404         page_index = NULL;
6405
6406         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6407
6408         if (lun->be_lun->lun_type != T_DIRECT)
6409                 control_dev = 1;
6410         else
6411                 control_dev = 0;
6412
6413         switch (ctsio->cdb[0]) {
6414         case MODE_SELECT_6: {
6415                 struct scsi_mode_select_6 *cdb;
6416
6417                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6418
6419                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6420                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6421
6422                 param_len = cdb->length;
6423                 header_size = sizeof(struct scsi_mode_header_6);
6424                 break;
6425         }
6426         case MODE_SELECT_10: {
6427                 struct scsi_mode_select_10 *cdb;
6428
6429                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6430
6431                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6432                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6433
6434                 param_len = scsi_2btoul(cdb->length);
6435                 header_size = sizeof(struct scsi_mode_header_10);
6436                 break;
6437         }
6438         default:
6439                 ctl_set_invalid_opcode(ctsio);
6440                 ctl_done((union ctl_io *)ctsio);
6441                 return (CTL_RETVAL_COMPLETE);
6442                 break; /* NOTREACHED */
6443         }
6444
6445         /*
6446          * From SPC-3:
6447          * "A parameter list length of zero indicates that the Data-Out Buffer
6448          * shall be empty. This condition shall not be considered as an error."
6449          */
6450         if (param_len == 0) {
6451                 ctl_set_success(ctsio);
6452                 ctl_done((union ctl_io *)ctsio);
6453                 return (CTL_RETVAL_COMPLETE);
6454         }
6455
6456         /*
6457          * Since we'll hit this the first time through, prior to
6458          * allocation, we don't need to free a data buffer here.
6459          */
6460         if (param_len < header_size) {
6461                 ctl_set_param_len_error(ctsio);
6462                 ctl_done((union ctl_io *)ctsio);
6463                 return (CTL_RETVAL_COMPLETE);
6464         }
6465
6466         /*
6467          * Allocate the data buffer and grab the user's data.  In theory,
6468          * we shouldn't have to sanity check the parameter list length here
6469          * because the maximum size is 64K.  We should be able to malloc
6470          * that much without too many problems.
6471          */
6472         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6473                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6474                 ctsio->kern_data_len = param_len;
6475                 ctsio->kern_total_len = param_len;
6476                 ctsio->kern_data_resid = 0;
6477                 ctsio->kern_rel_offset = 0;
6478                 ctsio->kern_sg_entries = 0;
6479                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6480                 ctsio->be_move_done = ctl_config_move_done;
6481                 ctl_datamove((union ctl_io *)ctsio);
6482
6483                 return (CTL_RETVAL_COMPLETE);
6484         }
6485
6486         switch (ctsio->cdb[0]) {
6487         case MODE_SELECT_6: {
6488                 struct scsi_mode_header_6 *mh6;
6489
6490                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6491                 bd_len = mh6->blk_desc_len;
6492                 break;
6493         }
6494         case MODE_SELECT_10: {
6495                 struct scsi_mode_header_10 *mh10;
6496
6497                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6498                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6499                 break;
6500         }
6501         default:
6502                 panic("Invalid CDB type %#x", ctsio->cdb[0]);
6503                 break;
6504         }
6505
6506         if (param_len < (header_size + bd_len)) {
6507                 free(ctsio->kern_data_ptr, M_CTL);
6508                 ctl_set_param_len_error(ctsio);
6509                 ctl_done((union ctl_io *)ctsio);
6510                 return (CTL_RETVAL_COMPLETE);
6511         }
6512
6513         /*
6514          * Set the IO_CONT flag, so that if this I/O gets passed to
6515          * ctl_config_write_done(), it'll get passed back to
6516          * ctl_do_mode_select() for further processing, or completion if
6517          * we're all done.
6518          */
6519         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6520         ctsio->io_cont = ctl_do_mode_select;
6521
6522         modepage_info = (union ctl_modepage_info *)
6523                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6524
6525         memset(modepage_info, 0, sizeof(*modepage_info));
6526
6527         len_left = param_len - header_size - bd_len;
6528         len_used = header_size + bd_len;
6529
6530         modepage_info->header.len_left = len_left;
6531         modepage_info->header.len_used = len_used;
6532
6533         return (ctl_do_mode_select((union ctl_io *)ctsio));
6534 }
6535
6536 int
6537 ctl_mode_sense(struct ctl_scsiio *ctsio)
6538 {
6539         struct ctl_lun *lun;
6540         int pc, page_code, dbd, llba, subpage;
6541         int alloc_len, page_len, header_len, total_len;
6542         struct scsi_mode_block_descr *block_desc;
6543         struct ctl_page_index *page_index;
6544         int control_dev;
6545
6546         dbd = 0;
6547         llba = 0;
6548         block_desc = NULL;
6549         page_index = NULL;
6550
6551         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6552
6553         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6554
6555         if (lun->be_lun->lun_type != T_DIRECT)
6556                 control_dev = 1;
6557         else
6558                 control_dev = 0;
6559
6560         switch (ctsio->cdb[0]) {
6561         case MODE_SENSE_6: {
6562                 struct scsi_mode_sense_6 *cdb;
6563
6564                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6565
6566                 header_len = sizeof(struct scsi_mode_hdr_6);
6567                 if (cdb->byte2 & SMS_DBD)
6568                         dbd = 1;
6569                 else
6570                         header_len += sizeof(struct scsi_mode_block_descr);
6571
6572                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6573                 page_code = cdb->page & SMS_PAGE_CODE;
6574                 subpage = cdb->subpage;
6575                 alloc_len = cdb->length;
6576                 break;
6577         }
6578         case MODE_SENSE_10: {
6579                 struct scsi_mode_sense_10 *cdb;
6580
6581                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6582
6583                 header_len = sizeof(struct scsi_mode_hdr_10);
6584
6585                 if (cdb->byte2 & SMS_DBD)
6586                         dbd = 1;
6587                 else
6588                         header_len += sizeof(struct scsi_mode_block_descr);
6589                 if (cdb->byte2 & SMS10_LLBAA)
6590                         llba = 1;
6591                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6592                 page_code = cdb->page & SMS_PAGE_CODE;
6593                 subpage = cdb->subpage;
6594                 alloc_len = scsi_2btoul(cdb->length);
6595                 break;
6596         }
6597         default:
6598                 ctl_set_invalid_opcode(ctsio);
6599                 ctl_done((union ctl_io *)ctsio);
6600                 return (CTL_RETVAL_COMPLETE);
6601                 break; /* NOTREACHED */
6602         }
6603
6604         /*
6605          * We have to make a first pass through to calculate the size of
6606          * the pages that match the user's query.  Then we allocate enough
6607          * memory to hold it, and actually copy the data into the buffer.
6608          */
6609         switch (page_code) {
6610         case SMS_ALL_PAGES_PAGE: {
6611                 int i;
6612
6613                 page_len = 0;
6614
6615                 /*
6616                  * At the moment, values other than 0 and 0xff here are
6617                  * reserved according to SPC-3.
6618                  */
6619                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6620                  && (subpage != SMS_SUBPAGE_ALL)) {
6621                         ctl_set_invalid_field(ctsio,
6622                                               /*sks_valid*/ 1,
6623                                               /*command*/ 1,
6624                                               /*field*/ 3,
6625                                               /*bit_valid*/ 0,
6626                                               /*bit*/ 0);
6627                         ctl_done((union ctl_io *)ctsio);
6628                         return (CTL_RETVAL_COMPLETE);
6629                 }
6630
6631                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6632                         if ((control_dev != 0)
6633                          && (lun->mode_pages.index[i].page_flags &
6634                              CTL_PAGE_FLAG_DISK_ONLY))
6635                                 continue;
6636
6637                         /*
6638                          * We don't use this subpage if the user didn't
6639                          * request all subpages.
6640                          */
6641                         if ((lun->mode_pages.index[i].subpage != 0)
6642                          && (subpage == SMS_SUBPAGE_PAGE_0))
6643                                 continue;
6644
6645 #if 0
6646                         printf("found page %#x len %d\n",
6647                                lun->mode_pages.index[i].page_code &
6648                                SMPH_PC_MASK,
6649                                lun->mode_pages.index[i].page_len);
6650 #endif
6651                         page_len += lun->mode_pages.index[i].page_len;
6652                 }
6653                 break;
6654         }
6655         default: {
6656                 int i;
6657
6658                 page_len = 0;
6659
6660                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6661                         /* Look for the right page code */
6662                         if ((lun->mode_pages.index[i].page_code &
6663                              SMPH_PC_MASK) != page_code)
6664                                 continue;
6665
6666                         /* Look for the right subpage or the subpage wildcard*/
6667                         if ((lun->mode_pages.index[i].subpage != subpage)
6668                          && (subpage != SMS_SUBPAGE_ALL))
6669                                 continue;
6670
6671                         /* Make sure the page is supported for this dev type */
6672                         if ((control_dev != 0)
6673                          && (lun->mode_pages.index[i].page_flags &
6674                              CTL_PAGE_FLAG_DISK_ONLY))
6675                                 continue;
6676
6677 #if 0
6678                         printf("found page %#x len %d\n",
6679                                lun->mode_pages.index[i].page_code &
6680                                SMPH_PC_MASK,
6681                                lun->mode_pages.index[i].page_len);
6682 #endif
6683
6684                         page_len += lun->mode_pages.index[i].page_len;
6685                 }
6686
6687                 if (page_len == 0) {
6688                         ctl_set_invalid_field(ctsio,
6689                                               /*sks_valid*/ 1,
6690                                               /*command*/ 1,
6691                                               /*field*/ 2,
6692                                               /*bit_valid*/ 1,
6693                                               /*bit*/ 5);
6694                         ctl_done((union ctl_io *)ctsio);
6695                         return (CTL_RETVAL_COMPLETE);
6696                 }
6697                 break;
6698         }
6699         }
6700
6701         total_len = header_len + page_len;
6702 #if 0
6703         printf("header_len = %d, page_len = %d, total_len = %d\n",
6704                header_len, page_len, total_len);
6705 #endif
6706
6707         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6708         ctsio->kern_sg_entries = 0;
6709         ctsio->kern_data_resid = 0;
6710         ctsio->kern_rel_offset = 0;
6711         if (total_len < alloc_len) {
6712                 ctsio->residual = alloc_len - total_len;
6713                 ctsio->kern_data_len = total_len;
6714                 ctsio->kern_total_len = total_len;
6715         } else {
6716                 ctsio->residual = 0;
6717                 ctsio->kern_data_len = alloc_len;
6718                 ctsio->kern_total_len = alloc_len;
6719         }
6720
6721         switch (ctsio->cdb[0]) {
6722         case MODE_SENSE_6: {
6723                 struct scsi_mode_hdr_6 *header;
6724
6725                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6726
6727                 header->datalen = ctl_min(total_len - 1, 254);
6728                 if (control_dev == 0) {
6729                         header->dev_specific = 0x10; /* DPOFUA */
6730                         if ((lun->flags & CTL_LUN_READONLY) ||
6731                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6732                             .eca_and_aen & SCP_SWP) != 0)
6733                                     header->dev_specific |= 0x80; /* WP */
6734                 }
6735                 if (dbd)
6736                         header->block_descr_len = 0;
6737                 else
6738                         header->block_descr_len =
6739                                 sizeof(struct scsi_mode_block_descr);
6740                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6741                 break;
6742         }
6743         case MODE_SENSE_10: {
6744                 struct scsi_mode_hdr_10 *header;
6745                 int datalen;
6746
6747                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6748
6749                 datalen = ctl_min(total_len - 2, 65533);
6750                 scsi_ulto2b(datalen, header->datalen);
6751                 if (control_dev == 0) {
6752                         header->dev_specific = 0x10; /* DPOFUA */
6753                         if ((lun->flags & CTL_LUN_READONLY) ||
6754                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6755                             .eca_and_aen & SCP_SWP) != 0)
6756                                     header->dev_specific |= 0x80; /* WP */
6757                 }
6758                 if (dbd)
6759                         scsi_ulto2b(0, header->block_descr_len);
6760                 else
6761                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6762                                     header->block_descr_len);
6763                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6764                 break;
6765         }
6766         default:
6767                 panic("invalid CDB type %#x", ctsio->cdb[0]);
6768                 break; /* NOTREACHED */
6769         }
6770
6771         /*
6772          * If we've got a disk, use its blocksize in the block
6773          * descriptor.  Otherwise, just set it to 0.
6774          */
6775         if (dbd == 0) {
6776                 if (control_dev == 0)
6777                         scsi_ulto3b(lun->be_lun->blocksize,
6778                                     block_desc->block_len);
6779                 else
6780                         scsi_ulto3b(0, block_desc->block_len);
6781         }
6782
6783         switch (page_code) {
6784         case SMS_ALL_PAGES_PAGE: {
6785                 int i, data_used;
6786
6787                 data_used = header_len;
6788                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6789                         struct ctl_page_index *page_index;
6790
6791                         page_index = &lun->mode_pages.index[i];
6792
6793                         if ((control_dev != 0)
6794                          && (page_index->page_flags &
6795                             CTL_PAGE_FLAG_DISK_ONLY))
6796                                 continue;
6797
6798                         /*
6799                          * We don't use this subpage if the user didn't
6800                          * request all subpages.  We already checked (above)
6801                          * to make sure the user only specified a subpage
6802                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6803                          */
6804                         if ((page_index->subpage != 0)
6805                          && (subpage == SMS_SUBPAGE_PAGE_0))
6806                                 continue;
6807
6808                         /*
6809                          * Call the handler, if it exists, to update the
6810                          * page to the latest values.
6811                          */
6812                         if (page_index->sense_handler != NULL)
6813                                 page_index->sense_handler(ctsio, page_index,pc);
6814
6815                         memcpy(ctsio->kern_data_ptr + data_used,
6816                                page_index->page_data +
6817                                (page_index->page_len * pc),
6818                                page_index->page_len);
6819                         data_used += page_index->page_len;
6820                 }
6821                 break;
6822         }
6823         default: {
6824                 int i, data_used;
6825
6826                 data_used = header_len;
6827
6828                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6829                         struct ctl_page_index *page_index;
6830
6831                         page_index = &lun->mode_pages.index[i];
6832
6833                         /* Look for the right page code */
6834                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6835                                 continue;
6836
6837                         /* Look for the right subpage or the subpage wildcard*/
6838                         if ((page_index->subpage != subpage)
6839                          && (subpage != SMS_SUBPAGE_ALL))
6840                                 continue;
6841
6842                         /* Make sure the page is supported for this dev type */
6843                         if ((control_dev != 0)
6844                          && (page_index->page_flags &
6845                              CTL_PAGE_FLAG_DISK_ONLY))
6846                                 continue;
6847
6848                         /*
6849                          * Call the handler, if it exists, to update the
6850                          * page to the latest values.
6851                          */
6852                         if (page_index->sense_handler != NULL)
6853                                 page_index->sense_handler(ctsio, page_index,pc);
6854
6855                         memcpy(ctsio->kern_data_ptr + data_used,
6856                                page_index->page_data +
6857                                (page_index->page_len * pc),
6858                                page_index->page_len);
6859                         data_used += page_index->page_len;
6860                 }
6861                 break;
6862         }
6863         }
6864
6865         ctl_set_success(ctsio);
6866         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6867         ctsio->be_move_done = ctl_config_move_done;
6868         ctl_datamove((union ctl_io *)ctsio);
6869         return (CTL_RETVAL_COMPLETE);
6870 }
6871
6872 int
6873 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6874                                struct ctl_page_index *page_index,
6875                                int pc)
6876 {
6877         struct ctl_lun *lun;
6878         struct scsi_log_param_header *phdr;
6879         uint8_t *data;
6880         uint64_t val;
6881
6882         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6883         data = page_index->page_data;
6884
6885         if (lun->backend->lun_attr != NULL &&
6886             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6887              != UINT64_MAX) {
6888                 phdr = (struct scsi_log_param_header *)data;
6889                 scsi_ulto2b(0x0001, phdr->param_code);
6890                 phdr->param_control = SLP_LBIN | SLP_LP;
6891                 phdr->param_len = 8;
6892                 data = (uint8_t *)(phdr + 1);
6893                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6894                 data[4] = 0x02; /* per-pool */
6895                 data += phdr->param_len;
6896         }
6897
6898         if (lun->backend->lun_attr != NULL &&
6899             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6900              != UINT64_MAX) {
6901                 phdr = (struct scsi_log_param_header *)data;
6902                 scsi_ulto2b(0x0002, phdr->param_code);
6903                 phdr->param_control = SLP_LBIN | SLP_LP;
6904                 phdr->param_len = 8;
6905                 data = (uint8_t *)(phdr + 1);
6906                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6907                 data[4] = 0x01; /* per-LUN */
6908                 data += phdr->param_len;
6909         }
6910
6911         if (lun->backend->lun_attr != NULL &&
6912             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6913              != UINT64_MAX) {
6914                 phdr = (struct scsi_log_param_header *)data;
6915                 scsi_ulto2b(0x00f1, phdr->param_code);
6916                 phdr->param_control = SLP_LBIN | SLP_LP;
6917                 phdr->param_len = 8;
6918                 data = (uint8_t *)(phdr + 1);
6919                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6920                 data[4] = 0x02; /* per-pool */
6921                 data += phdr->param_len;
6922         }
6923
6924         if (lun->backend->lun_attr != NULL &&
6925             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6926              != UINT64_MAX) {
6927                 phdr = (struct scsi_log_param_header *)data;
6928                 scsi_ulto2b(0x00f2, phdr->param_code);
6929                 phdr->param_control = SLP_LBIN | SLP_LP;
6930                 phdr->param_len = 8;
6931                 data = (uint8_t *)(phdr + 1);
6932                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6933                 data[4] = 0x02; /* per-pool */
6934                 data += phdr->param_len;
6935         }
6936
6937         page_index->page_len = data - page_index->page_data;
6938         return (0);
6939 }
6940
6941 int
6942 ctl_log_sense(struct ctl_scsiio *ctsio)
6943 {
6944         struct ctl_lun *lun;
6945         int i, pc, page_code, subpage;
6946         int alloc_len, total_len;
6947         struct ctl_page_index *page_index;
6948         struct scsi_log_sense *cdb;
6949         struct scsi_log_header *header;
6950
6951         CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6952
6953         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6954         cdb = (struct scsi_log_sense *)ctsio->cdb;
6955         pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6956         page_code = cdb->page & SLS_PAGE_CODE;
6957         subpage = cdb->subpage;
6958         alloc_len = scsi_2btoul(cdb->length);
6959
6960         page_index = NULL;
6961         for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6962                 page_index = &lun->log_pages.index[i];
6963
6964                 /* Look for the right page code */
6965                 if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6966                         continue;
6967
6968                 /* Look for the right subpage or the subpage wildcard*/
6969                 if (page_index->subpage != subpage)
6970                         continue;
6971
6972                 break;
6973         }
6974         if (i >= CTL_NUM_LOG_PAGES) {
6975                 ctl_set_invalid_field(ctsio,
6976                                       /*sks_valid*/ 1,
6977                                       /*command*/ 1,
6978                                       /*field*/ 2,
6979                                       /*bit_valid*/ 0,
6980                                       /*bit*/ 0);
6981                 ctl_done((union ctl_io *)ctsio);
6982                 return (CTL_RETVAL_COMPLETE);
6983         }
6984
6985         total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6986
6987         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6988         ctsio->kern_sg_entries = 0;
6989         ctsio->kern_data_resid = 0;
6990         ctsio->kern_rel_offset = 0;
6991         if (total_len < alloc_len) {
6992                 ctsio->residual = alloc_len - total_len;
6993                 ctsio->kern_data_len = total_len;
6994                 ctsio->kern_total_len = total_len;
6995         } else {
6996                 ctsio->residual = 0;
6997                 ctsio->kern_data_len = alloc_len;
6998                 ctsio->kern_total_len = alloc_len;
6999         }
7000
7001         header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7002         header->page = page_index->page_code;
7003         if (page_index->subpage) {
7004                 header->page |= SL_SPF;
7005                 header->subpage = page_index->subpage;
7006         }
7007         scsi_ulto2b(page_index->page_len, header->datalen);
7008
7009         /*
7010          * Call the handler, if it exists, to update the
7011          * page to the latest values.
7012          */
7013         if (page_index->sense_handler != NULL)
7014                 page_index->sense_handler(ctsio, page_index, pc);
7015
7016         memcpy(header + 1, page_index->page_data, page_index->page_len);
7017
7018         ctl_set_success(ctsio);
7019         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7020         ctsio->be_move_done = ctl_config_move_done;
7021         ctl_datamove((union ctl_io *)ctsio);
7022         return (CTL_RETVAL_COMPLETE);
7023 }
7024
7025 int
7026 ctl_read_capacity(struct ctl_scsiio *ctsio)
7027 {
7028         struct scsi_read_capacity *cdb;
7029         struct scsi_read_capacity_data *data;
7030         struct ctl_lun *lun;
7031         uint32_t lba;
7032
7033         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7034
7035         cdb = (struct scsi_read_capacity *)ctsio->cdb;
7036
7037         lba = scsi_4btoul(cdb->addr);
7038         if (((cdb->pmi & SRC_PMI) == 0)
7039          && (lba != 0)) {
7040                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7041                                       /*sks_valid*/ 1,
7042                                       /*command*/ 1,
7043                                       /*field*/ 2,
7044                                       /*bit_valid*/ 0,
7045                                       /*bit*/ 0);
7046                 ctl_done((union ctl_io *)ctsio);
7047                 return (CTL_RETVAL_COMPLETE);
7048         }
7049
7050         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7051
7052         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7053         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7054         ctsio->residual = 0;
7055         ctsio->kern_data_len = sizeof(*data);
7056         ctsio->kern_total_len = sizeof(*data);
7057         ctsio->kern_data_resid = 0;
7058         ctsio->kern_rel_offset = 0;
7059         ctsio->kern_sg_entries = 0;
7060
7061         /*
7062          * If the maximum LBA is greater than 0xfffffffe, the user must
7063          * issue a SERVICE ACTION IN (16) command, with the read capacity
7064          * serivce action set.
7065          */
7066         if (lun->be_lun->maxlba > 0xfffffffe)
7067                 scsi_ulto4b(0xffffffff, data->addr);
7068         else
7069                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7070
7071         /*
7072          * XXX KDM this may not be 512 bytes...
7073          */
7074         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7075
7076         ctl_set_success(ctsio);
7077         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7078         ctsio->be_move_done = ctl_config_move_done;
7079         ctl_datamove((union ctl_io *)ctsio);
7080         return (CTL_RETVAL_COMPLETE);
7081 }
7082
7083 int
7084 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7085 {
7086         struct scsi_read_capacity_16 *cdb;
7087         struct scsi_read_capacity_data_long *data;
7088         struct ctl_lun *lun;
7089         uint64_t lba;
7090         uint32_t alloc_len;
7091
7092         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7093
7094         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7095
7096         alloc_len = scsi_4btoul(cdb->alloc_len);
7097         lba = scsi_8btou64(cdb->addr);
7098
7099         if ((cdb->reladr & SRC16_PMI)
7100          && (lba != 0)) {
7101                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7102                                       /*sks_valid*/ 1,
7103                                       /*command*/ 1,
7104                                       /*field*/ 2,
7105                                       /*bit_valid*/ 0,
7106                                       /*bit*/ 0);
7107                 ctl_done((union ctl_io *)ctsio);
7108                 return (CTL_RETVAL_COMPLETE);
7109         }
7110
7111         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7112
7113         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7114         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7115
7116         if (sizeof(*data) < alloc_len) {
7117                 ctsio->residual = alloc_len - sizeof(*data);
7118                 ctsio->kern_data_len = sizeof(*data);
7119                 ctsio->kern_total_len = sizeof(*data);
7120         } else {
7121                 ctsio->residual = 0;
7122                 ctsio->kern_data_len = alloc_len;
7123                 ctsio->kern_total_len = alloc_len;
7124         }
7125         ctsio->kern_data_resid = 0;
7126         ctsio->kern_rel_offset = 0;
7127         ctsio->kern_sg_entries = 0;
7128
7129         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7130         /* XXX KDM this may not be 512 bytes... */
7131         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7132         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7133         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7134         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7135                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7136
7137         ctl_set_success(ctsio);
7138         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7139         ctsio->be_move_done = ctl_config_move_done;
7140         ctl_datamove((union ctl_io *)ctsio);
7141         return (CTL_RETVAL_COMPLETE);
7142 }
7143
7144 int
7145 ctl_read_defect(struct ctl_scsiio *ctsio)
7146 {
7147         struct scsi_read_defect_data_10 *ccb10;
7148         struct scsi_read_defect_data_12 *ccb12;
7149         struct scsi_read_defect_data_hdr_10 *data10;
7150         struct scsi_read_defect_data_hdr_12 *data12;
7151         uint32_t alloc_len, data_len;
7152         uint8_t format;
7153
7154         CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7155
7156         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7157                 ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7158                 format = ccb10->format;
7159                 alloc_len = scsi_2btoul(ccb10->alloc_length);
7160                 data_len = sizeof(*data10);
7161         } else {
7162                 ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7163                 format = ccb12->format;
7164                 alloc_len = scsi_4btoul(ccb12->alloc_length);
7165                 data_len = sizeof(*data12);
7166         }
7167         if (alloc_len == 0) {
7168                 ctl_set_success(ctsio);
7169                 ctl_done((union ctl_io *)ctsio);
7170                 return (CTL_RETVAL_COMPLETE);
7171         }
7172
7173         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7174         if (data_len < alloc_len) {
7175                 ctsio->residual = alloc_len - data_len;
7176                 ctsio->kern_data_len = data_len;
7177                 ctsio->kern_total_len = data_len;
7178         } else {
7179                 ctsio->residual = 0;
7180                 ctsio->kern_data_len = alloc_len;
7181                 ctsio->kern_total_len = alloc_len;
7182         }
7183         ctsio->kern_data_resid = 0;
7184         ctsio->kern_rel_offset = 0;
7185         ctsio->kern_sg_entries = 0;
7186
7187         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7188                 data10 = (struct scsi_read_defect_data_hdr_10 *)
7189                     ctsio->kern_data_ptr;
7190                 data10->format = format;
7191                 scsi_ulto2b(0, data10->length);
7192         } else {
7193                 data12 = (struct scsi_read_defect_data_hdr_12 *)
7194                     ctsio->kern_data_ptr;
7195                 data12->format = format;
7196                 scsi_ulto2b(0, data12->generation);
7197                 scsi_ulto4b(0, data12->length);
7198         }
7199
7200         ctl_set_success(ctsio);
7201         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7202         ctsio->be_move_done = ctl_config_move_done;
7203         ctl_datamove((union ctl_io *)ctsio);
7204         return (CTL_RETVAL_COMPLETE);
7205 }
7206
7207 int
7208 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7209 {
7210         struct scsi_maintenance_in *cdb;
7211         int retval;
7212         int alloc_len, ext, total_len = 0, g, p, pc, pg, gs, os;
7213         int num_target_port_groups, num_target_ports;
7214         struct ctl_lun *lun;
7215         struct ctl_softc *softc;
7216         struct ctl_port *port;
7217         struct scsi_target_group_data *rtg_ptr;
7218         struct scsi_target_group_data_extended *rtg_ext_ptr;
7219         struct scsi_target_port_group_descriptor *tpg_desc;
7220
7221         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7222
7223         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7224         softc = control_softc;
7225         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7226
7227         retval = CTL_RETVAL_COMPLETE;
7228
7229         switch (cdb->byte2 & STG_PDF_MASK) {
7230         case STG_PDF_LENGTH:
7231                 ext = 0;
7232                 break;
7233         case STG_PDF_EXTENDED:
7234                 ext = 1;
7235                 break;
7236         default:
7237                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7238                                       /*sks_valid*/ 1,
7239                                       /*command*/ 1,
7240                                       /*field*/ 2,
7241                                       /*bit_valid*/ 1,
7242                                       /*bit*/ 5);
7243                 ctl_done((union ctl_io *)ctsio);
7244                 return(retval);
7245         }
7246
7247         if (softc->is_single)
7248                 num_target_port_groups = 1;
7249         else
7250                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7251         num_target_ports = 0;
7252         mtx_lock(&softc->ctl_lock);
7253         STAILQ_FOREACH(port, &softc->port_list, links) {
7254                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7255                         continue;
7256                 if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7257                         continue;
7258                 num_target_ports++;
7259         }
7260         mtx_unlock(&softc->ctl_lock);
7261
7262         if (ext)
7263                 total_len = sizeof(struct scsi_target_group_data_extended);
7264         else
7265                 total_len = sizeof(struct scsi_target_group_data);
7266         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7267                 num_target_port_groups +
7268             sizeof(struct scsi_target_port_descriptor) *
7269                 num_target_ports * num_target_port_groups;
7270
7271         alloc_len = scsi_4btoul(cdb->length);
7272
7273         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7274
7275         ctsio->kern_sg_entries = 0;
7276
7277         if (total_len < alloc_len) {
7278                 ctsio->residual = alloc_len - total_len;
7279                 ctsio->kern_data_len = total_len;
7280                 ctsio->kern_total_len = total_len;
7281         } else {
7282                 ctsio->residual = 0;
7283                 ctsio->kern_data_len = alloc_len;
7284                 ctsio->kern_total_len = alloc_len;
7285         }
7286         ctsio->kern_data_resid = 0;
7287         ctsio->kern_rel_offset = 0;
7288
7289         if (ext) {
7290                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7291                     ctsio->kern_data_ptr;
7292                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7293                 rtg_ext_ptr->format_type = 0x10;
7294                 rtg_ext_ptr->implicit_transition_time = 0;
7295                 tpg_desc = &rtg_ext_ptr->groups[0];
7296         } else {
7297                 rtg_ptr = (struct scsi_target_group_data *)
7298                     ctsio->kern_data_ptr;
7299                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7300                 tpg_desc = &rtg_ptr->groups[0];
7301         }
7302
7303         mtx_lock(&softc->ctl_lock);
7304         pg = softc->port_offset / CTL_MAX_PORTS;
7305         if (softc->flags & CTL_FLAG_ACTIVE_SHELF) {
7306                 if (softc->ha_mode == CTL_HA_MODE_ACT_STBY) {
7307                         gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7308                         os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7309                 } else if (lun->flags & CTL_LUN_PRIMARY_SC) {
7310                         gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7311                         os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7312                 } else {
7313                         gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7314                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7315                 }
7316         } else {
7317                 gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7318                 os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7319         }
7320         for (g = 0; g < num_target_port_groups; g++) {
7321                 tpg_desc->pref_state = (g == pg) ? gs : os;
7322                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP;
7323                 scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7324                 tpg_desc->status = TPG_IMPLICIT;
7325                 pc = 0;
7326                 STAILQ_FOREACH(port, &softc->port_list, links) {
7327                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7328                                 continue;
7329                         if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7330                             CTL_MAX_LUNS)
7331                                 continue;
7332                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7333                         scsi_ulto2b(p, tpg_desc->descriptors[pc].
7334                             relative_target_port_identifier);
7335                         pc++;
7336                 }
7337                 tpg_desc->target_port_count = pc;
7338                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7339                     &tpg_desc->descriptors[pc];
7340         }
7341         mtx_unlock(&softc->ctl_lock);
7342
7343         ctl_set_success(ctsio);
7344         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7345         ctsio->be_move_done = ctl_config_move_done;
7346         ctl_datamove((union ctl_io *)ctsio);
7347         return(retval);
7348 }
7349
7350 int
7351 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7352 {
7353         struct ctl_lun *lun;
7354         struct scsi_report_supported_opcodes *cdb;
7355         const struct ctl_cmd_entry *entry, *sentry;
7356         struct scsi_report_supported_opcodes_all *all;
7357         struct scsi_report_supported_opcodes_descr *descr;
7358         struct scsi_report_supported_opcodes_one *one;
7359         int retval;
7360         int alloc_len, total_len;
7361         int opcode, service_action, i, j, num;
7362
7363         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7364
7365         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7366         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7367
7368         retval = CTL_RETVAL_COMPLETE;
7369
7370         opcode = cdb->requested_opcode;
7371         service_action = scsi_2btoul(cdb->requested_service_action);
7372         switch (cdb->options & RSO_OPTIONS_MASK) {
7373         case RSO_OPTIONS_ALL:
7374                 num = 0;
7375                 for (i = 0; i < 256; i++) {
7376                         entry = &ctl_cmd_table[i];
7377                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7378                                 for (j = 0; j < 32; j++) {
7379                                         sentry = &((const struct ctl_cmd_entry *)
7380                                             entry->execute)[j];
7381                                         if (ctl_cmd_applicable(
7382                                             lun->be_lun->lun_type, sentry))
7383                                                 num++;
7384                                 }
7385                         } else {
7386                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7387                                     entry))
7388                                         num++;
7389                         }
7390                 }
7391                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7392                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7393                 break;
7394         case RSO_OPTIONS_OC:
7395                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7396                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7397                                               /*sks_valid*/ 1,
7398                                               /*command*/ 1,
7399                                               /*field*/ 2,
7400                                               /*bit_valid*/ 1,
7401                                               /*bit*/ 2);
7402                         ctl_done((union ctl_io *)ctsio);
7403                         return (CTL_RETVAL_COMPLETE);
7404                 }
7405                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7406                 break;
7407         case RSO_OPTIONS_OC_SA:
7408                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7409                     service_action >= 32) {
7410                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7411                                               /*sks_valid*/ 1,
7412                                               /*command*/ 1,
7413                                               /*field*/ 2,
7414                                               /*bit_valid*/ 1,
7415                                               /*bit*/ 2);
7416                         ctl_done((union ctl_io *)ctsio);
7417                         return (CTL_RETVAL_COMPLETE);
7418                 }
7419                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7420                 break;
7421         default:
7422                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7423                                       /*sks_valid*/ 1,
7424                                       /*command*/ 1,
7425                                       /*field*/ 2,
7426                                       /*bit_valid*/ 1,
7427                                       /*bit*/ 2);
7428                 ctl_done((union ctl_io *)ctsio);
7429                 return (CTL_RETVAL_COMPLETE);
7430         }
7431
7432         alloc_len = scsi_4btoul(cdb->length);
7433
7434         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7435
7436         ctsio->kern_sg_entries = 0;
7437
7438         if (total_len < alloc_len) {
7439                 ctsio->residual = alloc_len - total_len;
7440                 ctsio->kern_data_len = total_len;
7441                 ctsio->kern_total_len = total_len;
7442         } else {
7443                 ctsio->residual = 0;
7444                 ctsio->kern_data_len = alloc_len;
7445                 ctsio->kern_total_len = alloc_len;
7446         }
7447         ctsio->kern_data_resid = 0;
7448         ctsio->kern_rel_offset = 0;
7449
7450         switch (cdb->options & RSO_OPTIONS_MASK) {
7451         case RSO_OPTIONS_ALL:
7452                 all = (struct scsi_report_supported_opcodes_all *)
7453                     ctsio->kern_data_ptr;
7454                 num = 0;
7455                 for (i = 0; i < 256; i++) {
7456                         entry = &ctl_cmd_table[i];
7457                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7458                                 for (j = 0; j < 32; j++) {
7459                                         sentry = &((const struct ctl_cmd_entry *)
7460                                             entry->execute)[j];
7461                                         if (!ctl_cmd_applicable(
7462                                             lun->be_lun->lun_type, sentry))
7463                                                 continue;
7464                                         descr = &all->descr[num++];
7465                                         descr->opcode = i;
7466                                         scsi_ulto2b(j, descr->service_action);
7467                                         descr->flags = RSO_SERVACTV;
7468                                         scsi_ulto2b(sentry->length,
7469                                             descr->cdb_length);
7470                                 }
7471                         } else {
7472                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7473                                     entry))
7474                                         continue;
7475                                 descr = &all->descr[num++];
7476                                 descr->opcode = i;
7477                                 scsi_ulto2b(0, descr->service_action);
7478                                 descr->flags = 0;
7479                                 scsi_ulto2b(entry->length, descr->cdb_length);
7480                         }
7481                 }
7482                 scsi_ulto4b(
7483                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7484                     all->length);
7485                 break;
7486         case RSO_OPTIONS_OC:
7487                 one = (struct scsi_report_supported_opcodes_one *)
7488                     ctsio->kern_data_ptr;
7489                 entry = &ctl_cmd_table[opcode];
7490                 goto fill_one;
7491         case RSO_OPTIONS_OC_SA:
7492                 one = (struct scsi_report_supported_opcodes_one *)
7493                     ctsio->kern_data_ptr;
7494                 entry = &ctl_cmd_table[opcode];
7495                 entry = &((const struct ctl_cmd_entry *)
7496                     entry->execute)[service_action];
7497 fill_one:
7498                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7499                         one->support = 3;
7500                         scsi_ulto2b(entry->length, one->cdb_length);
7501                         one->cdb_usage[0] = opcode;
7502                         memcpy(&one->cdb_usage[1], entry->usage,
7503                             entry->length - 1);
7504                 } else
7505                         one->support = 1;
7506                 break;
7507         }
7508
7509         ctl_set_success(ctsio);
7510         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7511         ctsio->be_move_done = ctl_config_move_done;
7512         ctl_datamove((union ctl_io *)ctsio);
7513         return(retval);
7514 }
7515
7516 int
7517 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7518 {
7519         struct scsi_report_supported_tmf *cdb;
7520         struct scsi_report_supported_tmf_data *data;
7521         int retval;
7522         int alloc_len, total_len;
7523
7524         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7525
7526         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7527
7528         retval = CTL_RETVAL_COMPLETE;
7529
7530         total_len = sizeof(struct scsi_report_supported_tmf_data);
7531         alloc_len = scsi_4btoul(cdb->length);
7532
7533         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7534
7535         ctsio->kern_sg_entries = 0;
7536
7537         if (total_len < alloc_len) {
7538                 ctsio->residual = alloc_len - total_len;
7539                 ctsio->kern_data_len = total_len;
7540                 ctsio->kern_total_len = total_len;
7541         } else {
7542                 ctsio->residual = 0;
7543                 ctsio->kern_data_len = alloc_len;
7544                 ctsio->kern_total_len = alloc_len;
7545         }
7546         ctsio->kern_data_resid = 0;
7547         ctsio->kern_rel_offset = 0;
7548
7549         data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7550         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7551         data->byte2 |= RST_ITNRS;
7552
7553         ctl_set_success(ctsio);
7554         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7555         ctsio->be_move_done = ctl_config_move_done;
7556         ctl_datamove((union ctl_io *)ctsio);
7557         return (retval);
7558 }
7559
7560 int
7561 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7562 {
7563         struct scsi_report_timestamp *cdb;
7564         struct scsi_report_timestamp_data *data;
7565         struct timeval tv;
7566         int64_t timestamp;
7567         int retval;
7568         int alloc_len, total_len;
7569
7570         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7571
7572         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7573
7574         retval = CTL_RETVAL_COMPLETE;
7575
7576         total_len = sizeof(struct scsi_report_timestamp_data);
7577         alloc_len = scsi_4btoul(cdb->length);
7578
7579         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7580
7581         ctsio->kern_sg_entries = 0;
7582
7583         if (total_len < alloc_len) {
7584                 ctsio->residual = alloc_len - total_len;
7585                 ctsio->kern_data_len = total_len;
7586                 ctsio->kern_total_len = total_len;
7587         } else {
7588                 ctsio->residual = 0;
7589                 ctsio->kern_data_len = alloc_len;
7590                 ctsio->kern_total_len = alloc_len;
7591         }
7592         ctsio->kern_data_resid = 0;
7593         ctsio->kern_rel_offset = 0;
7594
7595         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7596         scsi_ulto2b(sizeof(*data) - 2, data->length);
7597         data->origin = RTS_ORIG_OUTSIDE;
7598         getmicrotime(&tv);
7599         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7600         scsi_ulto4b(timestamp >> 16, data->timestamp);
7601         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7602
7603         ctl_set_success(ctsio);
7604         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7605         ctsio->be_move_done = ctl_config_move_done;
7606         ctl_datamove((union ctl_io *)ctsio);
7607         return (retval);
7608 }
7609
7610 int
7611 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7612 {
7613         struct scsi_per_res_in *cdb;
7614         int alloc_len, total_len = 0;
7615         /* struct scsi_per_res_in_rsrv in_data; */
7616         struct ctl_lun *lun;
7617         struct ctl_softc *softc;
7618
7619         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7620
7621         softc = control_softc;
7622
7623         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7624
7625         alloc_len = scsi_2btoul(cdb->length);
7626
7627         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7628
7629 retry:
7630         mtx_lock(&lun->lun_lock);
7631         switch (cdb->action) {
7632         case SPRI_RK: /* read keys */
7633                 total_len = sizeof(struct scsi_per_res_in_keys) +
7634                         lun->pr_key_count *
7635                         sizeof(struct scsi_per_res_key);
7636                 break;
7637         case SPRI_RR: /* read reservation */
7638                 if (lun->flags & CTL_LUN_PR_RESERVED)
7639                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7640                 else
7641                         total_len = sizeof(struct scsi_per_res_in_header);
7642                 break;
7643         case SPRI_RC: /* report capabilities */
7644                 total_len = sizeof(struct scsi_per_res_cap);
7645                 break;
7646         case SPRI_RS: /* read full status */
7647                 total_len = sizeof(struct scsi_per_res_in_header) +
7648                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7649                     lun->pr_key_count;
7650                 break;
7651         default:
7652                 panic("Invalid PR type %x", cdb->action);
7653         }
7654         mtx_unlock(&lun->lun_lock);
7655
7656         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7657
7658         if (total_len < alloc_len) {
7659                 ctsio->residual = alloc_len - total_len;
7660                 ctsio->kern_data_len = total_len;
7661                 ctsio->kern_total_len = total_len;
7662         } else {
7663                 ctsio->residual = 0;
7664                 ctsio->kern_data_len = alloc_len;
7665                 ctsio->kern_total_len = alloc_len;
7666         }
7667
7668         ctsio->kern_data_resid = 0;
7669         ctsio->kern_rel_offset = 0;
7670         ctsio->kern_sg_entries = 0;
7671
7672         mtx_lock(&lun->lun_lock);
7673         switch (cdb->action) {
7674         case SPRI_RK: { // read keys
7675         struct scsi_per_res_in_keys *res_keys;
7676                 int i, key_count;
7677
7678                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7679
7680                 /*
7681                  * We had to drop the lock to allocate our buffer, which
7682                  * leaves time for someone to come in with another
7683                  * persistent reservation.  (That is unlikely, though,
7684                  * since this should be the only persistent reservation
7685                  * command active right now.)
7686                  */
7687                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7688                     (lun->pr_key_count *
7689                      sizeof(struct scsi_per_res_key)))){
7690                         mtx_unlock(&lun->lun_lock);
7691                         free(ctsio->kern_data_ptr, M_CTL);
7692                         printf("%s: reservation length changed, retrying\n",
7693                                __func__);
7694                         goto retry;
7695                 }
7696
7697                 scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7698
7699                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7700                              lun->pr_key_count, res_keys->header.length);
7701
7702                 for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7703                         if (lun->pr_keys[i] == 0)
7704                                 continue;
7705
7706                         /*
7707                          * We used lun->pr_key_count to calculate the
7708                          * size to allocate.  If it turns out the number of
7709                          * initiators with the registered flag set is
7710                          * larger than that (i.e. they haven't been kept in
7711                          * sync), we've got a problem.
7712                          */
7713                         if (key_count >= lun->pr_key_count) {
7714 #ifdef NEEDTOPORT
7715                                 csevent_log(CSC_CTL | CSC_SHELF_SW |
7716                                             CTL_PR_ERROR,
7717                                             csevent_LogType_Fault,
7718                                             csevent_AlertLevel_Yellow,
7719                                             csevent_FRU_ShelfController,
7720                                             csevent_FRU_Firmware,
7721                                         csevent_FRU_Unknown,
7722                                             "registered keys %d >= key "
7723                                             "count %d", key_count,
7724                                             lun->pr_key_count);
7725 #endif
7726                                 key_count++;
7727                                 continue;
7728                         }
7729                         scsi_u64to8b(lun->pr_keys[i],
7730                             res_keys->keys[key_count].key);
7731                         key_count++;
7732                 }
7733                 break;
7734         }
7735         case SPRI_RR: { // read reservation
7736                 struct scsi_per_res_in_rsrv *res;
7737                 int tmp_len, header_only;
7738
7739                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7740
7741                 scsi_ulto4b(lun->PRGeneration, res->header.generation);
7742
7743                 if (lun->flags & CTL_LUN_PR_RESERVED)
7744                 {
7745                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7746                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7747                                     res->header.length);
7748                         header_only = 0;
7749                 } else {
7750                         tmp_len = sizeof(struct scsi_per_res_in_header);
7751                         scsi_ulto4b(0, res->header.length);
7752                         header_only = 1;
7753                 }
7754
7755                 /*
7756                  * We had to drop the lock to allocate our buffer, which
7757                  * leaves time for someone to come in with another
7758                  * persistent reservation.  (That is unlikely, though,
7759                  * since this should be the only persistent reservation
7760                  * command active right now.)
7761                  */
7762                 if (tmp_len != total_len) {
7763                         mtx_unlock(&lun->lun_lock);
7764                         free(ctsio->kern_data_ptr, M_CTL);
7765                         printf("%s: reservation status changed, retrying\n",
7766                                __func__);
7767                         goto retry;
7768                 }
7769
7770                 /*
7771                  * No reservation held, so we're done.
7772                  */
7773                 if (header_only != 0)
7774                         break;
7775
7776                 /*
7777                  * If the registration is an All Registrants type, the key
7778                  * is 0, since it doesn't really matter.
7779                  */
7780                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7781                         scsi_u64to8b(lun->pr_keys[lun->pr_res_idx],
7782                             res->data.reservation);
7783                 }
7784                 res->data.scopetype = lun->res_type;
7785                 break;
7786         }
7787         case SPRI_RC:     //report capabilities
7788         {
7789                 struct scsi_per_res_cap *res_cap;
7790                 uint16_t type_mask;
7791
7792                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7793                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7794                 res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7795                 type_mask = SPRI_TM_WR_EX_AR |
7796                             SPRI_TM_EX_AC_RO |
7797                             SPRI_TM_WR_EX_RO |
7798                             SPRI_TM_EX_AC |
7799                             SPRI_TM_WR_EX |
7800                             SPRI_TM_EX_AC_AR;
7801                 scsi_ulto2b(type_mask, res_cap->type_mask);
7802                 break;
7803         }
7804         case SPRI_RS: { // read full status
7805                 struct scsi_per_res_in_full *res_status;
7806                 struct scsi_per_res_in_full_desc *res_desc;
7807                 struct ctl_port *port;
7808                 int i, len;
7809
7810                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7811
7812                 /*
7813                  * We had to drop the lock to allocate our buffer, which
7814                  * leaves time for someone to come in with another
7815                  * persistent reservation.  (That is unlikely, though,
7816                  * since this should be the only persistent reservation
7817                  * command active right now.)
7818                  */
7819                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
7820                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7821                      lun->pr_key_count)){
7822                         mtx_unlock(&lun->lun_lock);
7823                         free(ctsio->kern_data_ptr, M_CTL);
7824                         printf("%s: reservation length changed, retrying\n",
7825                                __func__);
7826                         goto retry;
7827                 }
7828
7829                 scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7830
7831                 res_desc = &res_status->desc[0];
7832                 for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7833                         if (lun->pr_keys[i] == 0)
7834                                 continue;
7835
7836                         scsi_u64to8b(lun->pr_keys[i], res_desc->res_key.key);
7837                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7838                             (lun->pr_res_idx == i ||
7839                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7840                                 res_desc->flags = SPRI_FULL_R_HOLDER;
7841                                 res_desc->scopetype = lun->res_type;
7842                         }
7843                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7844                             res_desc->rel_trgt_port_id);
7845                         len = 0;
7846                         port = softc->ctl_ports[
7847                             ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
7848                         if (port != NULL)
7849                                 len = ctl_create_iid(port,
7850                                     i % CTL_MAX_INIT_PER_PORT,
7851                                     res_desc->transport_id);
7852                         scsi_ulto4b(len, res_desc->additional_length);
7853                         res_desc = (struct scsi_per_res_in_full_desc *)
7854                             &res_desc->transport_id[len];
7855                 }
7856                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7857                     res_status->header.length);
7858                 break;
7859         }
7860         default:
7861                 /*
7862                  * This is a bug, because we just checked for this above,
7863                  * and should have returned an error.
7864                  */
7865                 panic("Invalid PR type %x", cdb->action);
7866                 break; /* NOTREACHED */
7867         }
7868         mtx_unlock(&lun->lun_lock);
7869
7870         ctl_set_success(ctsio);
7871         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7872         ctsio->be_move_done = ctl_config_move_done;
7873         ctl_datamove((union ctl_io *)ctsio);
7874         return (CTL_RETVAL_COMPLETE);
7875 }
7876
7877 static void
7878 ctl_set_res_ua(struct ctl_lun *lun, uint32_t residx, ctl_ua_type ua)
7879 {
7880         int off = lun->ctl_softc->persis_offset;
7881
7882         if (residx >= off && residx < off + CTL_MAX_INITIATORS)
7883                 lun->pending_ua[residx - off] |= ua;
7884 }
7885
7886 /*
7887  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7888  * it should return.
7889  */
7890 static int
7891 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7892                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
7893                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7894                 struct scsi_per_res_out_parms* param)
7895 {
7896         union ctl_ha_msg persis_io;
7897         int retval, i;
7898         int isc_retval;
7899
7900         retval = 0;
7901
7902         mtx_lock(&lun->lun_lock);
7903         if (sa_res_key == 0) {
7904                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7905                         /* validate scope and type */
7906                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7907                              SPR_LU_SCOPE) {
7908                                 mtx_unlock(&lun->lun_lock);
7909                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7910                                                       /*sks_valid*/ 1,
7911                                                       /*command*/ 1,
7912                                                       /*field*/ 2,
7913                                                       /*bit_valid*/ 1,
7914                                                       /*bit*/ 4);
7915                                 ctl_done((union ctl_io *)ctsio);
7916                                 return (1);
7917                         }
7918
7919                         if (type>8 || type==2 || type==4 || type==0) {
7920                                 mtx_unlock(&lun->lun_lock);
7921                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7922                                                       /*sks_valid*/ 1,
7923                                                       /*command*/ 1,
7924                                                       /*field*/ 2,
7925                                                       /*bit_valid*/ 1,
7926                                                       /*bit*/ 0);
7927                                 ctl_done((union ctl_io *)ctsio);
7928                                 return (1);
7929                         }
7930
7931                         /*
7932                          * Unregister everybody else and build UA for
7933                          * them
7934                          */
7935                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7936                                 if (i == residx || lun->pr_keys[i] == 0)
7937                                         continue;
7938
7939                                 lun->pr_keys[i] = 0;
7940                                 ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
7941                         }
7942                         lun->pr_key_count = 1;
7943                         lun->res_type = type;
7944                         if (lun->res_type != SPR_TYPE_WR_EX_AR
7945                          && lun->res_type != SPR_TYPE_EX_AC_AR)
7946                                 lun->pr_res_idx = residx;
7947
7948                         /* send msg to other side */
7949                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7950                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7951                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7952                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
7953                         persis_io.pr.pr_info.res_type = type;
7954                         memcpy(persis_io.pr.pr_info.sa_res_key,
7955                                param->serv_act_res_key,
7956                                sizeof(param->serv_act_res_key));
7957                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7958                              &persis_io, sizeof(persis_io), 0)) >
7959                              CTL_HA_STATUS_SUCCESS) {
7960                                 printf("CTL:Persis Out error returned "
7961                                        "from ctl_ha_msg_send %d\n",
7962                                        isc_retval);
7963                         }
7964                 } else {
7965                         /* not all registrants */
7966                         mtx_unlock(&lun->lun_lock);
7967                         free(ctsio->kern_data_ptr, M_CTL);
7968                         ctl_set_invalid_field(ctsio,
7969                                               /*sks_valid*/ 1,
7970                                               /*command*/ 0,
7971                                               /*field*/ 8,
7972                                               /*bit_valid*/ 0,
7973                                               /*bit*/ 0);
7974                         ctl_done((union ctl_io *)ctsio);
7975                         return (1);
7976                 }
7977         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7978                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
7979                 int found = 0;
7980
7981                 if (res_key == sa_res_key) {
7982                         /* special case */
7983                         /*
7984                          * The spec implies this is not good but doesn't
7985                          * say what to do. There are two choices either
7986                          * generate a res conflict or check condition
7987                          * with illegal field in parameter data. Since
7988                          * that is what is done when the sa_res_key is
7989                          * zero I'll take that approach since this has
7990                          * to do with the sa_res_key.
7991                          */
7992                         mtx_unlock(&lun->lun_lock);
7993                         free(ctsio->kern_data_ptr, M_CTL);
7994                         ctl_set_invalid_field(ctsio,
7995                                               /*sks_valid*/ 1,
7996                                               /*command*/ 0,
7997                                               /*field*/ 8,
7998                                               /*bit_valid*/ 0,
7999                                               /*bit*/ 0);
8000                         ctl_done((union ctl_io *)ctsio);
8001                         return (1);
8002                 }
8003
8004                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8005                         if (lun->pr_keys[i] != sa_res_key)
8006                                 continue;
8007
8008                         found = 1;
8009                         lun->pr_keys[i] = 0;
8010                         lun->pr_key_count--;
8011                         ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8012                 }
8013                 if (!found) {
8014                         mtx_unlock(&lun->lun_lock);
8015                         free(ctsio->kern_data_ptr, M_CTL);
8016                         ctl_set_reservation_conflict(ctsio);
8017                         ctl_done((union ctl_io *)ctsio);
8018                         return (CTL_RETVAL_COMPLETE);
8019                 }
8020                 /* send msg to other side */
8021                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8022                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8023                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8024                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
8025                 persis_io.pr.pr_info.res_type = type;
8026                 memcpy(persis_io.pr.pr_info.sa_res_key,
8027                        param->serv_act_res_key,
8028                        sizeof(param->serv_act_res_key));
8029                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8030                      &persis_io, sizeof(persis_io), 0)) >
8031                      CTL_HA_STATUS_SUCCESS) {
8032                         printf("CTL:Persis Out error returned from "
8033                                "ctl_ha_msg_send %d\n", isc_retval);
8034                 }
8035         } else {
8036                 /* Reserved but not all registrants */
8037                 /* sa_res_key is res holder */
8038                 if (sa_res_key == lun->pr_keys[lun->pr_res_idx]) {
8039                         /* validate scope and type */
8040                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8041                              SPR_LU_SCOPE) {
8042                                 mtx_unlock(&lun->lun_lock);
8043                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8044                                                       /*sks_valid*/ 1,
8045                                                       /*command*/ 1,
8046                                                       /*field*/ 2,
8047                                                       /*bit_valid*/ 1,
8048                                                       /*bit*/ 4);
8049                                 ctl_done((union ctl_io *)ctsio);
8050                                 return (1);
8051                         }
8052
8053                         if (type>8 || type==2 || type==4 || type==0) {
8054                                 mtx_unlock(&lun->lun_lock);
8055                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8056                                                       /*sks_valid*/ 1,
8057                                                       /*command*/ 1,
8058                                                       /*field*/ 2,
8059                                                       /*bit_valid*/ 1,
8060                                                       /*bit*/ 0);
8061                                 ctl_done((union ctl_io *)ctsio);
8062                                 return (1);
8063                         }
8064
8065                         /*
8066                          * Do the following:
8067                          * if sa_res_key != res_key remove all
8068                          * registrants w/sa_res_key and generate UA
8069                          * for these registrants(Registrations
8070                          * Preempted) if it wasn't an exclusive
8071                          * reservation generate UA(Reservations
8072                          * Preempted) for all other registered nexuses
8073                          * if the type has changed. Establish the new
8074                          * reservation and holder. If res_key and
8075                          * sa_res_key are the same do the above
8076                          * except don't unregister the res holder.
8077                          */
8078
8079                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8080                                 if (i == residx || lun->pr_keys[i] == 0)
8081                                         continue;
8082
8083                                 if (sa_res_key == lun->pr_keys[i]) {
8084                                         lun->pr_keys[i] = 0;
8085                                         lun->pr_key_count--;
8086                                         ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8087                                 } else if (type != lun->res_type
8088                                         && (lun->res_type == SPR_TYPE_WR_EX_RO
8089                                          || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8090                                         ctl_set_res_ua(lun, i, CTL_UA_RES_RELEASE);
8091                                 }
8092                         }
8093                         lun->res_type = type;
8094                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8095                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8096                                 lun->pr_res_idx = residx;
8097                         else
8098                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8099
8100                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8101                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8102                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8103                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8104                         persis_io.pr.pr_info.res_type = type;
8105                         memcpy(persis_io.pr.pr_info.sa_res_key,
8106                                param->serv_act_res_key,
8107                                sizeof(param->serv_act_res_key));
8108                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8109                              &persis_io, sizeof(persis_io), 0)) >
8110                              CTL_HA_STATUS_SUCCESS) {
8111                                 printf("CTL:Persis Out error returned "
8112                                        "from ctl_ha_msg_send %d\n",
8113                                        isc_retval);
8114                         }
8115                 } else {
8116                         /*
8117                          * sa_res_key is not the res holder just
8118                          * remove registrants
8119                          */
8120                         int found=0;
8121
8122                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8123                                 if (sa_res_key != lun->pr_keys[i])
8124                                         continue;
8125
8126                                 found = 1;
8127                                 lun->pr_keys[i] = 0;
8128                                 lun->pr_key_count--;
8129                                 ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8130                         }
8131
8132                         if (!found) {
8133                                 mtx_unlock(&lun->lun_lock);
8134                                 free(ctsio->kern_data_ptr, M_CTL);
8135                                 ctl_set_reservation_conflict(ctsio);
8136                                 ctl_done((union ctl_io *)ctsio);
8137                                 return (1);
8138                         }
8139                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8140                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8141                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8142                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8143                         persis_io.pr.pr_info.res_type = type;
8144                         memcpy(persis_io.pr.pr_info.sa_res_key,
8145                                param->serv_act_res_key,
8146                                sizeof(param->serv_act_res_key));
8147                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8148                              &persis_io, sizeof(persis_io), 0)) >
8149                              CTL_HA_STATUS_SUCCESS) {
8150                                 printf("CTL:Persis Out error returned "
8151                                        "from ctl_ha_msg_send %d\n",
8152                                 isc_retval);
8153                         }
8154                 }
8155         }
8156
8157         lun->PRGeneration++;
8158         mtx_unlock(&lun->lun_lock);
8159
8160         return (retval);
8161 }
8162
8163 static void
8164 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8165 {
8166         uint64_t sa_res_key;
8167         int i;
8168
8169         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8170
8171         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8172          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8173          || sa_res_key != lun->pr_keys[lun->pr_res_idx]) {
8174                 if (sa_res_key == 0) {
8175                         /*
8176                          * Unregister everybody else and build UA for
8177                          * them
8178                          */
8179                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8180                                 if (i == msg->pr.pr_info.residx ||
8181                                     lun->pr_keys[i] == 0)
8182                                         continue;
8183
8184                                 lun->pr_keys[i] = 0;
8185                                 ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8186                         }
8187
8188                         lun->pr_key_count = 1;
8189                         lun->res_type = msg->pr.pr_info.res_type;
8190                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8191                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8192                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8193                 } else {
8194                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8195                                 if (sa_res_key == lun->pr_keys[i])
8196                                         continue;
8197
8198                                 lun->pr_keys[i] = 0;
8199                                 lun->pr_key_count--;
8200                                 ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8201                         }
8202                 }
8203         } else {
8204                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8205                         if (i == msg->pr.pr_info.residx ||
8206                             lun->pr_keys[i] == 0)
8207                                 continue;
8208
8209                         if (sa_res_key == lun->pr_keys[i]) {
8210                                 lun->pr_keys[i] = 0;
8211                                 lun->pr_key_count--;
8212                                 ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8213                         } else if (msg->pr.pr_info.res_type != lun->res_type
8214                                 && (lun->res_type == SPR_TYPE_WR_EX_RO
8215                                  || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8216                                 ctl_set_res_ua(lun, i, CTL_UA_RES_RELEASE);
8217                         }
8218                 }
8219                 lun->res_type = msg->pr.pr_info.res_type;
8220                 if (lun->res_type != SPR_TYPE_WR_EX_AR
8221                  && lun->res_type != SPR_TYPE_EX_AC_AR)
8222                         lun->pr_res_idx = msg->pr.pr_info.residx;
8223                 else
8224                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8225         }
8226         lun->PRGeneration++;
8227
8228 }
8229
8230
8231 int
8232 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8233 {
8234         int retval;
8235         int isc_retval;
8236         u_int32_t param_len;
8237         struct scsi_per_res_out *cdb;
8238         struct ctl_lun *lun;
8239         struct scsi_per_res_out_parms* param;
8240         struct ctl_softc *softc;
8241         uint32_t residx;
8242         uint64_t res_key, sa_res_key;
8243         uint8_t type;
8244         union ctl_ha_msg persis_io;
8245         int    i;
8246
8247         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8248
8249         retval = CTL_RETVAL_COMPLETE;
8250
8251         softc = control_softc;
8252
8253         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8254         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8255
8256         /*
8257          * We only support whole-LUN scope.  The scope & type are ignored for
8258          * register, register and ignore existing key and clear.
8259          * We sometimes ignore scope and type on preempts too!!
8260          * Verify reservation type here as well.
8261          */
8262         type = cdb->scope_type & SPR_TYPE_MASK;
8263         if ((cdb->action == SPRO_RESERVE)
8264          || (cdb->action == SPRO_RELEASE)) {
8265                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8266                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8267                                               /*sks_valid*/ 1,
8268                                               /*command*/ 1,
8269                                               /*field*/ 2,
8270                                               /*bit_valid*/ 1,
8271                                               /*bit*/ 4);
8272                         ctl_done((union ctl_io *)ctsio);
8273                         return (CTL_RETVAL_COMPLETE);
8274                 }
8275
8276                 if (type>8 || type==2 || type==4 || type==0) {
8277                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8278                                               /*sks_valid*/ 1,
8279                                               /*command*/ 1,
8280                                               /*field*/ 2,
8281                                               /*bit_valid*/ 1,
8282                                               /*bit*/ 0);
8283                         ctl_done((union ctl_io *)ctsio);
8284                         return (CTL_RETVAL_COMPLETE);
8285                 }
8286         }
8287
8288         param_len = scsi_4btoul(cdb->length);
8289
8290         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8291                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8292                 ctsio->kern_data_len = param_len;
8293                 ctsio->kern_total_len = param_len;
8294                 ctsio->kern_data_resid = 0;
8295                 ctsio->kern_rel_offset = 0;
8296                 ctsio->kern_sg_entries = 0;
8297                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8298                 ctsio->be_move_done = ctl_config_move_done;
8299                 ctl_datamove((union ctl_io *)ctsio);
8300
8301                 return (CTL_RETVAL_COMPLETE);
8302         }
8303
8304         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8305
8306         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8307         res_key = scsi_8btou64(param->res_key.key);
8308         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8309
8310         /*
8311          * Validate the reservation key here except for SPRO_REG_IGNO
8312          * This must be done for all other service actions
8313          */
8314         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8315                 mtx_lock(&lun->lun_lock);
8316                 if (lun->pr_keys[residx] != 0) {
8317                     if (res_key != lun->pr_keys[residx]) {
8318                                 /*
8319                                  * The current key passed in doesn't match
8320                                  * the one the initiator previously
8321                                  * registered.
8322                                  */
8323                                 mtx_unlock(&lun->lun_lock);
8324                                 free(ctsio->kern_data_ptr, M_CTL);
8325                                 ctl_set_reservation_conflict(ctsio);
8326                                 ctl_done((union ctl_io *)ctsio);
8327                                 return (CTL_RETVAL_COMPLETE);
8328                         }
8329                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8330                         /*
8331                          * We are not registered
8332                          */
8333                         mtx_unlock(&lun->lun_lock);
8334                         free(ctsio->kern_data_ptr, M_CTL);
8335                         ctl_set_reservation_conflict(ctsio);
8336                         ctl_done((union ctl_io *)ctsio);
8337                         return (CTL_RETVAL_COMPLETE);
8338                 } else if (res_key != 0) {
8339                         /*
8340                          * We are not registered and trying to register but
8341                          * the register key isn't zero.
8342                          */
8343                         mtx_unlock(&lun->lun_lock);
8344                         free(ctsio->kern_data_ptr, M_CTL);
8345                         ctl_set_reservation_conflict(ctsio);
8346                         ctl_done((union ctl_io *)ctsio);
8347                         return (CTL_RETVAL_COMPLETE);
8348                 }
8349                 mtx_unlock(&lun->lun_lock);
8350         }
8351
8352         switch (cdb->action & SPRO_ACTION_MASK) {
8353         case SPRO_REGISTER:
8354         case SPRO_REG_IGNO: {
8355
8356 #if 0
8357                 printf("Registration received\n");
8358 #endif
8359
8360                 /*
8361                  * We don't support any of these options, as we report in
8362                  * the read capabilities request (see
8363                  * ctl_persistent_reserve_in(), above).
8364                  */
8365                 if ((param->flags & SPR_SPEC_I_PT)
8366                  || (param->flags & SPR_ALL_TG_PT)
8367                  || (param->flags & SPR_APTPL)) {
8368                         int bit_ptr;
8369
8370                         if (param->flags & SPR_APTPL)
8371                                 bit_ptr = 0;
8372                         else if (param->flags & SPR_ALL_TG_PT)
8373                                 bit_ptr = 2;
8374                         else /* SPR_SPEC_I_PT */
8375                                 bit_ptr = 3;
8376
8377                         free(ctsio->kern_data_ptr, M_CTL);
8378                         ctl_set_invalid_field(ctsio,
8379                                               /*sks_valid*/ 1,
8380                                               /*command*/ 0,
8381                                               /*field*/ 20,
8382                                               /*bit_valid*/ 1,
8383                                               /*bit*/ bit_ptr);
8384                         ctl_done((union ctl_io *)ctsio);
8385                         return (CTL_RETVAL_COMPLETE);
8386                 }
8387
8388                 mtx_lock(&lun->lun_lock);
8389
8390                 /*
8391                  * The initiator wants to clear the
8392                  * key/unregister.
8393                  */
8394                 if (sa_res_key == 0) {
8395                         if ((res_key == 0
8396                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8397                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8398                           && lun->pr_keys[residx] == 0)) {
8399                                 mtx_unlock(&lun->lun_lock);
8400                                 goto done;
8401                         }
8402
8403                         lun->pr_keys[residx] = 0;
8404                         lun->pr_key_count--;
8405
8406                         if (residx == lun->pr_res_idx) {
8407                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8408                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8409
8410                                 if ((lun->res_type == SPR_TYPE_WR_EX_RO
8411                                   || lun->res_type == SPR_TYPE_EX_AC_RO)
8412                                  && lun->pr_key_count) {
8413                                         /*
8414                                          * If the reservation is a registrants
8415                                          * only type we need to generate a UA
8416                                          * for other registered inits.  The
8417                                          * sense code should be RESERVATIONS
8418                                          * RELEASED
8419                                          */
8420
8421                                         for (i = 0; i < CTL_MAX_INITIATORS;i++){
8422                                                 if (lun->pr_keys[i +
8423                                                     softc->persis_offset] == 0)
8424                                                         continue;
8425                                                 lun->pending_ua[i] |=
8426                                                         CTL_UA_RES_RELEASE;
8427                                         }
8428                                 }
8429                                 lun->res_type = 0;
8430                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8431                                 if (lun->pr_key_count==0) {
8432                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8433                                         lun->res_type = 0;
8434                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8435                                 }
8436                         }
8437                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8438                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8439                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8440                         persis_io.pr.pr_info.residx = residx;
8441                         if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8442                              &persis_io, sizeof(persis_io), 0 )) >
8443                              CTL_HA_STATUS_SUCCESS) {
8444                                 printf("CTL:Persis Out error returned from "
8445                                        "ctl_ha_msg_send %d\n", isc_retval);
8446                         }
8447                 } else /* sa_res_key != 0 */ {
8448
8449                         /*
8450                          * If we aren't registered currently then increment
8451                          * the key count and set the registered flag.
8452                          */
8453                         if (lun->pr_keys[residx] == 0)
8454                                 lun->pr_key_count++;
8455                         lun->pr_keys[residx] = sa_res_key;
8456
8457                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8458                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8459                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8460                         persis_io.pr.pr_info.residx = residx;
8461                         memcpy(persis_io.pr.pr_info.sa_res_key,
8462                                param->serv_act_res_key,
8463                                sizeof(param->serv_act_res_key));
8464                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8465                              &persis_io, sizeof(persis_io), 0)) >
8466                              CTL_HA_STATUS_SUCCESS) {
8467                                 printf("CTL:Persis Out error returned from "
8468                                        "ctl_ha_msg_send %d\n", isc_retval);
8469                         }
8470                 }
8471                 lun->PRGeneration++;
8472                 mtx_unlock(&lun->lun_lock);
8473
8474                 break;
8475         }
8476         case SPRO_RESERVE:
8477 #if 0
8478                 printf("Reserve executed type %d\n", type);
8479 #endif
8480                 mtx_lock(&lun->lun_lock);
8481                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8482                         /*
8483                          * if this isn't the reservation holder and it's
8484                          * not a "all registrants" type or if the type is
8485                          * different then we have a conflict
8486                          */
8487                         if ((lun->pr_res_idx != residx
8488                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8489                          || lun->res_type != type) {
8490                                 mtx_unlock(&lun->lun_lock);
8491                                 free(ctsio->kern_data_ptr, M_CTL);
8492                                 ctl_set_reservation_conflict(ctsio);
8493                                 ctl_done((union ctl_io *)ctsio);
8494                                 return (CTL_RETVAL_COMPLETE);
8495                         }
8496                         mtx_unlock(&lun->lun_lock);
8497                 } else /* create a reservation */ {
8498                         /*
8499                          * If it's not an "all registrants" type record
8500                          * reservation holder
8501                          */
8502                         if (type != SPR_TYPE_WR_EX_AR
8503                          && type != SPR_TYPE_EX_AC_AR)
8504                                 lun->pr_res_idx = residx; /* Res holder */
8505                         else
8506                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8507
8508                         lun->flags |= CTL_LUN_PR_RESERVED;
8509                         lun->res_type = type;
8510
8511                         mtx_unlock(&lun->lun_lock);
8512
8513                         /* send msg to other side */
8514                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8515                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8516                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8517                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8518                         persis_io.pr.pr_info.res_type = type;
8519                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8520                              &persis_io, sizeof(persis_io), 0)) >
8521                              CTL_HA_STATUS_SUCCESS) {
8522                                 printf("CTL:Persis Out error returned from "
8523                                        "ctl_ha_msg_send %d\n", isc_retval);
8524                         }
8525                 }
8526                 break;
8527
8528         case SPRO_RELEASE:
8529                 mtx_lock(&lun->lun_lock);
8530                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8531                         /* No reservation exists return good status */
8532                         mtx_unlock(&lun->lun_lock);
8533                         goto done;
8534                 }
8535                 /*
8536                  * Is this nexus a reservation holder?
8537                  */
8538                 if (lun->pr_res_idx != residx
8539                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8540                         /*
8541                          * not a res holder return good status but
8542                          * do nothing
8543                          */
8544                         mtx_unlock(&lun->lun_lock);
8545                         goto done;
8546                 }
8547
8548                 if (lun->res_type != type) {
8549                         mtx_unlock(&lun->lun_lock);
8550                         free(ctsio->kern_data_ptr, M_CTL);
8551                         ctl_set_illegal_pr_release(ctsio);
8552                         ctl_done((union ctl_io *)ctsio);
8553                         return (CTL_RETVAL_COMPLETE);
8554                 }
8555
8556                 /* okay to release */
8557                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8558                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8559                 lun->res_type = 0;
8560
8561                 /*
8562                  * if this isn't an exclusive access
8563                  * res generate UA for all other
8564                  * registrants.
8565                  */
8566                 if (type != SPR_TYPE_EX_AC
8567                  && type != SPR_TYPE_WR_EX) {
8568                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8569                                 if (i == residx ||
8570                                     lun->pr_keys[i + softc->persis_offset] == 0)
8571                                         continue;
8572                                 lun->pending_ua[i] |= CTL_UA_RES_RELEASE;
8573                         }
8574                 }
8575                 mtx_unlock(&lun->lun_lock);
8576                 /* Send msg to other side */
8577                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8578                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8579                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8580                 if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8581                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8582                         printf("CTL:Persis Out error returned from "
8583                                "ctl_ha_msg_send %d\n", isc_retval);
8584                 }
8585                 break;
8586
8587         case SPRO_CLEAR:
8588                 /* send msg to other side */
8589
8590                 mtx_lock(&lun->lun_lock);
8591                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8592                 lun->res_type = 0;
8593                 lun->pr_key_count = 0;
8594                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8595
8596                 lun->pr_keys[residx] = 0;
8597
8598                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8599                         if (lun->pr_keys[i] != 0) {
8600                                 lun->pr_keys[i] = 0;
8601                                 ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8602                         }
8603                 lun->PRGeneration++;
8604                 mtx_unlock(&lun->lun_lock);
8605                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8606                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8607                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8608                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8609                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8610                         printf("CTL:Persis Out error returned from "
8611                                "ctl_ha_msg_send %d\n", isc_retval);
8612                 }
8613                 break;
8614
8615         case SPRO_PREEMPT:
8616         case SPRO_PRE_ABO: {
8617                 int nretval;
8618
8619                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8620                                           residx, ctsio, cdb, param);
8621                 if (nretval != 0)
8622                         return (CTL_RETVAL_COMPLETE);
8623                 break;
8624         }
8625         default:
8626                 panic("Invalid PR type %x", cdb->action);
8627         }
8628
8629 done:
8630         free(ctsio->kern_data_ptr, M_CTL);
8631         ctl_set_success(ctsio);
8632         ctl_done((union ctl_io *)ctsio);
8633
8634         return (retval);
8635 }
8636
8637 /*
8638  * This routine is for handling a message from the other SC pertaining to
8639  * persistent reserve out. All the error checking will have been done
8640  * so only perorming the action need be done here to keep the two
8641  * in sync.
8642  */
8643 static void
8644 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8645 {
8646         struct ctl_lun *lun;
8647         struct ctl_softc *softc;
8648         int i;
8649         uint32_t targ_lun;
8650
8651         softc = control_softc;
8652
8653         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8654         lun = softc->ctl_luns[targ_lun];
8655         mtx_lock(&lun->lun_lock);
8656         switch(msg->pr.pr_info.action) {
8657         case CTL_PR_REG_KEY:
8658                 if (lun->pr_keys[msg->pr.pr_info.residx] == 0)
8659                         lun->pr_key_count++;
8660                 lun->pr_keys[msg->pr.pr_info.residx] =
8661                     scsi_8btou64(msg->pr.pr_info.sa_res_key);
8662                 lun->PRGeneration++;
8663                 break;
8664
8665         case CTL_PR_UNREG_KEY:
8666                 lun->pr_keys[msg->pr.pr_info.residx] = 0;
8667                 lun->pr_key_count--;
8668
8669                 /* XXX Need to see if the reservation has been released */
8670                 /* if so do we need to generate UA? */
8671                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8672                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8673                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8674
8675                         if ((lun->res_type == SPR_TYPE_WR_EX_RO
8676                           || lun->res_type == SPR_TYPE_EX_AC_RO)
8677                          && lun->pr_key_count) {
8678                                 /*
8679                                  * If the reservation is a registrants
8680                                  * only type we need to generate a UA
8681                                  * for other registered inits.  The
8682                                  * sense code should be RESERVATIONS
8683                                  * RELEASED
8684                                  */
8685
8686                                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8687                                         if (lun->pr_keys[i +
8688                                             softc->persis_offset] == 0)
8689                                                 continue;
8690
8691                                         lun->pending_ua[i] |=
8692                                                 CTL_UA_RES_RELEASE;
8693                                 }
8694                         }
8695                         lun->res_type = 0;
8696                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8697                         if (lun->pr_key_count==0) {
8698                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8699                                 lun->res_type = 0;
8700                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8701                         }
8702                 }
8703                 lun->PRGeneration++;
8704                 break;
8705
8706         case CTL_PR_RESERVE:
8707                 lun->flags |= CTL_LUN_PR_RESERVED;
8708                 lun->res_type = msg->pr.pr_info.res_type;
8709                 lun->pr_res_idx = msg->pr.pr_info.residx;
8710
8711                 break;
8712
8713         case CTL_PR_RELEASE:
8714                 /*
8715                  * if this isn't an exclusive access res generate UA for all
8716                  * other registrants.
8717                  */
8718                 if (lun->res_type != SPR_TYPE_EX_AC
8719                  && lun->res_type != SPR_TYPE_WR_EX) {
8720                         for (i = 0; i < CTL_MAX_INITIATORS; i++)
8721                                 if (lun->pr_keys[i + softc->persis_offset] != 0)
8722                                         lun->pending_ua[i] |=
8723                                                 CTL_UA_RES_RELEASE;
8724                 }
8725
8726                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8727                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8728                 lun->res_type = 0;
8729                 break;
8730
8731         case CTL_PR_PREEMPT:
8732                 ctl_pro_preempt_other(lun, msg);
8733                 break;
8734         case CTL_PR_CLEAR:
8735                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8736                 lun->res_type = 0;
8737                 lun->pr_key_count = 0;
8738                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8739
8740                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8741                         if (lun->pr_keys[i] == 0)
8742                                 continue;
8743                         lun->pr_keys[i] = 0;
8744                         ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8745                 }
8746                 lun->PRGeneration++;
8747                 break;
8748         }
8749
8750         mtx_unlock(&lun->lun_lock);
8751 }
8752
8753 int
8754 ctl_read_write(struct ctl_scsiio *ctsio)
8755 {
8756         struct ctl_lun *lun;
8757         struct ctl_lba_len_flags *lbalen;
8758         uint64_t lba;
8759         uint32_t num_blocks;
8760         int flags, retval;
8761         int isread;
8762
8763         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8764
8765         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8766
8767         flags = 0;
8768         retval = CTL_RETVAL_COMPLETE;
8769
8770         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8771               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8772         switch (ctsio->cdb[0]) {
8773         case READ_6:
8774         case WRITE_6: {
8775                 struct scsi_rw_6 *cdb;
8776
8777                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
8778
8779                 lba = scsi_3btoul(cdb->addr);
8780                 /* only 5 bits are valid in the most significant address byte */
8781                 lba &= 0x1fffff;
8782                 num_blocks = cdb->length;
8783                 /*
8784                  * This is correct according to SBC-2.
8785                  */
8786                 if (num_blocks == 0)
8787                         num_blocks = 256;
8788                 break;
8789         }
8790         case READ_10:
8791         case WRITE_10: {
8792                 struct scsi_rw_10 *cdb;
8793
8794                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
8795                 if (cdb->byte2 & SRW10_FUA)
8796                         flags |= CTL_LLF_FUA;
8797                 if (cdb->byte2 & SRW10_DPO)
8798                         flags |= CTL_LLF_DPO;
8799                 lba = scsi_4btoul(cdb->addr);
8800                 num_blocks = scsi_2btoul(cdb->length);
8801                 break;
8802         }
8803         case WRITE_VERIFY_10: {
8804                 struct scsi_write_verify_10 *cdb;
8805
8806                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8807                 flags |= CTL_LLF_FUA;
8808                 if (cdb->byte2 & SWV_DPO)
8809                         flags |= CTL_LLF_DPO;
8810                 lba = scsi_4btoul(cdb->addr);
8811                 num_blocks = scsi_2btoul(cdb->length);
8812                 break;
8813         }
8814         case READ_12:
8815         case WRITE_12: {
8816                 struct scsi_rw_12 *cdb;
8817
8818                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
8819                 if (cdb->byte2 & SRW12_FUA)
8820                         flags |= CTL_LLF_FUA;
8821                 if (cdb->byte2 & SRW12_DPO)
8822                         flags |= CTL_LLF_DPO;
8823                 lba = scsi_4btoul(cdb->addr);
8824                 num_blocks = scsi_4btoul(cdb->length);
8825                 break;
8826         }
8827         case WRITE_VERIFY_12: {
8828                 struct scsi_write_verify_12 *cdb;
8829
8830                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8831                 flags |= CTL_LLF_FUA;
8832                 if (cdb->byte2 & SWV_DPO)
8833                         flags |= CTL_LLF_DPO;
8834                 lba = scsi_4btoul(cdb->addr);
8835                 num_blocks = scsi_4btoul(cdb->length);
8836                 break;
8837         }
8838         case READ_16:
8839         case WRITE_16: {
8840                 struct scsi_rw_16 *cdb;
8841
8842                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8843                 if (cdb->byte2 & SRW12_FUA)
8844                         flags |= CTL_LLF_FUA;
8845                 if (cdb->byte2 & SRW12_DPO)
8846                         flags |= CTL_LLF_DPO;
8847                 lba = scsi_8btou64(cdb->addr);
8848                 num_blocks = scsi_4btoul(cdb->length);
8849                 break;
8850         }
8851         case WRITE_ATOMIC_16: {
8852                 struct scsi_rw_16 *cdb;
8853
8854                 if (lun->be_lun->atomicblock == 0) {
8855                         ctl_set_invalid_opcode(ctsio);
8856                         ctl_done((union ctl_io *)ctsio);
8857                         return (CTL_RETVAL_COMPLETE);
8858                 }
8859
8860                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8861                 if (cdb->byte2 & SRW12_FUA)
8862                         flags |= CTL_LLF_FUA;
8863                 if (cdb->byte2 & SRW12_DPO)
8864                         flags |= CTL_LLF_DPO;
8865                 lba = scsi_8btou64(cdb->addr);
8866                 num_blocks = scsi_4btoul(cdb->length);
8867                 if (num_blocks > lun->be_lun->atomicblock) {
8868                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8869                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8870                             /*bit*/ 0);
8871                         ctl_done((union ctl_io *)ctsio);
8872                         return (CTL_RETVAL_COMPLETE);
8873                 }
8874                 break;
8875         }
8876         case WRITE_VERIFY_16: {
8877                 struct scsi_write_verify_16 *cdb;
8878
8879                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8880                 flags |= CTL_LLF_FUA;
8881                 if (cdb->byte2 & SWV_DPO)
8882                         flags |= CTL_LLF_DPO;
8883                 lba = scsi_8btou64(cdb->addr);
8884                 num_blocks = scsi_4btoul(cdb->length);
8885                 break;
8886         }
8887         default:
8888                 /*
8889                  * We got a command we don't support.  This shouldn't
8890                  * happen, commands should be filtered out above us.
8891                  */
8892                 ctl_set_invalid_opcode(ctsio);
8893                 ctl_done((union ctl_io *)ctsio);
8894
8895                 return (CTL_RETVAL_COMPLETE);
8896                 break; /* NOTREACHED */
8897         }
8898
8899         /*
8900          * The first check is to make sure we're in bounds, the second
8901          * check is to catch wrap-around problems.  If the lba + num blocks
8902          * is less than the lba, then we've wrapped around and the block
8903          * range is invalid anyway.
8904          */
8905         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8906          || ((lba + num_blocks) < lba)) {
8907                 ctl_set_lba_out_of_range(ctsio);
8908                 ctl_done((union ctl_io *)ctsio);
8909                 return (CTL_RETVAL_COMPLETE);
8910         }
8911
8912         /*
8913          * According to SBC-3, a transfer length of 0 is not an error.
8914          * Note that this cannot happen with WRITE(6) or READ(6), since 0
8915          * translates to 256 blocks for those commands.
8916          */
8917         if (num_blocks == 0) {
8918                 ctl_set_success(ctsio);
8919                 ctl_done((union ctl_io *)ctsio);
8920                 return (CTL_RETVAL_COMPLETE);
8921         }
8922
8923         /* Set FUA and/or DPO if caches are disabled. */
8924         if (isread) {
8925                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8926                     SCP_RCD) != 0)
8927                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8928         } else {
8929                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8930                     SCP_WCE) == 0)
8931                         flags |= CTL_LLF_FUA;
8932         }
8933
8934         lbalen = (struct ctl_lba_len_flags *)
8935             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8936         lbalen->lba = lba;
8937         lbalen->len = num_blocks;
8938         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8939
8940         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8941         ctsio->kern_rel_offset = 0;
8942
8943         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8944
8945         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8946
8947         return (retval);
8948 }
8949
8950 static int
8951 ctl_cnw_cont(union ctl_io *io)
8952 {
8953         struct ctl_scsiio *ctsio;
8954         struct ctl_lun *lun;
8955         struct ctl_lba_len_flags *lbalen;
8956         int retval;
8957
8958         ctsio = &io->scsiio;
8959         ctsio->io_hdr.status = CTL_STATUS_NONE;
8960         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8961         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8962         lbalen = (struct ctl_lba_len_flags *)
8963             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8964         lbalen->flags &= ~CTL_LLF_COMPARE;
8965         lbalen->flags |= CTL_LLF_WRITE;
8966
8967         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8968         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8969         return (retval);
8970 }
8971
8972 int
8973 ctl_cnw(struct ctl_scsiio *ctsio)
8974 {
8975         struct ctl_lun *lun;
8976         struct ctl_lba_len_flags *lbalen;
8977         uint64_t lba;
8978         uint32_t num_blocks;
8979         int flags, retval;
8980
8981         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8982
8983         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8984
8985         flags = 0;
8986         retval = CTL_RETVAL_COMPLETE;
8987
8988         switch (ctsio->cdb[0]) {
8989         case COMPARE_AND_WRITE: {
8990                 struct scsi_compare_and_write *cdb;
8991
8992                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8993                 if (cdb->byte2 & SRW10_FUA)
8994                         flags |= CTL_LLF_FUA;
8995                 if (cdb->byte2 & SRW10_DPO)
8996                         flags |= CTL_LLF_DPO;
8997                 lba = scsi_8btou64(cdb->addr);
8998                 num_blocks = cdb->length;
8999                 break;
9000         }
9001         default:
9002                 /*
9003                  * We got a command we don't support.  This shouldn't
9004                  * happen, commands should be filtered out above us.
9005                  */
9006                 ctl_set_invalid_opcode(ctsio);
9007                 ctl_done((union ctl_io *)ctsio);
9008
9009                 return (CTL_RETVAL_COMPLETE);
9010                 break; /* NOTREACHED */
9011         }
9012
9013         /*
9014          * The first check is to make sure we're in bounds, the second
9015          * check is to catch wrap-around problems.  If the lba + num blocks
9016          * is less than the lba, then we've wrapped around and the block
9017          * range is invalid anyway.
9018          */
9019         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9020          || ((lba + num_blocks) < lba)) {
9021                 ctl_set_lba_out_of_range(ctsio);
9022                 ctl_done((union ctl_io *)ctsio);
9023                 return (CTL_RETVAL_COMPLETE);
9024         }
9025
9026         /*
9027          * According to SBC-3, a transfer length of 0 is not an error.
9028          */
9029         if (num_blocks == 0) {
9030                 ctl_set_success(ctsio);
9031                 ctl_done((union ctl_io *)ctsio);
9032                 return (CTL_RETVAL_COMPLETE);
9033         }
9034
9035         /* Set FUA if write cache is disabled. */
9036         if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9037             SCP_WCE) == 0)
9038                 flags |= CTL_LLF_FUA;
9039
9040         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9041         ctsio->kern_rel_offset = 0;
9042
9043         /*
9044          * Set the IO_CONT flag, so that if this I/O gets passed to
9045          * ctl_data_submit_done(), it'll get passed back to
9046          * ctl_ctl_cnw_cont() for further processing.
9047          */
9048         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9049         ctsio->io_cont = ctl_cnw_cont;
9050
9051         lbalen = (struct ctl_lba_len_flags *)
9052             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9053         lbalen->lba = lba;
9054         lbalen->len = num_blocks;
9055         lbalen->flags = CTL_LLF_COMPARE | flags;
9056
9057         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9058         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9059         return (retval);
9060 }
9061
9062 int
9063 ctl_verify(struct ctl_scsiio *ctsio)
9064 {
9065         struct ctl_lun *lun;
9066         struct ctl_lba_len_flags *lbalen;
9067         uint64_t lba;
9068         uint32_t num_blocks;
9069         int bytchk, flags;
9070         int retval;
9071
9072         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9073
9074         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9075
9076         bytchk = 0;
9077         flags = CTL_LLF_FUA;
9078         retval = CTL_RETVAL_COMPLETE;
9079
9080         switch (ctsio->cdb[0]) {
9081         case VERIFY_10: {
9082                 struct scsi_verify_10 *cdb;
9083
9084                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
9085                 if (cdb->byte2 & SVFY_BYTCHK)
9086                         bytchk = 1;
9087                 if (cdb->byte2 & SVFY_DPO)
9088                         flags |= CTL_LLF_DPO;
9089                 lba = scsi_4btoul(cdb->addr);
9090                 num_blocks = scsi_2btoul(cdb->length);
9091                 break;
9092         }
9093         case VERIFY_12: {
9094                 struct scsi_verify_12 *cdb;
9095
9096                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
9097                 if (cdb->byte2 & SVFY_BYTCHK)
9098                         bytchk = 1;
9099                 if (cdb->byte2 & SVFY_DPO)
9100                         flags |= CTL_LLF_DPO;
9101                 lba = scsi_4btoul(cdb->addr);
9102                 num_blocks = scsi_4btoul(cdb->length);
9103                 break;
9104         }
9105         case VERIFY_16: {
9106                 struct scsi_rw_16 *cdb;
9107
9108                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9109                 if (cdb->byte2 & SVFY_BYTCHK)
9110                         bytchk = 1;
9111                 if (cdb->byte2 & SVFY_DPO)
9112                         flags |= CTL_LLF_DPO;
9113                 lba = scsi_8btou64(cdb->addr);
9114                 num_blocks = scsi_4btoul(cdb->length);
9115                 break;
9116         }
9117         default:
9118                 /*
9119                  * We got a command we don't support.  This shouldn't
9120                  * happen, commands should be filtered out above us.
9121                  */
9122                 ctl_set_invalid_opcode(ctsio);
9123                 ctl_done((union ctl_io *)ctsio);
9124                 return (CTL_RETVAL_COMPLETE);
9125         }
9126
9127         /*
9128          * The first check is to make sure we're in bounds, the second
9129          * check is to catch wrap-around problems.  If the lba + num blocks
9130          * is less than the lba, then we've wrapped around and the block
9131          * range is invalid anyway.
9132          */
9133         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9134          || ((lba + num_blocks) < lba)) {
9135                 ctl_set_lba_out_of_range(ctsio);
9136                 ctl_done((union ctl_io *)ctsio);
9137                 return (CTL_RETVAL_COMPLETE);
9138         }
9139
9140         /*
9141          * According to SBC-3, a transfer length of 0 is not an error.
9142          */
9143         if (num_blocks == 0) {
9144                 ctl_set_success(ctsio);
9145                 ctl_done((union ctl_io *)ctsio);
9146                 return (CTL_RETVAL_COMPLETE);
9147         }
9148
9149         lbalen = (struct ctl_lba_len_flags *)
9150             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9151         lbalen->lba = lba;
9152         lbalen->len = num_blocks;
9153         if (bytchk) {
9154                 lbalen->flags = CTL_LLF_COMPARE | flags;
9155                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9156         } else {
9157                 lbalen->flags = CTL_LLF_VERIFY | flags;
9158                 ctsio->kern_total_len = 0;
9159         }
9160         ctsio->kern_rel_offset = 0;
9161
9162         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9163         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9164         return (retval);
9165 }
9166
9167 int
9168 ctl_report_luns(struct ctl_scsiio *ctsio)
9169 {
9170         struct scsi_report_luns *cdb;
9171         struct scsi_report_luns_data *lun_data;
9172         struct ctl_lun *lun, *request_lun;
9173         int num_luns, retval;
9174         uint32_t alloc_len, lun_datalen;
9175         int num_filled, well_known;
9176         uint32_t initidx, targ_lun_id, lun_id;
9177
9178         retval = CTL_RETVAL_COMPLETE;
9179         well_known = 0;
9180
9181         cdb = (struct scsi_report_luns *)ctsio->cdb;
9182
9183         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9184
9185         mtx_lock(&control_softc->ctl_lock);
9186         num_luns = control_softc->num_luns;
9187         mtx_unlock(&control_softc->ctl_lock);
9188
9189         switch (cdb->select_report) {
9190         case RPL_REPORT_DEFAULT:
9191         case RPL_REPORT_ALL:
9192                 break;
9193         case RPL_REPORT_WELLKNOWN:
9194                 well_known = 1;
9195                 num_luns = 0;
9196                 break;
9197         default:
9198                 ctl_set_invalid_field(ctsio,
9199                                       /*sks_valid*/ 1,
9200                                       /*command*/ 1,
9201                                       /*field*/ 2,
9202                                       /*bit_valid*/ 0,
9203                                       /*bit*/ 0);
9204                 ctl_done((union ctl_io *)ctsio);
9205                 return (retval);
9206                 break; /* NOTREACHED */
9207         }
9208
9209         alloc_len = scsi_4btoul(cdb->length);
9210         /*
9211          * The initiator has to allocate at least 16 bytes for this request,
9212          * so he can at least get the header and the first LUN.  Otherwise
9213          * we reject the request (per SPC-3 rev 14, section 6.21).
9214          */
9215         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9216             sizeof(struct scsi_report_luns_lundata))) {
9217                 ctl_set_invalid_field(ctsio,
9218                                       /*sks_valid*/ 1,
9219                                       /*command*/ 1,
9220                                       /*field*/ 6,
9221                                       /*bit_valid*/ 0,
9222                                       /*bit*/ 0);
9223                 ctl_done((union ctl_io *)ctsio);
9224                 return (retval);
9225         }
9226
9227         request_lun = (struct ctl_lun *)
9228                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9229
9230         lun_datalen = sizeof(*lun_data) +
9231                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9232
9233         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9234         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9235         ctsio->kern_sg_entries = 0;
9236
9237         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9238
9239         mtx_lock(&control_softc->ctl_lock);
9240         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9241                 lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9242                 if (lun_id >= CTL_MAX_LUNS)
9243                         continue;
9244                 lun = control_softc->ctl_luns[lun_id];
9245                 if (lun == NULL)
9246                         continue;
9247
9248                 if (targ_lun_id <= 0xff) {
9249                         /*
9250                          * Peripheral addressing method, bus number 0.
9251                          */
9252                         lun_data->luns[num_filled].lundata[0] =
9253                                 RPL_LUNDATA_ATYP_PERIPH;
9254                         lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9255                         num_filled++;
9256                 } else if (targ_lun_id <= 0x3fff) {
9257                         /*
9258                          * Flat addressing method.
9259                          */
9260                         lun_data->luns[num_filled].lundata[0] =
9261                                 RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9262                         lun_data->luns[num_filled].lundata[1] =
9263                                 (targ_lun_id & 0xff);
9264                         num_filled++;
9265                 } else if (targ_lun_id <= 0xffffff) {
9266                         /*
9267                          * Extended flat addressing method.
9268                          */
9269                         lun_data->luns[num_filled].lundata[0] =
9270                             RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9271                         scsi_ulto3b(targ_lun_id,
9272                             &lun_data->luns[num_filled].lundata[1]);
9273                         num_filled++;
9274                 } else {
9275                         printf("ctl_report_luns: bogus LUN number %jd, "
9276                                "skipping\n", (intmax_t)targ_lun_id);
9277                 }
9278                 /*
9279                  * According to SPC-3, rev 14 section 6.21:
9280                  *
9281                  * "The execution of a REPORT LUNS command to any valid and
9282                  * installed logical unit shall clear the REPORTED LUNS DATA
9283                  * HAS CHANGED unit attention condition for all logical
9284                  * units of that target with respect to the requesting
9285                  * initiator. A valid and installed logical unit is one
9286                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9287                  * INQUIRY data (see 6.4.2)."
9288                  *
9289                  * If request_lun is NULL, the LUN this report luns command
9290                  * was issued to is either disabled or doesn't exist. In that
9291                  * case, we shouldn't clear any pending lun change unit
9292                  * attention.
9293                  */
9294                 if (request_lun != NULL) {
9295                         mtx_lock(&lun->lun_lock);
9296                         lun->pending_ua[initidx] &= ~CTL_UA_LUN_CHANGE;
9297                         mtx_unlock(&lun->lun_lock);
9298                 }
9299         }
9300         mtx_unlock(&control_softc->ctl_lock);
9301
9302         /*
9303          * It's quite possible that we've returned fewer LUNs than we allocated
9304          * space for.  Trim it.
9305          */
9306         lun_datalen = sizeof(*lun_data) +
9307                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9308
9309         if (lun_datalen < alloc_len) {
9310                 ctsio->residual = alloc_len - lun_datalen;
9311                 ctsio->kern_data_len = lun_datalen;
9312                 ctsio->kern_total_len = lun_datalen;
9313         } else {
9314                 ctsio->residual = 0;
9315                 ctsio->kern_data_len = alloc_len;
9316                 ctsio->kern_total_len = alloc_len;
9317         }
9318         ctsio->kern_data_resid = 0;
9319         ctsio->kern_rel_offset = 0;
9320         ctsio->kern_sg_entries = 0;
9321
9322         /*
9323          * We set this to the actual data length, regardless of how much
9324          * space we actually have to return results.  If the user looks at
9325          * this value, he'll know whether or not he allocated enough space
9326          * and reissue the command if necessary.  We don't support well
9327          * known logical units, so if the user asks for that, return none.
9328          */
9329         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9330
9331         /*
9332          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9333          * this request.
9334          */
9335         ctl_set_success(ctsio);
9336         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9337         ctsio->be_move_done = ctl_config_move_done;
9338         ctl_datamove((union ctl_io *)ctsio);
9339         return (retval);
9340 }
9341
9342 int
9343 ctl_request_sense(struct ctl_scsiio *ctsio)
9344 {
9345         struct scsi_request_sense *cdb;
9346         struct scsi_sense_data *sense_ptr;
9347         struct ctl_lun *lun;
9348         uint32_t initidx;
9349         int have_error;
9350         scsi_sense_data_type sense_format;
9351
9352         cdb = (struct scsi_request_sense *)ctsio->cdb;
9353
9354         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9355
9356         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9357
9358         /*
9359          * Determine which sense format the user wants.
9360          */
9361         if (cdb->byte2 & SRS_DESC)
9362                 sense_format = SSD_TYPE_DESC;
9363         else
9364                 sense_format = SSD_TYPE_FIXED;
9365
9366         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9367         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9368         ctsio->kern_sg_entries = 0;
9369
9370         /*
9371          * struct scsi_sense_data, which is currently set to 256 bytes, is
9372          * larger than the largest allowed value for the length field in the
9373          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9374          */
9375         ctsio->residual = 0;
9376         ctsio->kern_data_len = cdb->length;
9377         ctsio->kern_total_len = cdb->length;
9378
9379         ctsio->kern_data_resid = 0;
9380         ctsio->kern_rel_offset = 0;
9381         ctsio->kern_sg_entries = 0;
9382
9383         /*
9384          * If we don't have a LUN, we don't have any pending sense.
9385          */
9386         if (lun == NULL)
9387                 goto no_sense;
9388
9389         have_error = 0;
9390         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9391         /*
9392          * Check for pending sense, and then for pending unit attentions.
9393          * Pending sense gets returned first, then pending unit attentions.
9394          */
9395         mtx_lock(&lun->lun_lock);
9396 #ifdef CTL_WITH_CA
9397         if (ctl_is_set(lun->have_ca, initidx)) {
9398                 scsi_sense_data_type stored_format;
9399
9400                 /*
9401                  * Check to see which sense format was used for the stored
9402                  * sense data.
9403                  */
9404                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9405
9406                 /*
9407                  * If the user requested a different sense format than the
9408                  * one we stored, then we need to convert it to the other
9409                  * format.  If we're going from descriptor to fixed format
9410                  * sense data, we may lose things in translation, depending
9411                  * on what options were used.
9412                  *
9413                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9414                  * for some reason we'll just copy it out as-is.
9415                  */
9416                 if ((stored_format == SSD_TYPE_FIXED)
9417                  && (sense_format == SSD_TYPE_DESC))
9418                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9419                             &lun->pending_sense[initidx],
9420                             (struct scsi_sense_data_desc *)sense_ptr);
9421                 else if ((stored_format == SSD_TYPE_DESC)
9422                       && (sense_format == SSD_TYPE_FIXED))
9423                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9424                             &lun->pending_sense[initidx],
9425                             (struct scsi_sense_data_fixed *)sense_ptr);
9426                 else
9427                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9428                                ctl_min(sizeof(*sense_ptr),
9429                                sizeof(lun->pending_sense[initidx])));
9430
9431                 ctl_clear_mask(lun->have_ca, initidx);
9432                 have_error = 1;
9433         } else
9434 #endif
9435         if (lun->pending_ua[initidx] != CTL_UA_NONE) {
9436                 ctl_ua_type ua_type;
9437
9438                 ua_type = ctl_build_ua(&lun->pending_ua[initidx],
9439                                        sense_ptr, sense_format);
9440                 if (ua_type != CTL_UA_NONE)
9441                         have_error = 1;
9442         }
9443         mtx_unlock(&lun->lun_lock);
9444
9445         /*
9446          * We already have a pending error, return it.
9447          */
9448         if (have_error != 0) {
9449                 /*
9450                  * We report the SCSI status as OK, since the status of the
9451                  * request sense command itself is OK.
9452                  * We report 0 for the sense length, because we aren't doing
9453                  * autosense in this case.  We're reporting sense as
9454                  * parameter data.
9455                  */
9456                 ctl_set_success(ctsio);
9457                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9458                 ctsio->be_move_done = ctl_config_move_done;
9459                 ctl_datamove((union ctl_io *)ctsio);
9460                 return (CTL_RETVAL_COMPLETE);
9461         }
9462
9463 no_sense:
9464
9465         /*
9466          * No sense information to report, so we report that everything is
9467          * okay.
9468          */
9469         ctl_set_sense_data(sense_ptr,
9470                            lun,
9471                            sense_format,
9472                            /*current_error*/ 1,
9473                            /*sense_key*/ SSD_KEY_NO_SENSE,
9474                            /*asc*/ 0x00,
9475                            /*ascq*/ 0x00,
9476                            SSD_ELEM_NONE);
9477
9478         /*
9479          * We report 0 for the sense length, because we aren't doing
9480          * autosense in this case.  We're reporting sense as parameter data.
9481          */
9482         ctl_set_success(ctsio);
9483         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9484         ctsio->be_move_done = ctl_config_move_done;
9485         ctl_datamove((union ctl_io *)ctsio);
9486         return (CTL_RETVAL_COMPLETE);
9487 }
9488
9489 int
9490 ctl_tur(struct ctl_scsiio *ctsio)
9491 {
9492
9493         CTL_DEBUG_PRINT(("ctl_tur\n"));
9494
9495         ctl_set_success(ctsio);
9496         ctl_done((union ctl_io *)ctsio);
9497
9498         return (CTL_RETVAL_COMPLETE);
9499 }
9500
9501 #ifdef notyet
9502 static int
9503 ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9504 {
9505
9506 }
9507 #endif
9508
9509 static int
9510 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9511 {
9512         struct scsi_vpd_supported_pages *pages;
9513         int sup_page_size;
9514         struct ctl_lun *lun;
9515
9516         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9517
9518         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9519             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9520         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9521         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9522         ctsio->kern_sg_entries = 0;
9523
9524         if (sup_page_size < alloc_len) {
9525                 ctsio->residual = alloc_len - sup_page_size;
9526                 ctsio->kern_data_len = sup_page_size;
9527                 ctsio->kern_total_len = sup_page_size;
9528         } else {
9529                 ctsio->residual = 0;
9530                 ctsio->kern_data_len = alloc_len;
9531                 ctsio->kern_total_len = alloc_len;
9532         }
9533         ctsio->kern_data_resid = 0;
9534         ctsio->kern_rel_offset = 0;
9535         ctsio->kern_sg_entries = 0;
9536
9537         /*
9538          * The control device is always connected.  The disk device, on the
9539          * other hand, may not be online all the time.  Need to change this
9540          * to figure out whether the disk device is actually online or not.
9541          */
9542         if (lun != NULL)
9543                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9544                                 lun->be_lun->lun_type;
9545         else
9546                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9547
9548         pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9549         /* Supported VPD pages */
9550         pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9551         /* Serial Number */
9552         pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9553         /* Device Identification */
9554         pages->page_list[2] = SVPD_DEVICE_ID;
9555         /* Extended INQUIRY Data */
9556         pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9557         /* Mode Page Policy */
9558         pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9559         /* SCSI Ports */
9560         pages->page_list[5] = SVPD_SCSI_PORTS;
9561         /* Third-party Copy */
9562         pages->page_list[6] = SVPD_SCSI_TPC;
9563         /* Block limits */
9564         pages->page_list[7] = SVPD_BLOCK_LIMITS;
9565         /* Block Device Characteristics */
9566         pages->page_list[8] = SVPD_BDC;
9567         /* Logical Block Provisioning */
9568         pages->page_list[9] = SVPD_LBP;
9569
9570         ctl_set_success(ctsio);
9571         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9572         ctsio->be_move_done = ctl_config_move_done;
9573         ctl_datamove((union ctl_io *)ctsio);
9574         return (CTL_RETVAL_COMPLETE);
9575 }
9576
9577 static int
9578 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9579 {
9580         struct scsi_vpd_unit_serial_number *sn_ptr;
9581         struct ctl_lun *lun;
9582         int data_len;
9583
9584         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9585
9586         data_len = 4 + CTL_SN_LEN;
9587         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9588         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9589         if (data_len < alloc_len) {
9590                 ctsio->residual = alloc_len - data_len;
9591                 ctsio->kern_data_len = data_len;
9592                 ctsio->kern_total_len = data_len;
9593         } else {
9594                 ctsio->residual = 0;
9595                 ctsio->kern_data_len = alloc_len;
9596                 ctsio->kern_total_len = alloc_len;
9597         }
9598         ctsio->kern_data_resid = 0;
9599         ctsio->kern_rel_offset = 0;
9600         ctsio->kern_sg_entries = 0;
9601
9602         /*
9603          * The control device is always connected.  The disk device, on the
9604          * other hand, may not be online all the time.  Need to change this
9605          * to figure out whether the disk device is actually online or not.
9606          */
9607         if (lun != NULL)
9608                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9609                                   lun->be_lun->lun_type;
9610         else
9611                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9612
9613         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9614         sn_ptr->length = CTL_SN_LEN;
9615         /*
9616          * If we don't have a LUN, we just leave the serial number as
9617          * all spaces.
9618          */
9619         if (lun != NULL) {
9620                 strncpy((char *)sn_ptr->serial_num,
9621                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9622         } else
9623                 memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9624
9625         ctl_set_success(ctsio);
9626         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9627         ctsio->be_move_done = ctl_config_move_done;
9628         ctl_datamove((union ctl_io *)ctsio);
9629         return (CTL_RETVAL_COMPLETE);
9630 }
9631
9632
9633 static int
9634 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9635 {
9636         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9637         struct ctl_lun *lun;
9638         int data_len;
9639
9640         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9641
9642         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9643         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9644         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9645         ctsio->kern_sg_entries = 0;
9646
9647         if (data_len < alloc_len) {
9648                 ctsio->residual = alloc_len - data_len;
9649                 ctsio->kern_data_len = data_len;
9650                 ctsio->kern_total_len = data_len;
9651         } else {
9652                 ctsio->residual = 0;
9653                 ctsio->kern_data_len = alloc_len;
9654                 ctsio->kern_total_len = alloc_len;
9655         }
9656         ctsio->kern_data_resid = 0;
9657         ctsio->kern_rel_offset = 0;
9658         ctsio->kern_sg_entries = 0;
9659
9660         /*
9661          * The control device is always connected.  The disk device, on the
9662          * other hand, may not be online all the time.
9663          */
9664         if (lun != NULL)
9665                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9666                                      lun->be_lun->lun_type;
9667         else
9668                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9669         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9670         eid_ptr->page_length = data_len - 4;
9671         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9672         eid_ptr->flags3 = SVPD_EID_V_SUP;
9673
9674         ctl_set_success(ctsio);
9675         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9676         ctsio->be_move_done = ctl_config_move_done;
9677         ctl_datamove((union ctl_io *)ctsio);
9678         return (CTL_RETVAL_COMPLETE);
9679 }
9680
9681 static int
9682 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9683 {
9684         struct scsi_vpd_mode_page_policy *mpp_ptr;
9685         struct ctl_lun *lun;
9686         int data_len;
9687
9688         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9689
9690         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9691             sizeof(struct scsi_vpd_mode_page_policy_descr);
9692
9693         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9694         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9695         ctsio->kern_sg_entries = 0;
9696
9697         if (data_len < alloc_len) {
9698                 ctsio->residual = alloc_len - data_len;
9699                 ctsio->kern_data_len = data_len;
9700                 ctsio->kern_total_len = data_len;
9701         } else {
9702                 ctsio->residual = 0;
9703                 ctsio->kern_data_len = alloc_len;
9704                 ctsio->kern_total_len = alloc_len;
9705         }
9706         ctsio->kern_data_resid = 0;
9707         ctsio->kern_rel_offset = 0;
9708         ctsio->kern_sg_entries = 0;
9709
9710         /*
9711          * The control device is always connected.  The disk device, on the
9712          * other hand, may not be online all the time.
9713          */
9714         if (lun != NULL)
9715                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9716                                      lun->be_lun->lun_type;
9717         else
9718                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9719         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9720         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9721         mpp_ptr->descr[0].page_code = 0x3f;
9722         mpp_ptr->descr[0].subpage_code = 0xff;
9723         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9724
9725         ctl_set_success(ctsio);
9726         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9727         ctsio->be_move_done = ctl_config_move_done;
9728         ctl_datamove((union ctl_io *)ctsio);
9729         return (CTL_RETVAL_COMPLETE);
9730 }
9731
9732 static int
9733 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9734 {
9735         struct scsi_vpd_device_id *devid_ptr;
9736         struct scsi_vpd_id_descriptor *desc;
9737         struct ctl_softc *ctl_softc;
9738         struct ctl_lun *lun;
9739         struct ctl_port *port;
9740         int data_len;
9741         uint8_t proto;
9742
9743         ctl_softc = control_softc;
9744
9745         port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9746         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9747
9748         data_len = sizeof(struct scsi_vpd_device_id) +
9749             sizeof(struct scsi_vpd_id_descriptor) +
9750                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9751             sizeof(struct scsi_vpd_id_descriptor) +
9752                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9753         if (lun && lun->lun_devid)
9754                 data_len += lun->lun_devid->len;
9755         if (port->port_devid)
9756                 data_len += port->port_devid->len;
9757         if (port->target_devid)
9758                 data_len += port->target_devid->len;
9759
9760         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9761         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9762         ctsio->kern_sg_entries = 0;
9763
9764         if (data_len < alloc_len) {
9765                 ctsio->residual = alloc_len - data_len;
9766                 ctsio->kern_data_len = data_len;
9767                 ctsio->kern_total_len = data_len;
9768         } else {
9769                 ctsio->residual = 0;
9770                 ctsio->kern_data_len = alloc_len;
9771                 ctsio->kern_total_len = alloc_len;
9772         }
9773         ctsio->kern_data_resid = 0;
9774         ctsio->kern_rel_offset = 0;
9775         ctsio->kern_sg_entries = 0;
9776
9777         /*
9778          * The control device is always connected.  The disk device, on the
9779          * other hand, may not be online all the time.
9780          */
9781         if (lun != NULL)
9782                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9783                                      lun->be_lun->lun_type;
9784         else
9785                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9786         devid_ptr->page_code = SVPD_DEVICE_ID;
9787         scsi_ulto2b(data_len - 4, devid_ptr->length);
9788
9789         if (port->port_type == CTL_PORT_FC)
9790                 proto = SCSI_PROTO_FC << 4;
9791         else if (port->port_type == CTL_PORT_ISCSI)
9792                 proto = SCSI_PROTO_ISCSI << 4;
9793         else
9794                 proto = SCSI_PROTO_SPI << 4;
9795         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9796
9797         /*
9798          * We're using a LUN association here.  i.e., this device ID is a
9799          * per-LUN identifier.
9800          */
9801         if (lun && lun->lun_devid) {
9802                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9803                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9804                     lun->lun_devid->len);
9805         }
9806
9807         /*
9808          * This is for the WWPN which is a port association.
9809          */
9810         if (port->port_devid) {
9811                 memcpy(desc, port->port_devid->data, port->port_devid->len);
9812                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9813                     port->port_devid->len);
9814         }
9815
9816         /*
9817          * This is for the Relative Target Port(type 4h) identifier
9818          */
9819         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9820         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9821             SVPD_ID_TYPE_RELTARG;
9822         desc->length = 4;
9823         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9824         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9825             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9826
9827         /*
9828          * This is for the Target Port Group(type 5h) identifier
9829          */
9830         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9831         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9832             SVPD_ID_TYPE_TPORTGRP;
9833         desc->length = 4;
9834         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
9835             &desc->identifier[2]);
9836         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9837             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9838
9839         /*
9840          * This is for the Target identifier
9841          */
9842         if (port->target_devid) {
9843                 memcpy(desc, port->target_devid->data, port->target_devid->len);
9844         }
9845
9846         ctl_set_success(ctsio);
9847         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9848         ctsio->be_move_done = ctl_config_move_done;
9849         ctl_datamove((union ctl_io *)ctsio);
9850         return (CTL_RETVAL_COMPLETE);
9851 }
9852
9853 static int
9854 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9855 {
9856         struct ctl_softc *softc = control_softc;
9857         struct scsi_vpd_scsi_ports *sp;
9858         struct scsi_vpd_port_designation *pd;
9859         struct scsi_vpd_port_designation_cont *pdc;
9860         struct ctl_lun *lun;
9861         struct ctl_port *port;
9862         int data_len, num_target_ports, iid_len, id_len, g, pg, p;
9863         int num_target_port_groups;
9864
9865         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9866
9867         if (softc->is_single)
9868                 num_target_port_groups = 1;
9869         else
9870                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
9871         num_target_ports = 0;
9872         iid_len = 0;
9873         id_len = 0;
9874         mtx_lock(&softc->ctl_lock);
9875         STAILQ_FOREACH(port, &softc->port_list, links) {
9876                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9877                         continue;
9878                 if (lun != NULL &&
9879                     ctl_map_lun_back(port->targ_port, lun->lun) >=
9880                     CTL_MAX_LUNS)
9881                         continue;
9882                 num_target_ports++;
9883                 if (port->init_devid)
9884                         iid_len += port->init_devid->len;
9885                 if (port->port_devid)
9886                         id_len += port->port_devid->len;
9887         }
9888         mtx_unlock(&softc->ctl_lock);
9889
9890         data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
9891             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9892              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9893         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9894         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9895         ctsio->kern_sg_entries = 0;
9896
9897         if (data_len < alloc_len) {
9898                 ctsio->residual = alloc_len - data_len;
9899                 ctsio->kern_data_len = data_len;
9900                 ctsio->kern_total_len = data_len;
9901         } else {
9902                 ctsio->residual = 0;
9903                 ctsio->kern_data_len = alloc_len;
9904                 ctsio->kern_total_len = alloc_len;
9905         }
9906         ctsio->kern_data_resid = 0;
9907         ctsio->kern_rel_offset = 0;
9908         ctsio->kern_sg_entries = 0;
9909
9910         /*
9911          * The control device is always connected.  The disk device, on the
9912          * other hand, may not be online all the time.  Need to change this
9913          * to figure out whether the disk device is actually online or not.
9914          */
9915         if (lun != NULL)
9916                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9917                                   lun->be_lun->lun_type;
9918         else
9919                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9920
9921         sp->page_code = SVPD_SCSI_PORTS;
9922         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9923             sp->page_length);
9924         pd = &sp->design[0];
9925
9926         mtx_lock(&softc->ctl_lock);
9927         pg = softc->port_offset / CTL_MAX_PORTS;
9928         for (g = 0; g < num_target_port_groups; g++) {
9929                 STAILQ_FOREACH(port, &softc->port_list, links) {
9930                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9931                                 continue;
9932                         if (lun != NULL &&
9933                             ctl_map_lun_back(port->targ_port, lun->lun) >=
9934                             CTL_MAX_LUNS)
9935                                 continue;
9936                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
9937                         scsi_ulto2b(p, pd->relative_port_id);
9938                         if (port->init_devid && g == pg) {
9939                                 iid_len = port->init_devid->len;
9940                                 memcpy(pd->initiator_transportid,
9941                                     port->init_devid->data, port->init_devid->len);
9942                         } else
9943                                 iid_len = 0;
9944                         scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9945                         pdc = (struct scsi_vpd_port_designation_cont *)
9946                             (&pd->initiator_transportid[iid_len]);
9947                         if (port->port_devid && g == pg) {
9948                                 id_len = port->port_devid->len;
9949                                 memcpy(pdc->target_port_descriptors,
9950                                     port->port_devid->data, port->port_devid->len);
9951                         } else
9952                                 id_len = 0;
9953                         scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9954                         pd = (struct scsi_vpd_port_designation *)
9955                             ((uint8_t *)pdc->target_port_descriptors + id_len);
9956                 }
9957         }
9958         mtx_unlock(&softc->ctl_lock);
9959
9960         ctl_set_success(ctsio);
9961         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9962         ctsio->be_move_done = ctl_config_move_done;
9963         ctl_datamove((union ctl_io *)ctsio);
9964         return (CTL_RETVAL_COMPLETE);
9965 }
9966
9967 static int
9968 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9969 {
9970         struct scsi_vpd_block_limits *bl_ptr;
9971         struct ctl_lun *lun;
9972         int bs;
9973
9974         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9975
9976         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9977         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9978         ctsio->kern_sg_entries = 0;
9979
9980         if (sizeof(*bl_ptr) < alloc_len) {
9981                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
9982                 ctsio->kern_data_len = sizeof(*bl_ptr);
9983                 ctsio->kern_total_len = sizeof(*bl_ptr);
9984         } else {
9985                 ctsio->residual = 0;
9986                 ctsio->kern_data_len = alloc_len;
9987                 ctsio->kern_total_len = alloc_len;
9988         }
9989         ctsio->kern_data_resid = 0;
9990         ctsio->kern_rel_offset = 0;
9991         ctsio->kern_sg_entries = 0;
9992
9993         /*
9994          * The control device is always connected.  The disk device, on the
9995          * other hand, may not be online all the time.  Need to change this
9996          * to figure out whether the disk device is actually online or not.
9997          */
9998         if (lun != NULL)
9999                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10000                                   lun->be_lun->lun_type;
10001         else
10002                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10003
10004         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10005         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10006         bl_ptr->max_cmp_write_len = 0xff;
10007         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10008         if (lun != NULL) {
10009                 bs = lun->be_lun->blocksize;
10010                 scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10011                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10012                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10013                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10014                         if (lun->be_lun->pblockexp != 0) {
10015                                 scsi_ulto4b((1 << lun->be_lun->pblockexp),
10016                                     bl_ptr->opt_unmap_grain);
10017                                 scsi_ulto4b(0x80000000 | lun->be_lun->pblockoff,
10018                                     bl_ptr->unmap_grain_align);
10019                         }
10020                 }
10021                 scsi_ulto4b(lun->be_lun->atomicblock,
10022                     bl_ptr->max_atomic_transfer_length);
10023                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
10024                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10025         }
10026         scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10027
10028         ctl_set_success(ctsio);
10029         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10030         ctsio->be_move_done = ctl_config_move_done;
10031         ctl_datamove((union ctl_io *)ctsio);
10032         return (CTL_RETVAL_COMPLETE);
10033 }
10034
10035 static int
10036 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10037 {
10038         struct scsi_vpd_block_device_characteristics *bdc_ptr;
10039         struct ctl_lun *lun;
10040         const char *value;
10041         u_int i;
10042
10043         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10044
10045         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10046         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10047         ctsio->kern_sg_entries = 0;
10048
10049         if (sizeof(*bdc_ptr) < alloc_len) {
10050                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10051                 ctsio->kern_data_len = sizeof(*bdc_ptr);
10052                 ctsio->kern_total_len = sizeof(*bdc_ptr);
10053         } else {
10054                 ctsio->residual = 0;
10055                 ctsio->kern_data_len = alloc_len;
10056                 ctsio->kern_total_len = alloc_len;
10057         }
10058         ctsio->kern_data_resid = 0;
10059         ctsio->kern_rel_offset = 0;
10060         ctsio->kern_sg_entries = 0;
10061
10062         /*
10063          * The control device is always connected.  The disk device, on the
10064          * other hand, may not be online all the time.  Need to change this
10065          * to figure out whether the disk device is actually online or not.
10066          */
10067         if (lun != NULL)
10068                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10069                                   lun->be_lun->lun_type;
10070         else
10071                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10072         bdc_ptr->page_code = SVPD_BDC;
10073         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10074         if (lun != NULL &&
10075             (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10076                 i = strtol(value, NULL, 0);
10077         else
10078                 i = CTL_DEFAULT_ROTATION_RATE;
10079         scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10080         if (lun != NULL &&
10081             (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10082                 i = strtol(value, NULL, 0);
10083         else
10084                 i = 0;
10085         bdc_ptr->wab_wac_ff = (i & 0x0f);
10086         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10087
10088         ctl_set_success(ctsio);
10089         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10090         ctsio->be_move_done = ctl_config_move_done;
10091         ctl_datamove((union ctl_io *)ctsio);
10092         return (CTL_RETVAL_COMPLETE);
10093 }
10094
10095 static int
10096 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10097 {
10098         struct scsi_vpd_logical_block_prov *lbp_ptr;
10099         struct ctl_lun *lun;
10100
10101         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10102
10103         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10104         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10105         ctsio->kern_sg_entries = 0;
10106
10107         if (sizeof(*lbp_ptr) < alloc_len) {
10108                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10109                 ctsio->kern_data_len = sizeof(*lbp_ptr);
10110                 ctsio->kern_total_len = sizeof(*lbp_ptr);
10111         } else {
10112                 ctsio->residual = 0;
10113                 ctsio->kern_data_len = alloc_len;
10114                 ctsio->kern_total_len = alloc_len;
10115         }
10116         ctsio->kern_data_resid = 0;
10117         ctsio->kern_rel_offset = 0;
10118         ctsio->kern_sg_entries = 0;
10119
10120         /*
10121          * The control device is always connected.  The disk device, on the
10122          * other hand, may not be online all the time.  Need to change this
10123          * to figure out whether the disk device is actually online or not.
10124          */
10125         if (lun != NULL)
10126                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10127                                   lun->be_lun->lun_type;
10128         else
10129                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10130
10131         lbp_ptr->page_code = SVPD_LBP;
10132         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10133         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10134                 lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10135                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10136                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10137                 lbp_ptr->prov_type = SVPD_LBP_THIN;
10138         }
10139
10140         ctl_set_success(ctsio);
10141         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10142         ctsio->be_move_done = ctl_config_move_done;
10143         ctl_datamove((union ctl_io *)ctsio);
10144         return (CTL_RETVAL_COMPLETE);
10145 }
10146
10147 static int
10148 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10149 {
10150         struct scsi_inquiry *cdb;
10151         int alloc_len, retval;
10152
10153         cdb = (struct scsi_inquiry *)ctsio->cdb;
10154
10155         retval = CTL_RETVAL_COMPLETE;
10156
10157         alloc_len = scsi_2btoul(cdb->length);
10158
10159         switch (cdb->page_code) {
10160         case SVPD_SUPPORTED_PAGES:
10161                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10162                 break;
10163         case SVPD_UNIT_SERIAL_NUMBER:
10164                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10165                 break;
10166         case SVPD_DEVICE_ID:
10167                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10168                 break;
10169         case SVPD_EXTENDED_INQUIRY_DATA:
10170                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10171                 break;
10172         case SVPD_MODE_PAGE_POLICY:
10173                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10174                 break;
10175         case SVPD_SCSI_PORTS:
10176                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10177                 break;
10178         case SVPD_SCSI_TPC:
10179                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10180                 break;
10181         case SVPD_BLOCK_LIMITS:
10182                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10183                 break;
10184         case SVPD_BDC:
10185                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10186                 break;
10187         case SVPD_LBP:
10188                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10189                 break;
10190         default:
10191                 ctl_set_invalid_field(ctsio,
10192                                       /*sks_valid*/ 1,
10193                                       /*command*/ 1,
10194                                       /*field*/ 2,
10195                                       /*bit_valid*/ 0,
10196                                       /*bit*/ 0);
10197                 ctl_done((union ctl_io *)ctsio);
10198                 retval = CTL_RETVAL_COMPLETE;
10199                 break;
10200         }
10201
10202         return (retval);
10203 }
10204
10205 static int
10206 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10207 {
10208         struct scsi_inquiry_data *inq_ptr;
10209         struct scsi_inquiry *cdb;
10210         struct ctl_softc *ctl_softc;
10211         struct ctl_lun *lun;
10212         char *val;
10213         uint32_t alloc_len, data_len;
10214         ctl_port_type port_type;
10215
10216         ctl_softc = control_softc;
10217
10218         /*
10219          * Figure out whether we're talking to a Fibre Channel port or not.
10220          * We treat the ioctl front end, and any SCSI adapters, as packetized
10221          * SCSI front ends.
10222          */
10223         port_type = ctl_softc->ctl_ports[
10224             ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10225         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10226                 port_type = CTL_PORT_SCSI;
10227
10228         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10229         cdb = (struct scsi_inquiry *)ctsio->cdb;
10230         alloc_len = scsi_2btoul(cdb->length);
10231
10232         /*
10233          * We malloc the full inquiry data size here and fill it
10234          * in.  If the user only asks for less, we'll give him
10235          * that much.
10236          */
10237         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10238         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10239         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10240         ctsio->kern_sg_entries = 0;
10241         ctsio->kern_data_resid = 0;
10242         ctsio->kern_rel_offset = 0;
10243
10244         if (data_len < alloc_len) {
10245                 ctsio->residual = alloc_len - data_len;
10246                 ctsio->kern_data_len = data_len;
10247                 ctsio->kern_total_len = data_len;
10248         } else {
10249                 ctsio->residual = 0;
10250                 ctsio->kern_data_len = alloc_len;
10251                 ctsio->kern_total_len = alloc_len;
10252         }
10253
10254         /*
10255          * If we have a LUN configured, report it as connected.  Otherwise,
10256          * report that it is offline or no device is supported, depending 
10257          * on the value of inquiry_pq_no_lun.
10258          *
10259          * According to the spec (SPC-4 r34), the peripheral qualifier
10260          * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10261          *
10262          * "A peripheral device having the specified peripheral device type 
10263          * is not connected to this logical unit. However, the device
10264          * server is capable of supporting the specified peripheral device
10265          * type on this logical unit."
10266          *
10267          * According to the same spec, the peripheral qualifier
10268          * SID_QUAL_BAD_LU (011b) is used in this scenario:
10269          *
10270          * "The device server is not capable of supporting a peripheral
10271          * device on this logical unit. For this peripheral qualifier the
10272          * peripheral device type shall be set to 1Fh. All other peripheral
10273          * device type values are reserved for this peripheral qualifier."
10274          *
10275          * Given the text, it would seem that we probably want to report that
10276          * the LUN is offline here.  There is no LUN connected, but we can
10277          * support a LUN at the given LUN number.
10278          *
10279          * In the real world, though, it sounds like things are a little
10280          * different:
10281          *
10282          * - Linux, when presented with a LUN with the offline peripheral
10283          *   qualifier, will create an sg driver instance for it.  So when
10284          *   you attach it to CTL, you wind up with a ton of sg driver
10285          *   instances.  (One for every LUN that Linux bothered to probe.)
10286          *   Linux does this despite the fact that it issues a REPORT LUNs
10287          *   to LUN 0 to get the inventory of supported LUNs.
10288          *
10289          * - There is other anecdotal evidence (from Emulex folks) about
10290          *   arrays that use the offline peripheral qualifier for LUNs that
10291          *   are on the "passive" path in an active/passive array.
10292          *
10293          * So the solution is provide a hopefully reasonable default
10294          * (return bad/no LUN) and allow the user to change the behavior
10295          * with a tunable/sysctl variable.
10296          */
10297         if (lun != NULL)
10298                 inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10299                                   lun->be_lun->lun_type;
10300         else if (ctl_softc->inquiry_pq_no_lun == 0)
10301                 inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10302         else
10303                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10304
10305         /* RMB in byte 2 is 0 */
10306         inq_ptr->version = SCSI_REV_SPC4;
10307
10308         /*
10309          * According to SAM-3, even if a device only supports a single
10310          * level of LUN addressing, it should still set the HISUP bit:
10311          *
10312          * 4.9.1 Logical unit numbers overview
10313          *
10314          * All logical unit number formats described in this standard are
10315          * hierarchical in structure even when only a single level in that
10316          * hierarchy is used. The HISUP bit shall be set to one in the
10317          * standard INQUIRY data (see SPC-2) when any logical unit number
10318          * format described in this standard is used.  Non-hierarchical
10319          * formats are outside the scope of this standard.
10320          *
10321          * Therefore we set the HiSup bit here.
10322          *
10323          * The reponse format is 2, per SPC-3.
10324          */
10325         inq_ptr->response_format = SID_HiSup | 2;
10326
10327         inq_ptr->additional_length = data_len -
10328             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10329         CTL_DEBUG_PRINT(("additional_length = %d\n",
10330                          inq_ptr->additional_length));
10331
10332         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10333         /* 16 bit addressing */
10334         if (port_type == CTL_PORT_SCSI)
10335                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10336         /* XXX set the SID_MultiP bit here if we're actually going to
10337            respond on multiple ports */
10338         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10339
10340         /* 16 bit data bus, synchronous transfers */
10341         if (port_type == CTL_PORT_SCSI)
10342                 inq_ptr->flags = SID_WBus16 | SID_Sync;
10343         /*
10344          * XXX KDM do we want to support tagged queueing on the control
10345          * device at all?
10346          */
10347         if ((lun == NULL)
10348          || (lun->be_lun->lun_type != T_PROCESSOR))
10349                 inq_ptr->flags |= SID_CmdQue;
10350         /*
10351          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10352          * We have 8 bytes for the vendor name, and 16 bytes for the device
10353          * name and 4 bytes for the revision.
10354          */
10355         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10356             "vendor")) == NULL) {
10357                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10358         } else {
10359                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10360                 strncpy(inq_ptr->vendor, val,
10361                     min(sizeof(inq_ptr->vendor), strlen(val)));
10362         }
10363         if (lun == NULL) {
10364                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10365                     sizeof(inq_ptr->product));
10366         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10367                 switch (lun->be_lun->lun_type) {
10368                 case T_DIRECT:
10369                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10370                             sizeof(inq_ptr->product));
10371                         break;
10372                 case T_PROCESSOR:
10373                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10374                             sizeof(inq_ptr->product));
10375                         break;
10376                 default:
10377                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10378                             sizeof(inq_ptr->product));
10379                         break;
10380                 }
10381         } else {
10382                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10383                 strncpy(inq_ptr->product, val,
10384                     min(sizeof(inq_ptr->product), strlen(val)));
10385         }
10386
10387         /*
10388          * XXX make this a macro somewhere so it automatically gets
10389          * incremented when we make changes.
10390          */
10391         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10392             "revision")) == NULL) {
10393                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10394         } else {
10395                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10396                 strncpy(inq_ptr->revision, val,
10397                     min(sizeof(inq_ptr->revision), strlen(val)));
10398         }
10399
10400         /*
10401          * For parallel SCSI, we support double transition and single
10402          * transition clocking.  We also support QAS (Quick Arbitration
10403          * and Selection) and Information Unit transfers on both the
10404          * control and array devices.
10405          */
10406         if (port_type == CTL_PORT_SCSI)
10407                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10408                                     SID_SPI_IUS;
10409
10410         /* SAM-5 (no version claimed) */
10411         scsi_ulto2b(0x00A0, inq_ptr->version1);
10412         /* SPC-4 (no version claimed) */
10413         scsi_ulto2b(0x0460, inq_ptr->version2);
10414         if (port_type == CTL_PORT_FC) {
10415                 /* FCP-2 ANSI INCITS.350:2003 */
10416                 scsi_ulto2b(0x0917, inq_ptr->version3);
10417         } else if (port_type == CTL_PORT_SCSI) {
10418                 /* SPI-4 ANSI INCITS.362:200x */
10419                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10420         } else if (port_type == CTL_PORT_ISCSI) {
10421                 /* iSCSI (no version claimed) */
10422                 scsi_ulto2b(0x0960, inq_ptr->version3);
10423         } else if (port_type == CTL_PORT_SAS) {
10424                 /* SAS (no version claimed) */
10425                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10426         }
10427
10428         if (lun == NULL) {
10429                 /* SBC-4 (no version claimed) */
10430                 scsi_ulto2b(0x0600, inq_ptr->version4);
10431         } else {
10432                 switch (lun->be_lun->lun_type) {
10433                 case T_DIRECT:
10434                         /* SBC-4 (no version claimed) */
10435                         scsi_ulto2b(0x0600, inq_ptr->version4);
10436                         break;
10437                 case T_PROCESSOR:
10438                 default:
10439                         break;
10440                 }
10441         }
10442
10443         ctl_set_success(ctsio);
10444         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10445         ctsio->be_move_done = ctl_config_move_done;
10446         ctl_datamove((union ctl_io *)ctsio);
10447         return (CTL_RETVAL_COMPLETE);
10448 }
10449
10450 int
10451 ctl_inquiry(struct ctl_scsiio *ctsio)
10452 {
10453         struct scsi_inquiry *cdb;
10454         int retval;
10455
10456         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10457
10458         cdb = (struct scsi_inquiry *)ctsio->cdb;
10459         if (cdb->byte2 & SI_EVPD)
10460                 retval = ctl_inquiry_evpd(ctsio);
10461         else if (cdb->page_code == 0)
10462                 retval = ctl_inquiry_std(ctsio);
10463         else {
10464                 ctl_set_invalid_field(ctsio,
10465                                       /*sks_valid*/ 1,
10466                                       /*command*/ 1,
10467                                       /*field*/ 2,
10468                                       /*bit_valid*/ 0,
10469                                       /*bit*/ 0);
10470                 ctl_done((union ctl_io *)ctsio);
10471                 return (CTL_RETVAL_COMPLETE);
10472         }
10473
10474         return (retval);
10475 }
10476
10477 /*
10478  * For known CDB types, parse the LBA and length.
10479  */
10480 static int
10481 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10482 {
10483         if (io->io_hdr.io_type != CTL_IO_SCSI)
10484                 return (1);
10485
10486         switch (io->scsiio.cdb[0]) {
10487         case COMPARE_AND_WRITE: {
10488                 struct scsi_compare_and_write *cdb;
10489
10490                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10491
10492                 *lba = scsi_8btou64(cdb->addr);
10493                 *len = cdb->length;
10494                 break;
10495         }
10496         case READ_6:
10497         case WRITE_6: {
10498                 struct scsi_rw_6 *cdb;
10499
10500                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10501
10502                 *lba = scsi_3btoul(cdb->addr);
10503                 /* only 5 bits are valid in the most significant address byte */
10504                 *lba &= 0x1fffff;
10505                 *len = cdb->length;
10506                 break;
10507         }
10508         case READ_10:
10509         case WRITE_10: {
10510                 struct scsi_rw_10 *cdb;
10511
10512                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10513
10514                 *lba = scsi_4btoul(cdb->addr);
10515                 *len = scsi_2btoul(cdb->length);
10516                 break;
10517         }
10518         case WRITE_VERIFY_10: {
10519                 struct scsi_write_verify_10 *cdb;
10520
10521                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10522
10523                 *lba = scsi_4btoul(cdb->addr);
10524                 *len = scsi_2btoul(cdb->length);
10525                 break;
10526         }
10527         case READ_12:
10528         case WRITE_12: {
10529                 struct scsi_rw_12 *cdb;
10530
10531                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10532
10533                 *lba = scsi_4btoul(cdb->addr);
10534                 *len = scsi_4btoul(cdb->length);
10535                 break;
10536         }
10537         case WRITE_VERIFY_12: {
10538                 struct scsi_write_verify_12 *cdb;
10539
10540                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10541
10542                 *lba = scsi_4btoul(cdb->addr);
10543                 *len = scsi_4btoul(cdb->length);
10544                 break;
10545         }
10546         case READ_16:
10547         case WRITE_16:
10548         case WRITE_ATOMIC_16: {
10549                 struct scsi_rw_16 *cdb;
10550
10551                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10552
10553                 *lba = scsi_8btou64(cdb->addr);
10554                 *len = scsi_4btoul(cdb->length);
10555                 break;
10556         }
10557         case WRITE_VERIFY_16: {
10558                 struct scsi_write_verify_16 *cdb;
10559
10560                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10561
10562                 *lba = scsi_8btou64(cdb->addr);
10563                 *len = scsi_4btoul(cdb->length);
10564                 break;
10565         }
10566         case WRITE_SAME_10: {
10567                 struct scsi_write_same_10 *cdb;
10568
10569                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10570
10571                 *lba = scsi_4btoul(cdb->addr);
10572                 *len = scsi_2btoul(cdb->length);
10573                 break;
10574         }
10575         case WRITE_SAME_16: {
10576                 struct scsi_write_same_16 *cdb;
10577
10578                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10579
10580                 *lba = scsi_8btou64(cdb->addr);
10581                 *len = scsi_4btoul(cdb->length);
10582                 break;
10583         }
10584         case VERIFY_10: {
10585                 struct scsi_verify_10 *cdb;
10586
10587                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10588
10589                 *lba = scsi_4btoul(cdb->addr);
10590                 *len = scsi_2btoul(cdb->length);
10591                 break;
10592         }
10593         case VERIFY_12: {
10594                 struct scsi_verify_12 *cdb;
10595
10596                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10597
10598                 *lba = scsi_4btoul(cdb->addr);
10599                 *len = scsi_4btoul(cdb->length);
10600                 break;
10601         }
10602         case VERIFY_16: {
10603                 struct scsi_verify_16 *cdb;
10604
10605                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10606
10607                 *lba = scsi_8btou64(cdb->addr);
10608                 *len = scsi_4btoul(cdb->length);
10609                 break;
10610         }
10611         case UNMAP: {
10612                 *lba = 0;
10613                 *len = UINT64_MAX;
10614                 break;
10615         }
10616         default:
10617                 return (1);
10618                 break; /* NOTREACHED */
10619         }
10620
10621         return (0);
10622 }
10623
10624 static ctl_action
10625 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2)
10626 {
10627         uint64_t endlba1, endlba2;
10628
10629         endlba1 = lba1 + len1 - 1;
10630         endlba2 = lba2 + len2 - 1;
10631
10632         if ((endlba1 < lba2)
10633          || (endlba2 < lba1))
10634                 return (CTL_ACTION_PASS);
10635         else
10636                 return (CTL_ACTION_BLOCK);
10637 }
10638
10639 static int
10640 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10641 {
10642         struct ctl_ptr_len_flags *ptrlen;
10643         struct scsi_unmap_desc *buf, *end, *range;
10644         uint64_t lba;
10645         uint32_t len;
10646
10647         /* If not UNMAP -- go other way. */
10648         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10649             io->scsiio.cdb[0] != UNMAP)
10650                 return (CTL_ACTION_ERROR);
10651
10652         /* If UNMAP without data -- block and wait for data. */
10653         ptrlen = (struct ctl_ptr_len_flags *)
10654             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10655         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10656             ptrlen->ptr == NULL)
10657                 return (CTL_ACTION_BLOCK);
10658
10659         /* UNMAP with data -- check for collision. */
10660         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10661         end = buf + ptrlen->len / sizeof(*buf);
10662         for (range = buf; range < end; range++) {
10663                 lba = scsi_8btou64(range->lba);
10664                 len = scsi_4btoul(range->length);
10665                 if ((lba < lba2 + len2) && (lba + len > lba2))
10666                         return (CTL_ACTION_BLOCK);
10667         }
10668         return (CTL_ACTION_PASS);
10669 }
10670
10671 static ctl_action
10672 ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10673 {
10674         uint64_t lba1, lba2;
10675         uint64_t len1, len2;
10676         int retval;
10677
10678         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10679                 return (CTL_ACTION_ERROR);
10680
10681         retval = ctl_extent_check_unmap(io2, lba1, len1);
10682         if (retval != CTL_ACTION_ERROR)
10683                 return (retval);
10684
10685         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10686                 return (CTL_ACTION_ERROR);
10687
10688         return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10689 }
10690
10691 static ctl_action
10692 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10693     union ctl_io *ooa_io)
10694 {
10695         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10696         ctl_serialize_action *serialize_row;
10697
10698         /*
10699          * The initiator attempted multiple untagged commands at the same
10700          * time.  Can't do that.
10701          */
10702         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10703          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10704          && ((pending_io->io_hdr.nexus.targ_port ==
10705               ooa_io->io_hdr.nexus.targ_port)
10706           && (pending_io->io_hdr.nexus.initid.id ==
10707               ooa_io->io_hdr.nexus.initid.id))
10708          && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10709                 return (CTL_ACTION_OVERLAP);
10710
10711         /*
10712          * The initiator attempted to send multiple tagged commands with
10713          * the same ID.  (It's fine if different initiators have the same
10714          * tag ID.)
10715          *
10716          * Even if all of those conditions are true, we don't kill the I/O
10717          * if the command ahead of us has been aborted.  We won't end up
10718          * sending it to the FETD, and it's perfectly legal to resend a
10719          * command with the same tag number as long as the previous
10720          * instance of this tag number has been aborted somehow.
10721          */
10722         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10723          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10724          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10725          && ((pending_io->io_hdr.nexus.targ_port ==
10726               ooa_io->io_hdr.nexus.targ_port)
10727           && (pending_io->io_hdr.nexus.initid.id ==
10728               ooa_io->io_hdr.nexus.initid.id))
10729          && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10730                 return (CTL_ACTION_OVERLAP_TAG);
10731
10732         /*
10733          * If we get a head of queue tag, SAM-3 says that we should
10734          * immediately execute it.
10735          *
10736          * What happens if this command would normally block for some other
10737          * reason?  e.g. a request sense with a head of queue tag
10738          * immediately after a write.  Normally that would block, but this
10739          * will result in its getting executed immediately...
10740          *
10741          * We currently return "pass" instead of "skip", so we'll end up
10742          * going through the rest of the queue to check for overlapped tags.
10743          *
10744          * XXX KDM check for other types of blockage first??
10745          */
10746         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10747                 return (CTL_ACTION_PASS);
10748
10749         /*
10750          * Ordered tags have to block until all items ahead of them
10751          * have completed.  If we get called with an ordered tag, we always
10752          * block, if something else is ahead of us in the queue.
10753          */
10754         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10755                 return (CTL_ACTION_BLOCK);
10756
10757         /*
10758          * Simple tags get blocked until all head of queue and ordered tags
10759          * ahead of them have completed.  I'm lumping untagged commands in
10760          * with simple tags here.  XXX KDM is that the right thing to do?
10761          */
10762         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10763           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10764          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10765           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10766                 return (CTL_ACTION_BLOCK);
10767
10768         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10769         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10770
10771         serialize_row = ctl_serialize_table[ooa_entry->seridx];
10772
10773         switch (serialize_row[pending_entry->seridx]) {
10774         case CTL_SER_BLOCK:
10775                 return (CTL_ACTION_BLOCK);
10776         case CTL_SER_EXTENT:
10777                 return (ctl_extent_check(pending_io, ooa_io));
10778         case CTL_SER_EXTENTOPT:
10779                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10780                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10781                         return (ctl_extent_check(pending_io, ooa_io));
10782                 /* FALLTHROUGH */
10783         case CTL_SER_PASS:
10784                 return (CTL_ACTION_PASS);
10785         case CTL_SER_BLOCKOPT:
10786                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10787                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10788                         return (CTL_ACTION_BLOCK);
10789                 return (CTL_ACTION_PASS);
10790         case CTL_SER_SKIP:
10791                 return (CTL_ACTION_SKIP);
10792         default:
10793                 panic("invalid serialization value %d",
10794                       serialize_row[pending_entry->seridx]);
10795         }
10796
10797         return (CTL_ACTION_ERROR);
10798 }
10799
10800 /*
10801  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10802  * Assumptions:
10803  * - pending_io is generally either incoming, or on the blocked queue
10804  * - starting I/O is the I/O we want to start the check with.
10805  */
10806 static ctl_action
10807 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10808               union ctl_io *starting_io)
10809 {
10810         union ctl_io *ooa_io;
10811         ctl_action action;
10812
10813         mtx_assert(&lun->lun_lock, MA_OWNED);
10814
10815         /*
10816          * Run back along the OOA queue, starting with the current
10817          * blocked I/O and going through every I/O before it on the
10818          * queue.  If starting_io is NULL, we'll just end up returning
10819          * CTL_ACTION_PASS.
10820          */
10821         for (ooa_io = starting_io; ooa_io != NULL;
10822              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10823              ooa_links)){
10824
10825                 /*
10826                  * This routine just checks to see whether
10827                  * cur_blocked is blocked by ooa_io, which is ahead
10828                  * of it in the queue.  It doesn't queue/dequeue
10829                  * cur_blocked.
10830                  */
10831                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10832                 switch (action) {
10833                 case CTL_ACTION_BLOCK:
10834                 case CTL_ACTION_OVERLAP:
10835                 case CTL_ACTION_OVERLAP_TAG:
10836                 case CTL_ACTION_SKIP:
10837                 case CTL_ACTION_ERROR:
10838                         return (action);
10839                         break; /* NOTREACHED */
10840                 case CTL_ACTION_PASS:
10841                         break;
10842                 default:
10843                         panic("invalid action %d", action);
10844                         break;  /* NOTREACHED */
10845                 }
10846         }
10847
10848         return (CTL_ACTION_PASS);
10849 }
10850
10851 /*
10852  * Assumptions:
10853  * - An I/O has just completed, and has been removed from the per-LUN OOA
10854  *   queue, so some items on the blocked queue may now be unblocked.
10855  */
10856 static int
10857 ctl_check_blocked(struct ctl_lun *lun)
10858 {
10859         union ctl_io *cur_blocked, *next_blocked;
10860
10861         mtx_assert(&lun->lun_lock, MA_OWNED);
10862
10863         /*
10864          * Run forward from the head of the blocked queue, checking each
10865          * entry against the I/Os prior to it on the OOA queue to see if
10866          * there is still any blockage.
10867          *
10868          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10869          * with our removing a variable on it while it is traversing the
10870          * list.
10871          */
10872         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10873              cur_blocked != NULL; cur_blocked = next_blocked) {
10874                 union ctl_io *prev_ooa;
10875                 ctl_action action;
10876
10877                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10878                                                           blocked_links);
10879
10880                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10881                                                       ctl_ooaq, ooa_links);
10882
10883                 /*
10884                  * If cur_blocked happens to be the first item in the OOA
10885                  * queue now, prev_ooa will be NULL, and the action
10886                  * returned will just be CTL_ACTION_PASS.
10887                  */
10888                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10889
10890                 switch (action) {
10891                 case CTL_ACTION_BLOCK:
10892                         /* Nothing to do here, still blocked */
10893                         break;
10894                 case CTL_ACTION_OVERLAP:
10895                 case CTL_ACTION_OVERLAP_TAG:
10896                         /*
10897                          * This shouldn't happen!  In theory we've already
10898                          * checked this command for overlap...
10899                          */
10900                         break;
10901                 case CTL_ACTION_PASS:
10902                 case CTL_ACTION_SKIP: {
10903                         struct ctl_softc *softc;
10904                         const struct ctl_cmd_entry *entry;
10905                         int isc_retval;
10906
10907                         /*
10908                          * The skip case shouldn't happen, this transaction
10909                          * should have never made it onto the blocked queue.
10910                          */
10911                         /*
10912                          * This I/O is no longer blocked, we can remove it
10913                          * from the blocked queue.  Since this is a TAILQ
10914                          * (doubly linked list), we can do O(1) removals
10915                          * from any place on the list.
10916                          */
10917                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
10918                                      blocked_links);
10919                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10920
10921                         if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
10922                                 /*
10923                                  * Need to send IO back to original side to
10924                                  * run
10925                                  */
10926                                 union ctl_ha_msg msg_info;
10927
10928                                 msg_info.hdr.original_sc =
10929                                         cur_blocked->io_hdr.original_sc;
10930                                 msg_info.hdr.serializing_sc = cur_blocked;
10931                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
10932                                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
10933                                      &msg_info, sizeof(msg_info), 0)) >
10934                                      CTL_HA_STATUS_SUCCESS) {
10935                                         printf("CTL:Check Blocked error from "
10936                                                "ctl_ha_msg_send %d\n",
10937                                                isc_retval);
10938                                 }
10939                                 break;
10940                         }
10941                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
10942                         softc = control_softc;
10943
10944                         /*
10945                          * Check this I/O for LUN state changes that may
10946                          * have happened while this command was blocked.
10947                          * The LUN state may have been changed by a command
10948                          * ahead of us in the queue, so we need to re-check
10949                          * for any states that can be caused by SCSI
10950                          * commands.
10951                          */
10952                         if (ctl_scsiio_lun_check(softc, lun, entry,
10953                                                  &cur_blocked->scsiio) == 0) {
10954                                 cur_blocked->io_hdr.flags |=
10955                                                       CTL_FLAG_IS_WAS_ON_RTR;
10956                                 ctl_enqueue_rtr(cur_blocked);
10957                         } else
10958                                 ctl_done(cur_blocked);
10959                         break;
10960                 }
10961                 default:
10962                         /*
10963                          * This probably shouldn't happen -- we shouldn't
10964                          * get CTL_ACTION_ERROR, or anything else.
10965                          */
10966                         break;
10967                 }
10968         }
10969
10970         return (CTL_RETVAL_COMPLETE);
10971 }
10972
10973 /*
10974  * This routine (with one exception) checks LUN flags that can be set by
10975  * commands ahead of us in the OOA queue.  These flags have to be checked
10976  * when a command initially comes in, and when we pull a command off the
10977  * blocked queue and are preparing to execute it.  The reason we have to
10978  * check these flags for commands on the blocked queue is that the LUN
10979  * state may have been changed by a command ahead of us while we're on the
10980  * blocked queue.
10981  *
10982  * Ordering is somewhat important with these checks, so please pay
10983  * careful attention to the placement of any new checks.
10984  */
10985 static int
10986 ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
10987     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
10988 {
10989         int retval;
10990         uint32_t residx;
10991
10992         retval = 0;
10993
10994         mtx_assert(&lun->lun_lock, MA_OWNED);
10995
10996         /*
10997          * If this shelf is a secondary shelf controller, we have to reject
10998          * any media access commands.
10999          */
11000         if ((ctl_softc->flags & CTL_FLAG_ACTIVE_SHELF) == 0 &&
11001             (entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0) {
11002                 ctl_set_lun_standby(ctsio);
11003                 retval = 1;
11004                 goto bailout;
11005         }
11006
11007         if (entry->pattern & CTL_LUN_PAT_WRITE) {
11008                 if (lun->flags & CTL_LUN_READONLY) {
11009                         ctl_set_sense(ctsio, /*current_error*/ 1,
11010                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11011                             /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11012                         retval = 1;
11013                         goto bailout;
11014                 }
11015                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11016                     .eca_and_aen & SCP_SWP) != 0) {
11017                         ctl_set_sense(ctsio, /*current_error*/ 1,
11018                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11019                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11020                         retval = 1;
11021                         goto bailout;
11022                 }
11023         }
11024
11025         /*
11026          * Check for a reservation conflict.  If this command isn't allowed
11027          * even on reserved LUNs, and if this initiator isn't the one who
11028          * reserved us, reject the command with a reservation conflict.
11029          */
11030         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11031         if ((lun->flags & CTL_LUN_RESERVED)
11032          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11033                 if (lun->res_idx != residx) {
11034                         ctl_set_reservation_conflict(ctsio);
11035                         retval = 1;
11036                         goto bailout;
11037                 }
11038         }
11039
11040         if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11041             (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11042                 /* No reservation or command is allowed. */;
11043         } else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11044             (lun->res_type == SPR_TYPE_WR_EX ||
11045              lun->res_type == SPR_TYPE_WR_EX_RO ||
11046              lun->res_type == SPR_TYPE_WR_EX_AR)) {
11047                 /* The command is allowed for Write Exclusive resv. */;
11048         } else {
11049                 /*
11050                  * if we aren't registered or it's a res holder type
11051                  * reservation and this isn't the res holder then set a
11052                  * conflict.
11053                  */
11054                 if (lun->pr_keys[residx] == 0
11055                  || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11056                         ctl_set_reservation_conflict(ctsio);
11057                         retval = 1;
11058                         goto bailout;
11059                 }
11060
11061         }
11062
11063         if ((lun->flags & CTL_LUN_OFFLINE)
11064          && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11065                 ctl_set_lun_not_ready(ctsio);
11066                 retval = 1;
11067                 goto bailout;
11068         }
11069
11070         /*
11071          * If the LUN is stopped, see if this particular command is allowed
11072          * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11073          */
11074         if ((lun->flags & CTL_LUN_STOPPED)
11075          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11076                 /* "Logical unit not ready, initializing cmd. required" */
11077                 ctl_set_lun_stopped(ctsio);
11078                 retval = 1;
11079                 goto bailout;
11080         }
11081
11082         if ((lun->flags & CTL_LUN_INOPERABLE)
11083          && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11084                 /* "Medium format corrupted" */
11085                 ctl_set_medium_format_corrupted(ctsio);
11086                 retval = 1;
11087                 goto bailout;
11088         }
11089
11090 bailout:
11091         return (retval);
11092
11093 }
11094
11095 static void
11096 ctl_failover_io(union ctl_io *io, int have_lock)
11097 {
11098         ctl_set_busy(&io->scsiio);
11099         ctl_done(io);
11100 }
11101
11102 static void
11103 ctl_failover(void)
11104 {
11105         struct ctl_lun *lun;
11106         struct ctl_softc *ctl_softc;
11107         union ctl_io *next_io, *pending_io;
11108         union ctl_io *io;
11109         int lun_idx;
11110         int i;
11111
11112         ctl_softc = control_softc;
11113
11114         mtx_lock(&ctl_softc->ctl_lock);
11115         /*
11116          * Remove any cmds from the other SC from the rtr queue.  These
11117          * will obviously only be for LUNs for which we're the primary.
11118          * We can't send status or get/send data for these commands.
11119          * Since they haven't been executed yet, we can just remove them.
11120          * We'll either abort them or delete them below, depending on
11121          * which HA mode we're in.
11122          */
11123 #ifdef notyet
11124         mtx_lock(&ctl_softc->queue_lock);
11125         for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11126              io != NULL; io = next_io) {
11127                 next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11128                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11129                         STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11130                                       ctl_io_hdr, links);
11131         }
11132         mtx_unlock(&ctl_softc->queue_lock);
11133 #endif
11134
11135         for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11136                 lun = ctl_softc->ctl_luns[lun_idx];
11137                 if (lun==NULL)
11138                         continue;
11139
11140                 /*
11141                  * Processor LUNs are primary on both sides.
11142                  * XXX will this always be true?
11143                  */
11144                 if (lun->be_lun->lun_type == T_PROCESSOR)
11145                         continue;
11146
11147                 if ((lun->flags & CTL_LUN_PRIMARY_SC)
11148                  && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11149                         printf("FAILOVER: primary lun %d\n", lun_idx);
11150                         /*
11151                          * Remove all commands from the other SC. First from the
11152                          * blocked queue then from the ooa queue. Once we have
11153                          * removed them. Call ctl_check_blocked to see if there
11154                          * is anything that can run.
11155                          */
11156                         for (io = (union ctl_io *)TAILQ_FIRST(
11157                              &lun->blocked_queue); io != NULL; io = next_io) {
11158
11159                                 next_io = (union ctl_io *)TAILQ_NEXT(
11160                                     &io->io_hdr, blocked_links);
11161
11162                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11163                                         TAILQ_REMOVE(&lun->blocked_queue,
11164                                                      &io->io_hdr,blocked_links);
11165                                         io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11166                                         TAILQ_REMOVE(&lun->ooa_queue,
11167                                                      &io->io_hdr, ooa_links);
11168
11169                                         ctl_free_io(io);
11170                                 }
11171                         }
11172
11173                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11174                              io != NULL; io = next_io) {
11175
11176                                 next_io = (union ctl_io *)TAILQ_NEXT(
11177                                     &io->io_hdr, ooa_links);
11178
11179                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11180
11181                                         TAILQ_REMOVE(&lun->ooa_queue,
11182                                                 &io->io_hdr,
11183                                                 ooa_links);
11184
11185                                         ctl_free_io(io);
11186                                 }
11187                         }
11188                         ctl_check_blocked(lun);
11189                 } else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11190                         && (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11191
11192                         printf("FAILOVER: primary lun %d\n", lun_idx);
11193                         /*
11194                          * Abort all commands from the other SC.  We can't
11195                          * send status back for them now.  These should get
11196                          * cleaned up when they are completed or come out
11197                          * for a datamove operation.
11198                          */
11199                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11200                              io != NULL; io = next_io) {
11201                                 next_io = (union ctl_io *)TAILQ_NEXT(
11202                                         &io->io_hdr, ooa_links);
11203
11204                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11205                                         io->io_hdr.flags |= CTL_FLAG_ABORT;
11206                         }
11207                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11208                         && (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11209
11210                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11211
11212                         lun->flags |= CTL_LUN_PRIMARY_SC;
11213
11214                         /*
11215                          * We send all I/O that was sent to this controller
11216                          * and redirected to the other side back with
11217                          * busy status, and have the initiator retry it.
11218                          * Figuring out how much data has been transferred,
11219                          * etc. and picking up where we left off would be 
11220                          * very tricky.
11221                          *
11222                          * XXX KDM need to remove I/O from the blocked
11223                          * queue as well!
11224                          */
11225                         for (pending_io = (union ctl_io *)TAILQ_FIRST(
11226                              &lun->ooa_queue); pending_io != NULL;
11227                              pending_io = next_io) {
11228
11229                                 next_io =  (union ctl_io *)TAILQ_NEXT(
11230                                         &pending_io->io_hdr, ooa_links);
11231
11232                                 pending_io->io_hdr.flags &=
11233                                         ~CTL_FLAG_SENT_2OTHER_SC;
11234
11235                                 if (pending_io->io_hdr.flags &
11236                                     CTL_FLAG_IO_ACTIVE) {
11237                                         pending_io->io_hdr.flags |=
11238                                                 CTL_FLAG_FAILOVER;
11239                                 } else {
11240                                         ctl_set_busy(&pending_io->scsiio);
11241                                         ctl_done(pending_io);
11242                                 }
11243                         }
11244
11245                         /*
11246                          * Build Unit Attention
11247                          */
11248                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11249                                 lun->pending_ua[i] |=
11250                                                      CTL_UA_ASYM_ACC_CHANGE;
11251                         }
11252                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11253                         && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11254                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11255                         /*
11256                          * if the first io on the OOA is not on the RtR queue
11257                          * add it.
11258                          */
11259                         lun->flags |= CTL_LUN_PRIMARY_SC;
11260
11261                         pending_io = (union ctl_io *)TAILQ_FIRST(
11262                             &lun->ooa_queue);
11263                         if (pending_io==NULL) {
11264                                 printf("Nothing on OOA queue\n");
11265                                 continue;
11266                         }
11267
11268                         pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11269                         if ((pending_io->io_hdr.flags &
11270                              CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11271                                 pending_io->io_hdr.flags |=
11272                                     CTL_FLAG_IS_WAS_ON_RTR;
11273                                 ctl_enqueue_rtr(pending_io);
11274                         }
11275 #if 0
11276                         else
11277                         {
11278                                 printf("Tag 0x%04x is running\n",
11279                                       pending_io->scsiio.tag_num);
11280                         }
11281 #endif
11282
11283                         next_io = (union ctl_io *)TAILQ_NEXT(
11284                             &pending_io->io_hdr, ooa_links);
11285                         for (pending_io=next_io; pending_io != NULL;
11286                              pending_io = next_io) {
11287                                 pending_io->io_hdr.flags &=
11288                                     ~CTL_FLAG_SENT_2OTHER_SC;
11289                                 next_io = (union ctl_io *)TAILQ_NEXT(
11290                                         &pending_io->io_hdr, ooa_links);
11291                                 if (pending_io->io_hdr.flags &
11292                                     CTL_FLAG_IS_WAS_ON_RTR) {
11293 #if 0
11294                                         printf("Tag 0x%04x is running\n",
11295                                                 pending_io->scsiio.tag_num);
11296 #endif
11297                                         continue;
11298                                 }
11299
11300                                 switch (ctl_check_ooa(lun, pending_io,
11301                                     (union ctl_io *)TAILQ_PREV(
11302                                     &pending_io->io_hdr, ctl_ooaq,
11303                                     ooa_links))) {
11304
11305                                 case CTL_ACTION_BLOCK:
11306                                         TAILQ_INSERT_TAIL(&lun->blocked_queue,
11307                                                           &pending_io->io_hdr,
11308                                                           blocked_links);
11309                                         pending_io->io_hdr.flags |=
11310                                             CTL_FLAG_BLOCKED;
11311                                         break;
11312                                 case CTL_ACTION_PASS:
11313                                 case CTL_ACTION_SKIP:
11314                                         pending_io->io_hdr.flags |=
11315                                             CTL_FLAG_IS_WAS_ON_RTR;
11316                                         ctl_enqueue_rtr(pending_io);
11317                                         break;
11318                                 case CTL_ACTION_OVERLAP:
11319                                         ctl_set_overlapped_cmd(
11320                                             (struct ctl_scsiio *)pending_io);
11321                                         ctl_done(pending_io);
11322                                         break;
11323                                 case CTL_ACTION_OVERLAP_TAG:
11324                                         ctl_set_overlapped_tag(
11325                                             (struct ctl_scsiio *)pending_io,
11326                                             pending_io->scsiio.tag_num & 0xff);
11327                                         ctl_done(pending_io);
11328                                         break;
11329                                 case CTL_ACTION_ERROR:
11330                                 default:
11331                                         ctl_set_internal_failure(
11332                                                 (struct ctl_scsiio *)pending_io,
11333                                                 0,  // sks_valid
11334                                                 0); //retry count
11335                                         ctl_done(pending_io);
11336                                         break;
11337                                 }
11338                         }
11339
11340                         /*
11341                          * Build Unit Attention
11342                          */
11343                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11344                                 lun->pending_ua[i] |=
11345                                                      CTL_UA_ASYM_ACC_CHANGE;
11346                         }
11347                 } else {
11348                         panic("Unhandled HA mode failover, LUN flags = %#x, "
11349                               "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11350                 }
11351         }
11352         ctl_pause_rtr = 0;
11353         mtx_unlock(&ctl_softc->ctl_lock);
11354 }
11355
11356 static int
11357 ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11358 {
11359         struct ctl_lun *lun;
11360         const struct ctl_cmd_entry *entry;
11361         uint32_t initidx, targ_lun;
11362         int retval;
11363
11364         retval = 0;
11365
11366         lun = NULL;
11367
11368         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11369         if ((targ_lun < CTL_MAX_LUNS)
11370          && ((lun = ctl_softc->ctl_luns[targ_lun]) != NULL)) {
11371                 /*
11372                  * If the LUN is invalid, pretend that it doesn't exist.
11373                  * It will go away as soon as all pending I/O has been
11374                  * completed.
11375                  */
11376                 mtx_lock(&lun->lun_lock);
11377                 if (lun->flags & CTL_LUN_DISABLED) {
11378                         mtx_unlock(&lun->lun_lock);
11379                         lun = NULL;
11380                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11381                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11382                 } else {
11383                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11384                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11385                                 lun->be_lun;
11386                         if (lun->be_lun->lun_type == T_PROCESSOR) {
11387                                 ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11388                         }
11389
11390                         /*
11391                          * Every I/O goes into the OOA queue for a
11392                          * particular LUN, and stays there until completion.
11393                          */
11394                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11395                             ooa_links);
11396                 }
11397         } else {
11398                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11399                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11400         }
11401
11402         /* Get command entry and return error if it is unsuppotyed. */
11403         entry = ctl_validate_command(ctsio);
11404         if (entry == NULL) {
11405                 if (lun)
11406                         mtx_unlock(&lun->lun_lock);
11407                 return (retval);
11408         }
11409
11410         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11411         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11412
11413         /*
11414          * Check to see whether we can send this command to LUNs that don't
11415          * exist.  This should pretty much only be the case for inquiry
11416          * and request sense.  Further checks, below, really require having
11417          * a LUN, so we can't really check the command anymore.  Just put
11418          * it on the rtr queue.
11419          */
11420         if (lun == NULL) {
11421                 if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11422                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11423                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11424                         return (retval);
11425                 }
11426
11427                 ctl_set_unsupported_lun(ctsio);
11428                 ctl_done((union ctl_io *)ctsio);
11429                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11430                 return (retval);
11431         } else {
11432                 /*
11433                  * Make sure we support this particular command on this LUN.
11434                  * e.g., we don't support writes to the control LUN.
11435                  */
11436                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11437                         mtx_unlock(&lun->lun_lock);
11438                         ctl_set_invalid_opcode(ctsio);
11439                         ctl_done((union ctl_io *)ctsio);
11440                         return (retval);
11441                 }
11442         }
11443
11444         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11445
11446 #ifdef CTL_WITH_CA
11447         /*
11448          * If we've got a request sense, it'll clear the contingent
11449          * allegiance condition.  Otherwise, if we have a CA condition for
11450          * this initiator, clear it, because it sent down a command other
11451          * than request sense.
11452          */
11453         if ((ctsio->cdb[0] != REQUEST_SENSE)
11454          && (ctl_is_set(lun->have_ca, initidx)))
11455                 ctl_clear_mask(lun->have_ca, initidx);
11456 #endif
11457
11458         /*
11459          * If the command has this flag set, it handles its own unit
11460          * attention reporting, we shouldn't do anything.  Otherwise we
11461          * check for any pending unit attentions, and send them back to the
11462          * initiator.  We only do this when a command initially comes in,
11463          * not when we pull it off the blocked queue.
11464          *
11465          * According to SAM-3, section 5.3.2, the order that things get
11466          * presented back to the host is basically unit attentions caused
11467          * by some sort of reset event, busy status, reservation conflicts
11468          * or task set full, and finally any other status.
11469          *
11470          * One issue here is that some of the unit attentions we report
11471          * don't fall into the "reset" category (e.g. "reported luns data
11472          * has changed").  So reporting it here, before the reservation
11473          * check, may be technically wrong.  I guess the only thing to do
11474          * would be to check for and report the reset events here, and then
11475          * check for the other unit attention types after we check for a
11476          * reservation conflict.
11477          *
11478          * XXX KDM need to fix this
11479          */
11480         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11481                 ctl_ua_type ua_type;
11482
11483                 if (lun->pending_ua[initidx] != CTL_UA_NONE) {
11484                         scsi_sense_data_type sense_format;
11485
11486                         if (lun != NULL)
11487                                 sense_format = (lun->flags &
11488                                     CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11489                                     SSD_TYPE_FIXED;
11490                         else
11491                                 sense_format = SSD_TYPE_FIXED;
11492
11493                         ua_type = ctl_build_ua(&lun->pending_ua[initidx],
11494                             &ctsio->sense_data, sense_format);
11495                         if (ua_type != CTL_UA_NONE) {
11496                                 ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11497                                 ctsio->io_hdr.status = CTL_SCSI_ERROR |
11498                                                        CTL_AUTOSENSE;
11499                                 ctsio->sense_len = SSD_FULL_SIZE;
11500                                 mtx_unlock(&lun->lun_lock);
11501                                 ctl_done((union ctl_io *)ctsio);
11502                                 return (retval);
11503                         }
11504                 }
11505         }
11506
11507
11508         if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11509                 mtx_unlock(&lun->lun_lock);
11510                 ctl_done((union ctl_io *)ctsio);
11511                 return (retval);
11512         }
11513
11514         /*
11515          * XXX CHD this is where we want to send IO to other side if
11516          * this LUN is secondary on this SC. We will need to make a copy
11517          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11518          * the copy we send as FROM_OTHER.
11519          * We also need to stuff the address of the original IO so we can
11520          * find it easily. Something similar will need be done on the other
11521          * side so when we are done we can find the copy.
11522          */
11523         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11524                 union ctl_ha_msg msg_info;
11525                 int isc_retval;
11526
11527                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11528
11529                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11530                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11531 #if 0
11532                 printf("1. ctsio %p\n", ctsio);
11533 #endif
11534                 msg_info.hdr.serializing_sc = NULL;
11535                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11536                 msg_info.scsi.tag_num = ctsio->tag_num;
11537                 msg_info.scsi.tag_type = ctsio->tag_type;
11538                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11539
11540                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11541
11542                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11543                     (void *)&msg_info, sizeof(msg_info), 0)) >
11544                     CTL_HA_STATUS_SUCCESS) {
11545                         printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11546                                isc_retval);
11547                         printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11548                 } else {
11549 #if 0
11550                         printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11551 #endif
11552                 }
11553
11554                 /*
11555                  * XXX KDM this I/O is off the incoming queue, but hasn't
11556                  * been inserted on any other queue.  We may need to come
11557                  * up with a holding queue while we wait for serialization
11558                  * so that we have an idea of what we're waiting for from
11559                  * the other side.
11560                  */
11561                 mtx_unlock(&lun->lun_lock);
11562                 return (retval);
11563         }
11564
11565         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11566                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11567                               ctl_ooaq, ooa_links))) {
11568         case CTL_ACTION_BLOCK:
11569                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11570                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11571                                   blocked_links);
11572                 mtx_unlock(&lun->lun_lock);
11573                 return (retval);
11574         case CTL_ACTION_PASS:
11575         case CTL_ACTION_SKIP:
11576                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11577                 mtx_unlock(&lun->lun_lock);
11578                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11579                 break;
11580         case CTL_ACTION_OVERLAP:
11581                 mtx_unlock(&lun->lun_lock);
11582                 ctl_set_overlapped_cmd(ctsio);
11583                 ctl_done((union ctl_io *)ctsio);
11584                 break;
11585         case CTL_ACTION_OVERLAP_TAG:
11586                 mtx_unlock(&lun->lun_lock);
11587                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11588                 ctl_done((union ctl_io *)ctsio);
11589                 break;
11590         case CTL_ACTION_ERROR:
11591         default:
11592                 mtx_unlock(&lun->lun_lock);
11593                 ctl_set_internal_failure(ctsio,
11594                                          /*sks_valid*/ 0,
11595                                          /*retry_count*/ 0);
11596                 ctl_done((union ctl_io *)ctsio);
11597                 break;
11598         }
11599         return (retval);
11600 }
11601
11602 const struct ctl_cmd_entry *
11603 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11604 {
11605         const struct ctl_cmd_entry *entry;
11606         int service_action;
11607
11608         entry = &ctl_cmd_table[ctsio->cdb[0]];
11609         if (sa)
11610                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11611         if (entry->flags & CTL_CMD_FLAG_SA5) {
11612                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11613                 entry = &((const struct ctl_cmd_entry *)
11614                     entry->execute)[service_action];
11615         }
11616         return (entry);
11617 }
11618
11619 const struct ctl_cmd_entry *
11620 ctl_validate_command(struct ctl_scsiio *ctsio)
11621 {
11622         const struct ctl_cmd_entry *entry;
11623         int i, sa;
11624         uint8_t diff;
11625
11626         entry = ctl_get_cmd_entry(ctsio, &sa);
11627         if (entry->execute == NULL) {
11628                 if (sa)
11629                         ctl_set_invalid_field(ctsio,
11630                                               /*sks_valid*/ 1,
11631                                               /*command*/ 1,
11632                                               /*field*/ 1,
11633                                               /*bit_valid*/ 1,
11634                                               /*bit*/ 4);
11635                 else
11636                         ctl_set_invalid_opcode(ctsio);
11637                 ctl_done((union ctl_io *)ctsio);
11638                 return (NULL);
11639         }
11640         KASSERT(entry->length > 0,
11641             ("Not defined length for command 0x%02x/0x%02x",
11642              ctsio->cdb[0], ctsio->cdb[1]));
11643         for (i = 1; i < entry->length; i++) {
11644                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11645                 if (diff == 0)
11646                         continue;
11647                 ctl_set_invalid_field(ctsio,
11648                                       /*sks_valid*/ 1,
11649                                       /*command*/ 1,
11650                                       /*field*/ i,
11651                                       /*bit_valid*/ 1,
11652                                       /*bit*/ fls(diff) - 1);
11653                 ctl_done((union ctl_io *)ctsio);
11654                 return (NULL);
11655         }
11656         return (entry);
11657 }
11658
11659 static int
11660 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11661 {
11662
11663         switch (lun_type) {
11664         case T_PROCESSOR:
11665                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11666                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11667                         return (0);
11668                 break;
11669         case T_DIRECT:
11670                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11671                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11672                         return (0);
11673                 break;
11674         default:
11675                 return (0);
11676         }
11677         return (1);
11678 }
11679
11680 static int
11681 ctl_scsiio(struct ctl_scsiio *ctsio)
11682 {
11683         int retval;
11684         const struct ctl_cmd_entry *entry;
11685
11686         retval = CTL_RETVAL_COMPLETE;
11687
11688         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11689
11690         entry = ctl_get_cmd_entry(ctsio, NULL);
11691
11692         /*
11693          * If this I/O has been aborted, just send it straight to
11694          * ctl_done() without executing it.
11695          */
11696         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11697                 ctl_done((union ctl_io *)ctsio);
11698                 goto bailout;
11699         }
11700
11701         /*
11702          * All the checks should have been handled by ctl_scsiio_precheck().
11703          * We should be clear now to just execute the I/O.
11704          */
11705         retval = entry->execute(ctsio);
11706
11707 bailout:
11708         return (retval);
11709 }
11710
11711 /*
11712  * Since we only implement one target right now, a bus reset simply resets
11713  * our single target.
11714  */
11715 static int
11716 ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11717 {
11718         return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11719 }
11720
11721 static int
11722 ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11723                  ctl_ua_type ua_type)
11724 {
11725         struct ctl_lun *lun;
11726         int retval;
11727
11728         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11729                 union ctl_ha_msg msg_info;
11730
11731                 io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11732                 msg_info.hdr.nexus = io->io_hdr.nexus;
11733                 if (ua_type==CTL_UA_TARG_RESET)
11734                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11735                 else
11736                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
11737                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11738                 msg_info.hdr.original_sc = NULL;
11739                 msg_info.hdr.serializing_sc = NULL;
11740                 if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11741                     (void *)&msg_info, sizeof(msg_info), 0)) {
11742                 }
11743         }
11744         retval = 0;
11745
11746         mtx_lock(&ctl_softc->ctl_lock);
11747         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11748                 retval += ctl_lun_reset(lun, io, ua_type);
11749         mtx_unlock(&ctl_softc->ctl_lock);
11750
11751         return (retval);
11752 }
11753
11754 /*
11755  * The LUN should always be set.  The I/O is optional, and is used to
11756  * distinguish between I/Os sent by this initiator, and by other
11757  * initiators.  We set unit attention for initiators other than this one.
11758  * SAM-3 is vague on this point.  It does say that a unit attention should
11759  * be established for other initiators when a LUN is reset (see section
11760  * 5.7.3), but it doesn't specifically say that the unit attention should
11761  * be established for this particular initiator when a LUN is reset.  Here
11762  * is the relevant text, from SAM-3 rev 8:
11763  *
11764  * 5.7.2 When a SCSI initiator port aborts its own tasks
11765  *
11766  * When a SCSI initiator port causes its own task(s) to be aborted, no
11767  * notification that the task(s) have been aborted shall be returned to
11768  * the SCSI initiator port other than the completion response for the
11769  * command or task management function action that caused the task(s) to
11770  * be aborted and notification(s) associated with related effects of the
11771  * action (e.g., a reset unit attention condition).
11772  *
11773  * XXX KDM for now, we're setting unit attention for all initiators.
11774  */
11775 static int
11776 ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11777 {
11778         union ctl_io *xio;
11779 #if 0
11780         uint32_t initidx;
11781 #endif
11782         int i;
11783
11784         mtx_lock(&lun->lun_lock);
11785         /*
11786          * Run through the OOA queue and abort each I/O.
11787          */
11788 #if 0
11789         TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11790 #endif
11791         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11792              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11793                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11794         }
11795
11796         /*
11797          * This version sets unit attention for every
11798          */
11799 #if 0
11800         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11801         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11802                 if (initidx == i)
11803                         continue;
11804                 lun->pending_ua[i] |= ua_type;
11805         }
11806 #endif
11807
11808         /*
11809          * A reset (any kind, really) clears reservations established with
11810          * RESERVE/RELEASE.  It does not clear reservations established
11811          * with PERSISTENT RESERVE OUT, but we don't support that at the
11812          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11813          * reservations made with the RESERVE/RELEASE commands, because
11814          * those commands are obsolete in SPC-3.
11815          */
11816         lun->flags &= ~CTL_LUN_RESERVED;
11817
11818         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11819 #ifdef CTL_WITH_CA
11820                 ctl_clear_mask(lun->have_ca, i);
11821 #endif
11822                 lun->pending_ua[i] |= ua_type;
11823         }
11824         mtx_unlock(&lun->lun_lock);
11825
11826         return (0);
11827 }
11828
11829 static void
11830 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11831     int other_sc)
11832 {
11833         union ctl_io *xio;
11834
11835         mtx_assert(&lun->lun_lock, MA_OWNED);
11836
11837         /*
11838          * Run through the OOA queue and attempt to find the given I/O.
11839          * The target port, initiator ID, tag type and tag number have to
11840          * match the values that we got from the initiator.  If we have an
11841          * untagged command to abort, simply abort the first untagged command
11842          * we come to.  We only allow one untagged command at a time of course.
11843          */
11844         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11845              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11846
11847                 if ((targ_port == UINT32_MAX ||
11848                      targ_port == xio->io_hdr.nexus.targ_port) &&
11849                     (init_id == UINT32_MAX ||
11850                      init_id == xio->io_hdr.nexus.initid.id)) {
11851                         if (targ_port != xio->io_hdr.nexus.targ_port ||
11852                             init_id != xio->io_hdr.nexus.initid.id)
11853                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11854                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
11855                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11856                                 union ctl_ha_msg msg_info;
11857
11858                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
11859                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11860                                 msg_info.task.tag_num = xio->scsiio.tag_num;
11861                                 msg_info.task.tag_type = xio->scsiio.tag_type;
11862                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11863                                 msg_info.hdr.original_sc = NULL;
11864                                 msg_info.hdr.serializing_sc = NULL;
11865                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11866                                     (void *)&msg_info, sizeof(msg_info), 0);
11867                         }
11868                 }
11869         }
11870 }
11871
11872 static int
11873 ctl_abort_task_set(union ctl_io *io)
11874 {
11875         struct ctl_softc *softc = control_softc;
11876         struct ctl_lun *lun;
11877         uint32_t targ_lun;
11878
11879         /*
11880          * Look up the LUN.
11881          */
11882         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11883         mtx_lock(&softc->ctl_lock);
11884         if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
11885                 lun = softc->ctl_luns[targ_lun];
11886         else {
11887                 mtx_unlock(&softc->ctl_lock);
11888                 return (1);
11889         }
11890
11891         mtx_lock(&lun->lun_lock);
11892         mtx_unlock(&softc->ctl_lock);
11893         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11894                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11895                     io->io_hdr.nexus.initid.id,
11896                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11897         } else { /* CTL_TASK_CLEAR_TASK_SET */
11898                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11899                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11900         }
11901         mtx_unlock(&lun->lun_lock);
11902         return (0);
11903 }
11904
11905 static int
11906 ctl_i_t_nexus_reset(union ctl_io *io)
11907 {
11908         struct ctl_softc *softc = control_softc;
11909         struct ctl_lun *lun;
11910         uint32_t initidx, residx;
11911
11912         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11913         residx = ctl_get_resindex(&io->io_hdr.nexus);
11914         mtx_lock(&softc->ctl_lock);
11915         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11916                 mtx_lock(&lun->lun_lock);
11917                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11918                     io->io_hdr.nexus.initid.id,
11919                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11920 #ifdef CTL_WITH_CA
11921                 ctl_clear_mask(lun->have_ca, initidx);
11922 #endif
11923                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
11924                         lun->flags &= ~CTL_LUN_RESERVED;
11925                 lun->pending_ua[initidx] |= CTL_UA_I_T_NEXUS_LOSS;
11926                 mtx_unlock(&lun->lun_lock);
11927         }
11928         mtx_unlock(&softc->ctl_lock);
11929         return (0);
11930 }
11931
11932 static int
11933 ctl_abort_task(union ctl_io *io)
11934 {
11935         union ctl_io *xio;
11936         struct ctl_lun *lun;
11937         struct ctl_softc *ctl_softc;
11938 #if 0
11939         struct sbuf sb;
11940         char printbuf[128];
11941 #endif
11942         int found;
11943         uint32_t targ_lun;
11944
11945         ctl_softc = control_softc;
11946         found = 0;
11947
11948         /*
11949          * Look up the LUN.
11950          */
11951         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11952         mtx_lock(&ctl_softc->ctl_lock);
11953         if ((targ_lun < CTL_MAX_LUNS)
11954          && (ctl_softc->ctl_luns[targ_lun] != NULL))
11955                 lun = ctl_softc->ctl_luns[targ_lun];
11956         else {
11957                 mtx_unlock(&ctl_softc->ctl_lock);
11958                 return (1);
11959         }
11960
11961 #if 0
11962         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11963                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11964 #endif
11965
11966         mtx_lock(&lun->lun_lock);
11967         mtx_unlock(&ctl_softc->ctl_lock);
11968         /*
11969          * Run through the OOA queue and attempt to find the given I/O.
11970          * The target port, initiator ID, tag type and tag number have to
11971          * match the values that we got from the initiator.  If we have an
11972          * untagged command to abort, simply abort the first untagged command
11973          * we come to.  We only allow one untagged command at a time of course.
11974          */
11975 #if 0
11976         TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11977 #endif
11978         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11979              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11980 #if 0
11981                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
11982
11983                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
11984                             lun->lun, xio->scsiio.tag_num,
11985                             xio->scsiio.tag_type,
11986                             (xio->io_hdr.blocked_links.tqe_prev
11987                             == NULL) ? "" : " BLOCKED",
11988                             (xio->io_hdr.flags &
11989                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
11990                             (xio->io_hdr.flags &
11991                             CTL_FLAG_ABORT) ? " ABORT" : "",
11992                             (xio->io_hdr.flags &
11993                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
11994                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
11995                 sbuf_finish(&sb);
11996                 printf("%s\n", sbuf_data(&sb));
11997 #endif
11998
11999                 if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12000                  && (xio->io_hdr.nexus.initid.id ==
12001                      io->io_hdr.nexus.initid.id)) {
12002                         /*
12003                          * If the abort says that the task is untagged, the
12004                          * task in the queue must be untagged.  Otherwise,
12005                          * we just check to see whether the tag numbers
12006                          * match.  This is because the QLogic firmware
12007                          * doesn't pass back the tag type in an abort
12008                          * request.
12009                          */
12010 #if 0
12011                         if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12012                           && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12013                          || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12014 #endif
12015                         /*
12016                          * XXX KDM we've got problems with FC, because it
12017                          * doesn't send down a tag type with aborts.  So we
12018                          * can only really go by the tag number...
12019                          * This may cause problems with parallel SCSI.
12020                          * Need to figure that out!!
12021                          */
12022                         if (xio->scsiio.tag_num == io->taskio.tag_num) {
12023                                 xio->io_hdr.flags |= CTL_FLAG_ABORT;
12024                                 found = 1;
12025                                 if ((io->io_hdr.flags &
12026                                      CTL_FLAG_FROM_OTHER_SC) == 0 &&
12027                                     !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12028                                         union ctl_ha_msg msg_info;
12029
12030                                         io->io_hdr.flags |=
12031                                                         CTL_FLAG_SENT_2OTHER_SC;
12032                                         msg_info.hdr.nexus = io->io_hdr.nexus;
12033                                         msg_info.task.task_action =
12034                                                 CTL_TASK_ABORT_TASK;
12035                                         msg_info.task.tag_num =
12036                                                 io->taskio.tag_num;
12037                                         msg_info.task.tag_type =
12038                                                 io->taskio.tag_type;
12039                                         msg_info.hdr.msg_type =
12040                                                 CTL_MSG_MANAGE_TASKS;
12041                                         msg_info.hdr.original_sc = NULL;
12042                                         msg_info.hdr.serializing_sc = NULL;
12043 #if 0
12044                                         printf("Sent Abort to other side\n");
12045 #endif
12046                                         if (CTL_HA_STATUS_SUCCESS !=
12047                                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12048                                                 (void *)&msg_info,
12049                                                 sizeof(msg_info), 0)) {
12050                                         }
12051                                 }
12052 #if 0
12053                                 printf("ctl_abort_task: found I/O to abort\n");
12054 #endif
12055                                 break;
12056                         }
12057                 }
12058         }
12059         mtx_unlock(&lun->lun_lock);
12060
12061         if (found == 0) {
12062                 /*
12063                  * This isn't really an error.  It's entirely possible for
12064                  * the abort and command completion to cross on the wire.
12065                  * This is more of an informative/diagnostic error.
12066                  */
12067 #if 0
12068                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12069                        "%d:%d:%d:%d tag %d type %d\n",
12070                        io->io_hdr.nexus.initid.id,
12071                        io->io_hdr.nexus.targ_port,
12072                        io->io_hdr.nexus.targ_target.id,
12073                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12074                        io->taskio.tag_type);
12075 #endif
12076         }
12077         return (0);
12078 }
12079
12080 static void
12081 ctl_run_task(union ctl_io *io)
12082 {
12083         struct ctl_softc *ctl_softc = control_softc;
12084         int retval = 1;
12085         const char *task_desc;
12086
12087         CTL_DEBUG_PRINT(("ctl_run_task\n"));
12088
12089         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12090             ("ctl_run_task: Unextected io_type %d\n",
12091              io->io_hdr.io_type));
12092
12093         task_desc = ctl_scsi_task_string(&io->taskio);
12094         if (task_desc != NULL) {
12095 #ifdef NEEDTOPORT
12096                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12097                             CTL_TASK_REPORT,
12098                             csevent_LogType_Trace,
12099                             csevent_Severity_Information,
12100                             csevent_AlertLevel_Green,
12101                             csevent_FRU_Firmware,
12102                             csevent_FRU_Unknown,
12103                             "CTL: received task: %s",task_desc);
12104 #endif
12105         } else {
12106 #ifdef NEEDTOPORT
12107                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12108                             CTL_TASK_REPORT,
12109                             csevent_LogType_Trace,
12110                             csevent_Severity_Information,
12111                             csevent_AlertLevel_Green,
12112                             csevent_FRU_Firmware,
12113                             csevent_FRU_Unknown,
12114                             "CTL: received unknown task "
12115                             "type: %d (%#x)",
12116                             io->taskio.task_action,
12117                             io->taskio.task_action);
12118 #endif
12119         }
12120         switch (io->taskio.task_action) {
12121         case CTL_TASK_ABORT_TASK:
12122                 retval = ctl_abort_task(io);
12123                 break;
12124         case CTL_TASK_ABORT_TASK_SET:
12125         case CTL_TASK_CLEAR_TASK_SET:
12126                 retval = ctl_abort_task_set(io);
12127                 break;
12128         case CTL_TASK_CLEAR_ACA:
12129                 break;
12130         case CTL_TASK_I_T_NEXUS_RESET:
12131                 retval = ctl_i_t_nexus_reset(io);
12132                 break;
12133         case CTL_TASK_LUN_RESET: {
12134                 struct ctl_lun *lun;
12135                 uint32_t targ_lun;
12136
12137                 targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12138                 mtx_lock(&ctl_softc->ctl_lock);
12139                 if ((targ_lun < CTL_MAX_LUNS)
12140                  && (ctl_softc->ctl_luns[targ_lun] != NULL))
12141                         lun = ctl_softc->ctl_luns[targ_lun];
12142                 else {
12143                         mtx_unlock(&ctl_softc->ctl_lock);
12144                         retval = 1;
12145                         break;
12146                 }
12147
12148                 if (!(io->io_hdr.flags &
12149                     CTL_FLAG_FROM_OTHER_SC)) {
12150                         union ctl_ha_msg msg_info;
12151
12152                         io->io_hdr.flags |=
12153                                 CTL_FLAG_SENT_2OTHER_SC;
12154                         msg_info.hdr.msg_type =
12155                                 CTL_MSG_MANAGE_TASKS;
12156                         msg_info.hdr.nexus = io->io_hdr.nexus;
12157                         msg_info.task.task_action =
12158                                 CTL_TASK_LUN_RESET;
12159                         msg_info.hdr.original_sc = NULL;
12160                         msg_info.hdr.serializing_sc = NULL;
12161                         if (CTL_HA_STATUS_SUCCESS !=
12162                             ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12163                             (void *)&msg_info,
12164                             sizeof(msg_info), 0)) {
12165                         }
12166                 }
12167
12168                 retval = ctl_lun_reset(lun, io,
12169                                        CTL_UA_LUN_RESET);
12170                 mtx_unlock(&ctl_softc->ctl_lock);
12171                 break;
12172         }
12173         case CTL_TASK_TARGET_RESET:
12174                 retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12175                 break;
12176         case CTL_TASK_BUS_RESET:
12177                 retval = ctl_bus_reset(ctl_softc, io);
12178                 break;
12179         case CTL_TASK_PORT_LOGIN:
12180                 break;
12181         case CTL_TASK_PORT_LOGOUT:
12182                 break;
12183         default:
12184                 printf("ctl_run_task: got unknown task management event %d\n",
12185                        io->taskio.task_action);
12186                 break;
12187         }
12188         if (retval == 0)
12189                 io->io_hdr.status = CTL_SUCCESS;
12190         else
12191                 io->io_hdr.status = CTL_ERROR;
12192         ctl_done(io);
12193 }
12194
12195 /*
12196  * For HA operation.  Handle commands that come in from the other
12197  * controller.
12198  */
12199 static void
12200 ctl_handle_isc(union ctl_io *io)
12201 {
12202         int free_io;
12203         struct ctl_lun *lun;
12204         struct ctl_softc *ctl_softc;
12205         uint32_t targ_lun;
12206
12207         ctl_softc = control_softc;
12208
12209         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12210         lun = ctl_softc->ctl_luns[targ_lun];
12211
12212         switch (io->io_hdr.msg_type) {
12213         case CTL_MSG_SERIALIZE:
12214                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12215                 break;
12216         case CTL_MSG_R2R: {
12217                 const struct ctl_cmd_entry *entry;
12218
12219                 /*
12220                  * This is only used in SER_ONLY mode.
12221                  */
12222                 free_io = 0;
12223                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12224                 mtx_lock(&lun->lun_lock);
12225                 if (ctl_scsiio_lun_check(ctl_softc, lun,
12226                     entry, (struct ctl_scsiio *)io) != 0) {
12227                         mtx_unlock(&lun->lun_lock);
12228                         ctl_done(io);
12229                         break;
12230                 }
12231                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12232                 mtx_unlock(&lun->lun_lock);
12233                 ctl_enqueue_rtr(io);
12234                 break;
12235         }
12236         case CTL_MSG_FINISH_IO:
12237                 if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12238                         free_io = 0;
12239                         ctl_done(io);
12240                 } else {
12241                         free_io = 1;
12242                         mtx_lock(&lun->lun_lock);
12243                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12244                                      ooa_links);
12245                         ctl_check_blocked(lun);
12246                         mtx_unlock(&lun->lun_lock);
12247                 }
12248                 break;
12249         case CTL_MSG_PERS_ACTION:
12250                 ctl_hndl_per_res_out_on_other_sc(
12251                         (union ctl_ha_msg *)&io->presio.pr_msg);
12252                 free_io = 1;
12253                 break;
12254         case CTL_MSG_BAD_JUJU:
12255                 free_io = 0;
12256                 ctl_done(io);
12257                 break;
12258         case CTL_MSG_DATAMOVE:
12259                 /* Only used in XFER mode */
12260                 free_io = 0;
12261                 ctl_datamove_remote(io);
12262                 break;
12263         case CTL_MSG_DATAMOVE_DONE:
12264                 /* Only used in XFER mode */
12265                 free_io = 0;
12266                 io->scsiio.be_move_done(io);
12267                 break;
12268         default:
12269                 free_io = 1;
12270                 printf("%s: Invalid message type %d\n",
12271                        __func__, io->io_hdr.msg_type);
12272                 break;
12273         }
12274         if (free_io)
12275                 ctl_free_io(io);
12276
12277 }
12278
12279
12280 /*
12281  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12282  * there is no match.
12283  */
12284 static ctl_lun_error_pattern
12285 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12286 {
12287         const struct ctl_cmd_entry *entry;
12288         ctl_lun_error_pattern filtered_pattern, pattern;
12289
12290         pattern = desc->error_pattern;
12291
12292         /*
12293          * XXX KDM we need more data passed into this function to match a
12294          * custom pattern, and we actually need to implement custom pattern
12295          * matching.
12296          */
12297         if (pattern & CTL_LUN_PAT_CMD)
12298                 return (CTL_LUN_PAT_CMD);
12299
12300         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12301                 return (CTL_LUN_PAT_ANY);
12302
12303         entry = ctl_get_cmd_entry(ctsio, NULL);
12304
12305         filtered_pattern = entry->pattern & pattern;
12306
12307         /*
12308          * If the user requested specific flags in the pattern (e.g.
12309          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12310          * flags.
12311          *
12312          * If the user did not specify any flags, it doesn't matter whether
12313          * or not the command supports the flags.
12314          */
12315         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12316              (pattern & ~CTL_LUN_PAT_MASK))
12317                 return (CTL_LUN_PAT_NONE);
12318
12319         /*
12320          * If the user asked for a range check, see if the requested LBA
12321          * range overlaps with this command's LBA range.
12322          */
12323         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12324                 uint64_t lba1;
12325                 uint64_t len1;
12326                 ctl_action action;
12327                 int retval;
12328
12329                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12330                 if (retval != 0)
12331                         return (CTL_LUN_PAT_NONE);
12332
12333                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12334                                               desc->lba_range.len);
12335                 /*
12336                  * A "pass" means that the LBA ranges don't overlap, so
12337                  * this doesn't match the user's range criteria.
12338                  */
12339                 if (action == CTL_ACTION_PASS)
12340                         return (CTL_LUN_PAT_NONE);
12341         }
12342
12343         return (filtered_pattern);
12344 }
12345
12346 static void
12347 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12348 {
12349         struct ctl_error_desc *desc, *desc2;
12350
12351         mtx_assert(&lun->lun_lock, MA_OWNED);
12352
12353         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12354                 ctl_lun_error_pattern pattern;
12355                 /*
12356                  * Check to see whether this particular command matches
12357                  * the pattern in the descriptor.
12358                  */
12359                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12360                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12361                         continue;
12362
12363                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12364                 case CTL_LUN_INJ_ABORTED:
12365                         ctl_set_aborted(&io->scsiio);
12366                         break;
12367                 case CTL_LUN_INJ_MEDIUM_ERR:
12368                         ctl_set_medium_error(&io->scsiio);
12369                         break;
12370                 case CTL_LUN_INJ_UA:
12371                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12372                          * OCCURRED */
12373                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12374                         break;
12375                 case CTL_LUN_INJ_CUSTOM:
12376                         /*
12377                          * We're assuming the user knows what he is doing.
12378                          * Just copy the sense information without doing
12379                          * checks.
12380                          */
12381                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12382                               ctl_min(sizeof(desc->custom_sense),
12383                                       sizeof(io->scsiio.sense_data)));
12384                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12385                         io->scsiio.sense_len = SSD_FULL_SIZE;
12386                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12387                         break;
12388                 case CTL_LUN_INJ_NONE:
12389                 default:
12390                         /*
12391                          * If this is an error injection type we don't know
12392                          * about, clear the continuous flag (if it is set)
12393                          * so it will get deleted below.
12394                          */
12395                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12396                         break;
12397                 }
12398                 /*
12399                  * By default, each error injection action is a one-shot
12400                  */
12401                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12402                         continue;
12403
12404                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12405
12406                 free(desc, M_CTL);
12407         }
12408 }
12409
12410 #ifdef CTL_IO_DELAY
12411 static void
12412 ctl_datamove_timer_wakeup(void *arg)
12413 {
12414         union ctl_io *io;
12415
12416         io = (union ctl_io *)arg;
12417
12418         ctl_datamove(io);
12419 }
12420 #endif /* CTL_IO_DELAY */
12421
12422 void
12423 ctl_datamove(union ctl_io *io)
12424 {
12425         void (*fe_datamove)(union ctl_io *io);
12426
12427         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12428
12429         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12430
12431 #ifdef CTL_TIME_IO
12432         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12433                 char str[256];
12434                 char path_str[64];
12435                 struct sbuf sb;
12436
12437                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12438                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12439
12440                 sbuf_cat(&sb, path_str);
12441                 switch (io->io_hdr.io_type) {
12442                 case CTL_IO_SCSI:
12443                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12444                         sbuf_printf(&sb, "\n");
12445                         sbuf_cat(&sb, path_str);
12446                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12447                                     io->scsiio.tag_num, io->scsiio.tag_type);
12448                         break;
12449                 case CTL_IO_TASK:
12450                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12451                                     "Tag Type: %d\n", io->taskio.task_action,
12452                                     io->taskio.tag_num, io->taskio.tag_type);
12453                         break;
12454                 default:
12455                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12456                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12457                         break;
12458                 }
12459                 sbuf_cat(&sb, path_str);
12460                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12461                             (intmax_t)time_uptime - io->io_hdr.start_time);
12462                 sbuf_finish(&sb);
12463                 printf("%s", sbuf_data(&sb));
12464         }
12465 #endif /* CTL_TIME_IO */
12466
12467 #ifdef CTL_IO_DELAY
12468         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12469                 struct ctl_lun *lun;
12470
12471                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12472
12473                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12474         } else {
12475                 struct ctl_lun *lun;
12476
12477                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12478                 if ((lun != NULL)
12479                  && (lun->delay_info.datamove_delay > 0)) {
12480                         struct callout *callout;
12481
12482                         callout = (struct callout *)&io->io_hdr.timer_bytes;
12483                         callout_init(callout, /*mpsafe*/ 1);
12484                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12485                         callout_reset(callout,
12486                                       lun->delay_info.datamove_delay * hz,
12487                                       ctl_datamove_timer_wakeup, io);
12488                         if (lun->delay_info.datamove_type ==
12489                             CTL_DELAY_TYPE_ONESHOT)
12490                                 lun->delay_info.datamove_delay = 0;
12491                         return;
12492                 }
12493         }
12494 #endif
12495
12496         /*
12497          * This command has been aborted.  Set the port status, so we fail
12498          * the data move.
12499          */
12500         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12501                 printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12502                        io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12503                        io->io_hdr.nexus.targ_port,
12504                        (uintmax_t)io->io_hdr.nexus.targ_target.id,
12505                        io->io_hdr.nexus.targ_lun);
12506                 io->io_hdr.port_status = 31337;
12507                 /*
12508                  * Note that the backend, in this case, will get the
12509                  * callback in its context.  In other cases it may get
12510                  * called in the frontend's interrupt thread context.
12511                  */
12512                 io->scsiio.be_move_done(io);
12513                 return;
12514         }
12515
12516         /* Don't confuse frontend with zero length data move. */
12517         if (io->scsiio.kern_data_len == 0) {
12518                 io->scsiio.be_move_done(io);
12519                 return;
12520         }
12521
12522         /*
12523          * If we're in XFER mode and this I/O is from the other shelf
12524          * controller, we need to send the DMA to the other side to
12525          * actually transfer the data to/from the host.  In serialize only
12526          * mode the transfer happens below CTL and ctl_datamove() is only
12527          * called on the machine that originally received the I/O.
12528          */
12529         if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12530          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12531                 union ctl_ha_msg msg;
12532                 uint32_t sg_entries_sent;
12533                 int do_sg_copy;
12534                 int i;
12535
12536                 memset(&msg, 0, sizeof(msg));
12537                 msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12538                 msg.hdr.original_sc = io->io_hdr.original_sc;
12539                 msg.hdr.serializing_sc = io;
12540                 msg.hdr.nexus = io->io_hdr.nexus;
12541                 msg.dt.flags = io->io_hdr.flags;
12542                 /*
12543                  * We convert everything into a S/G list here.  We can't
12544                  * pass by reference, only by value between controllers.
12545                  * So we can't pass a pointer to the S/G list, only as many
12546                  * S/G entries as we can fit in here.  If it's possible for
12547                  * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12548                  * then we need to break this up into multiple transfers.
12549                  */
12550                 if (io->scsiio.kern_sg_entries == 0) {
12551                         msg.dt.kern_sg_entries = 1;
12552                         /*
12553                          * If this is in cached memory, flush the cache
12554                          * before we send the DMA request to the other
12555                          * controller.  We want to do this in either the
12556                          * read or the write case.  The read case is
12557                          * straightforward.  In the write case, we want to
12558                          * make sure nothing is in the local cache that
12559                          * could overwrite the DMAed data.
12560                          */
12561                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12562                                 /*
12563                                  * XXX KDM use bus_dmamap_sync() here.
12564                                  */
12565                         }
12566
12567                         /*
12568                          * Convert to a physical address if this is a
12569                          * virtual address.
12570                          */
12571                         if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12572                                 msg.dt.sg_list[0].addr =
12573                                         io->scsiio.kern_data_ptr;
12574                         } else {
12575                                 /*
12576                                  * XXX KDM use busdma here!
12577                                  */
12578 #if 0
12579                                 msg.dt.sg_list[0].addr = (void *)
12580                                         vtophys(io->scsiio.kern_data_ptr);
12581 #endif
12582                         }
12583
12584                         msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12585                         do_sg_copy = 0;
12586                 } else {
12587                         struct ctl_sg_entry *sgl;
12588
12589                         do_sg_copy = 1;
12590                         msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12591                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12592                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12593                                 /*
12594                                  * XXX KDM use bus_dmamap_sync() here.
12595                                  */
12596                         }
12597                 }
12598
12599                 msg.dt.kern_data_len = io->scsiio.kern_data_len;
12600                 msg.dt.kern_total_len = io->scsiio.kern_total_len;
12601                 msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12602                 msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12603                 msg.dt.sg_sequence = 0;
12604
12605                 /*
12606                  * Loop until we've sent all of the S/G entries.  On the
12607                  * other end, we'll recompose these S/G entries into one
12608                  * contiguous list before passing it to the
12609                  */
12610                 for (sg_entries_sent = 0; sg_entries_sent <
12611                      msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12612                         msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12613                                 sizeof(msg.dt.sg_list[0])),
12614                                 msg.dt.kern_sg_entries - sg_entries_sent);
12615
12616                         if (do_sg_copy != 0) {
12617                                 struct ctl_sg_entry *sgl;
12618                                 int j;
12619
12620                                 sgl = (struct ctl_sg_entry *)
12621                                         io->scsiio.kern_data_ptr;
12622                                 /*
12623                                  * If this is in cached memory, flush the cache
12624                                  * before we send the DMA request to the other
12625                                  * controller.  We want to do this in either
12626                                  * the * read or the write case.  The read
12627                                  * case is straightforward.  In the write
12628                                  * case, we want to make sure nothing is
12629                                  * in the local cache that could overwrite
12630                                  * the DMAed data.
12631                                  */
12632
12633                                 for (i = sg_entries_sent, j = 0;
12634                                      i < msg.dt.cur_sg_entries; i++, j++) {
12635                                         if ((io->io_hdr.flags &
12636                                              CTL_FLAG_NO_DATASYNC) == 0) {
12637                                                 /*
12638                                                  * XXX KDM use bus_dmamap_sync()
12639                                                  */
12640                                         }
12641                                         if ((io->io_hdr.flags &
12642                                              CTL_FLAG_BUS_ADDR) == 0) {
12643                                                 /*
12644                                                  * XXX KDM use busdma.
12645                                                  */
12646 #if 0
12647                                                 msg.dt.sg_list[j].addr =(void *)
12648                                                        vtophys(sgl[i].addr);
12649 #endif
12650                                         } else {
12651                                                 msg.dt.sg_list[j].addr =
12652                                                         sgl[i].addr;
12653                                         }
12654                                         msg.dt.sg_list[j].len = sgl[i].len;
12655                                 }
12656                         }
12657
12658                         sg_entries_sent += msg.dt.cur_sg_entries;
12659                         if (sg_entries_sent >= msg.dt.kern_sg_entries)
12660                                 msg.dt.sg_last = 1;
12661                         else
12662                                 msg.dt.sg_last = 0;
12663
12664                         /*
12665                          * XXX KDM drop and reacquire the lock here?
12666                          */
12667                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12668                             sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12669                                 /*
12670                                  * XXX do something here.
12671                                  */
12672                         }
12673
12674                         msg.dt.sent_sg_entries = sg_entries_sent;
12675                 }
12676                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12677                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12678                         ctl_failover_io(io, /*have_lock*/ 0);
12679
12680         } else {
12681
12682                 /*
12683                  * Lookup the fe_datamove() function for this particular
12684                  * front end.
12685                  */
12686                 fe_datamove =
12687                     control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12688
12689                 fe_datamove(io);
12690         }
12691 }
12692
12693 static void
12694 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12695 {
12696         union ctl_ha_msg msg;
12697         int isc_status;
12698
12699         memset(&msg, 0, sizeof(msg));
12700
12701         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12702         msg.hdr.original_sc = io;
12703         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12704         msg.hdr.nexus = io->io_hdr.nexus;
12705         msg.hdr.status = io->io_hdr.status;
12706         msg.scsi.tag_num = io->scsiio.tag_num;
12707         msg.scsi.tag_type = io->scsiio.tag_type;
12708         msg.scsi.scsi_status = io->scsiio.scsi_status;
12709         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12710                sizeof(io->scsiio.sense_data));
12711         msg.scsi.sense_len = io->scsiio.sense_len;
12712         msg.scsi.sense_residual = io->scsiio.sense_residual;
12713         msg.scsi.fetd_status = io->io_hdr.port_status;
12714         msg.scsi.residual = io->scsiio.residual;
12715         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12716
12717         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12718                 ctl_failover_io(io, /*have_lock*/ have_lock);
12719                 return;
12720         }
12721
12722         isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12723         if (isc_status > CTL_HA_STATUS_SUCCESS) {
12724                 /* XXX do something if this fails */
12725         }
12726
12727 }
12728
12729 /*
12730  * The DMA to the remote side is done, now we need to tell the other side
12731  * we're done so it can continue with its data movement.
12732  */
12733 static void
12734 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12735 {
12736         union ctl_io *io;
12737
12738         io = rq->context;
12739
12740         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12741                 printf("%s: ISC DMA write failed with error %d", __func__,
12742                        rq->ret);
12743                 ctl_set_internal_failure(&io->scsiio,
12744                                          /*sks_valid*/ 1,
12745                                          /*retry_count*/ rq->ret);
12746         }
12747
12748         ctl_dt_req_free(rq);
12749
12750         /*
12751          * In this case, we had to malloc the memory locally.  Free it.
12752          */
12753         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12754                 int i;
12755                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12756                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
12757         }
12758         /*
12759          * The data is in local and remote memory, so now we need to send
12760          * status (good or back) back to the other side.
12761          */
12762         ctl_send_datamove_done(io, /*have_lock*/ 0);
12763 }
12764
12765 /*
12766  * We've moved the data from the host/controller into local memory.  Now we
12767  * need to push it over to the remote controller's memory.
12768  */
12769 static int
12770 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12771 {
12772         int retval;
12773
12774         retval = 0;
12775
12776         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12777                                           ctl_datamove_remote_write_cb);
12778
12779         return (retval);
12780 }
12781
12782 static void
12783 ctl_datamove_remote_write(union ctl_io *io)
12784 {
12785         int retval;
12786         void (*fe_datamove)(union ctl_io *io);
12787
12788         /*
12789          * - Get the data from the host/HBA into local memory.
12790          * - DMA memory from the local controller to the remote controller.
12791          * - Send status back to the remote controller.
12792          */
12793
12794         retval = ctl_datamove_remote_sgl_setup(io);
12795         if (retval != 0)
12796                 return;
12797
12798         /* Switch the pointer over so the FETD knows what to do */
12799         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12800
12801         /*
12802          * Use a custom move done callback, since we need to send completion
12803          * back to the other controller, not to the backend on this side.
12804          */
12805         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12806
12807         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12808
12809         fe_datamove(io);
12810
12811         return;
12812
12813 }
12814
12815 static int
12816 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12817 {
12818 #if 0
12819         char str[256];
12820         char path_str[64];
12821         struct sbuf sb;
12822 #endif
12823
12824         /*
12825          * In this case, we had to malloc the memory locally.  Free it.
12826          */
12827         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12828                 int i;
12829                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12830                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
12831         }
12832
12833 #if 0
12834         scsi_path_string(io, path_str, sizeof(path_str));
12835         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12836         sbuf_cat(&sb, path_str);
12837         scsi_command_string(&io->scsiio, NULL, &sb);
12838         sbuf_printf(&sb, "\n");
12839         sbuf_cat(&sb, path_str);
12840         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12841                     io->scsiio.tag_num, io->scsiio.tag_type);
12842         sbuf_cat(&sb, path_str);
12843         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12844                     io->io_hdr.flags, io->io_hdr.status);
12845         sbuf_finish(&sb);
12846         printk("%s", sbuf_data(&sb));
12847 #endif
12848
12849
12850         /*
12851          * The read is done, now we need to send status (good or bad) back
12852          * to the other side.
12853          */
12854         ctl_send_datamove_done(io, /*have_lock*/ 0);
12855
12856         return (0);
12857 }
12858
12859 static void
12860 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12861 {
12862         union ctl_io *io;
12863         void (*fe_datamove)(union ctl_io *io);
12864
12865         io = rq->context;
12866
12867         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12868                 printf("%s: ISC DMA read failed with error %d", __func__,
12869                        rq->ret);
12870                 ctl_set_internal_failure(&io->scsiio,
12871                                          /*sks_valid*/ 1,
12872                                          /*retry_count*/ rq->ret);
12873         }
12874
12875         ctl_dt_req_free(rq);
12876
12877         /* Switch the pointer over so the FETD knows what to do */
12878         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12879
12880         /*
12881          * Use a custom move done callback, since we need to send completion
12882          * back to the other controller, not to the backend on this side.
12883          */
12884         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12885
12886         /* XXX KDM add checks like the ones in ctl_datamove? */
12887
12888         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12889
12890         fe_datamove(io);
12891 }
12892
12893 static int
12894 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12895 {
12896         struct ctl_sg_entry *local_sglist, *remote_sglist;
12897         struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
12898         struct ctl_softc *softc;
12899         int retval;
12900         int i;
12901
12902         retval = 0;
12903         softc = control_softc;
12904
12905         local_sglist = io->io_hdr.local_sglist;
12906         local_dma_sglist = io->io_hdr.local_dma_sglist;
12907         remote_sglist = io->io_hdr.remote_sglist;
12908         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12909
12910         if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
12911                 for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
12912                         local_sglist[i].len = remote_sglist[i].len;
12913
12914                         /*
12915                          * XXX Detect the situation where the RS-level I/O
12916                          * redirector on the other side has already read the
12917                          * data off of the AOR RS on this side, and
12918                          * transferred it to remote (mirror) memory on the
12919                          * other side.  Since we already have the data in
12920                          * memory here, we just need to use it.
12921                          *
12922                          * XXX KDM this can probably be removed once we
12923                          * get the cache device code in and take the
12924                          * current AOR implementation out.
12925                          */
12926 #ifdef NEEDTOPORT
12927                         if ((remote_sglist[i].addr >=
12928                              (void *)vtophys(softc->mirr->addr))
12929                          && (remote_sglist[i].addr <
12930                              ((void *)vtophys(softc->mirr->addr) +
12931                              CacheMirrorOffset))) {
12932                                 local_sglist[i].addr = remote_sglist[i].addr -
12933                                         CacheMirrorOffset;
12934                                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12935                                      CTL_FLAG_DATA_IN)
12936                                         io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
12937                         } else {
12938                                 local_sglist[i].addr = remote_sglist[i].addr +
12939                                         CacheMirrorOffset;
12940                         }
12941 #endif
12942 #if 0
12943                         printf("%s: local %p, remote %p, len %d\n",
12944                                __func__, local_sglist[i].addr,
12945                                remote_sglist[i].addr, local_sglist[i].len);
12946 #endif
12947                 }
12948         } else {
12949                 uint32_t len_to_go;
12950
12951                 /*
12952                  * In this case, we don't have automatically allocated
12953                  * memory for this I/O on this controller.  This typically
12954                  * happens with internal CTL I/O -- e.g. inquiry, mode
12955                  * sense, etc.  Anything coming from RAIDCore will have
12956                  * a mirror area available.
12957                  */
12958                 len_to_go = io->scsiio.kern_data_len;
12959
12960                 /*
12961                  * Clear the no datasync flag, we have to use malloced
12962                  * buffers.
12963                  */
12964                 io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
12965
12966                 /*
12967                  * The difficult thing here is that the size of the various
12968                  * S/G segments may be different than the size from the
12969                  * remote controller.  That'll make it harder when DMAing
12970                  * the data back to the other side.
12971                  */
12972                 for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
12973                      sizeof(io->io_hdr.remote_sglist[0])) &&
12974                      (len_to_go > 0); i++) {
12975                         local_sglist[i].len = ctl_min(len_to_go, 131072);
12976                         CTL_SIZE_8B(local_dma_sglist[i].len,
12977                                     local_sglist[i].len);
12978                         local_sglist[i].addr =
12979                                 malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
12980
12981                         local_dma_sglist[i].addr = local_sglist[i].addr;
12982
12983                         if (local_sglist[i].addr == NULL) {
12984                                 int j;
12985
12986                                 printf("malloc failed for %zd bytes!",
12987                                        local_dma_sglist[i].len);
12988                                 for (j = 0; j < i; j++) {
12989                                         free(local_sglist[j].addr, M_CTL);
12990                                 }
12991                                 ctl_set_internal_failure(&io->scsiio,
12992                                                          /*sks_valid*/ 1,
12993                                                          /*retry_count*/ 4857);
12994                                 retval = 1;
12995                                 goto bailout_error;
12996                                 
12997                         }
12998                         /* XXX KDM do we need a sync here? */
12999
13000                         len_to_go -= local_sglist[i].len;
13001                 }
13002                 /*
13003                  * Reset the number of S/G entries accordingly.  The
13004                  * original number of S/G entries is available in
13005                  * rem_sg_entries.
13006                  */
13007                 io->scsiio.kern_sg_entries = i;
13008
13009 #if 0
13010                 printf("%s: kern_sg_entries = %d\n", __func__,
13011                        io->scsiio.kern_sg_entries);
13012                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13013                         printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13014                                local_sglist[i].addr, local_sglist[i].len,
13015                                local_dma_sglist[i].len);
13016 #endif
13017         }
13018
13019
13020         return (retval);
13021
13022 bailout_error:
13023
13024         ctl_send_datamove_done(io, /*have_lock*/ 0);
13025
13026         return (retval);
13027 }
13028
13029 static int
13030 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13031                          ctl_ha_dt_cb callback)
13032 {
13033         struct ctl_ha_dt_req *rq;
13034         struct ctl_sg_entry *remote_sglist, *local_sglist;
13035         struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13036         uint32_t local_used, remote_used, total_used;
13037         int retval;
13038         int i, j;
13039
13040         retval = 0;
13041
13042         rq = ctl_dt_req_alloc();
13043
13044         /*
13045          * If we failed to allocate the request, and if the DMA didn't fail
13046          * anyway, set busy status.  This is just a resource allocation
13047          * failure.
13048          */
13049         if ((rq == NULL)
13050          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13051                 ctl_set_busy(&io->scsiio);
13052
13053         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13054
13055                 if (rq != NULL)
13056                         ctl_dt_req_free(rq);
13057
13058                 /*
13059                  * The data move failed.  We need to return status back
13060                  * to the other controller.  No point in trying to DMA
13061                  * data to the remote controller.
13062                  */
13063
13064                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13065
13066                 retval = 1;
13067
13068                 goto bailout;
13069         }
13070
13071         local_sglist = io->io_hdr.local_sglist;
13072         local_dma_sglist = io->io_hdr.local_dma_sglist;
13073         remote_sglist = io->io_hdr.remote_sglist;
13074         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13075         local_used = 0;
13076         remote_used = 0;
13077         total_used = 0;
13078
13079         if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13080                 rq->ret = CTL_HA_STATUS_SUCCESS;
13081                 rq->context = io;
13082                 callback(rq);
13083                 goto bailout;
13084         }
13085
13086         /*
13087          * Pull/push the data over the wire from/to the other controller.
13088          * This takes into account the possibility that the local and
13089          * remote sglists may not be identical in terms of the size of
13090          * the elements and the number of elements.
13091          *
13092          * One fundamental assumption here is that the length allocated for
13093          * both the local and remote sglists is identical.  Otherwise, we've
13094          * essentially got a coding error of some sort.
13095          */
13096         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13097                 int isc_ret;
13098                 uint32_t cur_len, dma_length;
13099                 uint8_t *tmp_ptr;
13100
13101                 rq->id = CTL_HA_DATA_CTL;
13102                 rq->command = command;
13103                 rq->context = io;
13104
13105                 /*
13106                  * Both pointers should be aligned.  But it is possible
13107                  * that the allocation length is not.  They should both
13108                  * also have enough slack left over at the end, though,
13109                  * to round up to the next 8 byte boundary.
13110                  */
13111                 cur_len = ctl_min(local_sglist[i].len - local_used,
13112                                   remote_sglist[j].len - remote_used);
13113
13114                 /*
13115                  * In this case, we have a size issue and need to decrease
13116                  * the size, except in the case where we actually have less
13117                  * than 8 bytes left.  In that case, we need to increase
13118                  * the DMA length to get the last bit.
13119                  */
13120                 if ((cur_len & 0x7) != 0) {
13121                         if (cur_len > 0x7) {
13122                                 cur_len = cur_len - (cur_len & 0x7);
13123                                 dma_length = cur_len;
13124                         } else {
13125                                 CTL_SIZE_8B(dma_length, cur_len);
13126                         }
13127
13128                 } else
13129                         dma_length = cur_len;
13130
13131                 /*
13132                  * If we had to allocate memory for this I/O, instead of using
13133                  * the non-cached mirror memory, we'll need to flush the cache
13134                  * before trying to DMA to the other controller.
13135                  *
13136                  * We could end up doing this multiple times for the same
13137                  * segment if we have a larger local segment than remote
13138                  * segment.  That shouldn't be an issue.
13139                  */
13140                 if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13141                         /*
13142                          * XXX KDM use bus_dmamap_sync() here.
13143                          */
13144                 }
13145
13146                 rq->size = dma_length;
13147
13148                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
13149                 tmp_ptr += local_used;
13150
13151                 /* Use physical addresses when talking to ISC hardware */
13152                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13153                         /* XXX KDM use busdma */
13154 #if 0
13155                         rq->local = vtophys(tmp_ptr);
13156 #endif
13157                 } else
13158                         rq->local = tmp_ptr;
13159
13160                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13161                 tmp_ptr += remote_used;
13162                 rq->remote = tmp_ptr;
13163
13164                 rq->callback = NULL;
13165
13166                 local_used += cur_len;
13167                 if (local_used >= local_sglist[i].len) {
13168                         i++;
13169                         local_used = 0;
13170                 }
13171
13172                 remote_used += cur_len;
13173                 if (remote_used >= remote_sglist[j].len) {
13174                         j++;
13175                         remote_used = 0;
13176                 }
13177                 total_used += cur_len;
13178
13179                 if (total_used >= io->scsiio.kern_data_len)
13180                         rq->callback = callback;
13181
13182                 if ((rq->size & 0x7) != 0) {
13183                         printf("%s: warning: size %d is not on 8b boundary\n",
13184                                __func__, rq->size);
13185                 }
13186                 if (((uintptr_t)rq->local & 0x7) != 0) {
13187                         printf("%s: warning: local %p not on 8b boundary\n",
13188                                __func__, rq->local);
13189                 }
13190                 if (((uintptr_t)rq->remote & 0x7) != 0) {
13191                         printf("%s: warning: remote %p not on 8b boundary\n",
13192                                __func__, rq->local);
13193                 }
13194 #if 0
13195                 printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13196                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13197                        rq->local, rq->remote, rq->size);
13198 #endif
13199
13200                 isc_ret = ctl_dt_single(rq);
13201                 if (isc_ret == CTL_HA_STATUS_WAIT)
13202                         continue;
13203
13204                 if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13205                         rq->ret = CTL_HA_STATUS_SUCCESS;
13206                 } else {
13207                         rq->ret = isc_ret;
13208                 }
13209                 callback(rq);
13210                 goto bailout;
13211         }
13212
13213 bailout:
13214         return (retval);
13215
13216 }
13217
13218 static void
13219 ctl_datamove_remote_read(union ctl_io *io)
13220 {
13221         int retval;
13222         int i;
13223
13224         /*
13225          * This will send an error to the other controller in the case of a
13226          * failure.
13227          */
13228         retval = ctl_datamove_remote_sgl_setup(io);
13229         if (retval != 0)
13230                 return;
13231
13232         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13233                                           ctl_datamove_remote_read_cb);
13234         if ((retval != 0)
13235          && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13236                 /*
13237                  * Make sure we free memory if there was an error..  The
13238                  * ctl_datamove_remote_xfer() function will send the
13239                  * datamove done message, or call the callback with an
13240                  * error if there is a problem.
13241                  */
13242                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13243                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13244         }
13245
13246         return;
13247 }
13248
13249 /*
13250  * Process a datamove request from the other controller.  This is used for
13251  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13252  * first.  Once that is complete, the data gets DMAed into the remote
13253  * controller's memory.  For reads, we DMA from the remote controller's
13254  * memory into our memory first, and then move it out to the FETD.
13255  */
13256 static void
13257 ctl_datamove_remote(union ctl_io *io)
13258 {
13259         struct ctl_softc *softc;
13260
13261         softc = control_softc;
13262
13263         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13264
13265         /*
13266          * Note that we look for an aborted I/O here, but don't do some of
13267          * the other checks that ctl_datamove() normally does.
13268          * We don't need to run the datamove delay code, since that should
13269          * have been done if need be on the other controller.
13270          */
13271         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13272                 printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13273                        io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13274                        io->io_hdr.nexus.targ_port,
13275                        io->io_hdr.nexus.targ_target.id,
13276                        io->io_hdr.nexus.targ_lun);
13277                 io->io_hdr.port_status = 31338;
13278                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13279                 return;
13280         }
13281
13282         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13283                 ctl_datamove_remote_write(io);
13284         } else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13285                 ctl_datamove_remote_read(io);
13286         } else {
13287                 union ctl_ha_msg msg;
13288                 struct scsi_sense_data *sense;
13289                 uint8_t sks[3];
13290                 int retry_count;
13291
13292                 memset(&msg, 0, sizeof(msg));
13293
13294                 msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13295                 msg.hdr.status = CTL_SCSI_ERROR;
13296                 msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13297
13298                 retry_count = 4243;
13299
13300                 sense = &msg.scsi.sense_data;
13301                 sks[0] = SSD_SCS_VALID;
13302                 sks[1] = (retry_count >> 8) & 0xff;
13303                 sks[2] = retry_count & 0xff;
13304
13305                 /* "Internal target failure" */
13306                 scsi_set_sense_data(sense,
13307                                     /*sense_format*/ SSD_TYPE_NONE,
13308                                     /*current_error*/ 1,
13309                                     /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13310                                     /*asc*/ 0x44,
13311                                     /*ascq*/ 0x00,
13312                                     /*type*/ SSD_ELEM_SKS,
13313                                     /*size*/ sizeof(sks),
13314                                     /*data*/ sks,
13315                                     SSD_ELEM_NONE);
13316
13317                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13318                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13319                         ctl_failover_io(io, /*have_lock*/ 1);
13320                         return;
13321                 }
13322
13323                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13324                     CTL_HA_STATUS_SUCCESS) {
13325                         /* XXX KDM what to do if this fails? */
13326                 }
13327                 return;
13328         }
13329         
13330 }
13331
13332 static int
13333 ctl_process_done(union ctl_io *io)
13334 {
13335         struct ctl_lun *lun;
13336         struct ctl_softc *ctl_softc = control_softc;
13337         void (*fe_done)(union ctl_io *io);
13338         uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13339
13340         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13341
13342         fe_done =
13343             control_softc->ctl_ports[targ_port]->fe_done;
13344
13345 #ifdef CTL_TIME_IO
13346         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13347                 char str[256];
13348                 char path_str[64];
13349                 struct sbuf sb;
13350
13351                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13352                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13353
13354                 sbuf_cat(&sb, path_str);
13355                 switch (io->io_hdr.io_type) {
13356                 case CTL_IO_SCSI:
13357                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13358                         sbuf_printf(&sb, "\n");
13359                         sbuf_cat(&sb, path_str);
13360                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13361                                     io->scsiio.tag_num, io->scsiio.tag_type);
13362                         break;
13363                 case CTL_IO_TASK:
13364                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13365                                     "Tag Type: %d\n", io->taskio.task_action,
13366                                     io->taskio.tag_num, io->taskio.tag_type);
13367                         break;
13368                 default:
13369                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13370                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13371                         break;
13372                 }
13373                 sbuf_cat(&sb, path_str);
13374                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13375                             (intmax_t)time_uptime - io->io_hdr.start_time);
13376                 sbuf_finish(&sb);
13377                 printf("%s", sbuf_data(&sb));
13378         }
13379 #endif /* CTL_TIME_IO */
13380
13381         switch (io->io_hdr.io_type) {
13382         case CTL_IO_SCSI:
13383                 break;
13384         case CTL_IO_TASK:
13385                 if (bootverbose || (ctl_debug & CTL_DEBUG_INFO))
13386                         ctl_io_error_print(io, NULL);
13387                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13388                         ctl_free_io(io);
13389                 else
13390                         fe_done(io);
13391                 return (CTL_RETVAL_COMPLETE);
13392         default:
13393                 panic("ctl_process_done: invalid io type %d\n",
13394                       io->io_hdr.io_type);
13395                 break; /* NOTREACHED */
13396         }
13397
13398         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13399         if (lun == NULL) {
13400                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13401                                  io->io_hdr.nexus.targ_mapped_lun));
13402                 goto bailout;
13403         }
13404
13405         mtx_lock(&lun->lun_lock);
13406
13407         /*
13408          * Check to see if we have any errors to inject here.  We only
13409          * inject errors for commands that don't already have errors set.
13410          */
13411         if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13412             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13413             ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13414                 ctl_inject_error(lun, io);
13415
13416         /*
13417          * XXX KDM how do we treat commands that aren't completed
13418          * successfully?
13419          *
13420          * XXX KDM should we also track I/O latency?
13421          */
13422         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13423             io->io_hdr.io_type == CTL_IO_SCSI) {
13424 #ifdef CTL_TIME_IO
13425                 struct bintime cur_bt;
13426 #endif
13427                 int type;
13428
13429                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13430                     CTL_FLAG_DATA_IN)
13431                         type = CTL_STATS_READ;
13432                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13433                     CTL_FLAG_DATA_OUT)
13434                         type = CTL_STATS_WRITE;
13435                 else
13436                         type = CTL_STATS_NO_IO;
13437
13438                 lun->stats.ports[targ_port].bytes[type] +=
13439                     io->scsiio.kern_total_len;
13440                 lun->stats.ports[targ_port].operations[type]++;
13441 #ifdef CTL_TIME_IO
13442                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13443                    &io->io_hdr.dma_bt);
13444                 lun->stats.ports[targ_port].num_dmas[type] +=
13445                     io->io_hdr.num_dmas;
13446                 getbintime(&cur_bt);
13447                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13448                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13449 #endif
13450         }
13451
13452         /*
13453          * Remove this from the OOA queue.
13454          */
13455         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13456
13457         /*
13458          * Run through the blocked queue on this LUN and see if anything
13459          * has become unblocked, now that this transaction is done.
13460          */
13461         ctl_check_blocked(lun);
13462
13463         /*
13464          * If the LUN has been invalidated, free it if there is nothing
13465          * left on its OOA queue.
13466          */
13467         if ((lun->flags & CTL_LUN_INVALID)
13468          && TAILQ_EMPTY(&lun->ooa_queue)) {
13469                 mtx_unlock(&lun->lun_lock);
13470                 mtx_lock(&ctl_softc->ctl_lock);
13471                 ctl_free_lun(lun);
13472                 mtx_unlock(&ctl_softc->ctl_lock);
13473         } else
13474                 mtx_unlock(&lun->lun_lock);
13475
13476 bailout:
13477
13478         /*
13479          * If this command has been aborted, make sure we set the status
13480          * properly.  The FETD is responsible for freeing the I/O and doing
13481          * whatever it needs to do to clean up its state.
13482          */
13483         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13484                 ctl_set_task_aborted(&io->scsiio);
13485
13486         /*
13487          * If enabled, print command error status.
13488          * We don't print UAs unless debugging was enabled explicitly.
13489          */
13490         do {
13491                 if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)
13492                         break;
13493                 if (!bootverbose && (ctl_debug & CTL_DEBUG_INFO) == 0)
13494                         break;
13495                 if ((ctl_debug & CTL_DEBUG_INFO) == 0 &&
13496                     ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR) &&
13497                      (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13498                         int error_code, sense_key, asc, ascq;
13499
13500                         scsi_extract_sense_len(&io->scsiio.sense_data,
13501                             io->scsiio.sense_len, &error_code, &sense_key,
13502                             &asc, &ascq, /*show_errors*/ 0);
13503                         if (sense_key == SSD_KEY_UNIT_ATTENTION)
13504                                 break;
13505                 }
13506
13507                 ctl_io_error_print(io, NULL);
13508         } while (0);
13509
13510         /*
13511          * Tell the FETD or the other shelf controller we're done with this
13512          * command.  Note that only SCSI commands get to this point.  Task
13513          * management commands are completed above.
13514          *
13515          * We only send status to the other controller if we're in XFER
13516          * mode.  In SER_ONLY mode, the I/O is done on the controller that
13517          * received the I/O (from CTL's perspective), and so the status is
13518          * generated there.
13519          * 
13520          * XXX KDM if we hold the lock here, we could cause a deadlock
13521          * if the frontend comes back in in this context to queue
13522          * something.
13523          */
13524         if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13525          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13526                 union ctl_ha_msg msg;
13527
13528                 memset(&msg, 0, sizeof(msg));
13529                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13530                 msg.hdr.original_sc = io->io_hdr.original_sc;
13531                 msg.hdr.nexus = io->io_hdr.nexus;
13532                 msg.hdr.status = io->io_hdr.status;
13533                 msg.scsi.scsi_status = io->scsiio.scsi_status;
13534                 msg.scsi.tag_num = io->scsiio.tag_num;
13535                 msg.scsi.tag_type = io->scsiio.tag_type;
13536                 msg.scsi.sense_len = io->scsiio.sense_len;
13537                 msg.scsi.sense_residual = io->scsiio.sense_residual;
13538                 msg.scsi.residual = io->scsiio.residual;
13539                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13540                        sizeof(io->scsiio.sense_data));
13541                 /*
13542                  * We copy this whether or not this is an I/O-related
13543                  * command.  Otherwise, we'd have to go and check to see
13544                  * whether it's a read/write command, and it really isn't
13545                  * worth it.
13546                  */
13547                 memcpy(&msg.scsi.lbalen,
13548                        &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13549                        sizeof(msg.scsi.lbalen));
13550
13551                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13552                                 sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13553                         /* XXX do something here */
13554                 }
13555
13556                 ctl_free_io(io);
13557         } else 
13558                 fe_done(io);
13559
13560         return (CTL_RETVAL_COMPLETE);
13561 }
13562
13563 #ifdef CTL_WITH_CA
13564 /*
13565  * Front end should call this if it doesn't do autosense.  When the request
13566  * sense comes back in from the initiator, we'll dequeue this and send it.
13567  */
13568 int
13569 ctl_queue_sense(union ctl_io *io)
13570 {
13571         struct ctl_lun *lun;
13572         struct ctl_softc *ctl_softc;
13573         uint32_t initidx, targ_lun;
13574
13575         ctl_softc = control_softc;
13576
13577         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13578
13579         /*
13580          * LUN lookup will likely move to the ctl_work_thread() once we
13581          * have our new queueing infrastructure (that doesn't put things on
13582          * a per-LUN queue initially).  That is so that we can handle
13583          * things like an INQUIRY to a LUN that we don't have enabled.  We
13584          * can't deal with that right now.
13585          */
13586         mtx_lock(&ctl_softc->ctl_lock);
13587
13588         /*
13589          * If we don't have a LUN for this, just toss the sense
13590          * information.
13591          */
13592         targ_lun = io->io_hdr.nexus.targ_lun;
13593         targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13594         if ((targ_lun < CTL_MAX_LUNS)
13595          && (ctl_softc->ctl_luns[targ_lun] != NULL))
13596                 lun = ctl_softc->ctl_luns[targ_lun];
13597         else
13598                 goto bailout;
13599
13600         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13601
13602         mtx_lock(&lun->lun_lock);
13603         /*
13604          * Already have CA set for this LUN...toss the sense information.
13605          */
13606         if (ctl_is_set(lun->have_ca, initidx)) {
13607                 mtx_unlock(&lun->lun_lock);
13608                 goto bailout;
13609         }
13610
13611         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13612                ctl_min(sizeof(lun->pending_sense[initidx]),
13613                sizeof(io->scsiio.sense_data)));
13614         ctl_set_mask(lun->have_ca, initidx);
13615         mtx_unlock(&lun->lun_lock);
13616
13617 bailout:
13618         mtx_unlock(&ctl_softc->ctl_lock);
13619
13620         ctl_free_io(io);
13621
13622         return (CTL_RETVAL_COMPLETE);
13623 }
13624 #endif
13625
13626 /*
13627  * Primary command inlet from frontend ports.  All SCSI and task I/O
13628  * requests must go through this function.
13629  */
13630 int
13631 ctl_queue(union ctl_io *io)
13632 {
13633         struct ctl_softc *ctl_softc;
13634
13635         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13636
13637         ctl_softc = control_softc;
13638
13639 #ifdef CTL_TIME_IO
13640         io->io_hdr.start_time = time_uptime;
13641         getbintime(&io->io_hdr.start_bt);
13642 #endif /* CTL_TIME_IO */
13643
13644         /* Map FE-specific LUN ID into global one. */
13645         io->io_hdr.nexus.targ_mapped_lun =
13646             ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13647
13648         switch (io->io_hdr.io_type) {
13649         case CTL_IO_SCSI:
13650         case CTL_IO_TASK:
13651                 if (ctl_debug & CTL_DEBUG_CDB)
13652                         ctl_io_print(io);
13653                 ctl_enqueue_incoming(io);
13654                 break;
13655         default:
13656                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13657                 return (EINVAL);
13658         }
13659
13660         return (CTL_RETVAL_COMPLETE);
13661 }
13662
13663 #ifdef CTL_IO_DELAY
13664 static void
13665 ctl_done_timer_wakeup(void *arg)
13666 {
13667         union ctl_io *io;
13668
13669         io = (union ctl_io *)arg;
13670         ctl_done(io);
13671 }
13672 #endif /* CTL_IO_DELAY */
13673
13674 void
13675 ctl_done(union ctl_io *io)
13676 {
13677         struct ctl_softc *ctl_softc;
13678
13679         ctl_softc = control_softc;
13680
13681         /*
13682          * Enable this to catch duplicate completion issues.
13683          */
13684 #if 0
13685         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13686                 printf("%s: type %d msg %d cdb %x iptl: "
13687                        "%d:%d:%d:%d tag 0x%04x "
13688                        "flag %#x status %x\n",
13689                         __func__,
13690                         io->io_hdr.io_type,
13691                         io->io_hdr.msg_type,
13692                         io->scsiio.cdb[0],
13693                         io->io_hdr.nexus.initid.id,
13694                         io->io_hdr.nexus.targ_port,
13695                         io->io_hdr.nexus.targ_target.id,
13696                         io->io_hdr.nexus.targ_lun,
13697                         (io->io_hdr.io_type ==
13698                         CTL_IO_TASK) ?
13699                         io->taskio.tag_num :
13700                         io->scsiio.tag_num,
13701                         io->io_hdr.flags,
13702                         io->io_hdr.status);
13703         } else
13704                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13705 #endif
13706
13707         /*
13708          * This is an internal copy of an I/O, and should not go through
13709          * the normal done processing logic.
13710          */
13711         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13712                 return;
13713
13714         /*
13715          * We need to send a msg to the serializing shelf to finish the IO
13716          * as well.  We don't send a finish message to the other shelf if
13717          * this is a task management command.  Task management commands
13718          * aren't serialized in the OOA queue, but rather just executed on
13719          * both shelf controllers for commands that originated on that
13720          * controller.
13721          */
13722         if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13723          && (io->io_hdr.io_type != CTL_IO_TASK)) {
13724                 union ctl_ha_msg msg_io;
13725
13726                 msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13727                 msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13728                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13729                     sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13730                 }
13731                 /* continue on to finish IO */
13732         }
13733 #ifdef CTL_IO_DELAY
13734         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13735                 struct ctl_lun *lun;
13736
13737                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13738
13739                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13740         } else {
13741                 struct ctl_lun *lun;
13742
13743                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13744
13745                 if ((lun != NULL)
13746                  && (lun->delay_info.done_delay > 0)) {
13747                         struct callout *callout;
13748
13749                         callout = (struct callout *)&io->io_hdr.timer_bytes;
13750                         callout_init(callout, /*mpsafe*/ 1);
13751                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13752                         callout_reset(callout,
13753                                       lun->delay_info.done_delay * hz,
13754                                       ctl_done_timer_wakeup, io);
13755                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13756                                 lun->delay_info.done_delay = 0;
13757                         return;
13758                 }
13759         }
13760 #endif /* CTL_IO_DELAY */
13761
13762         ctl_enqueue_done(io);
13763 }
13764
13765 int
13766 ctl_isc(struct ctl_scsiio *ctsio)
13767 {
13768         struct ctl_lun *lun;
13769         int retval;
13770
13771         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13772
13773         CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13774
13775         CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13776
13777         retval = lun->backend->data_submit((union ctl_io *)ctsio);
13778
13779         return (retval);
13780 }
13781
13782
13783 static void
13784 ctl_work_thread(void *arg)
13785 {
13786         struct ctl_thread *thr = (struct ctl_thread *)arg;
13787         struct ctl_softc *softc = thr->ctl_softc;
13788         union ctl_io *io;
13789         int retval;
13790
13791         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13792
13793         for (;;) {
13794                 retval = 0;
13795
13796                 /*
13797                  * We handle the queues in this order:
13798                  * - ISC
13799                  * - done queue (to free up resources, unblock other commands)
13800                  * - RtR queue
13801                  * - incoming queue
13802                  *
13803                  * If those queues are empty, we break out of the loop and
13804                  * go to sleep.
13805                  */
13806                 mtx_lock(&thr->queue_lock);
13807                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13808                 if (io != NULL) {
13809                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13810                         mtx_unlock(&thr->queue_lock);
13811                         ctl_handle_isc(io);
13812                         continue;
13813                 }
13814                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13815                 if (io != NULL) {
13816                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13817                         /* clear any blocked commands, call fe_done */
13818                         mtx_unlock(&thr->queue_lock);
13819                         retval = ctl_process_done(io);
13820                         continue;
13821                 }
13822                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13823                 if (io != NULL) {
13824                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13825                         mtx_unlock(&thr->queue_lock);
13826                         if (io->io_hdr.io_type == CTL_IO_TASK)
13827                                 ctl_run_task(io);
13828                         else
13829                                 ctl_scsiio_precheck(softc, &io->scsiio);
13830                         continue;
13831                 }
13832                 if (!ctl_pause_rtr) {
13833                         io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13834                         if (io != NULL) {
13835                                 STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13836                                 mtx_unlock(&thr->queue_lock);
13837                                 retval = ctl_scsiio(&io->scsiio);
13838                                 if (retval != CTL_RETVAL_COMPLETE)
13839                                         CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13840                                 continue;
13841                         }
13842                 }
13843
13844                 /* Sleep until we have something to do. */
13845                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13846         }
13847 }
13848
13849 static void
13850 ctl_lun_thread(void *arg)
13851 {
13852         struct ctl_softc *softc = (struct ctl_softc *)arg;
13853         struct ctl_be_lun *be_lun;
13854         int retval;
13855
13856         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13857
13858         for (;;) {
13859                 retval = 0;
13860                 mtx_lock(&softc->ctl_lock);
13861                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13862                 if (be_lun != NULL) {
13863                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13864                         mtx_unlock(&softc->ctl_lock);
13865                         ctl_create_lun(be_lun);
13866                         continue;
13867                 }
13868
13869                 /* Sleep until we have something to do. */
13870                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13871                     PDROP | PRIBIO, "-", 0);
13872         }
13873 }
13874
13875 static void
13876 ctl_thresh_thread(void *arg)
13877 {
13878         struct ctl_softc *softc = (struct ctl_softc *)arg;
13879         struct ctl_lun *lun;
13880         struct ctl_be_lun *be_lun;
13881         struct scsi_da_rw_recovery_page *rwpage;
13882         struct ctl_logical_block_provisioning_page *page;
13883         const char *attr;
13884         uint64_t thres, val;
13885         int i, e;
13886
13887         CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13888
13889         for (;;) {
13890                 mtx_lock(&softc->ctl_lock);
13891                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
13892                         be_lun = lun->be_lun;
13893                         if ((lun->flags & CTL_LUN_DISABLED) ||
13894                             (lun->flags & CTL_LUN_OFFLINE) ||
13895                             (be_lun->flags & CTL_LUN_FLAG_UNMAP) == 0 ||
13896                             lun->backend->lun_attr == NULL)
13897                                 continue;
13898                         rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13899                         if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13900                                 continue;
13901                         e = 0;
13902                         page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13903                         for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13904                                 if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13905                                         continue;
13906                                 thres = scsi_4btoul(page->descr[i].count);
13907                                 thres <<= CTL_LBP_EXPONENT;
13908                                 switch (page->descr[i].resource) {
13909                                 case 0x01:
13910                                         attr = "blocksavail";
13911                                         break;
13912                                 case 0x02:
13913                                         attr = "blocksused";
13914                                         break;
13915                                 case 0xf1:
13916                                         attr = "poolblocksavail";
13917                                         break;
13918                                 case 0xf2:
13919                                         attr = "poolblocksused";
13920                                         break;
13921                                 default:
13922                                         continue;
13923                                 }
13924                                 mtx_unlock(&softc->ctl_lock); // XXX
13925                                 val = lun->backend->lun_attr(
13926                                     lun->be_lun->be_lun, attr);
13927                                 mtx_lock(&softc->ctl_lock);
13928                                 if (val == UINT64_MAX)
13929                                         continue;
13930                                 if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13931                                     == SLBPPD_ARMING_INC)
13932                                         e |= (val >= thres);
13933                                 else
13934                                         e |= (val <= thres);
13935                         }
13936                         mtx_lock(&lun->lun_lock);
13937                         if (e) {
13938                                 if (lun->lasttpt == 0 ||
13939                                     time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13940                                         lun->lasttpt = time_uptime;
13941                                         for (i = 0; i < CTL_MAX_INITIATORS; i++)
13942                                                 lun->pending_ua[i] |=
13943                                                     CTL_UA_THIN_PROV_THRES;
13944                                 }
13945                         } else {
13946                                 lun->lasttpt = 0;
13947                                 for (i = 0; i < CTL_MAX_INITIATORS; i++)
13948                                         lun->pending_ua[i] &= ~CTL_UA_THIN_PROV_THRES;
13949                         }
13950                         mtx_unlock(&lun->lun_lock);
13951                 }
13952                 mtx_unlock(&softc->ctl_lock);
13953                 pause("-", CTL_LBP_PERIOD * hz);
13954         }
13955 }
13956
13957 static void
13958 ctl_enqueue_incoming(union ctl_io *io)
13959 {
13960         struct ctl_softc *softc = control_softc;
13961         struct ctl_thread *thr;
13962         u_int idx;
13963
13964         idx = (io->io_hdr.nexus.targ_port * 127 +
13965                io->io_hdr.nexus.initid.id) % worker_threads;
13966         thr = &softc->threads[idx];
13967         mtx_lock(&thr->queue_lock);
13968         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13969         mtx_unlock(&thr->queue_lock);
13970         wakeup(thr);
13971 }
13972
13973 static void
13974 ctl_enqueue_rtr(union ctl_io *io)
13975 {
13976         struct ctl_softc *softc = control_softc;
13977         struct ctl_thread *thr;
13978
13979         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13980         mtx_lock(&thr->queue_lock);
13981         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13982         mtx_unlock(&thr->queue_lock);
13983         wakeup(thr);
13984 }
13985
13986 static void
13987 ctl_enqueue_done(union ctl_io *io)
13988 {
13989         struct ctl_softc *softc = control_softc;
13990         struct ctl_thread *thr;
13991
13992         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13993         mtx_lock(&thr->queue_lock);
13994         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13995         mtx_unlock(&thr->queue_lock);
13996         wakeup(thr);
13997 }
13998
13999 static void
14000 ctl_enqueue_isc(union ctl_io *io)
14001 {
14002         struct ctl_softc *softc = control_softc;
14003         struct ctl_thread *thr;
14004
14005         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14006         mtx_lock(&thr->queue_lock);
14007         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14008         mtx_unlock(&thr->queue_lock);
14009         wakeup(thr);
14010 }
14011
14012 /* Initialization and failover */
14013
14014 void
14015 ctl_init_isc_msg(void)
14016 {
14017         printf("CTL: Still calling this thing\n");
14018 }
14019
14020 /*
14021  * Init component
14022  *      Initializes component into configuration defined by bootMode
14023  *      (see hasc-sv.c)
14024  *      returns hasc_Status:
14025  *              OK
14026  *              ERROR - fatal error
14027  */
14028 static ctl_ha_comp_status
14029 ctl_isc_init(struct ctl_ha_component *c)
14030 {
14031         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14032
14033         c->status = ret;
14034         return ret;
14035 }
14036
14037 /* Start component
14038  *      Starts component in state requested. If component starts successfully,
14039  *      it must set its own state to the requestrd state
14040  *      When requested state is HASC_STATE_HA, the component may refine it
14041  *      by adding _SLAVE or _MASTER flags.
14042  *      Currently allowed state transitions are:
14043  *      UNKNOWN->HA             - initial startup
14044  *      UNKNOWN->SINGLE - initial startup when no parter detected
14045  *      HA->SINGLE              - failover
14046  * returns ctl_ha_comp_status:
14047  *              OK      - component successfully started in requested state
14048  *              FAILED  - could not start the requested state, failover may
14049  *                        be possible
14050  *              ERROR   - fatal error detected, no future startup possible
14051  */
14052 static ctl_ha_comp_status
14053 ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14054 {
14055         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14056
14057         printf("%s: go\n", __func__);
14058
14059         // UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14060         if (c->state == CTL_HA_STATE_UNKNOWN ) {
14061                 control_softc->is_single = 0;
14062                 if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14063                     != CTL_HA_STATUS_SUCCESS) {
14064                         printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14065                         ret = CTL_HA_COMP_STATUS_ERROR;
14066                 }
14067         } else if (CTL_HA_STATE_IS_HA(c->state)
14068                 && CTL_HA_STATE_IS_SINGLE(state)){
14069                 // HA->SINGLE transition
14070                 ctl_failover();
14071                 control_softc->is_single = 1;
14072         } else {
14073                 printf("ctl_isc_start:Invalid state transition %X->%X\n",
14074                        c->state, state);
14075                 ret = CTL_HA_COMP_STATUS_ERROR;
14076         }
14077         if (CTL_HA_STATE_IS_SINGLE(state))
14078                 control_softc->is_single = 1;
14079
14080         c->state = state;
14081         c->status = ret;
14082         return ret;
14083 }
14084
14085 /*
14086  * Quiesce component
14087  * The component must clear any error conditions (set status to OK) and
14088  * prepare itself to another Start call
14089  * returns ctl_ha_comp_status:
14090  *      OK
14091  *      ERROR
14092  */
14093 static ctl_ha_comp_status
14094 ctl_isc_quiesce(struct ctl_ha_component *c)
14095 {
14096         int ret = CTL_HA_COMP_STATUS_OK;
14097
14098         ctl_pause_rtr = 1;
14099         c->status = ret;
14100         return ret;
14101 }
14102
14103 struct ctl_ha_component ctl_ha_component_ctlisc =
14104 {
14105         .name = "CTL ISC",
14106         .state = CTL_HA_STATE_UNKNOWN,
14107         .init = ctl_isc_init,
14108         .start = ctl_isc_start,
14109         .quiesce = ctl_isc_quiesce
14110 };
14111
14112 /*
14113  *  vim: ts=8
14114  */