]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/ctl.c
MFC r278037: CTL LUN mapping rewrite.
[FreeBSD/stable/10.git] / sys / cam / ctl / ctl.c
1 /*-
2  * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3  * Copyright (c) 2012 The FreeBSD Foundation
4  * All rights reserved.
5  *
6  * Portions of this software were developed by Edward Tomasz Napierala
7  * under sponsorship from the FreeBSD Foundation.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions, and the following disclaimer,
14  *    without modification.
15  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
16  *    substantially similar to the "NO WARRANTY" disclaimer below
17  *    ("Disclaimer") and any redistribution must be conditioned upon
18  *    including a substantially similar Disclaimer requirement for further
19  *    binary redistribution.
20  *
21  * NO WARRANTY
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
25  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
31  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGES.
33  *
34  * $Id$
35  */
36 /*
37  * CAM Target Layer, a SCSI device emulation subsystem.
38  *
39  * Author: Ken Merry <ken@FreeBSD.org>
40  */
41
42 #define _CTL_C
43
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/ctype.h>
50 #include <sys/kernel.h>
51 #include <sys/types.h>
52 #include <sys/kthread.h>
53 #include <sys/bio.h>
54 #include <sys/fcntl.h>
55 #include <sys/lock.h>
56 #include <sys/module.h>
57 #include <sys/mutex.h>
58 #include <sys/condvar.h>
59 #include <sys/malloc.h>
60 #include <sys/conf.h>
61 #include <sys/ioccom.h>
62 #include <sys/queue.h>
63 #include <sys/sbuf.h>
64 #include <sys/smp.h>
65 #include <sys/endian.h>
66 #include <sys/sysctl.h>
67 #include <vm/uma.h>
68
69 #include <cam/cam.h>
70 #include <cam/scsi/scsi_all.h>
71 #include <cam/scsi/scsi_da.h>
72 #include <cam/ctl/ctl_io.h>
73 #include <cam/ctl/ctl.h>
74 #include <cam/ctl/ctl_frontend.h>
75 #include <cam/ctl/ctl_frontend_internal.h>
76 #include <cam/ctl/ctl_util.h>
77 #include <cam/ctl/ctl_backend.h>
78 #include <cam/ctl/ctl_ioctl.h>
79 #include <cam/ctl/ctl_ha.h>
80 #include <cam/ctl/ctl_private.h>
81 #include <cam/ctl/ctl_debug.h>
82 #include <cam/ctl/ctl_scsi_all.h>
83 #include <cam/ctl/ctl_error.h>
84
85 struct ctl_softc *control_softc = NULL;
86
87 /*
88  * Size and alignment macros needed for Copan-specific HA hardware.  These
89  * can go away when the HA code is re-written, and uses busdma for any
90  * hardware.
91  */
92 #define CTL_ALIGN_8B(target, source, type)                              \
93         if (((uint32_t)source & 0x7) != 0)                              \
94                 target = (type)(source + (0x8 - ((uint32_t)source & 0x7)));\
95         else                                                            \
96                 target = (type)source;
97
98 #define CTL_SIZE_8B(target, size)                                       \
99         if ((size & 0x7) != 0)                                          \
100                 target = size + (0x8 - (size & 0x7));                   \
101         else                                                            \
102                 target = size;
103
104 #define CTL_ALIGN_8B_MARGIN     16
105
106 /*
107  * Template mode pages.
108  */
109
110 /*
111  * Note that these are default values only.  The actual values will be
112  * filled in when the user does a mode sense.
113  */
114 const static struct copan_debugconf_subpage debugconf_page_default = {
115         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
116         DBGCNF_SUBPAGE_CODE,            /* subpage */
117         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
118          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
119         DBGCNF_VERSION,                 /* page_version */
120         {CTL_TIME_IO_DEFAULT_SECS>>8,
121          CTL_TIME_IO_DEFAULT_SECS>>0},  /* ctl_time_io_secs */
122 };
123
124 const static struct copan_debugconf_subpage debugconf_page_changeable = {
125         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
126         DBGCNF_SUBPAGE_CODE,            /* subpage */
127         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
128          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
129         0,                              /* page_version */
130         {0xff,0xff},                    /* ctl_time_io_secs */
131 };
132
133 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
134         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
135         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
136         /*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
137         /*read_retry_count*/0,
138         /*correction_span*/0,
139         /*head_offset_count*/0,
140         /*data_strobe_offset_cnt*/0,
141         /*byte8*/SMS_RWER_LBPERE,
142         /*write_retry_count*/0,
143         /*reserved2*/0,
144         /*recovery_time_limit*/{0, 0},
145 };
146
147 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
148         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
149         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
150         /*byte3*/0,
151         /*read_retry_count*/0,
152         /*correction_span*/0,
153         /*head_offset_count*/0,
154         /*data_strobe_offset_cnt*/0,
155         /*byte8*/0,
156         /*write_retry_count*/0,
157         /*reserved2*/0,
158         /*recovery_time_limit*/{0, 0},
159 };
160
161 const static struct scsi_format_page format_page_default = {
162         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
163         /*page_length*/sizeof(struct scsi_format_page) - 2,
164         /*tracks_per_zone*/ {0, 0},
165         /*alt_sectors_per_zone*/ {0, 0},
166         /*alt_tracks_per_zone*/ {0, 0},
167         /*alt_tracks_per_lun*/ {0, 0},
168         /*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
169                                 CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
170         /*bytes_per_sector*/ {0, 0},
171         /*interleave*/ {0, 0},
172         /*track_skew*/ {0, 0},
173         /*cylinder_skew*/ {0, 0},
174         /*flags*/ SFP_HSEC,
175         /*reserved*/ {0, 0, 0}
176 };
177
178 const static struct scsi_format_page format_page_changeable = {
179         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
180         /*page_length*/sizeof(struct scsi_format_page) - 2,
181         /*tracks_per_zone*/ {0, 0},
182         /*alt_sectors_per_zone*/ {0, 0},
183         /*alt_tracks_per_zone*/ {0, 0},
184         /*alt_tracks_per_lun*/ {0, 0},
185         /*sectors_per_track*/ {0, 0},
186         /*bytes_per_sector*/ {0, 0},
187         /*interleave*/ {0, 0},
188         /*track_skew*/ {0, 0},
189         /*cylinder_skew*/ {0, 0},
190         /*flags*/ 0,
191         /*reserved*/ {0, 0, 0}
192 };
193
194 const static struct scsi_rigid_disk_page rigid_disk_page_default = {
195         /*page_code*/SMS_RIGID_DISK_PAGE,
196         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
197         /*cylinders*/ {0, 0, 0},
198         /*heads*/ CTL_DEFAULT_HEADS,
199         /*start_write_precomp*/ {0, 0, 0},
200         /*start_reduced_current*/ {0, 0, 0},
201         /*step_rate*/ {0, 0},
202         /*landing_zone_cylinder*/ {0, 0, 0},
203         /*rpl*/ SRDP_RPL_DISABLED,
204         /*rotational_offset*/ 0,
205         /*reserved1*/ 0,
206         /*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
207                            CTL_DEFAULT_ROTATION_RATE & 0xff},
208         /*reserved2*/ {0, 0}
209 };
210
211 const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
212         /*page_code*/SMS_RIGID_DISK_PAGE,
213         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
214         /*cylinders*/ {0, 0, 0},
215         /*heads*/ 0,
216         /*start_write_precomp*/ {0, 0, 0},
217         /*start_reduced_current*/ {0, 0, 0},
218         /*step_rate*/ {0, 0},
219         /*landing_zone_cylinder*/ {0, 0, 0},
220         /*rpl*/ 0,
221         /*rotational_offset*/ 0,
222         /*reserved1*/ 0,
223         /*rotation_rate*/ {0, 0},
224         /*reserved2*/ {0, 0}
225 };
226
227 const static struct scsi_caching_page caching_page_default = {
228         /*page_code*/SMS_CACHING_PAGE,
229         /*page_length*/sizeof(struct scsi_caching_page) - 2,
230         /*flags1*/ SCP_DISC | SCP_WCE,
231         /*ret_priority*/ 0,
232         /*disable_pf_transfer_len*/ {0xff, 0xff},
233         /*min_prefetch*/ {0, 0},
234         /*max_prefetch*/ {0xff, 0xff},
235         /*max_pf_ceiling*/ {0xff, 0xff},
236         /*flags2*/ 0,
237         /*cache_segments*/ 0,
238         /*cache_seg_size*/ {0, 0},
239         /*reserved*/ 0,
240         /*non_cache_seg_size*/ {0, 0, 0}
241 };
242
243 const static struct scsi_caching_page caching_page_changeable = {
244         /*page_code*/SMS_CACHING_PAGE,
245         /*page_length*/sizeof(struct scsi_caching_page) - 2,
246         /*flags1*/ SCP_WCE | SCP_RCD,
247         /*ret_priority*/ 0,
248         /*disable_pf_transfer_len*/ {0, 0},
249         /*min_prefetch*/ {0, 0},
250         /*max_prefetch*/ {0, 0},
251         /*max_pf_ceiling*/ {0, 0},
252         /*flags2*/ 0,
253         /*cache_segments*/ 0,
254         /*cache_seg_size*/ {0, 0},
255         /*reserved*/ 0,
256         /*non_cache_seg_size*/ {0, 0, 0}
257 };
258
259 const static struct scsi_control_page control_page_default = {
260         /*page_code*/SMS_CONTROL_MODE_PAGE,
261         /*page_length*/sizeof(struct scsi_control_page) - 2,
262         /*rlec*/0,
263         /*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
264         /*eca_and_aen*/0,
265         /*flags4*/SCP_TAS,
266         /*aen_holdoff_period*/{0, 0},
267         /*busy_timeout_period*/{0, 0},
268         /*extended_selftest_completion_time*/{0, 0}
269 };
270
271 const static struct scsi_control_page control_page_changeable = {
272         /*page_code*/SMS_CONTROL_MODE_PAGE,
273         /*page_length*/sizeof(struct scsi_control_page) - 2,
274         /*rlec*/SCP_DSENSE,
275         /*queue_flags*/SCP_QUEUE_ALG_MASK,
276         /*eca_and_aen*/SCP_SWP,
277         /*flags4*/0,
278         /*aen_holdoff_period*/{0, 0},
279         /*busy_timeout_period*/{0, 0},
280         /*extended_selftest_completion_time*/{0, 0}
281 };
282
283 const static struct scsi_info_exceptions_page ie_page_default = {
284         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
285         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
286         /*info_flags*/SIEP_FLAGS_DEXCPT,
287         /*mrie*/0,
288         /*interval_timer*/{0, 0, 0, 0},
289         /*report_count*/{0, 0, 0, 0}
290 };
291
292 const static struct scsi_info_exceptions_page ie_page_changeable = {
293         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
294         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
295         /*info_flags*/0,
296         /*mrie*/0,
297         /*interval_timer*/{0, 0, 0, 0},
298         /*report_count*/{0, 0, 0, 0}
299 };
300
301 #define CTL_LBPM_LEN    (sizeof(struct ctl_logical_block_provisioning_page) - 4)
302
303 const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
304         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
305         /*subpage_code*/0x02,
306         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
307         /*flags*/0,
308         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
309         /*descr*/{}},
310         {{/*flags*/0,
311           /*resource*/0x01,
312           /*reserved*/{0, 0},
313           /*count*/{0, 0, 0, 0}},
314          {/*flags*/0,
315           /*resource*/0x02,
316           /*reserved*/{0, 0},
317           /*count*/{0, 0, 0, 0}},
318          {/*flags*/0,
319           /*resource*/0xf1,
320           /*reserved*/{0, 0},
321           /*count*/{0, 0, 0, 0}},
322          {/*flags*/0,
323           /*resource*/0xf2,
324           /*reserved*/{0, 0},
325           /*count*/{0, 0, 0, 0}}
326         }
327 };
328
329 const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
330         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
331         /*subpage_code*/0x02,
332         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
333         /*flags*/0,
334         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
335         /*descr*/{}},
336         {{/*flags*/0,
337           /*resource*/0,
338           /*reserved*/{0, 0},
339           /*count*/{0, 0, 0, 0}},
340          {/*flags*/0,
341           /*resource*/0,
342           /*reserved*/{0, 0},
343           /*count*/{0, 0, 0, 0}},
344          {/*flags*/0,
345           /*resource*/0,
346           /*reserved*/{0, 0},
347           /*count*/{0, 0, 0, 0}},
348          {/*flags*/0,
349           /*resource*/0,
350           /*reserved*/{0, 0},
351           /*count*/{0, 0, 0, 0}}
352         }
353 };
354
355 /*
356  * XXX KDM move these into the softc.
357  */
358 static int rcv_sync_msg;
359 static uint8_t ctl_pause_rtr;
360
361 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
362 static int worker_threads = -1;
363 TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
364 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
365     &worker_threads, 1, "Number of worker threads");
366 static int ctl_debug = CTL_DEBUG_NONE;
367 TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
368 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
369     &ctl_debug, 0, "Enabled debug flags");
370
371 /*
372  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
373  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
374  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
375  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
376  */
377 #define SCSI_EVPD_NUM_SUPPORTED_PAGES   10
378
379 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
380                                   int param);
381 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
382 static int ctl_init(void);
383 void ctl_shutdown(void);
384 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
385 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
386 static void ctl_ioctl_online(void *arg);
387 static void ctl_ioctl_offline(void *arg);
388 static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
389 static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
390 static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
391 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
392 static int ctl_ioctl_submit_wait(union ctl_io *io);
393 static void ctl_ioctl_datamove(union ctl_io *io);
394 static void ctl_ioctl_done(union ctl_io *io);
395 static void ctl_ioctl_hard_startstop_callback(void *arg,
396                                               struct cfi_metatask *metatask);
397 static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
398 static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
399                               struct ctl_ooa *ooa_hdr,
400                               struct ctl_ooa_entry *kern_entries);
401 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
402                      struct thread *td);
403 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
404                          struct ctl_be_lun *be_lun, struct ctl_id target_id);
405 static int ctl_free_lun(struct ctl_lun *lun);
406 static void ctl_create_lun(struct ctl_be_lun *be_lun);
407 static struct ctl_port * ctl_io_port(struct ctl_io_hdr *io_hdr);
408 /**
409 static void ctl_failover_change_pages(struct ctl_softc *softc,
410                                       struct ctl_scsiio *ctsio, int master);
411 **/
412
413 static int ctl_do_mode_select(union ctl_io *io);
414 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
415                            uint64_t res_key, uint64_t sa_res_key,
416                            uint8_t type, uint32_t residx,
417                            struct ctl_scsiio *ctsio,
418                            struct scsi_per_res_out *cdb,
419                            struct scsi_per_res_out_parms* param);
420 static void ctl_pro_preempt_other(struct ctl_lun *lun,
421                                   union ctl_ha_msg *msg);
422 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
423 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
424 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
425 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
426 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
427 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
428 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
429                                          int alloc_len);
430 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
431                                          int alloc_len);
432 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
433 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
434 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
435 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
436 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
437 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
438     bool seq);
439 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
440 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
441     union ctl_io *pending_io, union ctl_io *ooa_io);
442 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
443                                 union ctl_io *starting_io);
444 static int ctl_check_blocked(struct ctl_lun *lun);
445 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
446                                 const struct ctl_cmd_entry *entry,
447                                 struct ctl_scsiio *ctsio);
448 //static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
449 static void ctl_failover(void);
450 static void ctl_clear_ua(struct ctl_softc *ctl_softc, uint32_t initidx,
451                          ctl_ua_type ua_type);
452 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
453                                struct ctl_scsiio *ctsio);
454 static int ctl_scsiio(struct ctl_scsiio *ctsio);
455
456 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
457 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
458                             ctl_ua_type ua_type);
459 static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
460                          ctl_ua_type ua_type);
461 static int ctl_abort_task(union ctl_io *io);
462 static int ctl_abort_task_set(union ctl_io *io);
463 static int ctl_i_t_nexus_reset(union ctl_io *io);
464 static void ctl_run_task(union ctl_io *io);
465 #ifdef CTL_IO_DELAY
466 static void ctl_datamove_timer_wakeup(void *arg);
467 static void ctl_done_timer_wakeup(void *arg);
468 #endif /* CTL_IO_DELAY */
469
470 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
471 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
472 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
473 static void ctl_datamove_remote_write(union ctl_io *io);
474 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
475 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
476 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
477 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
478                                     ctl_ha_dt_cb callback);
479 static void ctl_datamove_remote_read(union ctl_io *io);
480 static void ctl_datamove_remote(union ctl_io *io);
481 static int ctl_process_done(union ctl_io *io);
482 static void ctl_lun_thread(void *arg);
483 static void ctl_thresh_thread(void *arg);
484 static void ctl_work_thread(void *arg);
485 static void ctl_enqueue_incoming(union ctl_io *io);
486 static void ctl_enqueue_rtr(union ctl_io *io);
487 static void ctl_enqueue_done(union ctl_io *io);
488 static void ctl_enqueue_isc(union ctl_io *io);
489 static const struct ctl_cmd_entry *
490     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
491 static const struct ctl_cmd_entry *
492     ctl_validate_command(struct ctl_scsiio *ctsio);
493 static int ctl_cmd_applicable(uint8_t lun_type,
494     const struct ctl_cmd_entry *entry);
495
496 /*
497  * Load the serialization table.  This isn't very pretty, but is probably
498  * the easiest way to do it.
499  */
500 #include "ctl_ser_table.c"
501
502 /*
503  * We only need to define open, close and ioctl routines for this driver.
504  */
505 static struct cdevsw ctl_cdevsw = {
506         .d_version =    D_VERSION,
507         .d_flags =      0,
508         .d_open =       ctl_open,
509         .d_close =      ctl_close,
510         .d_ioctl =      ctl_ioctl,
511         .d_name =       "ctl",
512 };
513
514
515 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
516 MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
517
518 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
519
520 static moduledata_t ctl_moduledata = {
521         "ctl",
522         ctl_module_event_handler,
523         NULL
524 };
525
526 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
527 MODULE_VERSION(ctl, 1);
528
529 static struct ctl_frontend ioctl_frontend =
530 {
531         .name = "ioctl",
532 };
533
534 static void
535 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
536                             union ctl_ha_msg *msg_info)
537 {
538         struct ctl_scsiio *ctsio;
539
540         if (msg_info->hdr.original_sc == NULL) {
541                 printf("%s: original_sc == NULL!\n", __func__);
542                 /* XXX KDM now what? */
543                 return;
544         }
545
546         ctsio = &msg_info->hdr.original_sc->scsiio;
547         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
548         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
549         ctsio->io_hdr.status = msg_info->hdr.status;
550         ctsio->scsi_status = msg_info->scsi.scsi_status;
551         ctsio->sense_len = msg_info->scsi.sense_len;
552         ctsio->sense_residual = msg_info->scsi.sense_residual;
553         ctsio->residual = msg_info->scsi.residual;
554         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
555                sizeof(ctsio->sense_data));
556         memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
557                &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
558         ctl_enqueue_isc((union ctl_io *)ctsio);
559 }
560
561 static void
562 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
563                                 union ctl_ha_msg *msg_info)
564 {
565         struct ctl_scsiio *ctsio;
566
567         if (msg_info->hdr.serializing_sc == NULL) {
568                 printf("%s: serializing_sc == NULL!\n", __func__);
569                 /* XXX KDM now what? */
570                 return;
571         }
572
573         ctsio = &msg_info->hdr.serializing_sc->scsiio;
574 #if 0
575         /*
576          * Attempt to catch the situation where an I/O has
577          * been freed, and we're using it again.
578          */
579         if (ctsio->io_hdr.io_type == 0xff) {
580                 union ctl_io *tmp_io;
581                 tmp_io = (union ctl_io *)ctsio;
582                 printf("%s: %p use after free!\n", __func__,
583                        ctsio);
584                 printf("%s: type %d msg %d cdb %x iptl: "
585                        "%d:%d:%d:%d tag 0x%04x "
586                        "flag %#x status %x\n",
587                         __func__,
588                         tmp_io->io_hdr.io_type,
589                         tmp_io->io_hdr.msg_type,
590                         tmp_io->scsiio.cdb[0],
591                         tmp_io->io_hdr.nexus.initid.id,
592                         tmp_io->io_hdr.nexus.targ_port,
593                         tmp_io->io_hdr.nexus.targ_target.id,
594                         tmp_io->io_hdr.nexus.targ_lun,
595                         (tmp_io->io_hdr.io_type ==
596                         CTL_IO_TASK) ?
597                         tmp_io->taskio.tag_num :
598                         tmp_io->scsiio.tag_num,
599                         tmp_io->io_hdr.flags,
600                         tmp_io->io_hdr.status);
601         }
602 #endif
603         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
604         ctl_enqueue_isc((union ctl_io *)ctsio);
605 }
606
607 /*
608  * ISC (Inter Shelf Communication) event handler.  Events from the HA
609  * subsystem come in here.
610  */
611 static void
612 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
613 {
614         struct ctl_softc *softc;
615         union ctl_io *io;
616         struct ctl_prio *presio;
617         ctl_ha_status isc_status;
618
619         softc = control_softc;
620         io = NULL;
621
622
623 #if 0
624         printf("CTL: Isc Msg event %d\n", event);
625 #endif
626         if (event == CTL_HA_EVT_MSG_RECV) {
627                 union ctl_ha_msg msg_info;
628
629                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
630                                              sizeof(msg_info), /*wait*/ 0);
631 #if 0
632                 printf("CTL: msg_type %d\n", msg_info.msg_type);
633 #endif
634                 if (isc_status != 0) {
635                         printf("Error receiving message, status = %d\n",
636                                isc_status);
637                         return;
638                 }
639
640                 switch (msg_info.hdr.msg_type) {
641                 case CTL_MSG_SERIALIZE:
642 #if 0
643                         printf("Serialize\n");
644 #endif
645                         io = ctl_alloc_io_nowait(softc->othersc_pool);
646                         if (io == NULL) {
647                                 printf("ctl_isc_event_handler: can't allocate "
648                                        "ctl_io!\n");
649                                 /* Bad Juju */
650                                 /* Need to set busy and send msg back */
651                                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
652                                 msg_info.hdr.status = CTL_SCSI_ERROR;
653                                 msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
654                                 msg_info.scsi.sense_len = 0;
655                                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
656                                     sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
657                                 }
658                                 goto bailout;
659                         }
660                         ctl_zero_io(io);
661                         // populate ctsio from msg_info
662                         io->io_hdr.io_type = CTL_IO_SCSI;
663                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
664                         io->io_hdr.original_sc = msg_info.hdr.original_sc;
665 #if 0
666                         printf("pOrig %x\n", (int)msg_info.original_sc);
667 #endif
668                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
669                                             CTL_FLAG_IO_ACTIVE;
670                         /*
671                          * If we're in serialization-only mode, we don't
672                          * want to go through full done processing.  Thus
673                          * the COPY flag.
674                          *
675                          * XXX KDM add another flag that is more specific.
676                          */
677                         if (softc->ha_mode == CTL_HA_MODE_SER_ONLY)
678                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
679                         io->io_hdr.nexus = msg_info.hdr.nexus;
680 #if 0
681                         printf("targ %d, port %d, iid %d, lun %d\n",
682                                io->io_hdr.nexus.targ_target.id,
683                                io->io_hdr.nexus.targ_port,
684                                io->io_hdr.nexus.initid.id,
685                                io->io_hdr.nexus.targ_lun);
686 #endif
687                         io->scsiio.tag_num = msg_info.scsi.tag_num;
688                         io->scsiio.tag_type = msg_info.scsi.tag_type;
689                         memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
690                                CTL_MAX_CDBLEN);
691                         if (softc->ha_mode == CTL_HA_MODE_XFER) {
692                                 const struct ctl_cmd_entry *entry;
693
694                                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
695                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
696                                 io->io_hdr.flags |=
697                                         entry->flags & CTL_FLAG_DATA_MASK;
698                         }
699                         ctl_enqueue_isc(io);
700                         break;
701
702                 /* Performed on the Originating SC, XFER mode only */
703                 case CTL_MSG_DATAMOVE: {
704                         struct ctl_sg_entry *sgl;
705                         int i, j;
706
707                         io = msg_info.hdr.original_sc;
708                         if (io == NULL) {
709                                 printf("%s: original_sc == NULL!\n", __func__);
710                                 /* XXX KDM do something here */
711                                 break;
712                         }
713                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
714                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
715                         /*
716                          * Keep track of this, we need to send it back over
717                          * when the datamove is complete.
718                          */
719                         io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
720
721                         if (msg_info.dt.sg_sequence == 0) {
722                                 /*
723                                  * XXX KDM we use the preallocated S/G list
724                                  * here, but we'll need to change this to
725                                  * dynamic allocation if we need larger S/G
726                                  * lists.
727                                  */
728                                 if (msg_info.dt.kern_sg_entries >
729                                     sizeof(io->io_hdr.remote_sglist) /
730                                     sizeof(io->io_hdr.remote_sglist[0])) {
731                                         printf("%s: number of S/G entries "
732                                             "needed %u > allocated num %zd\n",
733                                             __func__,
734                                             msg_info.dt.kern_sg_entries,
735                                             sizeof(io->io_hdr.remote_sglist)/
736                                             sizeof(io->io_hdr.remote_sglist[0]));
737                                 
738                                         /*
739                                          * XXX KDM send a message back to
740                                          * the other side to shut down the
741                                          * DMA.  The error will come back
742                                          * through via the normal channel.
743                                          */
744                                         break;
745                                 }
746                                 sgl = io->io_hdr.remote_sglist;
747                                 memset(sgl, 0,
748                                        sizeof(io->io_hdr.remote_sglist));
749
750                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
751
752                                 io->scsiio.kern_sg_entries =
753                                         msg_info.dt.kern_sg_entries;
754                                 io->scsiio.rem_sg_entries =
755                                         msg_info.dt.kern_sg_entries;
756                                 io->scsiio.kern_data_len =
757                                         msg_info.dt.kern_data_len;
758                                 io->scsiio.kern_total_len =
759                                         msg_info.dt.kern_total_len;
760                                 io->scsiio.kern_data_resid =
761                                         msg_info.dt.kern_data_resid;
762                                 io->scsiio.kern_rel_offset =
763                                         msg_info.dt.kern_rel_offset;
764                                 /*
765                                  * Clear out per-DMA flags.
766                                  */
767                                 io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
768                                 /*
769                                  * Add per-DMA flags that are set for this
770                                  * particular DMA request.
771                                  */
772                                 io->io_hdr.flags |= msg_info.dt.flags &
773                                                     CTL_FLAG_RDMA_MASK;
774                         } else
775                                 sgl = (struct ctl_sg_entry *)
776                                         io->scsiio.kern_data_ptr;
777
778                         for (i = msg_info.dt.sent_sg_entries, j = 0;
779                              i < (msg_info.dt.sent_sg_entries +
780                              msg_info.dt.cur_sg_entries); i++, j++) {
781                                 sgl[i].addr = msg_info.dt.sg_list[j].addr;
782                                 sgl[i].len = msg_info.dt.sg_list[j].len;
783
784 #if 0
785                                 printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
786                                        __func__,
787                                        msg_info.dt.sg_list[j].addr,
788                                        msg_info.dt.sg_list[j].len,
789                                        sgl[i].addr, sgl[i].len, j, i);
790 #endif
791                         }
792 #if 0
793                         memcpy(&sgl[msg_info.dt.sent_sg_entries],
794                                msg_info.dt.sg_list,
795                                sizeof(*sgl) * msg_info.dt.cur_sg_entries);
796 #endif
797
798                         /*
799                          * If this is the last piece of the I/O, we've got
800                          * the full S/G list.  Queue processing in the thread.
801                          * Otherwise wait for the next piece.
802                          */
803                         if (msg_info.dt.sg_last != 0)
804                                 ctl_enqueue_isc(io);
805                         break;
806                 }
807                 /* Performed on the Serializing (primary) SC, XFER mode only */
808                 case CTL_MSG_DATAMOVE_DONE: {
809                         if (msg_info.hdr.serializing_sc == NULL) {
810                                 printf("%s: serializing_sc == NULL!\n",
811                                        __func__);
812                                 /* XXX KDM now what? */
813                                 break;
814                         }
815                         /*
816                          * We grab the sense information here in case
817                          * there was a failure, so we can return status
818                          * back to the initiator.
819                          */
820                         io = msg_info.hdr.serializing_sc;
821                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
822                         io->io_hdr.status = msg_info.hdr.status;
823                         io->scsiio.scsi_status = msg_info.scsi.scsi_status;
824                         io->scsiio.sense_len = msg_info.scsi.sense_len;
825                         io->scsiio.sense_residual =msg_info.scsi.sense_residual;
826                         io->io_hdr.port_status = msg_info.scsi.fetd_status;
827                         io->scsiio.residual = msg_info.scsi.residual;
828                         memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
829                                sizeof(io->scsiio.sense_data));
830                         ctl_enqueue_isc(io);
831                         break;
832                 }
833
834                 /* Preformed on Originating SC, SER_ONLY mode */
835                 case CTL_MSG_R2R:
836                         io = msg_info.hdr.original_sc;
837                         if (io == NULL) {
838                                 printf("%s: Major Bummer\n", __func__);
839                                 return;
840                         } else {
841 #if 0
842                                 printf("pOrig %x\n",(int) ctsio);
843 #endif
844                         }
845                         io->io_hdr.msg_type = CTL_MSG_R2R;
846                         io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
847                         ctl_enqueue_isc(io);
848                         break;
849
850                 /*
851                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
852                  * mode.
853                  * Performed on the Originating (i.e. secondary) SC in XFER
854                  * mode
855                  */
856                 case CTL_MSG_FINISH_IO:
857                         if (softc->ha_mode == CTL_HA_MODE_XFER)
858                                 ctl_isc_handler_finish_xfer(softc,
859                                                             &msg_info);
860                         else
861                                 ctl_isc_handler_finish_ser_only(softc,
862                                                                 &msg_info);
863                         break;
864
865                 /* Preformed on Originating SC */
866                 case CTL_MSG_BAD_JUJU:
867                         io = msg_info.hdr.original_sc;
868                         if (io == NULL) {
869                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
870                                        __func__);
871                                 break;
872                         }
873                         ctl_copy_sense_data(&msg_info, io);
874                         /*
875                          * IO should have already been cleaned up on other
876                          * SC so clear this flag so we won't send a message
877                          * back to finish the IO there.
878                          */
879                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
880                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
881
882                         /* io = msg_info.hdr.serializing_sc; */
883                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
884                         ctl_enqueue_isc(io);
885                         break;
886
887                 /* Handle resets sent from the other side */
888                 case CTL_MSG_MANAGE_TASKS: {
889                         struct ctl_taskio *taskio;
890                         taskio = (struct ctl_taskio *)ctl_alloc_io_nowait(
891                             softc->othersc_pool);
892                         if (taskio == NULL) {
893                                 printf("ctl_isc_event_handler: can't allocate "
894                                        "ctl_io!\n");
895                                 /* Bad Juju */
896                                 /* should I just call the proper reset func
897                                    here??? */
898                                 goto bailout;
899                         }
900                         ctl_zero_io((union ctl_io *)taskio);
901                         taskio->io_hdr.io_type = CTL_IO_TASK;
902                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
903                         taskio->io_hdr.nexus = msg_info.hdr.nexus;
904                         taskio->task_action = msg_info.task.task_action;
905                         taskio->tag_num = msg_info.task.tag_num;
906                         taskio->tag_type = msg_info.task.tag_type;
907 #ifdef CTL_TIME_IO
908                         taskio->io_hdr.start_time = time_uptime;
909                         getbintime(&taskio->io_hdr.start_bt);
910 #if 0
911                         cs_prof_gettime(&taskio->io_hdr.start_ticks);
912 #endif
913 #endif /* CTL_TIME_IO */
914                         ctl_run_task((union ctl_io *)taskio);
915                         break;
916                 }
917                 /* Persistent Reserve action which needs attention */
918                 case CTL_MSG_PERS_ACTION:
919                         presio = (struct ctl_prio *)ctl_alloc_io_nowait(
920                             softc->othersc_pool);
921                         if (presio == NULL) {
922                                 printf("ctl_isc_event_handler: can't allocate "
923                                        "ctl_io!\n");
924                                 /* Bad Juju */
925                                 /* Need to set busy and send msg back */
926                                 goto bailout;
927                         }
928                         ctl_zero_io((union ctl_io *)presio);
929                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
930                         presio->pr_msg = msg_info.pr;
931                         ctl_enqueue_isc((union ctl_io *)presio);
932                         break;
933                 case CTL_MSG_SYNC_FE:
934                         rcv_sync_msg = 1;
935                         break;
936                 default:
937                         printf("How did I get here?\n");
938                 }
939         } else if (event == CTL_HA_EVT_MSG_SENT) {
940                 if (param != CTL_HA_STATUS_SUCCESS) {
941                         printf("Bad status from ctl_ha_msg_send status %d\n",
942                                param);
943                 }
944                 return;
945         } else if (event == CTL_HA_EVT_DISCONNECT) {
946                 printf("CTL: Got a disconnect from Isc\n");
947                 return;
948         } else {
949                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
950                 return;
951         }
952
953 bailout:
954         return;
955 }
956
957 static void
958 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
959 {
960         struct scsi_sense_data *sense;
961
962         sense = &dest->scsiio.sense_data;
963         bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
964         dest->scsiio.scsi_status = src->scsi.scsi_status;
965         dest->scsiio.sense_len = src->scsi.sense_len;
966         dest->io_hdr.status = src->hdr.status;
967 }
968
969 static void
970 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
971 {
972         ctl_ua_type *pu;
973
974         mtx_assert(&lun->lun_lock, MA_OWNED);
975         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
976         if (pu == NULL)
977                 return;
978         pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
979 }
980
981 static void
982 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
983 {
984         int i, j;
985
986         mtx_assert(&lun->lun_lock, MA_OWNED);
987         for (i = 0; i < CTL_MAX_PORTS; i++) {
988                 if (lun->pending_ua[i] == NULL)
989                         continue;
990                 for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
991                         if (i * CTL_MAX_INIT_PER_PORT + j == except)
992                                 continue;
993                         lun->pending_ua[i][j] |= ua;
994                 }
995         }
996 }
997
998 static void
999 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1000 {
1001         ctl_ua_type *pu;
1002
1003         mtx_assert(&lun->lun_lock, MA_OWNED);
1004         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1005         if (pu == NULL)
1006                 return;
1007         pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1008 }
1009
1010 static void
1011 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1012 {
1013         int i, j;
1014
1015         mtx_assert(&lun->lun_lock, MA_OWNED);
1016         for (i = 0; i < CTL_MAX_PORTS; i++) {
1017                 if (lun->pending_ua[i] == NULL)
1018                         continue;
1019                 for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1020                         if (i * CTL_MAX_INIT_PER_PORT + j == except)
1021                                 continue;
1022                         lun->pending_ua[i][j] &= ~ua;
1023                 }
1024         }
1025 }
1026
1027 static int
1028 ctl_ha_state_sysctl(SYSCTL_HANDLER_ARGS)
1029 {
1030         struct ctl_softc *softc = (struct ctl_softc *)arg1;
1031         struct ctl_lun *lun;
1032         int error, value;
1033
1034         if (softc->flags & CTL_FLAG_ACTIVE_SHELF)
1035                 value = 0;
1036         else
1037                 value = 1;
1038
1039         error = sysctl_handle_int(oidp, &value, 0, req);
1040         if ((error != 0) || (req->newptr == NULL))
1041                 return (error);
1042
1043         mtx_lock(&softc->ctl_lock);
1044         if (value == 0)
1045                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1046         else
1047                 softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1048         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1049                 mtx_lock(&lun->lun_lock);
1050                 ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1051                 mtx_unlock(&lun->lun_lock);
1052         }
1053         mtx_unlock(&softc->ctl_lock);
1054         return (0);
1055 }
1056
1057 static int
1058 ctl_init(void)
1059 {
1060         struct ctl_softc *softc;
1061         void *other_pool;
1062         struct ctl_port *port;
1063         int i, error, retval;
1064         //int isc_retval;
1065
1066         retval = 0;
1067         ctl_pause_rtr = 0;
1068         rcv_sync_msg = 0;
1069
1070         control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1071                                M_WAITOK | M_ZERO);
1072         softc = control_softc;
1073
1074         softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1075                               "cam/ctl");
1076
1077         softc->dev->si_drv1 = softc;
1078
1079         /*
1080          * By default, return a "bad LUN" peripheral qualifier for unknown
1081          * LUNs.  The user can override this default using the tunable or
1082          * sysctl.  See the comment in ctl_inquiry_std() for more details.
1083          */
1084         softc->inquiry_pq_no_lun = 1;
1085         TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
1086                           &softc->inquiry_pq_no_lun);
1087         sysctl_ctx_init(&softc->sysctl_ctx);
1088         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1089                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1090                 CTLFLAG_RD, 0, "CAM Target Layer");
1091
1092         if (softc->sysctl_tree == NULL) {
1093                 printf("%s: unable to allocate sysctl tree\n", __func__);
1094                 destroy_dev(softc->dev);
1095                 free(control_softc, M_DEVBUF);
1096                 control_softc = NULL;
1097                 return (ENOMEM);
1098         }
1099
1100         SYSCTL_ADD_INT(&softc->sysctl_ctx,
1101                        SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1102                        "inquiry_pq_no_lun", CTLFLAG_RW,
1103                        &softc->inquiry_pq_no_lun, 0,
1104                        "Report no lun possible for invalid LUNs");
1105
1106         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1107         softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1108             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1109         softc->open_count = 0;
1110
1111         /*
1112          * Default to actually sending a SYNCHRONIZE CACHE command down to
1113          * the drive.
1114          */
1115         softc->flags = CTL_FLAG_REAL_SYNC;
1116
1117         /*
1118          * In Copan's HA scheme, the "master" and "slave" roles are
1119          * figured out through the slot the controller is in.  Although it
1120          * is an active/active system, someone has to be in charge.
1121          */
1122         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1123             OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1124             "HA head ID (0 - no HA)");
1125         if (softc->ha_id == 0) {
1126                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1127                 softc->is_single = 1;
1128                 softc->port_offset = 0;
1129         } else
1130                 softc->port_offset = (softc->ha_id - 1) * CTL_MAX_PORTS;
1131         softc->persis_offset = softc->port_offset * CTL_MAX_INIT_PER_PORT;
1132
1133         /*
1134          * XXX KDM need to figure out where we want to get our target ID
1135          * and WWID.  Is it different on each port?
1136          */
1137         softc->target.id = 0;
1138         softc->target.wwid[0] = 0x12345678;
1139         softc->target.wwid[1] = 0x87654321;
1140         STAILQ_INIT(&softc->lun_list);
1141         STAILQ_INIT(&softc->pending_lun_queue);
1142         STAILQ_INIT(&softc->fe_list);
1143         STAILQ_INIT(&softc->port_list);
1144         STAILQ_INIT(&softc->be_list);
1145         ctl_tpc_init(softc);
1146
1147         if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1148                             &other_pool) != 0)
1149         {
1150                 printf("ctl: can't allocate %d entry other SC pool, "
1151                        "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1152                 return (ENOMEM);
1153         }
1154         softc->othersc_pool = other_pool;
1155
1156         if (worker_threads <= 0)
1157                 worker_threads = max(1, mp_ncpus / 4);
1158         if (worker_threads > CTL_MAX_THREADS)
1159                 worker_threads = CTL_MAX_THREADS;
1160
1161         for (i = 0; i < worker_threads; i++) {
1162                 struct ctl_thread *thr = &softc->threads[i];
1163
1164                 mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1165                 thr->ctl_softc = softc;
1166                 STAILQ_INIT(&thr->incoming_queue);
1167                 STAILQ_INIT(&thr->rtr_queue);
1168                 STAILQ_INIT(&thr->done_queue);
1169                 STAILQ_INIT(&thr->isc_queue);
1170
1171                 error = kproc_kthread_add(ctl_work_thread, thr,
1172                     &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1173                 if (error != 0) {
1174                         printf("error creating CTL work thread!\n");
1175                         ctl_pool_free(other_pool);
1176                         return (error);
1177                 }
1178         }
1179         error = kproc_kthread_add(ctl_lun_thread, softc,
1180             &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1181         if (error != 0) {
1182                 printf("error creating CTL lun thread!\n");
1183                 ctl_pool_free(other_pool);
1184                 return (error);
1185         }
1186         error = kproc_kthread_add(ctl_thresh_thread, softc,
1187             &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1188         if (error != 0) {
1189                 printf("error creating CTL threshold thread!\n");
1190                 ctl_pool_free(other_pool);
1191                 return (error);
1192         }
1193         if (bootverbose)
1194                 printf("ctl: CAM Target Layer loaded\n");
1195
1196         /*
1197          * Initialize the ioctl front end.
1198          */
1199         ctl_frontend_register(&ioctl_frontend);
1200         port = &softc->ioctl_info.port;
1201         port->frontend = &ioctl_frontend;
1202         sprintf(softc->ioctl_info.port_name, "ioctl");
1203         port->port_type = CTL_PORT_IOCTL;
1204         port->num_requested_ctl_io = 100;
1205         port->port_name = softc->ioctl_info.port_name;
1206         port->port_online = ctl_ioctl_online;
1207         port->port_offline = ctl_ioctl_offline;
1208         port->onoff_arg = &softc->ioctl_info;
1209         port->lun_enable = ctl_ioctl_lun_enable;
1210         port->lun_disable = ctl_ioctl_lun_disable;
1211         port->targ_lun_arg = &softc->ioctl_info;
1212         port->fe_datamove = ctl_ioctl_datamove;
1213         port->fe_done = ctl_ioctl_done;
1214         port->max_targets = 15;
1215         port->max_target_id = 15;
1216
1217         if (ctl_port_register(&softc->ioctl_info.port) != 0) {
1218                 printf("ctl: ioctl front end registration failed, will "
1219                        "continue anyway\n");
1220         }
1221
1222         SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1223             OID_AUTO, "ha_state", CTLTYPE_INT | CTLFLAG_RWTUN,
1224             softc, 0, ctl_ha_state_sysctl, "I", "HA state for this head");
1225
1226 #ifdef CTL_IO_DELAY
1227         if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1228                 printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1229                        sizeof(struct callout), CTL_TIMER_BYTES);
1230                 return (EINVAL);
1231         }
1232 #endif /* CTL_IO_DELAY */
1233
1234         return (0);
1235 }
1236
1237 void
1238 ctl_shutdown(void)
1239 {
1240         struct ctl_softc *softc;
1241         struct ctl_lun *lun, *next_lun;
1242
1243         softc = (struct ctl_softc *)control_softc;
1244
1245         if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1246                 printf("ctl: ioctl front end deregistration failed\n");
1247
1248         mtx_lock(&softc->ctl_lock);
1249
1250         /*
1251          * Free up each LUN.
1252          */
1253         for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1254                 next_lun = STAILQ_NEXT(lun, links);
1255                 ctl_free_lun(lun);
1256         }
1257
1258         mtx_unlock(&softc->ctl_lock);
1259
1260         ctl_frontend_deregister(&ioctl_frontend);
1261
1262 #if 0
1263         ctl_shutdown_thread(softc->work_thread);
1264         mtx_destroy(&softc->queue_lock);
1265 #endif
1266
1267         ctl_tpc_shutdown(softc);
1268         uma_zdestroy(softc->io_zone);
1269         mtx_destroy(&softc->ctl_lock);
1270
1271         destroy_dev(softc->dev);
1272
1273         sysctl_ctx_free(&softc->sysctl_ctx);
1274
1275         free(control_softc, M_DEVBUF);
1276         control_softc = NULL;
1277
1278         if (bootverbose)
1279                 printf("ctl: CAM Target Layer unloaded\n");
1280 }
1281
1282 static int
1283 ctl_module_event_handler(module_t mod, int what, void *arg)
1284 {
1285
1286         switch (what) {
1287         case MOD_LOAD:
1288                 return (ctl_init());
1289         case MOD_UNLOAD:
1290                 return (EBUSY);
1291         default:
1292                 return (EOPNOTSUPP);
1293         }
1294 }
1295
1296 /*
1297  * XXX KDM should we do some access checks here?  Bump a reference count to
1298  * prevent a CTL module from being unloaded while someone has it open?
1299  */
1300 static int
1301 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1302 {
1303         return (0);
1304 }
1305
1306 static int
1307 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1308 {
1309         return (0);
1310 }
1311
1312 int
1313 ctl_port_enable(ctl_port_type port_type)
1314 {
1315         struct ctl_softc *softc = control_softc;
1316         struct ctl_port *port;
1317
1318         if (softc->is_single == 0) {
1319                 union ctl_ha_msg msg_info;
1320                 int isc_retval;
1321
1322 #if 0
1323                 printf("%s: HA mode, synchronizing frontend enable\n",
1324                         __func__);
1325 #endif
1326                 msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1327                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1328                         sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1329                         printf("Sync msg send error retval %d\n", isc_retval);
1330                 }
1331                 if (!rcv_sync_msg) {
1332                         isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1333                                 sizeof(msg_info), 1);
1334                 }
1335 #if 0
1336                 printf("CTL:Frontend Enable\n");
1337         } else {
1338                 printf("%s: single mode, skipping frontend synchronization\n",
1339                         __func__);
1340 #endif
1341         }
1342
1343         STAILQ_FOREACH(port, &softc->port_list, links) {
1344                 if (port_type & port->port_type)
1345                 {
1346 #if 0
1347                         printf("port %d\n", port->targ_port);
1348 #endif
1349                         ctl_port_online(port);
1350                 }
1351         }
1352
1353         return (0);
1354 }
1355
1356 int
1357 ctl_port_disable(ctl_port_type port_type)
1358 {
1359         struct ctl_softc *softc;
1360         struct ctl_port *port;
1361
1362         softc = control_softc;
1363
1364         STAILQ_FOREACH(port, &softc->port_list, links) {
1365                 if (port_type & port->port_type)
1366                         ctl_port_offline(port);
1367         }
1368
1369         return (0);
1370 }
1371
1372 /*
1373  * Returns 0 for success, 1 for failure.
1374  * Currently the only failure mode is if there aren't enough entries
1375  * allocated.  So, in case of a failure, look at num_entries_dropped,
1376  * reallocate and try again.
1377  */
1378 int
1379 ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1380               int *num_entries_filled, int *num_entries_dropped,
1381               ctl_port_type port_type, int no_virtual)
1382 {
1383         struct ctl_softc *softc;
1384         struct ctl_port *port;
1385         int entries_dropped, entries_filled;
1386         int retval;
1387         int i;
1388
1389         softc = control_softc;
1390
1391         retval = 0;
1392         entries_filled = 0;
1393         entries_dropped = 0;
1394
1395         i = 0;
1396         mtx_lock(&softc->ctl_lock);
1397         STAILQ_FOREACH(port, &softc->port_list, links) {
1398                 struct ctl_port_entry *entry;
1399
1400                 if ((port->port_type & port_type) == 0)
1401                         continue;
1402
1403                 if ((no_virtual != 0)
1404                  && (port->virtual_port != 0))
1405                         continue;
1406
1407                 if (entries_filled >= num_entries_alloced) {
1408                         entries_dropped++;
1409                         continue;
1410                 }
1411                 entry = &entries[i];
1412
1413                 entry->port_type = port->port_type;
1414                 strlcpy(entry->port_name, port->port_name,
1415                         sizeof(entry->port_name));
1416                 entry->physical_port = port->physical_port;
1417                 entry->virtual_port = port->virtual_port;
1418                 entry->wwnn = port->wwnn;
1419                 entry->wwpn = port->wwpn;
1420
1421                 i++;
1422                 entries_filled++;
1423         }
1424
1425         mtx_unlock(&softc->ctl_lock);
1426
1427         if (entries_dropped > 0)
1428                 retval = 1;
1429
1430         *num_entries_dropped = entries_dropped;
1431         *num_entries_filled = entries_filled;
1432
1433         return (retval);
1434 }
1435
1436 static void
1437 ctl_ioctl_online(void *arg)
1438 {
1439         struct ctl_ioctl_info *ioctl_info;
1440
1441         ioctl_info = (struct ctl_ioctl_info *)arg;
1442
1443         ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1444 }
1445
1446 static void
1447 ctl_ioctl_offline(void *arg)
1448 {
1449         struct ctl_ioctl_info *ioctl_info;
1450
1451         ioctl_info = (struct ctl_ioctl_info *)arg;
1452
1453         ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1454 }
1455
1456 /*
1457  * Remove an initiator by port number and initiator ID.
1458  * Returns 0 for success, -1 for failure.
1459  */
1460 int
1461 ctl_remove_initiator(struct ctl_port *port, int iid)
1462 {
1463         struct ctl_softc *softc = control_softc;
1464
1465         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1466
1467         if (iid > CTL_MAX_INIT_PER_PORT) {
1468                 printf("%s: initiator ID %u > maximun %u!\n",
1469                        __func__, iid, CTL_MAX_INIT_PER_PORT);
1470                 return (-1);
1471         }
1472
1473         mtx_lock(&softc->ctl_lock);
1474         port->wwpn_iid[iid].in_use--;
1475         port->wwpn_iid[iid].last_use = time_uptime;
1476         mtx_unlock(&softc->ctl_lock);
1477
1478         return (0);
1479 }
1480
1481 /*
1482  * Add an initiator to the initiator map.
1483  * Returns iid for success, < 0 for failure.
1484  */
1485 int
1486 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1487 {
1488         struct ctl_softc *softc = control_softc;
1489         time_t best_time;
1490         int i, best;
1491
1492         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1493
1494         if (iid >= CTL_MAX_INIT_PER_PORT) {
1495                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1496                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1497                 free(name, M_CTL);
1498                 return (-1);
1499         }
1500
1501         mtx_lock(&softc->ctl_lock);
1502
1503         if (iid < 0 && (wwpn != 0 || name != NULL)) {
1504                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1505                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1506                                 iid = i;
1507                                 break;
1508                         }
1509                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
1510                             strcmp(name, port->wwpn_iid[i].name) == 0) {
1511                                 iid = i;
1512                                 break;
1513                         }
1514                 }
1515         }
1516
1517         if (iid < 0) {
1518                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1519                         if (port->wwpn_iid[i].in_use == 0 &&
1520                             port->wwpn_iid[i].wwpn == 0 &&
1521                             port->wwpn_iid[i].name == NULL) {
1522                                 iid = i;
1523                                 break;
1524                         }
1525                 }
1526         }
1527
1528         if (iid < 0) {
1529                 best = -1;
1530                 best_time = INT32_MAX;
1531                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1532                         if (port->wwpn_iid[i].in_use == 0) {
1533                                 if (port->wwpn_iid[i].last_use < best_time) {
1534                                         best = i;
1535                                         best_time = port->wwpn_iid[i].last_use;
1536                                 }
1537                         }
1538                 }
1539                 iid = best;
1540         }
1541
1542         if (iid < 0) {
1543                 mtx_unlock(&softc->ctl_lock);
1544                 free(name, M_CTL);
1545                 return (-2);
1546         }
1547
1548         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1549                 /*
1550                  * This is not an error yet.
1551                  */
1552                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1553 #if 0
1554                         printf("%s: port %d iid %u WWPN %#jx arrived"
1555                             " again\n", __func__, port->targ_port,
1556                             iid, (uintmax_t)wwpn);
1557 #endif
1558                         goto take;
1559                 }
1560                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1561                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
1562 #if 0
1563                         printf("%s: port %d iid %u name '%s' arrived"
1564                             " again\n", __func__, port->targ_port,
1565                             iid, name);
1566 #endif
1567                         goto take;
1568                 }
1569
1570                 /*
1571                  * This is an error, but what do we do about it?  The
1572                  * driver is telling us we have a new WWPN for this
1573                  * initiator ID, so we pretty much need to use it.
1574                  */
1575                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1576                     " but WWPN %#jx '%s' is still at that address\n",
1577                     __func__, port->targ_port, iid, wwpn, name,
1578                     (uintmax_t)port->wwpn_iid[iid].wwpn,
1579                     port->wwpn_iid[iid].name);
1580
1581                 /*
1582                  * XXX KDM clear have_ca and ua_pending on each LUN for
1583                  * this initiator.
1584                  */
1585         }
1586 take:
1587         free(port->wwpn_iid[iid].name, M_CTL);
1588         port->wwpn_iid[iid].name = name;
1589         port->wwpn_iid[iid].wwpn = wwpn;
1590         port->wwpn_iid[iid].in_use++;
1591         mtx_unlock(&softc->ctl_lock);
1592
1593         return (iid);
1594 }
1595
1596 static int
1597 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1598 {
1599         int len;
1600
1601         switch (port->port_type) {
1602         case CTL_PORT_FC:
1603         {
1604                 struct scsi_transportid_fcp *id =
1605                     (struct scsi_transportid_fcp *)buf;
1606                 if (port->wwpn_iid[iid].wwpn == 0)
1607                         return (0);
1608                 memset(id, 0, sizeof(*id));
1609                 id->format_protocol = SCSI_PROTO_FC;
1610                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1611                 return (sizeof(*id));
1612         }
1613         case CTL_PORT_ISCSI:
1614         {
1615                 struct scsi_transportid_iscsi_port *id =
1616                     (struct scsi_transportid_iscsi_port *)buf;
1617                 if (port->wwpn_iid[iid].name == NULL)
1618                         return (0);
1619                 memset(id, 0, 256);
1620                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1621                     SCSI_PROTO_ISCSI;
1622                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1623                 len = roundup2(min(len, 252), 4);
1624                 scsi_ulto2b(len, id->additional_length);
1625                 return (sizeof(*id) + len);
1626         }
1627         case CTL_PORT_SAS:
1628         {
1629                 struct scsi_transportid_sas *id =
1630                     (struct scsi_transportid_sas *)buf;
1631                 if (port->wwpn_iid[iid].wwpn == 0)
1632                         return (0);
1633                 memset(id, 0, sizeof(*id));
1634                 id->format_protocol = SCSI_PROTO_SAS;
1635                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1636                 return (sizeof(*id));
1637         }
1638         default:
1639         {
1640                 struct scsi_transportid_spi *id =
1641                     (struct scsi_transportid_spi *)buf;
1642                 memset(id, 0, sizeof(*id));
1643                 id->format_protocol = SCSI_PROTO_SPI;
1644                 scsi_ulto2b(iid, id->scsi_addr);
1645                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1646                 return (sizeof(*id));
1647         }
1648         }
1649 }
1650
1651 static int
1652 ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1653 {
1654         return (0);
1655 }
1656
1657 static int
1658 ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1659 {
1660         return (0);
1661 }
1662
1663 /*
1664  * Data movement routine for the CTL ioctl frontend port.
1665  */
1666 static int
1667 ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1668 {
1669         struct ctl_sg_entry *ext_sglist, *kern_sglist;
1670         struct ctl_sg_entry ext_entry, kern_entry;
1671         int ext_sglen, ext_sg_entries, kern_sg_entries;
1672         int ext_sg_start, ext_offset;
1673         int len_to_copy, len_copied;
1674         int kern_watermark, ext_watermark;
1675         int ext_sglist_malloced;
1676         int i, j;
1677
1678         ext_sglist_malloced = 0;
1679         ext_sg_start = 0;
1680         ext_offset = 0;
1681
1682         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1683
1684         /*
1685          * If this flag is set, fake the data transfer.
1686          */
1687         if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1688                 ctsio->ext_data_filled = ctsio->ext_data_len;
1689                 goto bailout;
1690         }
1691
1692         /*
1693          * To simplify things here, if we have a single buffer, stick it in
1694          * a S/G entry and just make it a single entry S/G list.
1695          */
1696         if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1697                 int len_seen;
1698
1699                 ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1700
1701                 ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1702                                                            M_WAITOK);
1703                 ext_sglist_malloced = 1;
1704                 if (copyin(ctsio->ext_data_ptr, ext_sglist,
1705                                    ext_sglen) != 0) {
1706                         ctl_set_internal_failure(ctsio,
1707                                                  /*sks_valid*/ 0,
1708                                                  /*retry_count*/ 0);
1709                         goto bailout;
1710                 }
1711                 ext_sg_entries = ctsio->ext_sg_entries;
1712                 len_seen = 0;
1713                 for (i = 0; i < ext_sg_entries; i++) {
1714                         if ((len_seen + ext_sglist[i].len) >=
1715                              ctsio->ext_data_filled) {
1716                                 ext_sg_start = i;
1717                                 ext_offset = ctsio->ext_data_filled - len_seen;
1718                                 break;
1719                         }
1720                         len_seen += ext_sglist[i].len;
1721                 }
1722         } else {
1723                 ext_sglist = &ext_entry;
1724                 ext_sglist->addr = ctsio->ext_data_ptr;
1725                 ext_sglist->len = ctsio->ext_data_len;
1726                 ext_sg_entries = 1;
1727                 ext_sg_start = 0;
1728                 ext_offset = ctsio->ext_data_filled;
1729         }
1730
1731         if (ctsio->kern_sg_entries > 0) {
1732                 kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1733                 kern_sg_entries = ctsio->kern_sg_entries;
1734         } else {
1735                 kern_sglist = &kern_entry;
1736                 kern_sglist->addr = ctsio->kern_data_ptr;
1737                 kern_sglist->len = ctsio->kern_data_len;
1738                 kern_sg_entries = 1;
1739         }
1740
1741
1742         kern_watermark = 0;
1743         ext_watermark = ext_offset;
1744         len_copied = 0;
1745         for (i = ext_sg_start, j = 0;
1746              i < ext_sg_entries && j < kern_sg_entries;) {
1747                 uint8_t *ext_ptr, *kern_ptr;
1748
1749                 len_to_copy = MIN(ext_sglist[i].len - ext_watermark,
1750                                   kern_sglist[j].len - kern_watermark);
1751
1752                 ext_ptr = (uint8_t *)ext_sglist[i].addr;
1753                 ext_ptr = ext_ptr + ext_watermark;
1754                 if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1755                         /*
1756                          * XXX KDM fix this!
1757                          */
1758                         panic("need to implement bus address support");
1759 #if 0
1760                         kern_ptr = bus_to_virt(kern_sglist[j].addr);
1761 #endif
1762                 } else
1763                         kern_ptr = (uint8_t *)kern_sglist[j].addr;
1764                 kern_ptr = kern_ptr + kern_watermark;
1765
1766                 kern_watermark += len_to_copy;
1767                 ext_watermark += len_to_copy;
1768
1769                 if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1770                      CTL_FLAG_DATA_IN) {
1771                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1772                                          "bytes to user\n", len_to_copy));
1773                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1774                                          "to %p\n", kern_ptr, ext_ptr));
1775                         if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1776                                 ctl_set_internal_failure(ctsio,
1777                                                          /*sks_valid*/ 0,
1778                                                          /*retry_count*/ 0);
1779                                 goto bailout;
1780                         }
1781                 } else {
1782                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1783                                          "bytes from user\n", len_to_copy));
1784                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1785                                          "to %p\n", ext_ptr, kern_ptr));
1786                         if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1787                                 ctl_set_internal_failure(ctsio,
1788                                                          /*sks_valid*/ 0,
1789                                                          /*retry_count*/0);
1790                                 goto bailout;
1791                         }
1792                 }
1793
1794                 len_copied += len_to_copy;
1795
1796                 if (ext_sglist[i].len == ext_watermark) {
1797                         i++;
1798                         ext_watermark = 0;
1799                 }
1800
1801                 if (kern_sglist[j].len == kern_watermark) {
1802                         j++;
1803                         kern_watermark = 0;
1804                 }
1805         }
1806
1807         ctsio->ext_data_filled += len_copied;
1808
1809         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1810                          "kern_sg_entries: %d\n", ext_sg_entries,
1811                          kern_sg_entries));
1812         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1813                          "kern_data_len = %d\n", ctsio->ext_data_len,
1814                          ctsio->kern_data_len));
1815
1816
1817         /* XXX KDM set residual?? */
1818 bailout:
1819
1820         if (ext_sglist_malloced != 0)
1821                 free(ext_sglist, M_CTL);
1822
1823         return (CTL_RETVAL_COMPLETE);
1824 }
1825
1826 /*
1827  * Serialize a command that went down the "wrong" side, and so was sent to
1828  * this controller for execution.  The logic is a little different than the
1829  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1830  * sent back to the other side, but in the success case, we execute the
1831  * command on this side (XFER mode) or tell the other side to execute it
1832  * (SER_ONLY mode).
1833  */
1834 static int
1835 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1836 {
1837         struct ctl_softc *softc;
1838         union ctl_ha_msg msg_info;
1839         struct ctl_lun *lun;
1840         int retval = 0;
1841         uint32_t targ_lun;
1842
1843         softc = control_softc;
1844
1845         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1846         lun = softc->ctl_luns[targ_lun];
1847         if (lun==NULL)
1848         {
1849                 /*
1850                  * Why isn't LUN defined? The other side wouldn't
1851                  * send a cmd if the LUN is undefined.
1852                  */
1853                 printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1854
1855                 /* "Logical unit not supported" */
1856                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1857                                    lun,
1858                                    /*sense_format*/SSD_TYPE_NONE,
1859                                    /*current_error*/ 1,
1860                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1861                                    /*asc*/ 0x25,
1862                                    /*ascq*/ 0x00,
1863                                    SSD_ELEM_NONE);
1864
1865                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1866                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1867                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1868                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1869                 msg_info.hdr.serializing_sc = NULL;
1870                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1871                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1872                                 sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1873                 }
1874                 return(1);
1875
1876         }
1877
1878         mtx_lock(&lun->lun_lock);
1879         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1880
1881         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1882                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1883                  ooa_links))) {
1884         case CTL_ACTION_BLOCK:
1885                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1886                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1887                                   blocked_links);
1888                 break;
1889         case CTL_ACTION_PASS:
1890         case CTL_ACTION_SKIP:
1891                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
1892                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1893                         ctl_enqueue_rtr((union ctl_io *)ctsio);
1894                 } else {
1895
1896                         /* send msg back to other side */
1897                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1898                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1899                         msg_info.hdr.msg_type = CTL_MSG_R2R;
1900 #if 0
1901                         printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1902 #endif
1903                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1904                             sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1905                         }
1906                 }
1907                 break;
1908         case CTL_ACTION_OVERLAP:
1909                 /* OVERLAPPED COMMANDS ATTEMPTED */
1910                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1911                                    lun,
1912                                    /*sense_format*/SSD_TYPE_NONE,
1913                                    /*current_error*/ 1,
1914                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1915                                    /*asc*/ 0x4E,
1916                                    /*ascq*/ 0x00,
1917                                    SSD_ELEM_NONE);
1918
1919                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1920                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1921                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1922                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1923                 msg_info.hdr.serializing_sc = NULL;
1924                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1925 #if 0
1926                 printf("BAD JUJU:Major Bummer Overlap\n");
1927 #endif
1928                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1929                 retval = 1;
1930                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1931                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1932                 }
1933                 break;
1934         case CTL_ACTION_OVERLAP_TAG:
1935                 /* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1936                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1937                                    lun,
1938                                    /*sense_format*/SSD_TYPE_NONE,
1939                                    /*current_error*/ 1,
1940                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1941                                    /*asc*/ 0x4D,
1942                                    /*ascq*/ ctsio->tag_num & 0xff,
1943                                    SSD_ELEM_NONE);
1944
1945                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1946                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1947                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1948                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1949                 msg_info.hdr.serializing_sc = NULL;
1950                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1951 #if 0
1952                 printf("BAD JUJU:Major Bummer Overlap Tag\n");
1953 #endif
1954                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1955                 retval = 1;
1956                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1957                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1958                 }
1959                 break;
1960         case CTL_ACTION_ERROR:
1961         default:
1962                 /* "Internal target failure" */
1963                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1964                                    lun,
1965                                    /*sense_format*/SSD_TYPE_NONE,
1966                                    /*current_error*/ 1,
1967                                    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1968                                    /*asc*/ 0x44,
1969                                    /*ascq*/ 0x00,
1970                                    SSD_ELEM_NONE);
1971
1972                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1973                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1974                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1975                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1976                 msg_info.hdr.serializing_sc = NULL;
1977                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1978 #if 0
1979                 printf("BAD JUJU:Major Bummer HW Error\n");
1980 #endif
1981                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1982                 retval = 1;
1983                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1984                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1985                 }
1986                 break;
1987         }
1988         mtx_unlock(&lun->lun_lock);
1989         return (retval);
1990 }
1991
1992 static int
1993 ctl_ioctl_submit_wait(union ctl_io *io)
1994 {
1995         struct ctl_fe_ioctl_params params;
1996         ctl_fe_ioctl_state last_state;
1997         int done, retval;
1998
1999         retval = 0;
2000
2001         bzero(&params, sizeof(params));
2002
2003         mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
2004         cv_init(&params.sem, "ctlioccv");
2005         params.state = CTL_IOCTL_INPROG;
2006         last_state = params.state;
2007
2008         io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
2009
2010         CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
2011
2012         /* This shouldn't happen */
2013         if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
2014                 return (retval);
2015
2016         done = 0;
2017
2018         do {
2019                 mtx_lock(&params.ioctl_mtx);
2020                 /*
2021                  * Check the state here, and don't sleep if the state has
2022                  * already changed (i.e. wakeup has already occured, but we
2023                  * weren't waiting yet).
2024                  */
2025                 if (params.state == last_state) {
2026                         /* XXX KDM cv_wait_sig instead? */
2027                         cv_wait(&params.sem, &params.ioctl_mtx);
2028                 }
2029                 last_state = params.state;
2030
2031                 switch (params.state) {
2032                 case CTL_IOCTL_INPROG:
2033                         /* Why did we wake up? */
2034                         /* XXX KDM error here? */
2035                         mtx_unlock(&params.ioctl_mtx);
2036                         break;
2037                 case CTL_IOCTL_DATAMOVE:
2038                         CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
2039
2040                         /*
2041                          * change last_state back to INPROG to avoid
2042                          * deadlock on subsequent data moves.
2043                          */
2044                         params.state = last_state = CTL_IOCTL_INPROG;
2045
2046                         mtx_unlock(&params.ioctl_mtx);
2047                         ctl_ioctl_do_datamove(&io->scsiio);
2048                         /*
2049                          * Note that in some cases, most notably writes,
2050                          * this will queue the I/O and call us back later.
2051                          * In other cases, generally reads, this routine
2052                          * will immediately call back and wake us up,
2053                          * probably using our own context.
2054                          */
2055                         io->scsiio.be_move_done(io);
2056                         break;
2057                 case CTL_IOCTL_DONE:
2058                         mtx_unlock(&params.ioctl_mtx);
2059                         CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
2060                         done = 1;
2061                         break;
2062                 default:
2063                         mtx_unlock(&params.ioctl_mtx);
2064                         /* XXX KDM error here? */
2065                         break;
2066                 }
2067         } while (done == 0);
2068
2069         mtx_destroy(&params.ioctl_mtx);
2070         cv_destroy(&params.sem);
2071
2072         return (CTL_RETVAL_COMPLETE);
2073 }
2074
2075 static void
2076 ctl_ioctl_datamove(union ctl_io *io)
2077 {
2078         struct ctl_fe_ioctl_params *params;
2079
2080         params = (struct ctl_fe_ioctl_params *)
2081                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2082
2083         mtx_lock(&params->ioctl_mtx);
2084         params->state = CTL_IOCTL_DATAMOVE;
2085         cv_broadcast(&params->sem);
2086         mtx_unlock(&params->ioctl_mtx);
2087 }
2088
2089 static void
2090 ctl_ioctl_done(union ctl_io *io)
2091 {
2092         struct ctl_fe_ioctl_params *params;
2093
2094         params = (struct ctl_fe_ioctl_params *)
2095                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2096
2097         mtx_lock(&params->ioctl_mtx);
2098         params->state = CTL_IOCTL_DONE;
2099         cv_broadcast(&params->sem);
2100         mtx_unlock(&params->ioctl_mtx);
2101 }
2102
2103 static void
2104 ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2105 {
2106         struct ctl_fe_ioctl_startstop_info *sd_info;
2107
2108         sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2109
2110         sd_info->hs_info.status = metatask->status;
2111         sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2112         sd_info->hs_info.luns_complete =
2113                 metatask->taskinfo.startstop.luns_complete;
2114         sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2115
2116         cv_broadcast(&sd_info->sem);
2117 }
2118
2119 static void
2120 ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2121 {
2122         struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2123
2124         fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2125
2126         mtx_lock(fe_bbr_info->lock);
2127         fe_bbr_info->bbr_info->status = metatask->status;
2128         fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2129         fe_bbr_info->wakeup_done = 1;
2130         mtx_unlock(fe_bbr_info->lock);
2131
2132         cv_broadcast(&fe_bbr_info->sem);
2133 }
2134
2135 /*
2136  * Returns 0 for success, errno for failure.
2137  */
2138 static int
2139 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2140                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2141 {
2142         union ctl_io *io;
2143         int retval;
2144
2145         retval = 0;
2146
2147         mtx_lock(&lun->lun_lock);
2148         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2149              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2150              ooa_links)) {
2151                 struct ctl_ooa_entry *entry;
2152
2153                 /*
2154                  * If we've got more than we can fit, just count the
2155                  * remaining entries.
2156                  */
2157                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2158                         continue;
2159
2160                 entry = &kern_entries[*cur_fill_num];
2161
2162                 entry->tag_num = io->scsiio.tag_num;
2163                 entry->lun_num = lun->lun;
2164 #ifdef CTL_TIME_IO
2165                 entry->start_bt = io->io_hdr.start_bt;
2166 #endif
2167                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2168                 entry->cdb_len = io->scsiio.cdb_len;
2169                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2170                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2171
2172                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2173                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2174
2175                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2176                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2177
2178                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2179                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2180
2181                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2182                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2183         }
2184         mtx_unlock(&lun->lun_lock);
2185
2186         return (retval);
2187 }
2188
2189 static void *
2190 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2191                  size_t error_str_len)
2192 {
2193         void *kptr;
2194
2195         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2196
2197         if (copyin(user_addr, kptr, len) != 0) {
2198                 snprintf(error_str, error_str_len, "Error copying %d bytes "
2199                          "from user address %p to kernel address %p", len,
2200                          user_addr, kptr);
2201                 free(kptr, M_CTL);
2202                 return (NULL);
2203         }
2204
2205         return (kptr);
2206 }
2207
2208 static void
2209 ctl_free_args(int num_args, struct ctl_be_arg *args)
2210 {
2211         int i;
2212
2213         if (args == NULL)
2214                 return;
2215
2216         for (i = 0; i < num_args; i++) {
2217                 free(args[i].kname, M_CTL);
2218                 free(args[i].kvalue, M_CTL);
2219         }
2220
2221         free(args, M_CTL);
2222 }
2223
2224 static struct ctl_be_arg *
2225 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2226                 char *error_str, size_t error_str_len)
2227 {
2228         struct ctl_be_arg *args;
2229         int i;
2230
2231         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2232                                 error_str, error_str_len);
2233
2234         if (args == NULL)
2235                 goto bailout;
2236
2237         for (i = 0; i < num_args; i++) {
2238                 args[i].kname = NULL;
2239                 args[i].kvalue = NULL;
2240         }
2241
2242         for (i = 0; i < num_args; i++) {
2243                 uint8_t *tmpptr;
2244
2245                 args[i].kname = ctl_copyin_alloc(args[i].name,
2246                         args[i].namelen, error_str, error_str_len);
2247                 if (args[i].kname == NULL)
2248                         goto bailout;
2249
2250                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2251                         snprintf(error_str, error_str_len, "Argument %d "
2252                                  "name is not NUL-terminated", i);
2253                         goto bailout;
2254                 }
2255
2256                 if (args[i].flags & CTL_BEARG_RD) {
2257                         tmpptr = ctl_copyin_alloc(args[i].value,
2258                                 args[i].vallen, error_str, error_str_len);
2259                         if (tmpptr == NULL)
2260                                 goto bailout;
2261                         if ((args[i].flags & CTL_BEARG_ASCII)
2262                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2263                                 snprintf(error_str, error_str_len, "Argument "
2264                                     "%d value is not NUL-terminated", i);
2265                                 goto bailout;
2266                         }
2267                         args[i].kvalue = tmpptr;
2268                 } else {
2269                         args[i].kvalue = malloc(args[i].vallen,
2270                             M_CTL, M_WAITOK | M_ZERO);
2271                 }
2272         }
2273
2274         return (args);
2275 bailout:
2276
2277         ctl_free_args(num_args, args);
2278
2279         return (NULL);
2280 }
2281
2282 static void
2283 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2284 {
2285         int i;
2286
2287         for (i = 0; i < num_args; i++) {
2288                 if (args[i].flags & CTL_BEARG_WR)
2289                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2290         }
2291 }
2292
2293 /*
2294  * Escape characters that are illegal or not recommended in XML.
2295  */
2296 int
2297 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2298 {
2299         char *end = str + size;
2300         int retval;
2301
2302         retval = 0;
2303
2304         for (; *str && str < end; str++) {
2305                 switch (*str) {
2306                 case '&':
2307                         retval = sbuf_printf(sb, "&amp;");
2308                         break;
2309                 case '>':
2310                         retval = sbuf_printf(sb, "&gt;");
2311                         break;
2312                 case '<':
2313                         retval = sbuf_printf(sb, "&lt;");
2314                         break;
2315                 default:
2316                         retval = sbuf_putc(sb, *str);
2317                         break;
2318                 }
2319
2320                 if (retval != 0)
2321                         break;
2322
2323         }
2324
2325         return (retval);
2326 }
2327
2328 static void
2329 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2330 {
2331         struct scsi_vpd_id_descriptor *desc;
2332         int i;
2333
2334         if (id == NULL || id->len < 4)
2335                 return;
2336         desc = (struct scsi_vpd_id_descriptor *)id->data;
2337         switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2338         case SVPD_ID_TYPE_T10:
2339                 sbuf_printf(sb, "t10.");
2340                 break;
2341         case SVPD_ID_TYPE_EUI64:
2342                 sbuf_printf(sb, "eui.");
2343                 break;
2344         case SVPD_ID_TYPE_NAA:
2345                 sbuf_printf(sb, "naa.");
2346                 break;
2347         case SVPD_ID_TYPE_SCSI_NAME:
2348                 break;
2349         }
2350         switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2351         case SVPD_ID_CODESET_BINARY:
2352                 for (i = 0; i < desc->length; i++)
2353                         sbuf_printf(sb, "%02x", desc->identifier[i]);
2354                 break;
2355         case SVPD_ID_CODESET_ASCII:
2356                 sbuf_printf(sb, "%.*s", (int)desc->length,
2357                     (char *)desc->identifier);
2358                 break;
2359         case SVPD_ID_CODESET_UTF8:
2360                 sbuf_printf(sb, "%s", (char *)desc->identifier);
2361                 break;
2362         }
2363 }
2364
2365 static int
2366 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2367           struct thread *td)
2368 {
2369         struct ctl_softc *softc;
2370         int retval;
2371
2372         softc = control_softc;
2373
2374         retval = 0;
2375
2376         switch (cmd) {
2377         case CTL_IO: {
2378                 union ctl_io *io;
2379                 void *pool_tmp;
2380
2381                 /*
2382                  * If we haven't been "enabled", don't allow any SCSI I/O
2383                  * to this FETD.
2384                  */
2385                 if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2386                         retval = EPERM;
2387                         break;
2388                 }
2389
2390                 io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2391
2392                 /*
2393                  * Need to save the pool reference so it doesn't get
2394                  * spammed by the user's ctl_io.
2395                  */
2396                 pool_tmp = io->io_hdr.pool;
2397                 memcpy(io, (void *)addr, sizeof(*io));
2398                 io->io_hdr.pool = pool_tmp;
2399
2400                 /*
2401                  * No status yet, so make sure the status is set properly.
2402                  */
2403                 io->io_hdr.status = CTL_STATUS_NONE;
2404
2405                 /*
2406                  * The user sets the initiator ID, target and LUN IDs.
2407                  */
2408                 io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2409                 io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2410                 if ((io->io_hdr.io_type == CTL_IO_SCSI)
2411                  && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2412                         io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2413
2414                 retval = ctl_ioctl_submit_wait(io);
2415
2416                 if (retval != 0) {
2417                         ctl_free_io(io);
2418                         break;
2419                 }
2420
2421                 memcpy((void *)addr, io, sizeof(*io));
2422
2423                 /* return this to our pool */
2424                 ctl_free_io(io);
2425
2426                 break;
2427         }
2428         case CTL_ENABLE_PORT:
2429         case CTL_DISABLE_PORT:
2430         case CTL_SET_PORT_WWNS: {
2431                 struct ctl_port *port;
2432                 struct ctl_port_entry *entry;
2433
2434                 entry = (struct ctl_port_entry *)addr;
2435                 
2436                 mtx_lock(&softc->ctl_lock);
2437                 STAILQ_FOREACH(port, &softc->port_list, links) {
2438                         int action, done;
2439
2440                         action = 0;
2441                         done = 0;
2442
2443                         if ((entry->port_type == CTL_PORT_NONE)
2444                          && (entry->targ_port == port->targ_port)) {
2445                                 /*
2446                                  * If the user only wants to enable or
2447                                  * disable or set WWNs on a specific port,
2448                                  * do the operation and we're done.
2449                                  */
2450                                 action = 1;
2451                                 done = 1;
2452                         } else if (entry->port_type & port->port_type) {
2453                                 /*
2454                                  * Compare the user's type mask with the
2455                                  * particular frontend type to see if we
2456                                  * have a match.
2457                                  */
2458                                 action = 1;
2459                                 done = 0;
2460
2461                                 /*
2462                                  * Make sure the user isn't trying to set
2463                                  * WWNs on multiple ports at the same time.
2464                                  */
2465                                 if (cmd == CTL_SET_PORT_WWNS) {
2466                                         printf("%s: Can't set WWNs on "
2467                                                "multiple ports\n", __func__);
2468                                         retval = EINVAL;
2469                                         break;
2470                                 }
2471                         }
2472                         if (action != 0) {
2473                                 /*
2474                                  * XXX KDM we have to drop the lock here,
2475                                  * because the online/offline operations
2476                                  * can potentially block.  We need to
2477                                  * reference count the frontends so they
2478                                  * can't go away,
2479                                  */
2480                                 mtx_unlock(&softc->ctl_lock);
2481
2482                                 if (cmd == CTL_ENABLE_PORT) {
2483                                         struct ctl_lun *lun;
2484
2485                                         STAILQ_FOREACH(lun, &softc->lun_list,
2486                                                        links) {
2487                                                 port->lun_enable(port->targ_lun_arg,
2488                                                     lun->target,
2489                                                     lun->lun);
2490                                         }
2491
2492                                         ctl_port_online(port);
2493                                 } else if (cmd == CTL_DISABLE_PORT) {
2494                                         struct ctl_lun *lun;
2495
2496                                         ctl_port_offline(port);
2497
2498                                         STAILQ_FOREACH(lun, &softc->lun_list,
2499                                                        links) {
2500                                                 port->lun_disable(
2501                                                     port->targ_lun_arg,
2502                                                     lun->target,
2503                                                     lun->lun);
2504                                         }
2505                                 }
2506
2507                                 mtx_lock(&softc->ctl_lock);
2508
2509                                 if (cmd == CTL_SET_PORT_WWNS)
2510                                         ctl_port_set_wwns(port,
2511                                             (entry->flags & CTL_PORT_WWNN_VALID) ?
2512                                             1 : 0, entry->wwnn,
2513                                             (entry->flags & CTL_PORT_WWPN_VALID) ?
2514                                             1 : 0, entry->wwpn);
2515                         }
2516                         if (done != 0)
2517                                 break;
2518                 }
2519                 mtx_unlock(&softc->ctl_lock);
2520                 break;
2521         }
2522         case CTL_GET_PORT_LIST: {
2523                 struct ctl_port *port;
2524                 struct ctl_port_list *list;
2525                 int i;
2526
2527                 list = (struct ctl_port_list *)addr;
2528
2529                 if (list->alloc_len != (list->alloc_num *
2530                     sizeof(struct ctl_port_entry))) {
2531                         printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2532                                "alloc_num %u * sizeof(struct ctl_port_entry) "
2533                                "%zu\n", __func__, list->alloc_len,
2534                                list->alloc_num, sizeof(struct ctl_port_entry));
2535                         retval = EINVAL;
2536                         break;
2537                 }
2538                 list->fill_len = 0;
2539                 list->fill_num = 0;
2540                 list->dropped_num = 0;
2541                 i = 0;
2542                 mtx_lock(&softc->ctl_lock);
2543                 STAILQ_FOREACH(port, &softc->port_list, links) {
2544                         struct ctl_port_entry entry, *list_entry;
2545
2546                         if (list->fill_num >= list->alloc_num) {
2547                                 list->dropped_num++;
2548                                 continue;
2549                         }
2550
2551                         entry.port_type = port->port_type;
2552                         strlcpy(entry.port_name, port->port_name,
2553                                 sizeof(entry.port_name));
2554                         entry.targ_port = port->targ_port;
2555                         entry.physical_port = port->physical_port;
2556                         entry.virtual_port = port->virtual_port;
2557                         entry.wwnn = port->wwnn;
2558                         entry.wwpn = port->wwpn;
2559                         if (port->status & CTL_PORT_STATUS_ONLINE)
2560                                 entry.online = 1;
2561                         else
2562                                 entry.online = 0;
2563
2564                         list_entry = &list->entries[i];
2565
2566                         retval = copyout(&entry, list_entry, sizeof(entry));
2567                         if (retval != 0) {
2568                                 printf("%s: CTL_GET_PORT_LIST: copyout "
2569                                        "returned %d\n", __func__, retval);
2570                                 break;
2571                         }
2572                         i++;
2573                         list->fill_num++;
2574                         list->fill_len += sizeof(entry);
2575                 }
2576                 mtx_unlock(&softc->ctl_lock);
2577
2578                 /*
2579                  * If this is non-zero, we had a copyout fault, so there's
2580                  * probably no point in attempting to set the status inside
2581                  * the structure.
2582                  */
2583                 if (retval != 0)
2584                         break;
2585
2586                 if (list->dropped_num > 0)
2587                         list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2588                 else
2589                         list->status = CTL_PORT_LIST_OK;
2590                 break;
2591         }
2592         case CTL_DUMP_OOA: {
2593                 struct ctl_lun *lun;
2594                 union ctl_io *io;
2595                 char printbuf[128];
2596                 struct sbuf sb;
2597
2598                 mtx_lock(&softc->ctl_lock);
2599                 printf("Dumping OOA queues:\n");
2600                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2601                         mtx_lock(&lun->lun_lock);
2602                         for (io = (union ctl_io *)TAILQ_FIRST(
2603                              &lun->ooa_queue); io != NULL;
2604                              io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2605                              ooa_links)) {
2606                                 sbuf_new(&sb, printbuf, sizeof(printbuf),
2607                                          SBUF_FIXEDLEN);
2608                                 sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2609                                             (intmax_t)lun->lun,
2610                                             io->scsiio.tag_num,
2611                                             (io->io_hdr.flags &
2612                                             CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2613                                             (io->io_hdr.flags &
2614                                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2615                                             (io->io_hdr.flags &
2616                                             CTL_FLAG_ABORT) ? " ABORT" : "",
2617                                             (io->io_hdr.flags &
2618                                         CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2619                                 ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2620                                 sbuf_finish(&sb);
2621                                 printf("%s\n", sbuf_data(&sb));
2622                         }
2623                         mtx_unlock(&lun->lun_lock);
2624                 }
2625                 printf("OOA queues dump done\n");
2626                 mtx_unlock(&softc->ctl_lock);
2627                 break;
2628         }
2629         case CTL_GET_OOA: {
2630                 struct ctl_lun *lun;
2631                 struct ctl_ooa *ooa_hdr;
2632                 struct ctl_ooa_entry *entries;
2633                 uint32_t cur_fill_num;
2634
2635                 ooa_hdr = (struct ctl_ooa *)addr;
2636
2637                 if ((ooa_hdr->alloc_len == 0)
2638                  || (ooa_hdr->alloc_num == 0)) {
2639                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2640                                "must be non-zero\n", __func__,
2641                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2642                         retval = EINVAL;
2643                         break;
2644                 }
2645
2646                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2647                     sizeof(struct ctl_ooa_entry))) {
2648                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2649                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2650                                __func__, ooa_hdr->alloc_len,
2651                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2652                         retval = EINVAL;
2653                         break;
2654                 }
2655
2656                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2657                 if (entries == NULL) {
2658                         printf("%s: could not allocate %d bytes for OOA "
2659                                "dump\n", __func__, ooa_hdr->alloc_len);
2660                         retval = ENOMEM;
2661                         break;
2662                 }
2663
2664                 mtx_lock(&softc->ctl_lock);
2665                 if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2666                  && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2667                   || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2668                         mtx_unlock(&softc->ctl_lock);
2669                         free(entries, M_CTL);
2670                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2671                                __func__, (uintmax_t)ooa_hdr->lun_num);
2672                         retval = EINVAL;
2673                         break;
2674                 }
2675
2676                 cur_fill_num = 0;
2677
2678                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2679                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2680                                 retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2681                                         ooa_hdr, entries);
2682                                 if (retval != 0)
2683                                         break;
2684                         }
2685                         if (retval != 0) {
2686                                 mtx_unlock(&softc->ctl_lock);
2687                                 free(entries, M_CTL);
2688                                 break;
2689                         }
2690                 } else {
2691                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2692
2693                         retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2694                                                     entries);
2695                 }
2696                 mtx_unlock(&softc->ctl_lock);
2697
2698                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2699                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2700                         sizeof(struct ctl_ooa_entry);
2701                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2702                 if (retval != 0) {
2703                         printf("%s: error copying out %d bytes for OOA dump\n", 
2704                                __func__, ooa_hdr->fill_len);
2705                 }
2706
2707                 getbintime(&ooa_hdr->cur_bt);
2708
2709                 if (cur_fill_num > ooa_hdr->alloc_num) {
2710                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2711                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2712                 } else {
2713                         ooa_hdr->dropped_num = 0;
2714                         ooa_hdr->status = CTL_OOA_OK;
2715                 }
2716
2717                 free(entries, M_CTL);
2718                 break;
2719         }
2720         case CTL_CHECK_OOA: {
2721                 union ctl_io *io;
2722                 struct ctl_lun *lun;
2723                 struct ctl_ooa_info *ooa_info;
2724
2725
2726                 ooa_info = (struct ctl_ooa_info *)addr;
2727
2728                 if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2729                         ooa_info->status = CTL_OOA_INVALID_LUN;
2730                         break;
2731                 }
2732                 mtx_lock(&softc->ctl_lock);
2733                 lun = softc->ctl_luns[ooa_info->lun_id];
2734                 if (lun == NULL) {
2735                         mtx_unlock(&softc->ctl_lock);
2736                         ooa_info->status = CTL_OOA_INVALID_LUN;
2737                         break;
2738                 }
2739                 mtx_lock(&lun->lun_lock);
2740                 mtx_unlock(&softc->ctl_lock);
2741                 ooa_info->num_entries = 0;
2742                 for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2743                      io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2744                      &io->io_hdr, ooa_links)) {
2745                         ooa_info->num_entries++;
2746                 }
2747                 mtx_unlock(&lun->lun_lock);
2748
2749                 ooa_info->status = CTL_OOA_SUCCESS;
2750
2751                 break;
2752         }
2753         case CTL_HARD_START:
2754         case CTL_HARD_STOP: {
2755                 struct ctl_fe_ioctl_startstop_info ss_info;
2756                 struct cfi_metatask *metatask;
2757                 struct mtx hs_mtx;
2758
2759                 mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2760
2761                 cv_init(&ss_info.sem, "hard start/stop cv" );
2762
2763                 metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2764                 if (metatask == NULL) {
2765                         retval = ENOMEM;
2766                         mtx_destroy(&hs_mtx);
2767                         break;
2768                 }
2769
2770                 if (cmd == CTL_HARD_START)
2771                         metatask->tasktype = CFI_TASK_STARTUP;
2772                 else
2773                         metatask->tasktype = CFI_TASK_SHUTDOWN;
2774
2775                 metatask->callback = ctl_ioctl_hard_startstop_callback;
2776                 metatask->callback_arg = &ss_info;
2777
2778                 cfi_action(metatask);
2779
2780                 /* Wait for the callback */
2781                 mtx_lock(&hs_mtx);
2782                 cv_wait_sig(&ss_info.sem, &hs_mtx);
2783                 mtx_unlock(&hs_mtx);
2784
2785                 /*
2786                  * All information has been copied from the metatask by the
2787                  * time cv_broadcast() is called, so we free the metatask here.
2788                  */
2789                 cfi_free_metatask(metatask);
2790
2791                 memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2792
2793                 mtx_destroy(&hs_mtx);
2794                 break;
2795         }
2796         case CTL_BBRREAD: {
2797                 struct ctl_bbrread_info *bbr_info;
2798                 struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2799                 struct mtx bbr_mtx;
2800                 struct cfi_metatask *metatask;
2801
2802                 bbr_info = (struct ctl_bbrread_info *)addr;
2803
2804                 bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2805
2806                 bzero(&bbr_mtx, sizeof(bbr_mtx));
2807                 mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2808
2809                 fe_bbr_info.bbr_info = bbr_info;
2810                 fe_bbr_info.lock = &bbr_mtx;
2811
2812                 cv_init(&fe_bbr_info.sem, "BBR read cv");
2813                 metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2814
2815                 if (metatask == NULL) {
2816                         mtx_destroy(&bbr_mtx);
2817                         cv_destroy(&fe_bbr_info.sem);
2818                         retval = ENOMEM;
2819                         break;
2820                 }
2821                 metatask->tasktype = CFI_TASK_BBRREAD;
2822                 metatask->callback = ctl_ioctl_bbrread_callback;
2823                 metatask->callback_arg = &fe_bbr_info;
2824                 metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2825                 metatask->taskinfo.bbrread.lba = bbr_info->lba;
2826                 metatask->taskinfo.bbrread.len = bbr_info->len;
2827
2828                 cfi_action(metatask);
2829
2830                 mtx_lock(&bbr_mtx);
2831                 while (fe_bbr_info.wakeup_done == 0)
2832                         cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2833                 mtx_unlock(&bbr_mtx);
2834
2835                 bbr_info->status = metatask->status;
2836                 bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2837                 bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2838                 memcpy(&bbr_info->sense_data,
2839                        &metatask->taskinfo.bbrread.sense_data,
2840                        MIN(sizeof(bbr_info->sense_data),
2841                            sizeof(metatask->taskinfo.bbrread.sense_data)));
2842
2843                 cfi_free_metatask(metatask);
2844
2845                 mtx_destroy(&bbr_mtx);
2846                 cv_destroy(&fe_bbr_info.sem);
2847
2848                 break;
2849         }
2850         case CTL_DELAY_IO: {
2851                 struct ctl_io_delay_info *delay_info;
2852 #ifdef CTL_IO_DELAY
2853                 struct ctl_lun *lun;
2854 #endif /* CTL_IO_DELAY */
2855
2856                 delay_info = (struct ctl_io_delay_info *)addr;
2857
2858 #ifdef CTL_IO_DELAY
2859                 mtx_lock(&softc->ctl_lock);
2860
2861                 if ((delay_info->lun_id >= CTL_MAX_LUNS)
2862                  || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2863                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2864                 } else {
2865                         lun = softc->ctl_luns[delay_info->lun_id];
2866                         mtx_lock(&lun->lun_lock);
2867
2868                         delay_info->status = CTL_DELAY_STATUS_OK;
2869
2870                         switch (delay_info->delay_type) {
2871                         case CTL_DELAY_TYPE_CONT:
2872                                 break;
2873                         case CTL_DELAY_TYPE_ONESHOT:
2874                                 break;
2875                         default:
2876                                 delay_info->status =
2877                                         CTL_DELAY_STATUS_INVALID_TYPE;
2878                                 break;
2879                         }
2880
2881                         switch (delay_info->delay_loc) {
2882                         case CTL_DELAY_LOC_DATAMOVE:
2883                                 lun->delay_info.datamove_type =
2884                                         delay_info->delay_type;
2885                                 lun->delay_info.datamove_delay =
2886                                         delay_info->delay_secs;
2887                                 break;
2888                         case CTL_DELAY_LOC_DONE:
2889                                 lun->delay_info.done_type =
2890                                         delay_info->delay_type;
2891                                 lun->delay_info.done_delay =
2892                                         delay_info->delay_secs;
2893                                 break;
2894                         default:
2895                                 delay_info->status =
2896                                         CTL_DELAY_STATUS_INVALID_LOC;
2897                                 break;
2898                         }
2899                         mtx_unlock(&lun->lun_lock);
2900                 }
2901
2902                 mtx_unlock(&softc->ctl_lock);
2903 #else
2904                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2905 #endif /* CTL_IO_DELAY */
2906                 break;
2907         }
2908         case CTL_REALSYNC_SET: {
2909                 int *syncstate;
2910
2911                 syncstate = (int *)addr;
2912
2913                 mtx_lock(&softc->ctl_lock);
2914                 switch (*syncstate) {
2915                 case 0:
2916                         softc->flags &= ~CTL_FLAG_REAL_SYNC;
2917                         break;
2918                 case 1:
2919                         softc->flags |= CTL_FLAG_REAL_SYNC;
2920                         break;
2921                 default:
2922                         retval = EINVAL;
2923                         break;
2924                 }
2925                 mtx_unlock(&softc->ctl_lock);
2926                 break;
2927         }
2928         case CTL_REALSYNC_GET: {
2929                 int *syncstate;
2930
2931                 syncstate = (int*)addr;
2932
2933                 mtx_lock(&softc->ctl_lock);
2934                 if (softc->flags & CTL_FLAG_REAL_SYNC)
2935                         *syncstate = 1;
2936                 else
2937                         *syncstate = 0;
2938                 mtx_unlock(&softc->ctl_lock);
2939
2940                 break;
2941         }
2942         case CTL_SETSYNC:
2943         case CTL_GETSYNC: {
2944                 struct ctl_sync_info *sync_info;
2945                 struct ctl_lun *lun;
2946
2947                 sync_info = (struct ctl_sync_info *)addr;
2948
2949                 mtx_lock(&softc->ctl_lock);
2950                 lun = softc->ctl_luns[sync_info->lun_id];
2951                 if (lun == NULL) {
2952                         mtx_unlock(&softc->ctl_lock);
2953                         sync_info->status = CTL_GS_SYNC_NO_LUN;
2954                 }
2955                 /*
2956                  * Get or set the sync interval.  We're not bounds checking
2957                  * in the set case, hopefully the user won't do something
2958                  * silly.
2959                  */
2960                 mtx_lock(&lun->lun_lock);
2961                 mtx_unlock(&softc->ctl_lock);
2962                 if (cmd == CTL_GETSYNC)
2963                         sync_info->sync_interval = lun->sync_interval;
2964                 else
2965                         lun->sync_interval = sync_info->sync_interval;
2966                 mtx_unlock(&lun->lun_lock);
2967
2968                 sync_info->status = CTL_GS_SYNC_OK;
2969
2970                 break;
2971         }
2972         case CTL_GETSTATS: {
2973                 struct ctl_stats *stats;
2974                 struct ctl_lun *lun;
2975                 int i;
2976
2977                 stats = (struct ctl_stats *)addr;
2978
2979                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2980                      stats->alloc_len) {
2981                         stats->status = CTL_SS_NEED_MORE_SPACE;
2982                         stats->num_luns = softc->num_luns;
2983                         break;
2984                 }
2985                 /*
2986                  * XXX KDM no locking here.  If the LUN list changes,
2987                  * things can blow up.
2988                  */
2989                 for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2990                      i++, lun = STAILQ_NEXT(lun, links)) {
2991                         retval = copyout(&lun->stats, &stats->lun_stats[i],
2992                                          sizeof(lun->stats));
2993                         if (retval != 0)
2994                                 break;
2995                 }
2996                 stats->num_luns = softc->num_luns;
2997                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2998                                  softc->num_luns;
2999                 stats->status = CTL_SS_OK;
3000 #ifdef CTL_TIME_IO
3001                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
3002 #else
3003                 stats->flags = CTL_STATS_FLAG_NONE;
3004 #endif
3005                 getnanouptime(&stats->timestamp);
3006                 break;
3007         }
3008         case CTL_ERROR_INJECT: {
3009                 struct ctl_error_desc *err_desc, *new_err_desc;
3010                 struct ctl_lun *lun;
3011
3012                 err_desc = (struct ctl_error_desc *)addr;
3013
3014                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
3015                                       M_WAITOK | M_ZERO);
3016                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
3017
3018                 mtx_lock(&softc->ctl_lock);
3019                 lun = softc->ctl_luns[err_desc->lun_id];
3020                 if (lun == NULL) {
3021                         mtx_unlock(&softc->ctl_lock);
3022                         free(new_err_desc, M_CTL);
3023                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
3024                                __func__, (uintmax_t)err_desc->lun_id);
3025                         retval = EINVAL;
3026                         break;
3027                 }
3028                 mtx_lock(&lun->lun_lock);
3029                 mtx_unlock(&softc->ctl_lock);
3030
3031                 /*
3032                  * We could do some checking here to verify the validity
3033                  * of the request, but given the complexity of error
3034                  * injection requests, the checking logic would be fairly
3035                  * complex.
3036                  *
3037                  * For now, if the request is invalid, it just won't get
3038                  * executed and might get deleted.
3039                  */
3040                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
3041
3042                 /*
3043                  * XXX KDM check to make sure the serial number is unique,
3044                  * in case we somehow manage to wrap.  That shouldn't
3045                  * happen for a very long time, but it's the right thing to
3046                  * do.
3047                  */
3048                 new_err_desc->serial = lun->error_serial;
3049                 err_desc->serial = lun->error_serial;
3050                 lun->error_serial++;
3051
3052                 mtx_unlock(&lun->lun_lock);
3053                 break;
3054         }
3055         case CTL_ERROR_INJECT_DELETE: {
3056                 struct ctl_error_desc *delete_desc, *desc, *desc2;
3057                 struct ctl_lun *lun;
3058                 int delete_done;
3059
3060                 delete_desc = (struct ctl_error_desc *)addr;
3061                 delete_done = 0;
3062
3063                 mtx_lock(&softc->ctl_lock);
3064                 lun = softc->ctl_luns[delete_desc->lun_id];
3065                 if (lun == NULL) {
3066                         mtx_unlock(&softc->ctl_lock);
3067                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
3068                                __func__, (uintmax_t)delete_desc->lun_id);
3069                         retval = EINVAL;
3070                         break;
3071                 }
3072                 mtx_lock(&lun->lun_lock);
3073                 mtx_unlock(&softc->ctl_lock);
3074                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
3075                         if (desc->serial != delete_desc->serial)
3076                                 continue;
3077
3078                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
3079                                       links);
3080                         free(desc, M_CTL);
3081                         delete_done = 1;
3082                 }
3083                 mtx_unlock(&lun->lun_lock);
3084                 if (delete_done == 0) {
3085                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
3086                                "error serial %ju on LUN %u\n", __func__, 
3087                                delete_desc->serial, delete_desc->lun_id);
3088                         retval = EINVAL;
3089                         break;
3090                 }
3091                 break;
3092         }
3093         case CTL_DUMP_STRUCTS: {
3094                 int i, j, k;
3095                 struct ctl_port *port;
3096                 struct ctl_frontend *fe;
3097
3098                 mtx_lock(&softc->ctl_lock);
3099                 printf("CTL Persistent Reservation information start:\n");
3100                 for (i = 0; i < CTL_MAX_LUNS; i++) {
3101                         struct ctl_lun *lun;
3102
3103                         lun = softc->ctl_luns[i];
3104
3105                         if ((lun == NULL)
3106                          || ((lun->flags & CTL_LUN_DISABLED) != 0))
3107                                 continue;
3108
3109                         for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
3110                                 if (lun->pr_keys[j] == NULL)
3111                                         continue;
3112                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3113                                         if (lun->pr_keys[j][k] == 0)
3114                                                 continue;
3115                                         printf("  LUN %d port %d iid %d key "
3116                                                "%#jx\n", i, j, k,
3117                                                (uintmax_t)lun->pr_keys[j][k]);
3118                                 }
3119                         }
3120                 }
3121                 printf("CTL Persistent Reservation information end\n");
3122                 printf("CTL Ports:\n");
3123                 STAILQ_FOREACH(port, &softc->port_list, links) {
3124                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3125                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3126                                port->frontend->name, port->port_type,
3127                                port->physical_port, port->virtual_port,
3128                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3129                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3130                                 if (port->wwpn_iid[j].in_use == 0 &&
3131                                     port->wwpn_iid[j].wwpn == 0 &&
3132                                     port->wwpn_iid[j].name == NULL)
3133                                         continue;
3134
3135                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
3136                                     j, port->wwpn_iid[j].in_use,
3137                                     (uintmax_t)port->wwpn_iid[j].wwpn,
3138                                     port->wwpn_iid[j].name);
3139                         }
3140                 }
3141                 printf("CTL Port information end\n");
3142                 mtx_unlock(&softc->ctl_lock);
3143                 /*
3144                  * XXX KDM calling this without a lock.  We'd likely want
3145                  * to drop the lock before calling the frontend's dump
3146                  * routine anyway.
3147                  */
3148                 printf("CTL Frontends:\n");
3149                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
3150                         printf("  Frontend '%s'\n", fe->name);
3151                         if (fe->fe_dump != NULL)
3152                                 fe->fe_dump();
3153                 }
3154                 printf("CTL Frontend information end\n");
3155                 break;
3156         }
3157         case CTL_LUN_REQ: {
3158                 struct ctl_lun_req *lun_req;
3159                 struct ctl_backend_driver *backend;
3160
3161                 lun_req = (struct ctl_lun_req *)addr;
3162
3163                 backend = ctl_backend_find(lun_req->backend);
3164                 if (backend == NULL) {
3165                         lun_req->status = CTL_LUN_ERROR;
3166                         snprintf(lun_req->error_str,
3167                                  sizeof(lun_req->error_str),
3168                                  "Backend \"%s\" not found.",
3169                                  lun_req->backend);
3170                         break;
3171                 }
3172                 if (lun_req->num_be_args > 0) {
3173                         lun_req->kern_be_args = ctl_copyin_args(
3174                                 lun_req->num_be_args,
3175                                 lun_req->be_args,
3176                                 lun_req->error_str,
3177                                 sizeof(lun_req->error_str));
3178                         if (lun_req->kern_be_args == NULL) {
3179                                 lun_req->status = CTL_LUN_ERROR;
3180                                 break;
3181                         }
3182                 }
3183
3184                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3185
3186                 if (lun_req->num_be_args > 0) {
3187                         ctl_copyout_args(lun_req->num_be_args,
3188                                       lun_req->kern_be_args);
3189                         ctl_free_args(lun_req->num_be_args,
3190                                       lun_req->kern_be_args);
3191                 }
3192                 break;
3193         }
3194         case CTL_LUN_LIST: {
3195                 struct sbuf *sb;
3196                 struct ctl_lun *lun;
3197                 struct ctl_lun_list *list;
3198                 struct ctl_option *opt;
3199
3200                 list = (struct ctl_lun_list *)addr;
3201
3202                 /*
3203                  * Allocate a fixed length sbuf here, based on the length
3204                  * of the user's buffer.  We could allocate an auto-extending
3205                  * buffer, and then tell the user how much larger our
3206                  * amount of data is than his buffer, but that presents
3207                  * some problems:
3208                  *
3209                  * 1.  The sbuf(9) routines use a blocking malloc, and so
3210                  *     we can't hold a lock while calling them with an
3211                  *     auto-extending buffer.
3212                  *
3213                  * 2.  There is not currently a LUN reference counting
3214                  *     mechanism, outside of outstanding transactions on
3215                  *     the LUN's OOA queue.  So a LUN could go away on us
3216                  *     while we're getting the LUN number, backend-specific
3217                  *     information, etc.  Thus, given the way things
3218                  *     currently work, we need to hold the CTL lock while
3219                  *     grabbing LUN information.
3220                  *
3221                  * So, from the user's standpoint, the best thing to do is
3222                  * allocate what he thinks is a reasonable buffer length,
3223                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3224                  * double the buffer length and try again.  (And repeat
3225                  * that until he succeeds.)
3226                  */
3227                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3228                 if (sb == NULL) {
3229                         list->status = CTL_LUN_LIST_ERROR;
3230                         snprintf(list->error_str, sizeof(list->error_str),
3231                                  "Unable to allocate %d bytes for LUN list",
3232                                  list->alloc_len);
3233                         break;
3234                 }
3235
3236                 sbuf_printf(sb, "<ctllunlist>\n");
3237
3238                 mtx_lock(&softc->ctl_lock);
3239                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3240                         mtx_lock(&lun->lun_lock);
3241                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3242                                              (uintmax_t)lun->lun);
3243
3244                         /*
3245                          * Bail out as soon as we see that we've overfilled
3246                          * the buffer.
3247                          */
3248                         if (retval != 0)
3249                                 break;
3250
3251                         retval = sbuf_printf(sb, "\t<backend_type>%s"
3252                                              "</backend_type>\n",
3253                                              (lun->backend == NULL) ?  "none" :
3254                                              lun->backend->name);
3255
3256                         if (retval != 0)
3257                                 break;
3258
3259                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3260                                              lun->be_lun->lun_type);
3261
3262                         if (retval != 0)
3263                                 break;
3264
3265                         if (lun->backend == NULL) {
3266                                 retval = sbuf_printf(sb, "</lun>\n");
3267                                 if (retval != 0)
3268                                         break;
3269                                 continue;
3270                         }
3271
3272                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3273                                              (lun->be_lun->maxlba > 0) ?
3274                                              lun->be_lun->maxlba + 1 : 0);
3275
3276                         if (retval != 0)
3277                                 break;
3278
3279                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3280                                              lun->be_lun->blocksize);
3281
3282                         if (retval != 0)
3283                                 break;
3284
3285                         retval = sbuf_printf(sb, "\t<serial_number>");
3286
3287                         if (retval != 0)
3288                                 break;
3289
3290                         retval = ctl_sbuf_printf_esc(sb,
3291                             lun->be_lun->serial_num,
3292                             sizeof(lun->be_lun->serial_num));
3293
3294                         if (retval != 0)
3295                                 break;
3296
3297                         retval = sbuf_printf(sb, "</serial_number>\n");
3298                 
3299                         if (retval != 0)
3300                                 break;
3301
3302                         retval = sbuf_printf(sb, "\t<device_id>");
3303
3304                         if (retval != 0)
3305                                 break;
3306
3307                         retval = ctl_sbuf_printf_esc(sb,
3308                             lun->be_lun->device_id,
3309                             sizeof(lun->be_lun->device_id));
3310
3311                         if (retval != 0)
3312                                 break;
3313
3314                         retval = sbuf_printf(sb, "</device_id>\n");
3315
3316                         if (retval != 0)
3317                                 break;
3318
3319                         if (lun->backend->lun_info != NULL) {
3320                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3321                                 if (retval != 0)
3322                                         break;
3323                         }
3324                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3325                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3326                                     opt->name, opt->value, opt->name);
3327                                 if (retval != 0)
3328                                         break;
3329                         }
3330
3331                         retval = sbuf_printf(sb, "</lun>\n");
3332
3333                         if (retval != 0)
3334                                 break;
3335                         mtx_unlock(&lun->lun_lock);
3336                 }
3337                 if (lun != NULL)
3338                         mtx_unlock(&lun->lun_lock);
3339                 mtx_unlock(&softc->ctl_lock);
3340
3341                 if ((retval != 0)
3342                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3343                         retval = 0;
3344                         sbuf_delete(sb);
3345                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3346                         snprintf(list->error_str, sizeof(list->error_str),
3347                                  "Out of space, %d bytes is too small",
3348                                  list->alloc_len);
3349                         break;
3350                 }
3351
3352                 sbuf_finish(sb);
3353
3354                 retval = copyout(sbuf_data(sb), list->lun_xml,
3355                                  sbuf_len(sb) + 1);
3356
3357                 list->fill_len = sbuf_len(sb) + 1;
3358                 list->status = CTL_LUN_LIST_OK;
3359                 sbuf_delete(sb);
3360                 break;
3361         }
3362         case CTL_ISCSI: {
3363                 struct ctl_iscsi *ci;
3364                 struct ctl_frontend *fe;
3365
3366                 ci = (struct ctl_iscsi *)addr;
3367
3368                 fe = ctl_frontend_find("iscsi");
3369                 if (fe == NULL) {
3370                         ci->status = CTL_ISCSI_ERROR;
3371                         snprintf(ci->error_str, sizeof(ci->error_str),
3372                             "Frontend \"iscsi\" not found.");
3373                         break;
3374                 }
3375
3376                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3377                 break;
3378         }
3379         case CTL_PORT_REQ: {
3380                 struct ctl_req *req;
3381                 struct ctl_frontend *fe;
3382
3383                 req = (struct ctl_req *)addr;
3384
3385                 fe = ctl_frontend_find(req->driver);
3386                 if (fe == NULL) {
3387                         req->status = CTL_LUN_ERROR;
3388                         snprintf(req->error_str, sizeof(req->error_str),
3389                             "Frontend \"%s\" not found.", req->driver);
3390                         break;
3391                 }
3392                 if (req->num_args > 0) {
3393                         req->kern_args = ctl_copyin_args(req->num_args,
3394                             req->args, req->error_str, sizeof(req->error_str));
3395                         if (req->kern_args == NULL) {
3396                                 req->status = CTL_LUN_ERROR;
3397                                 break;
3398                         }
3399                 }
3400
3401                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3402
3403                 if (req->num_args > 0) {
3404                         ctl_copyout_args(req->num_args, req->kern_args);
3405                         ctl_free_args(req->num_args, req->kern_args);
3406                 }
3407                 break;
3408         }
3409         case CTL_PORT_LIST: {
3410                 struct sbuf *sb;
3411                 struct ctl_port *port;
3412                 struct ctl_lun_list *list;
3413                 struct ctl_option *opt;
3414                 int j;
3415                 uint32_t plun;
3416
3417                 list = (struct ctl_lun_list *)addr;
3418
3419                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3420                 if (sb == NULL) {
3421                         list->status = CTL_LUN_LIST_ERROR;
3422                         snprintf(list->error_str, sizeof(list->error_str),
3423                                  "Unable to allocate %d bytes for LUN list",
3424                                  list->alloc_len);
3425                         break;
3426                 }
3427
3428                 sbuf_printf(sb, "<ctlportlist>\n");
3429
3430                 mtx_lock(&softc->ctl_lock);
3431                 STAILQ_FOREACH(port, &softc->port_list, links) {
3432                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3433                                              (uintmax_t)port->targ_port);
3434
3435                         /*
3436                          * Bail out as soon as we see that we've overfilled
3437                          * the buffer.
3438                          */
3439                         if (retval != 0)
3440                                 break;
3441
3442                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3443                             "</frontend_type>\n", port->frontend->name);
3444                         if (retval != 0)
3445                                 break;
3446
3447                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3448                                              port->port_type);
3449                         if (retval != 0)
3450                                 break;
3451
3452                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3453                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3454                         if (retval != 0)
3455                                 break;
3456
3457                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3458                             port->port_name);
3459                         if (retval != 0)
3460                                 break;
3461
3462                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3463                             port->physical_port);
3464                         if (retval != 0)
3465                                 break;
3466
3467                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3468                             port->virtual_port);
3469                         if (retval != 0)
3470                                 break;
3471
3472                         if (port->target_devid != NULL) {
3473                                 sbuf_printf(sb, "\t<target>");
3474                                 ctl_id_sbuf(port->target_devid, sb);
3475                                 sbuf_printf(sb, "</target>\n");
3476                         }
3477
3478                         if (port->port_devid != NULL) {
3479                                 sbuf_printf(sb, "\t<port>");
3480                                 ctl_id_sbuf(port->port_devid, sb);
3481                                 sbuf_printf(sb, "</port>\n");
3482                         }
3483
3484                         if (port->port_info != NULL) {
3485                                 retval = port->port_info(port->onoff_arg, sb);
3486                                 if (retval != 0)
3487                                         break;
3488                         }
3489                         STAILQ_FOREACH(opt, &port->options, links) {
3490                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3491                                     opt->name, opt->value, opt->name);
3492                                 if (retval != 0)
3493                                         break;
3494                         }
3495
3496                         if (port->lun_map != NULL) {
3497                                 sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3498                                 for (j = 0; j < CTL_MAX_LUNS; j++) {
3499                                         plun = ctl_lun_map_from_port(port, j);
3500                                         if (plun >= CTL_MAX_LUNS)
3501                                                 continue;
3502                                         sbuf_printf(sb,
3503                                             "\t<lun id=\"%u\">%u</lun>\n",
3504                                             j, plun);
3505                                 }
3506                         }
3507
3508                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3509                                 if (port->wwpn_iid[j].in_use == 0 ||
3510                                     (port->wwpn_iid[j].wwpn == 0 &&
3511                                      port->wwpn_iid[j].name == NULL))
3512                                         continue;
3513
3514                                 if (port->wwpn_iid[j].name != NULL)
3515                                         retval = sbuf_printf(sb,
3516                                             "\t<initiator id=\"%u\">%s</initiator>\n",
3517                                             j, port->wwpn_iid[j].name);
3518                                 else
3519                                         retval = sbuf_printf(sb,
3520                                             "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3521                                             j, port->wwpn_iid[j].wwpn);
3522                                 if (retval != 0)
3523                                         break;
3524                         }
3525                         if (retval != 0)
3526                                 break;
3527
3528                         retval = sbuf_printf(sb, "</targ_port>\n");
3529                         if (retval != 0)
3530                                 break;
3531                 }
3532                 mtx_unlock(&softc->ctl_lock);
3533
3534                 if ((retval != 0)
3535                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3536                         retval = 0;
3537                         sbuf_delete(sb);
3538                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3539                         snprintf(list->error_str, sizeof(list->error_str),
3540                                  "Out of space, %d bytes is too small",
3541                                  list->alloc_len);
3542                         break;
3543                 }
3544
3545                 sbuf_finish(sb);
3546
3547                 retval = copyout(sbuf_data(sb), list->lun_xml,
3548                                  sbuf_len(sb) + 1);
3549
3550                 list->fill_len = sbuf_len(sb) + 1;
3551                 list->status = CTL_LUN_LIST_OK;
3552                 sbuf_delete(sb);
3553                 break;
3554         }
3555         case CTL_LUN_MAP: {
3556                 struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3557                 struct ctl_port *port;
3558
3559                 mtx_lock(&softc->ctl_lock);
3560                 if (lm->port >= CTL_MAX_PORTS ||
3561                     (port = softc->ctl_ports[lm->port]) == NULL) {
3562                         mtx_unlock(&softc->ctl_lock);
3563                         return (ENXIO);
3564                 }
3565                 if (lm->plun < CTL_MAX_LUNS) {
3566                         if (lm->lun == UINT32_MAX)
3567                                 retval = ctl_lun_map_unset(port, lm->plun);
3568                         else if (lm->lun < CTL_MAX_LUNS &&
3569                             softc->ctl_luns[lm->lun] != NULL)
3570                                 retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3571                         else {
3572                                 mtx_unlock(&softc->ctl_lock);
3573                                 return (ENXIO);
3574                         }
3575                 } else if (lm->plun == UINT32_MAX) {
3576                         if (lm->lun == UINT32_MAX)
3577                                 retval = ctl_lun_map_deinit(port);
3578                         else
3579                                 retval = ctl_lun_map_init(port);
3580                 } else {
3581                         mtx_unlock(&softc->ctl_lock);
3582                         return (ENXIO);
3583                 }
3584                 mtx_unlock(&softc->ctl_lock);
3585                 break;
3586         }
3587         default: {
3588                 /* XXX KDM should we fix this? */
3589 #if 0
3590                 struct ctl_backend_driver *backend;
3591                 unsigned int type;
3592                 int found;
3593
3594                 found = 0;
3595
3596                 /*
3597                  * We encode the backend type as the ioctl type for backend
3598                  * ioctls.  So parse it out here, and then search for a
3599                  * backend of this type.
3600                  */
3601                 type = _IOC_TYPE(cmd);
3602
3603                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3604                         if (backend->type == type) {
3605                                 found = 1;
3606                                 break;
3607                         }
3608                 }
3609                 if (found == 0) {
3610                         printf("ctl: unknown ioctl command %#lx or backend "
3611                                "%d\n", cmd, type);
3612                         retval = EINVAL;
3613                         break;
3614                 }
3615                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3616 #endif
3617                 retval = ENOTTY;
3618                 break;
3619         }
3620         }
3621         return (retval);
3622 }
3623
3624 uint32_t
3625 ctl_get_initindex(struct ctl_nexus *nexus)
3626 {
3627         if (nexus->targ_port < CTL_MAX_PORTS)
3628                 return (nexus->initid.id +
3629                         (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3630         else
3631                 return (nexus->initid.id +
3632                        ((nexus->targ_port - CTL_MAX_PORTS) *
3633                         CTL_MAX_INIT_PER_PORT));
3634 }
3635
3636 uint32_t
3637 ctl_get_resindex(struct ctl_nexus *nexus)
3638 {
3639         return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3640 }
3641
3642 uint32_t
3643 ctl_port_idx(int port_num)
3644 {
3645         if (port_num < CTL_MAX_PORTS)
3646                 return(port_num);
3647         else
3648                 return(port_num - CTL_MAX_PORTS);
3649 }
3650
3651 int
3652 ctl_lun_map_init(struct ctl_port *port)
3653 {
3654         uint32_t i;
3655
3656         if (port->lun_map == NULL)
3657                 port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3658                     M_CTL, M_NOWAIT);
3659         if (port->lun_map == NULL)
3660                 return (ENOMEM);
3661         for (i = 0; i < CTL_MAX_LUNS; i++)
3662                 port->lun_map[i] = UINT32_MAX;
3663         return (0);
3664 }
3665
3666 int
3667 ctl_lun_map_deinit(struct ctl_port *port)
3668 {
3669
3670         if (port->lun_map == NULL)
3671                 return (0);
3672         free(port->lun_map, M_CTL);
3673         port->lun_map = NULL;
3674         return (0);
3675 }
3676
3677 int
3678 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3679 {
3680         int status;
3681
3682         if (port->lun_map == NULL) {
3683                 status = ctl_lun_map_init(port);
3684                 if (status != 0)
3685                         return (status);
3686         }
3687         port->lun_map[plun] = glun;
3688         return (0);
3689 }
3690
3691 int
3692 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3693 {
3694
3695         if (port->lun_map == NULL)
3696                 return (0);
3697         port->lun_map[plun] = UINT32_MAX;
3698         return (0);
3699 }
3700
3701 int
3702 ctl_lun_map_unsetg(struct ctl_port *port, uint32_t glun)
3703 {
3704         int i;
3705
3706         if (port->lun_map == NULL)
3707                 return (0);
3708         for (i = 0; i < CTL_MAX_LUNS; i++) {
3709                 if (port->lun_map[i] == glun)
3710                         port->lun_map[i] = UINT32_MAX;
3711         }
3712         return (0);
3713 }
3714
3715 uint32_t
3716 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3717 {
3718
3719         if (port == NULL)
3720                 return (UINT32_MAX);
3721         if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3722                 return (lun_id);
3723         return (port->lun_map[lun_id]);
3724 }
3725
3726 uint32_t
3727 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3728 {
3729         uint32_t i;
3730
3731         if (port == NULL)
3732                 return (UINT32_MAX);
3733         if (port->lun_map == NULL)
3734                 return (lun_id);
3735         for (i = 0; i < CTL_MAX_LUNS; i++) {
3736                 if (port->lun_map[i] == lun_id)
3737                         return (i);
3738         }
3739         return (UINT32_MAX);
3740 }
3741
3742 static struct ctl_port *
3743 ctl_io_port(struct ctl_io_hdr *io_hdr)
3744 {
3745         int port_num;
3746
3747         port_num = io_hdr->nexus.targ_port;
3748         return (control_softc->ctl_ports[ctl_port_idx(port_num)]);
3749 }
3750
3751 /*
3752  * Note:  This only works for bitmask sizes that are at least 32 bits, and
3753  * that are a power of 2.
3754  */
3755 int
3756 ctl_ffz(uint32_t *mask, uint32_t size)
3757 {
3758         uint32_t num_chunks, num_pieces;
3759         int i, j;
3760
3761         num_chunks = (size >> 5);
3762         if (num_chunks == 0)
3763                 num_chunks++;
3764         num_pieces = MIN((sizeof(uint32_t) * 8), size);
3765
3766         for (i = 0; i < num_chunks; i++) {
3767                 for (j = 0; j < num_pieces; j++) {
3768                         if ((mask[i] & (1 << j)) == 0)
3769                                 return ((i << 5) + j);
3770                 }
3771         }
3772
3773         return (-1);
3774 }
3775
3776 int
3777 ctl_set_mask(uint32_t *mask, uint32_t bit)
3778 {
3779         uint32_t chunk, piece;
3780
3781         chunk = bit >> 5;
3782         piece = bit % (sizeof(uint32_t) * 8);
3783
3784         if ((mask[chunk] & (1 << piece)) != 0)
3785                 return (-1);
3786         else
3787                 mask[chunk] |= (1 << piece);
3788
3789         return (0);
3790 }
3791
3792 int
3793 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3794 {
3795         uint32_t chunk, piece;
3796
3797         chunk = bit >> 5;
3798         piece = bit % (sizeof(uint32_t) * 8);
3799
3800         if ((mask[chunk] & (1 << piece)) == 0)
3801                 return (-1);
3802         else
3803                 mask[chunk] &= ~(1 << piece);
3804
3805         return (0);
3806 }
3807
3808 int
3809 ctl_is_set(uint32_t *mask, uint32_t bit)
3810 {
3811         uint32_t chunk, piece;
3812
3813         chunk = bit >> 5;
3814         piece = bit % (sizeof(uint32_t) * 8);
3815
3816         if ((mask[chunk] & (1 << piece)) == 0)
3817                 return (0);
3818         else
3819                 return (1);
3820 }
3821
3822 static uint64_t
3823 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3824 {
3825         uint64_t *t;
3826
3827         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3828         if (t == NULL)
3829                 return (0);
3830         return (t[residx % CTL_MAX_INIT_PER_PORT]);
3831 }
3832
3833 static void
3834 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3835 {
3836         uint64_t *t;
3837
3838         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3839         if (t == NULL)
3840                 return;
3841         t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3842 }
3843
3844 static void
3845 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3846 {
3847         uint64_t *p;
3848         u_int i;
3849
3850         i = residx/CTL_MAX_INIT_PER_PORT;
3851         if (lun->pr_keys[i] != NULL)
3852                 return;
3853         mtx_unlock(&lun->lun_lock);
3854         p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3855             M_WAITOK | M_ZERO);
3856         mtx_lock(&lun->lun_lock);
3857         if (lun->pr_keys[i] == NULL)
3858                 lun->pr_keys[i] = p;
3859         else
3860                 free(p, M_CTL);
3861 }
3862
3863 static void
3864 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3865 {
3866         uint64_t *t;
3867
3868         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3869         KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3870         t[residx % CTL_MAX_INIT_PER_PORT] = key;
3871 }
3872
3873 /*
3874  * ctl_softc, pool_name, total_ctl_io are passed in.
3875  * npool is passed out.
3876  */
3877 int
3878 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3879                 uint32_t total_ctl_io, void **npool)
3880 {
3881 #ifdef IO_POOLS
3882         struct ctl_io_pool *pool;
3883
3884         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3885                                             M_NOWAIT | M_ZERO);
3886         if (pool == NULL)
3887                 return (ENOMEM);
3888
3889         snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3890         pool->ctl_softc = ctl_softc;
3891         pool->zone = uma_zsecond_create(pool->name, NULL,
3892             NULL, NULL, NULL, ctl_softc->io_zone);
3893         /* uma_prealloc(pool->zone, total_ctl_io); */
3894
3895         *npool = pool;
3896 #else
3897         *npool = ctl_softc->io_zone;
3898 #endif
3899         return (0);
3900 }
3901
3902 void
3903 ctl_pool_free(struct ctl_io_pool *pool)
3904 {
3905
3906         if (pool == NULL)
3907                 return;
3908
3909 #ifdef IO_POOLS
3910         uma_zdestroy(pool->zone);
3911         free(pool, M_CTL);
3912 #endif
3913 }
3914
3915 union ctl_io *
3916 ctl_alloc_io(void *pool_ref)
3917 {
3918         union ctl_io *io;
3919 #ifdef IO_POOLS
3920         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3921
3922         io = uma_zalloc(pool->zone, M_WAITOK);
3923 #else
3924         io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3925 #endif
3926         if (io != NULL)
3927                 io->io_hdr.pool = pool_ref;
3928         return (io);
3929 }
3930
3931 union ctl_io *
3932 ctl_alloc_io_nowait(void *pool_ref)
3933 {
3934         union ctl_io *io;
3935 #ifdef IO_POOLS
3936         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3937
3938         io = uma_zalloc(pool->zone, M_NOWAIT);
3939 #else
3940         io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3941 #endif
3942         if (io != NULL)
3943                 io->io_hdr.pool = pool_ref;
3944         return (io);
3945 }
3946
3947 void
3948 ctl_free_io(union ctl_io *io)
3949 {
3950 #ifdef IO_POOLS
3951         struct ctl_io_pool *pool;
3952 #endif
3953
3954         if (io == NULL)
3955                 return;
3956
3957 #ifdef IO_POOLS
3958         pool = (struct ctl_io_pool *)io->io_hdr.pool;
3959         uma_zfree(pool->zone, io);
3960 #else
3961         uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3962 #endif
3963 }
3964
3965 void
3966 ctl_zero_io(union ctl_io *io)
3967 {
3968         void *pool_ref;
3969
3970         if (io == NULL)
3971                 return;
3972
3973         /*
3974          * May need to preserve linked list pointers at some point too.
3975          */
3976         pool_ref = io->io_hdr.pool;
3977         memset(io, 0, sizeof(*io));
3978         io->io_hdr.pool = pool_ref;
3979 }
3980
3981 /*
3982  * This routine is currently used for internal copies of ctl_ios that need
3983  * to persist for some reason after we've already returned status to the
3984  * FETD.  (Thus the flag set.)
3985  *
3986  * XXX XXX
3987  * Note that this makes a blind copy of all fields in the ctl_io, except
3988  * for the pool reference.  This includes any memory that has been
3989  * allocated!  That memory will no longer be valid after done has been
3990  * called, so this would be VERY DANGEROUS for command that actually does
3991  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3992  * start and stop commands, which don't transfer any data, so this is not a
3993  * problem.  If it is used for anything else, the caller would also need to
3994  * allocate data buffer space and this routine would need to be modified to
3995  * copy the data buffer(s) as well.
3996  */
3997 void
3998 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3999 {
4000         void *pool_ref;
4001
4002         if ((src == NULL)
4003          || (dest == NULL))
4004                 return;
4005
4006         /*
4007          * May need to preserve linked list pointers at some point too.
4008          */
4009         pool_ref = dest->io_hdr.pool;
4010
4011         memcpy(dest, src, MIN(sizeof(*src), sizeof(*dest)));
4012
4013         dest->io_hdr.pool = pool_ref;
4014         /*
4015          * We need to know that this is an internal copy, and doesn't need
4016          * to get passed back to the FETD that allocated it.
4017          */
4018         dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
4019 }
4020
4021 int
4022 ctl_expand_number(const char *buf, uint64_t *num)
4023 {
4024         char *endptr;
4025         uint64_t number;
4026         unsigned shift;
4027
4028         number = strtoq(buf, &endptr, 0);
4029
4030         switch (tolower((unsigned char)*endptr)) {
4031         case 'e':
4032                 shift = 60;
4033                 break;
4034         case 'p':
4035                 shift = 50;
4036                 break;
4037         case 't':
4038                 shift = 40;
4039                 break;
4040         case 'g':
4041                 shift = 30;
4042                 break;
4043         case 'm':
4044                 shift = 20;
4045                 break;
4046         case 'k':
4047                 shift = 10;
4048                 break;
4049         case 'b':
4050         case '\0': /* No unit. */
4051                 *num = number;
4052                 return (0);
4053         default:
4054                 /* Unrecognized unit. */
4055                 return (-1);
4056         }
4057
4058         if ((number << shift) >> shift != number) {
4059                 /* Overflow */
4060                 return (-1);
4061         }
4062         *num = number << shift;
4063         return (0);
4064 }
4065
4066
4067 /*
4068  * This routine could be used in the future to load default and/or saved
4069  * mode page parameters for a particuar lun.
4070  */
4071 static int
4072 ctl_init_page_index(struct ctl_lun *lun)
4073 {
4074         int i;
4075         struct ctl_page_index *page_index;
4076         const char *value;
4077         uint64_t ival;
4078
4079         memcpy(&lun->mode_pages.index, page_index_template,
4080                sizeof(page_index_template));
4081
4082         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4083
4084                 page_index = &lun->mode_pages.index[i];
4085                 /*
4086                  * If this is a disk-only mode page, there's no point in
4087                  * setting it up.  For some pages, we have to have some
4088                  * basic information about the disk in order to calculate the
4089                  * mode page data.
4090                  */
4091                 if ((lun->be_lun->lun_type != T_DIRECT)
4092                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4093                         continue;
4094
4095                 switch (page_index->page_code & SMPH_PC_MASK) {
4096                 case SMS_RW_ERROR_RECOVERY_PAGE: {
4097                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4098                                 panic("subpage is incorrect!");
4099                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4100                                &rw_er_page_default,
4101                                sizeof(rw_er_page_default));
4102                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4103                                &rw_er_page_changeable,
4104                                sizeof(rw_er_page_changeable));
4105                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4106                                &rw_er_page_default,
4107                                sizeof(rw_er_page_default));
4108                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4109                                &rw_er_page_default,
4110                                sizeof(rw_er_page_default));
4111                         page_index->page_data =
4112                                 (uint8_t *)lun->mode_pages.rw_er_page;
4113                         break;
4114                 }
4115                 case SMS_FORMAT_DEVICE_PAGE: {
4116                         struct scsi_format_page *format_page;
4117
4118                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4119                                 panic("subpage is incorrect!");
4120
4121                         /*
4122                          * Sectors per track are set above.  Bytes per
4123                          * sector need to be set here on a per-LUN basis.
4124                          */
4125                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4126                                &format_page_default,
4127                                sizeof(format_page_default));
4128                         memcpy(&lun->mode_pages.format_page[
4129                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
4130                                sizeof(format_page_changeable));
4131                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4132                                &format_page_default,
4133                                sizeof(format_page_default));
4134                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4135                                &format_page_default,
4136                                sizeof(format_page_default));
4137
4138                         format_page = &lun->mode_pages.format_page[
4139                                 CTL_PAGE_CURRENT];
4140                         scsi_ulto2b(lun->be_lun->blocksize,
4141                                     format_page->bytes_per_sector);
4142
4143                         format_page = &lun->mode_pages.format_page[
4144                                 CTL_PAGE_DEFAULT];
4145                         scsi_ulto2b(lun->be_lun->blocksize,
4146                                     format_page->bytes_per_sector);
4147
4148                         format_page = &lun->mode_pages.format_page[
4149                                 CTL_PAGE_SAVED];
4150                         scsi_ulto2b(lun->be_lun->blocksize,
4151                                     format_page->bytes_per_sector);
4152
4153                         page_index->page_data =
4154                                 (uint8_t *)lun->mode_pages.format_page;
4155                         break;
4156                 }
4157                 case SMS_RIGID_DISK_PAGE: {
4158                         struct scsi_rigid_disk_page *rigid_disk_page;
4159                         uint32_t sectors_per_cylinder;
4160                         uint64_t cylinders;
4161 #ifndef __XSCALE__
4162                         int shift;
4163 #endif /* !__XSCALE__ */
4164
4165                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4166                                 panic("invalid subpage value %d",
4167                                       page_index->subpage);
4168
4169                         /*
4170                          * Rotation rate and sectors per track are set
4171                          * above.  We calculate the cylinders here based on
4172                          * capacity.  Due to the number of heads and
4173                          * sectors per track we're using, smaller arrays
4174                          * may turn out to have 0 cylinders.  Linux and
4175                          * FreeBSD don't pay attention to these mode pages
4176                          * to figure out capacity, but Solaris does.  It
4177                          * seems to deal with 0 cylinders just fine, and
4178                          * works out a fake geometry based on the capacity.
4179                          */
4180                         memcpy(&lun->mode_pages.rigid_disk_page[
4181                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4182                                sizeof(rigid_disk_page_default));
4183                         memcpy(&lun->mode_pages.rigid_disk_page[
4184                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4185                                sizeof(rigid_disk_page_changeable));
4186
4187                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4188                                 CTL_DEFAULT_HEADS;
4189
4190                         /*
4191                          * The divide method here will be more accurate,
4192                          * probably, but results in floating point being
4193                          * used in the kernel on i386 (__udivdi3()).  On the
4194                          * XScale, though, __udivdi3() is implemented in
4195                          * software.
4196                          *
4197                          * The shift method for cylinder calculation is
4198                          * accurate if sectors_per_cylinder is a power of
4199                          * 2.  Otherwise it might be slightly off -- you
4200                          * might have a bit of a truncation problem.
4201                          */
4202 #ifdef  __XSCALE__
4203                         cylinders = (lun->be_lun->maxlba + 1) /
4204                                 sectors_per_cylinder;
4205 #else
4206                         for (shift = 31; shift > 0; shift--) {
4207                                 if (sectors_per_cylinder & (1 << shift))
4208                                         break;
4209                         }
4210                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
4211 #endif
4212
4213                         /*
4214                          * We've basically got 3 bytes, or 24 bits for the
4215                          * cylinder size in the mode page.  If we're over,
4216                          * just round down to 2^24.
4217                          */
4218                         if (cylinders > 0xffffff)
4219                                 cylinders = 0xffffff;
4220
4221                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4222                                 CTL_PAGE_DEFAULT];
4223                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4224
4225                         if ((value = ctl_get_opt(&lun->be_lun->options,
4226                             "rpm")) != NULL) {
4227                                 scsi_ulto2b(strtol(value, NULL, 0),
4228                                      rigid_disk_page->rotation_rate);
4229                         }
4230
4231                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4232                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4233                                sizeof(rigid_disk_page_default));
4234                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4235                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4236                                sizeof(rigid_disk_page_default));
4237
4238                         page_index->page_data =
4239                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
4240                         break;
4241                 }
4242                 case SMS_CACHING_PAGE: {
4243                         struct scsi_caching_page *caching_page;
4244
4245                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4246                                 panic("invalid subpage value %d",
4247                                       page_index->subpage);
4248                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4249                                &caching_page_default,
4250                                sizeof(caching_page_default));
4251                         memcpy(&lun->mode_pages.caching_page[
4252                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4253                                sizeof(caching_page_changeable));
4254                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4255                                &caching_page_default,
4256                                sizeof(caching_page_default));
4257                         caching_page = &lun->mode_pages.caching_page[
4258                             CTL_PAGE_SAVED];
4259                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
4260                         if (value != NULL && strcmp(value, "off") == 0)
4261                                 caching_page->flags1 &= ~SCP_WCE;
4262                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
4263                         if (value != NULL && strcmp(value, "off") == 0)
4264                                 caching_page->flags1 |= SCP_RCD;
4265                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4266                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4267                                sizeof(caching_page_default));
4268                         page_index->page_data =
4269                                 (uint8_t *)lun->mode_pages.caching_page;
4270                         break;
4271                 }
4272                 case SMS_CONTROL_MODE_PAGE: {
4273                         struct scsi_control_page *control_page;
4274
4275                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4276                                 panic("invalid subpage value %d",
4277                                       page_index->subpage);
4278
4279                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4280                                &control_page_default,
4281                                sizeof(control_page_default));
4282                         memcpy(&lun->mode_pages.control_page[
4283                                CTL_PAGE_CHANGEABLE], &control_page_changeable,
4284                                sizeof(control_page_changeable));
4285                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4286                                &control_page_default,
4287                                sizeof(control_page_default));
4288                         control_page = &lun->mode_pages.control_page[
4289                             CTL_PAGE_SAVED];
4290                         value = ctl_get_opt(&lun->be_lun->options, "reordering");
4291                         if (value != NULL && strcmp(value, "unrestricted") == 0) {
4292                                 control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4293                                 control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4294                         }
4295                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4296                                &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4297                                sizeof(control_page_default));
4298                         page_index->page_data =
4299                                 (uint8_t *)lun->mode_pages.control_page;
4300                         break;
4301
4302                 }
4303                 case SMS_INFO_EXCEPTIONS_PAGE: {
4304                         switch (page_index->subpage) {
4305                         case SMS_SUBPAGE_PAGE_0:
4306                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4307                                        &ie_page_default,
4308                                        sizeof(ie_page_default));
4309                                 memcpy(&lun->mode_pages.ie_page[
4310                                        CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4311                                        sizeof(ie_page_changeable));
4312                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4313                                        &ie_page_default,
4314                                        sizeof(ie_page_default));
4315                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4316                                        &ie_page_default,
4317                                        sizeof(ie_page_default));
4318                                 page_index->page_data =
4319                                         (uint8_t *)lun->mode_pages.ie_page;
4320                                 break;
4321                         case 0x02: {
4322                                 struct ctl_logical_block_provisioning_page *page;
4323
4324                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4325                                        &lbp_page_default,
4326                                        sizeof(lbp_page_default));
4327                                 memcpy(&lun->mode_pages.lbp_page[
4328                                        CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4329                                        sizeof(lbp_page_changeable));
4330                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4331                                        &lbp_page_default,
4332                                        sizeof(lbp_page_default));
4333                                 page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4334                                 value = ctl_get_opt(&lun->be_lun->options,
4335                                     "avail-threshold");
4336                                 if (value != NULL &&
4337                                     ctl_expand_number(value, &ival) == 0) {
4338                                         page->descr[0].flags |= SLBPPD_ENABLED |
4339                                             SLBPPD_ARMING_DEC;
4340                                         if (lun->be_lun->blocksize)
4341                                                 ival /= lun->be_lun->blocksize;
4342                                         else
4343                                                 ival /= 512;
4344                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4345                                             page->descr[0].count);
4346                                 }
4347                                 value = ctl_get_opt(&lun->be_lun->options,
4348                                     "used-threshold");
4349                                 if (value != NULL &&
4350                                     ctl_expand_number(value, &ival) == 0) {
4351                                         page->descr[1].flags |= SLBPPD_ENABLED |
4352                                             SLBPPD_ARMING_INC;
4353                                         if (lun->be_lun->blocksize)
4354                                                 ival /= lun->be_lun->blocksize;
4355                                         else
4356                                                 ival /= 512;
4357                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4358                                             page->descr[1].count);
4359                                 }
4360                                 value = ctl_get_opt(&lun->be_lun->options,
4361                                     "pool-avail-threshold");
4362                                 if (value != NULL &&
4363                                     ctl_expand_number(value, &ival) == 0) {
4364                                         page->descr[2].flags |= SLBPPD_ENABLED |
4365                                             SLBPPD_ARMING_DEC;
4366                                         if (lun->be_lun->blocksize)
4367                                                 ival /= lun->be_lun->blocksize;
4368                                         else
4369                                                 ival /= 512;
4370                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4371                                             page->descr[2].count);
4372                                 }
4373                                 value = ctl_get_opt(&lun->be_lun->options,
4374                                     "pool-used-threshold");
4375                                 if (value != NULL &&
4376                                     ctl_expand_number(value, &ival) == 0) {
4377                                         page->descr[3].flags |= SLBPPD_ENABLED |
4378                                             SLBPPD_ARMING_INC;
4379                                         if (lun->be_lun->blocksize)
4380                                                 ival /= lun->be_lun->blocksize;
4381                                         else
4382                                                 ival /= 512;
4383                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4384                                             page->descr[3].count);
4385                                 }
4386                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4387                                        &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4388                                        sizeof(lbp_page_default));
4389                                 page_index->page_data =
4390                                         (uint8_t *)lun->mode_pages.lbp_page;
4391                         }}
4392                         break;
4393                 }
4394                 case SMS_VENDOR_SPECIFIC_PAGE:{
4395                         switch (page_index->subpage) {
4396                         case DBGCNF_SUBPAGE_CODE: {
4397                                 struct copan_debugconf_subpage *current_page,
4398                                                                *saved_page;
4399
4400                                 memcpy(&lun->mode_pages.debugconf_subpage[
4401                                        CTL_PAGE_CURRENT],
4402                                        &debugconf_page_default,
4403                                        sizeof(debugconf_page_default));
4404                                 memcpy(&lun->mode_pages.debugconf_subpage[
4405                                        CTL_PAGE_CHANGEABLE],
4406                                        &debugconf_page_changeable,
4407                                        sizeof(debugconf_page_changeable));
4408                                 memcpy(&lun->mode_pages.debugconf_subpage[
4409                                        CTL_PAGE_DEFAULT],
4410                                        &debugconf_page_default,
4411                                        sizeof(debugconf_page_default));
4412                                 memcpy(&lun->mode_pages.debugconf_subpage[
4413                                        CTL_PAGE_SAVED],
4414                                        &debugconf_page_default,
4415                                        sizeof(debugconf_page_default));
4416                                 page_index->page_data =
4417                                         (uint8_t *)lun->mode_pages.debugconf_subpage;
4418
4419                                 current_page = (struct copan_debugconf_subpage *)
4420                                         (page_index->page_data +
4421                                          (page_index->page_len *
4422                                           CTL_PAGE_CURRENT));
4423                                 saved_page = (struct copan_debugconf_subpage *)
4424                                         (page_index->page_data +
4425                                          (page_index->page_len *
4426                                           CTL_PAGE_SAVED));
4427                                 break;
4428                         }
4429                         default:
4430                                 panic("invalid subpage value %d",
4431                                       page_index->subpage);
4432                                 break;
4433                         }
4434                         break;
4435                 }
4436                 default:
4437                         panic("invalid page value %d",
4438                               page_index->page_code & SMPH_PC_MASK);
4439                         break;
4440         }
4441         }
4442
4443         return (CTL_RETVAL_COMPLETE);
4444 }
4445
4446 static int
4447 ctl_init_log_page_index(struct ctl_lun *lun)
4448 {
4449         struct ctl_page_index *page_index;
4450         int i, j, k, prev;
4451
4452         memcpy(&lun->log_pages.index, log_page_index_template,
4453                sizeof(log_page_index_template));
4454
4455         prev = -1;
4456         for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4457
4458                 page_index = &lun->log_pages.index[i];
4459                 /*
4460                  * If this is a disk-only mode page, there's no point in
4461                  * setting it up.  For some pages, we have to have some
4462                  * basic information about the disk in order to calculate the
4463                  * mode page data.
4464                  */
4465                 if ((lun->be_lun->lun_type != T_DIRECT)
4466                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4467                         continue;
4468
4469                 if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4470                      lun->backend->lun_attr == NULL)
4471                         continue;
4472
4473                 if (page_index->page_code != prev) {
4474                         lun->log_pages.pages_page[j] = page_index->page_code;
4475                         prev = page_index->page_code;
4476                         j++;
4477                 }
4478                 lun->log_pages.subpages_page[k*2] = page_index->page_code;
4479                 lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4480                 k++;
4481         }
4482         lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4483         lun->log_pages.index[0].page_len = j;
4484         lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4485         lun->log_pages.index[1].page_len = k * 2;
4486         lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4487         lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4488
4489         return (CTL_RETVAL_COMPLETE);
4490 }
4491
4492 static int
4493 hex2bin(const char *str, uint8_t *buf, int buf_size)
4494 {
4495         int i;
4496         u_char c;
4497
4498         memset(buf, 0, buf_size);
4499         while (isspace(str[0]))
4500                 str++;
4501         if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4502                 str += 2;
4503         buf_size *= 2;
4504         for (i = 0; str[i] != 0 && i < buf_size; i++) {
4505                 c = str[i];
4506                 if (isdigit(c))
4507                         c -= '0';
4508                 else if (isalpha(c))
4509                         c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4510                 else
4511                         break;
4512                 if (c >= 16)
4513                         break;
4514                 if ((i & 1) == 0)
4515                         buf[i / 2] |= (c << 4);
4516                 else
4517                         buf[i / 2] |= c;
4518         }
4519         return ((i + 1) / 2);
4520 }
4521
4522 /*
4523  * LUN allocation.
4524  *
4525  * Requirements:
4526  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4527  *   wants us to allocate the LUN and he can block.
4528  * - ctl_softc is always set
4529  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4530  *
4531  * Returns 0 for success, non-zero (errno) for failure.
4532  */
4533 static int
4534 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4535               struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4536 {
4537         struct ctl_lun *nlun, *lun;
4538         struct ctl_port *port;
4539         struct scsi_vpd_id_descriptor *desc;
4540         struct scsi_vpd_id_t10 *t10id;
4541         const char *eui, *naa, *scsiname, *vendor, *value;
4542         int lun_number, i, lun_malloced;
4543         int devidlen, idlen1, idlen2 = 0, len;
4544
4545         if (be_lun == NULL)
4546                 return (EINVAL);
4547
4548         /*
4549          * We currently only support Direct Access or Processor LUN types.
4550          */
4551         switch (be_lun->lun_type) {
4552         case T_DIRECT:
4553                 break;
4554         case T_PROCESSOR:
4555                 break;
4556         case T_SEQUENTIAL:
4557         case T_CHANGER:
4558         default:
4559                 be_lun->lun_config_status(be_lun->be_lun,
4560                                           CTL_LUN_CONFIG_FAILURE);
4561                 break;
4562         }
4563         if (ctl_lun == NULL) {
4564                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4565                 lun_malloced = 1;
4566         } else {
4567                 lun_malloced = 0;
4568                 lun = ctl_lun;
4569         }
4570
4571         memset(lun, 0, sizeof(*lun));
4572         if (lun_malloced)
4573                 lun->flags = CTL_LUN_MALLOCED;
4574
4575         /* Generate LUN ID. */
4576         devidlen = max(CTL_DEVID_MIN_LEN,
4577             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4578         idlen1 = sizeof(*t10id) + devidlen;
4579         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4580         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4581         if (scsiname != NULL) {
4582                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4583                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4584         }
4585         eui = ctl_get_opt(&be_lun->options, "eui");
4586         if (eui != NULL) {
4587                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4588         }
4589         naa = ctl_get_opt(&be_lun->options, "naa");
4590         if (naa != NULL) {
4591                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4592         }
4593         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4594             M_CTL, M_WAITOK | M_ZERO);
4595         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4596         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4597         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4598         desc->length = idlen1;
4599         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4600         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4601         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4602                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4603         } else {
4604                 strncpy(t10id->vendor, vendor,
4605                     min(sizeof(t10id->vendor), strlen(vendor)));
4606         }
4607         strncpy((char *)t10id->vendor_spec_id,
4608             (char *)be_lun->device_id, devidlen);
4609         if (scsiname != NULL) {
4610                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4611                     desc->length);
4612                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4613                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4614                     SVPD_ID_TYPE_SCSI_NAME;
4615                 desc->length = idlen2;
4616                 strlcpy(desc->identifier, scsiname, idlen2);
4617         }
4618         if (eui != NULL) {
4619                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4620                     desc->length);
4621                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4622                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4623                     SVPD_ID_TYPE_EUI64;
4624                 desc->length = hex2bin(eui, desc->identifier, 16);
4625                 desc->length = desc->length > 12 ? 16 :
4626                     (desc->length > 8 ? 12 : 8);
4627                 len -= 16 - desc->length;
4628         }
4629         if (naa != NULL) {
4630                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4631                     desc->length);
4632                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4633                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4634                     SVPD_ID_TYPE_NAA;
4635                 desc->length = hex2bin(naa, desc->identifier, 16);
4636                 desc->length = desc->length > 8 ? 16 : 8;
4637                 len -= 16 - desc->length;
4638         }
4639         lun->lun_devid->len = len;
4640
4641         mtx_lock(&ctl_softc->ctl_lock);
4642         /*
4643          * See if the caller requested a particular LUN number.  If so, see
4644          * if it is available.  Otherwise, allocate the first available LUN.
4645          */
4646         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4647                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4648                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4649                         mtx_unlock(&ctl_softc->ctl_lock);
4650                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4651                                 printf("ctl: requested LUN ID %d is higher "
4652                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4653                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4654                         } else {
4655                                 /*
4656                                  * XXX KDM return an error, or just assign
4657                                  * another LUN ID in this case??
4658                                  */
4659                                 printf("ctl: requested LUN ID %d is already "
4660                                        "in use\n", be_lun->req_lun_id);
4661                         }
4662                         if (lun->flags & CTL_LUN_MALLOCED)
4663                                 free(lun, M_CTL);
4664                         be_lun->lun_config_status(be_lun->be_lun,
4665                                                   CTL_LUN_CONFIG_FAILURE);
4666                         return (ENOSPC);
4667                 }
4668                 lun_number = be_lun->req_lun_id;
4669         } else {
4670                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4671                 if (lun_number == -1) {
4672                         mtx_unlock(&ctl_softc->ctl_lock);
4673                         printf("ctl: can't allocate LUN on target %ju, out of "
4674                                "LUNs\n", (uintmax_t)target_id.id);
4675                         if (lun->flags & CTL_LUN_MALLOCED)
4676                                 free(lun, M_CTL);
4677                         be_lun->lun_config_status(be_lun->be_lun,
4678                                                   CTL_LUN_CONFIG_FAILURE);
4679                         return (ENOSPC);
4680                 }
4681         }
4682         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4683
4684         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4685         lun->target = target_id;
4686         lun->lun = lun_number;
4687         lun->be_lun = be_lun;
4688         /*
4689          * The processor LUN is always enabled.  Disk LUNs come on line
4690          * disabled, and must be enabled by the backend.
4691          */
4692         lun->flags |= CTL_LUN_DISABLED;
4693         lun->backend = be_lun->be;
4694         be_lun->ctl_lun = lun;
4695         be_lun->lun_id = lun_number;
4696         atomic_add_int(&be_lun->be->num_luns, 1);
4697         if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4698                 lun->flags |= CTL_LUN_OFFLINE;
4699
4700         if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4701                 lun->flags |= CTL_LUN_STOPPED;
4702
4703         if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4704                 lun->flags |= CTL_LUN_INOPERABLE;
4705
4706         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4707                 lun->flags |= CTL_LUN_PRIMARY_SC;
4708
4709         value = ctl_get_opt(&be_lun->options, "readonly");
4710         if (value != NULL && strcmp(value, "on") == 0)
4711                 lun->flags |= CTL_LUN_READONLY;
4712
4713         lun->serseq = CTL_LUN_SERSEQ_OFF;
4714         if (be_lun->flags & CTL_LUN_FLAG_SERSEQ_READ)
4715                 lun->serseq = CTL_LUN_SERSEQ_READ;
4716         value = ctl_get_opt(&be_lun->options, "serseq");
4717         if (value != NULL && strcmp(value, "on") == 0)
4718                 lun->serseq = CTL_LUN_SERSEQ_ON;
4719         else if (value != NULL && strcmp(value, "read") == 0)
4720                 lun->serseq = CTL_LUN_SERSEQ_READ;
4721         else if (value != NULL && strcmp(value, "off") == 0)
4722                 lun->serseq = CTL_LUN_SERSEQ_OFF;
4723
4724         lun->ctl_softc = ctl_softc;
4725         TAILQ_INIT(&lun->ooa_queue);
4726         TAILQ_INIT(&lun->blocked_queue);
4727         STAILQ_INIT(&lun->error_list);
4728         ctl_tpc_lun_init(lun);
4729
4730         /*
4731          * Initialize the mode and log page index.
4732          */
4733         ctl_init_page_index(lun);
4734         ctl_init_log_page_index(lun);
4735
4736         /*
4737          * Now, before we insert this lun on the lun list, set the lun
4738          * inventory changed UA for all other luns.
4739          */
4740         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4741                 mtx_lock(&nlun->lun_lock);
4742                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4743                 mtx_unlock(&nlun->lun_lock);
4744         }
4745
4746         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4747
4748         ctl_softc->ctl_luns[lun_number] = lun;
4749
4750         ctl_softc->num_luns++;
4751
4752         /* Setup statistics gathering */
4753         lun->stats.device_type = be_lun->lun_type;
4754         lun->stats.lun_number = lun_number;
4755         if (lun->stats.device_type == T_DIRECT)
4756                 lun->stats.blocksize = be_lun->blocksize;
4757         else
4758                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4759         for (i = 0;i < CTL_MAX_PORTS;i++)
4760                 lun->stats.ports[i].targ_port = i;
4761
4762         mtx_unlock(&ctl_softc->ctl_lock);
4763
4764         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4765
4766         /*
4767          * Run through each registered FETD and bring it online if it isn't
4768          * already.  Enable the target ID if it hasn't been enabled, and
4769          * enable this particular LUN.
4770          */
4771         STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4772                 int retval;
4773
4774                 retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4775                 if (retval != 0) {
4776                         printf("ctl_alloc_lun: FETD %s port %d returned error "
4777                                "%d for lun_enable on target %ju lun %d\n",
4778                                port->port_name, port->targ_port, retval,
4779                                (uintmax_t)target_id.id, lun_number);
4780                 } else
4781                         port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4782         }
4783         return (0);
4784 }
4785
4786 /*
4787  * Delete a LUN.
4788  * Assumptions:
4789  * - LUN has already been marked invalid and any pending I/O has been taken
4790  *   care of.
4791  */
4792 static int
4793 ctl_free_lun(struct ctl_lun *lun)
4794 {
4795         struct ctl_softc *softc;
4796         struct ctl_port *port;
4797         struct ctl_lun *nlun;
4798         int i;
4799
4800         softc = lun->ctl_softc;
4801
4802         mtx_assert(&softc->ctl_lock, MA_OWNED);
4803
4804         STAILQ_FOREACH(port, &softc->port_list, links)
4805                 ctl_lun_map_unsetg(port, lun->lun);
4806
4807         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4808
4809         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4810
4811         softc->ctl_luns[lun->lun] = NULL;
4812
4813         if (!TAILQ_EMPTY(&lun->ooa_queue))
4814                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4815
4816         softc->num_luns--;
4817
4818         /*
4819          * XXX KDM this scheme only works for a single target/multiple LUN
4820          * setup.  It needs to be revamped for a multiple target scheme.
4821          *
4822          * XXX KDM this results in port->lun_disable() getting called twice,
4823          * once when ctl_disable_lun() is called, and a second time here.
4824          * We really need to re-think the LUN disable semantics.  There
4825          * should probably be several steps/levels to LUN removal:
4826          *  - disable
4827          *  - invalidate
4828          *  - free
4829          *
4830          * Right now we only have a disable method when communicating to
4831          * the front end ports, at least for individual LUNs.
4832          */
4833 #if 0
4834         STAILQ_FOREACH(port, &softc->port_list, links) {
4835                 int retval;
4836
4837                 retval = port->lun_disable(port->targ_lun_arg, lun->target,
4838                                          lun->lun);
4839                 if (retval != 0) {
4840                         printf("ctl_free_lun: FETD %s port %d returned error "
4841                                "%d for lun_disable on target %ju lun %jd\n",
4842                                port->port_name, port->targ_port, retval,
4843                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4844                 }
4845
4846                 if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4847                         port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4848
4849                         retval = port->targ_disable(port->targ_lun_arg,lun->target);
4850                         if (retval != 0) {
4851                                 printf("ctl_free_lun: FETD %s port %d "
4852                                        "returned error %d for targ_disable on "
4853                                        "target %ju\n", port->port_name,
4854                                        port->targ_port, retval,
4855                                        (uintmax_t)lun->target.id);
4856                         } else
4857                                 port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4858
4859                         if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4860                                 continue;
4861
4862 #if 0
4863                         port->port_offline(port->onoff_arg);
4864                         port->status &= ~CTL_PORT_STATUS_ONLINE;
4865 #endif
4866                 }
4867         }
4868 #endif
4869
4870         /*
4871          * Tell the backend to free resources, if this LUN has a backend.
4872          */
4873         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4874         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4875
4876         ctl_tpc_lun_shutdown(lun);
4877         mtx_destroy(&lun->lun_lock);
4878         free(lun->lun_devid, M_CTL);
4879         for (i = 0; i < CTL_MAX_PORTS; i++)
4880                 free(lun->pending_ua[i], M_CTL);
4881         for (i = 0; i < 2 * CTL_MAX_PORTS; i++)
4882                 free(lun->pr_keys[i], M_CTL);
4883         free(lun->write_buffer, M_CTL);
4884         if (lun->flags & CTL_LUN_MALLOCED)
4885                 free(lun, M_CTL);
4886
4887         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4888                 mtx_lock(&nlun->lun_lock);
4889                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4890                 mtx_unlock(&nlun->lun_lock);
4891         }
4892
4893         return (0);
4894 }
4895
4896 static void
4897 ctl_create_lun(struct ctl_be_lun *be_lun)
4898 {
4899         struct ctl_softc *softc;
4900
4901         softc = control_softc;
4902
4903         /*
4904          * ctl_alloc_lun() should handle all potential failure cases.
4905          */
4906         ctl_alloc_lun(softc, NULL, be_lun, softc->target);
4907 }
4908
4909 int
4910 ctl_add_lun(struct ctl_be_lun *be_lun)
4911 {
4912         struct ctl_softc *softc = control_softc;
4913
4914         mtx_lock(&softc->ctl_lock);
4915         STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4916         mtx_unlock(&softc->ctl_lock);
4917         wakeup(&softc->pending_lun_queue);
4918
4919         return (0);
4920 }
4921
4922 int
4923 ctl_enable_lun(struct ctl_be_lun *be_lun)
4924 {
4925         struct ctl_softc *softc;
4926         struct ctl_port *port, *nport;
4927         struct ctl_lun *lun;
4928         int retval;
4929
4930         lun = (struct ctl_lun *)be_lun->ctl_lun;
4931         softc = lun->ctl_softc;
4932
4933         mtx_lock(&softc->ctl_lock);
4934         mtx_lock(&lun->lun_lock);
4935         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4936                 /*
4937                  * eh?  Why did we get called if the LUN is already
4938                  * enabled?
4939                  */
4940                 mtx_unlock(&lun->lun_lock);
4941                 mtx_unlock(&softc->ctl_lock);
4942                 return (0);
4943         }
4944         lun->flags &= ~CTL_LUN_DISABLED;
4945         mtx_unlock(&lun->lun_lock);
4946
4947         for (port = STAILQ_FIRST(&softc->port_list); port != NULL; port = nport) {
4948                 nport = STAILQ_NEXT(port, links);
4949
4950                 /*
4951                  * Drop the lock while we call the FETD's enable routine.
4952                  * This can lead to a callback into CTL (at least in the
4953                  * case of the internal initiator frontend.
4954                  */
4955                 mtx_unlock(&softc->ctl_lock);
4956                 retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4957                 mtx_lock(&softc->ctl_lock);
4958                 if (retval != 0) {
4959                         printf("%s: FETD %s port %d returned error "
4960                                "%d for lun_enable on target %ju lun %jd\n",
4961                                __func__, port->port_name, port->targ_port, retval,
4962                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4963                 }
4964 #if 0
4965                  else {
4966             /* NOTE:  TODO:  why does lun enable affect port status? */
4967                         port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4968                 }
4969 #endif
4970         }
4971
4972         mtx_unlock(&softc->ctl_lock);
4973
4974         return (0);
4975 }
4976
4977 int
4978 ctl_disable_lun(struct ctl_be_lun *be_lun)
4979 {
4980         struct ctl_softc *softc;
4981         struct ctl_port *port;
4982         struct ctl_lun *lun;
4983         int retval;
4984
4985         lun = (struct ctl_lun *)be_lun->ctl_lun;
4986         softc = lun->ctl_softc;
4987
4988         mtx_lock(&softc->ctl_lock);
4989         mtx_lock(&lun->lun_lock);
4990         if (lun->flags & CTL_LUN_DISABLED) {
4991                 mtx_unlock(&lun->lun_lock);
4992                 mtx_unlock(&softc->ctl_lock);
4993                 return (0);
4994         }
4995         lun->flags |= CTL_LUN_DISABLED;
4996         mtx_unlock(&lun->lun_lock);
4997
4998         STAILQ_FOREACH(port, &softc->port_list, links) {
4999                 mtx_unlock(&softc->ctl_lock);
5000                 /*
5001                  * Drop the lock before we call the frontend's disable
5002                  * routine, to avoid lock order reversals.
5003                  *
5004                  * XXX KDM what happens if the frontend list changes while
5005                  * we're traversing it?  It's unlikely, but should be handled.
5006                  */
5007                 retval = port->lun_disable(port->targ_lun_arg, lun->target,
5008                                          lun->lun);
5009                 mtx_lock(&softc->ctl_lock);
5010                 if (retval != 0) {
5011                         printf("ctl_alloc_lun: FETD %s port %d returned error "
5012                                "%d for lun_disable on target %ju lun %jd\n",
5013                                port->port_name, port->targ_port, retval,
5014                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
5015                 }
5016         }
5017
5018         mtx_unlock(&softc->ctl_lock);
5019
5020         return (0);
5021 }
5022
5023 int
5024 ctl_start_lun(struct ctl_be_lun *be_lun)
5025 {
5026         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5027
5028         mtx_lock(&lun->lun_lock);
5029         lun->flags &= ~CTL_LUN_STOPPED;
5030         mtx_unlock(&lun->lun_lock);
5031         return (0);
5032 }
5033
5034 int
5035 ctl_stop_lun(struct ctl_be_lun *be_lun)
5036 {
5037         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5038
5039         mtx_lock(&lun->lun_lock);
5040         lun->flags |= CTL_LUN_STOPPED;
5041         mtx_unlock(&lun->lun_lock);
5042         return (0);
5043 }
5044
5045 int
5046 ctl_lun_offline(struct ctl_be_lun *be_lun)
5047 {
5048         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5049
5050         mtx_lock(&lun->lun_lock);
5051         lun->flags |= CTL_LUN_OFFLINE;
5052         mtx_unlock(&lun->lun_lock);
5053         return (0);
5054 }
5055
5056 int
5057 ctl_lun_online(struct ctl_be_lun *be_lun)
5058 {
5059         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5060
5061         mtx_lock(&lun->lun_lock);
5062         lun->flags &= ~CTL_LUN_OFFLINE;
5063         mtx_unlock(&lun->lun_lock);
5064         return (0);
5065 }
5066
5067 int
5068 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
5069 {
5070         struct ctl_softc *softc;
5071         struct ctl_lun *lun;
5072
5073         lun = (struct ctl_lun *)be_lun->ctl_lun;
5074         softc = lun->ctl_softc;
5075
5076         mtx_lock(&lun->lun_lock);
5077
5078         /*
5079          * The LUN needs to be disabled before it can be marked invalid.
5080          */
5081         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
5082                 mtx_unlock(&lun->lun_lock);
5083                 return (-1);
5084         }
5085         /*
5086          * Mark the LUN invalid.
5087          */
5088         lun->flags |= CTL_LUN_INVALID;
5089
5090         /*
5091          * If there is nothing in the OOA queue, go ahead and free the LUN.
5092          * If we have something in the OOA queue, we'll free it when the
5093          * last I/O completes.
5094          */
5095         if (TAILQ_EMPTY(&lun->ooa_queue)) {
5096                 mtx_unlock(&lun->lun_lock);
5097                 mtx_lock(&softc->ctl_lock);
5098                 ctl_free_lun(lun);
5099                 mtx_unlock(&softc->ctl_lock);
5100         } else
5101                 mtx_unlock(&lun->lun_lock);
5102
5103         return (0);
5104 }
5105
5106 int
5107 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5108 {
5109         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5110
5111         mtx_lock(&lun->lun_lock);
5112         lun->flags |= CTL_LUN_INOPERABLE;
5113         mtx_unlock(&lun->lun_lock);
5114         return (0);
5115 }
5116
5117 int
5118 ctl_lun_operable(struct ctl_be_lun *be_lun)
5119 {
5120         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5121
5122         mtx_lock(&lun->lun_lock);
5123         lun->flags &= ~CTL_LUN_INOPERABLE;
5124         mtx_unlock(&lun->lun_lock);
5125         return (0);
5126 }
5127
5128 void
5129 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5130 {
5131         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5132
5133         mtx_lock(&lun->lun_lock);
5134         ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGED);
5135         mtx_unlock(&lun->lun_lock);
5136 }
5137
5138 /*
5139  * Backend "memory move is complete" callback for requests that never
5140  * make it down to say RAIDCore's configuration code.
5141  */
5142 int
5143 ctl_config_move_done(union ctl_io *io)
5144 {
5145         int retval;
5146
5147         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5148         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5149             ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5150
5151         if ((io->io_hdr.port_status != 0) &&
5152             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5153              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5154                 /*
5155                  * For hardware error sense keys, the sense key
5156                  * specific value is defined to be a retry count,
5157                  * but we use it to pass back an internal FETD
5158                  * error code.  XXX KDM  Hopefully the FETD is only
5159                  * using 16 bits for an error code, since that's
5160                  * all the space we have in the sks field.
5161                  */
5162                 ctl_set_internal_failure(&io->scsiio,
5163                                          /*sks_valid*/ 1,
5164                                          /*retry_count*/
5165                                          io->io_hdr.port_status);
5166         }
5167
5168         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5169             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5170              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5171             ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5172                 /*
5173                  * XXX KDM just assuming a single pointer here, and not a
5174                  * S/G list.  If we start using S/G lists for config data,
5175                  * we'll need to know how to clean them up here as well.
5176                  */
5177                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5178                         free(io->scsiio.kern_data_ptr, M_CTL);
5179                 ctl_done(io);
5180                 retval = CTL_RETVAL_COMPLETE;
5181         } else {
5182                 /*
5183                  * XXX KDM now we need to continue data movement.  Some
5184                  * options:
5185                  * - call ctl_scsiio() again?  We don't do this for data
5186                  *   writes, because for those at least we know ahead of
5187                  *   time where the write will go and how long it is.  For
5188                  *   config writes, though, that information is largely
5189                  *   contained within the write itself, thus we need to
5190                  *   parse out the data again.
5191                  *
5192                  * - Call some other function once the data is in?
5193                  */
5194                 if (ctl_debug & CTL_DEBUG_CDB_DATA)
5195                         ctl_data_print(io);
5196
5197                 /*
5198                  * XXX KDM call ctl_scsiio() again for now, and check flag
5199                  * bits to see whether we're allocated or not.
5200                  */
5201                 retval = ctl_scsiio(&io->scsiio);
5202         }
5203         return (retval);
5204 }
5205
5206 /*
5207  * This gets called by a backend driver when it is done with a
5208  * data_submit method.
5209  */
5210 void
5211 ctl_data_submit_done(union ctl_io *io)
5212 {
5213         /*
5214          * If the IO_CONT flag is set, we need to call the supplied
5215          * function to continue processing the I/O, instead of completing
5216          * the I/O just yet.
5217          *
5218          * If there is an error, though, we don't want to keep processing.
5219          * Instead, just send status back to the initiator.
5220          */
5221         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5222             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5223             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5224              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5225                 io->scsiio.io_cont(io);
5226                 return;
5227         }
5228         ctl_done(io);
5229 }
5230
5231 /*
5232  * This gets called by a backend driver when it is done with a
5233  * configuration write.
5234  */
5235 void
5236 ctl_config_write_done(union ctl_io *io)
5237 {
5238         uint8_t *buf;
5239
5240         /*
5241          * If the IO_CONT flag is set, we need to call the supplied
5242          * function to continue processing the I/O, instead of completing
5243          * the I/O just yet.
5244          *
5245          * If there is an error, though, we don't want to keep processing.
5246          * Instead, just send status back to the initiator.
5247          */
5248         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5249             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5250             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5251              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5252                 io->scsiio.io_cont(io);
5253                 return;
5254         }
5255         /*
5256          * Since a configuration write can be done for commands that actually
5257          * have data allocated, like write buffer, and commands that have
5258          * no data, like start/stop unit, we need to check here.
5259          */
5260         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5261                 buf = io->scsiio.kern_data_ptr;
5262         else
5263                 buf = NULL;
5264         ctl_done(io);
5265         if (buf)
5266                 free(buf, M_CTL);
5267 }
5268
5269 void
5270 ctl_config_read_done(union ctl_io *io)
5271 {
5272         uint8_t *buf;
5273
5274         /*
5275          * If there is some error -- we are done, skip data transfer.
5276          */
5277         if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5278             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5279              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5280                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5281                         buf = io->scsiio.kern_data_ptr;
5282                 else
5283                         buf = NULL;
5284                 ctl_done(io);
5285                 if (buf)
5286                         free(buf, M_CTL);
5287                 return;
5288         }
5289
5290         /*
5291          * If the IO_CONT flag is set, we need to call the supplied
5292          * function to continue processing the I/O, instead of completing
5293          * the I/O just yet.
5294          */
5295         if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5296                 io->scsiio.io_cont(io);
5297                 return;
5298         }
5299
5300         ctl_datamove(io);
5301 }
5302
5303 /*
5304  * SCSI release command.
5305  */
5306 int
5307 ctl_scsi_release(struct ctl_scsiio *ctsio)
5308 {
5309         int length, longid, thirdparty_id, resv_id;
5310         struct ctl_lun *lun;
5311         uint32_t residx;
5312
5313         length = 0;
5314         resv_id = 0;
5315
5316         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5317
5318         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5319         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5320
5321         switch (ctsio->cdb[0]) {
5322         case RELEASE_10: {
5323                 struct scsi_release_10 *cdb;
5324
5325                 cdb = (struct scsi_release_10 *)ctsio->cdb;
5326
5327                 if (cdb->byte2 & SR10_LONGID)
5328                         longid = 1;
5329                 else
5330                         thirdparty_id = cdb->thirdparty_id;
5331
5332                 resv_id = cdb->resv_id;
5333                 length = scsi_2btoul(cdb->length);
5334                 break;
5335         }
5336         }
5337
5338
5339         /*
5340          * XXX KDM right now, we only support LUN reservation.  We don't
5341          * support 3rd party reservations, or extent reservations, which
5342          * might actually need the parameter list.  If we've gotten this
5343          * far, we've got a LUN reservation.  Anything else got kicked out
5344          * above.  So, according to SPC, ignore the length.
5345          */
5346         length = 0;
5347
5348         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5349          && (length > 0)) {
5350                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5351                 ctsio->kern_data_len = length;
5352                 ctsio->kern_total_len = length;
5353                 ctsio->kern_data_resid = 0;
5354                 ctsio->kern_rel_offset = 0;
5355                 ctsio->kern_sg_entries = 0;
5356                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5357                 ctsio->be_move_done = ctl_config_move_done;
5358                 ctl_datamove((union ctl_io *)ctsio);
5359
5360                 return (CTL_RETVAL_COMPLETE);
5361         }
5362
5363         if (length > 0)
5364                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5365
5366         mtx_lock(&lun->lun_lock);
5367
5368         /*
5369          * According to SPC, it is not an error for an intiator to attempt
5370          * to release a reservation on a LUN that isn't reserved, or that
5371          * is reserved by another initiator.  The reservation can only be
5372          * released, though, by the initiator who made it or by one of
5373          * several reset type events.
5374          */
5375         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5376                         lun->flags &= ~CTL_LUN_RESERVED;
5377
5378         mtx_unlock(&lun->lun_lock);
5379
5380         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5381                 free(ctsio->kern_data_ptr, M_CTL);
5382                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5383         }
5384
5385         ctl_set_success(ctsio);
5386         ctl_done((union ctl_io *)ctsio);
5387         return (CTL_RETVAL_COMPLETE);
5388 }
5389
5390 int
5391 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5392 {
5393         int extent, thirdparty, longid;
5394         int resv_id, length;
5395         uint64_t thirdparty_id;
5396         struct ctl_lun *lun;
5397         uint32_t residx;
5398
5399         extent = 0;
5400         thirdparty = 0;
5401         longid = 0;
5402         resv_id = 0;
5403         length = 0;
5404         thirdparty_id = 0;
5405
5406         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5407
5408         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5409         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5410
5411         switch (ctsio->cdb[0]) {
5412         case RESERVE_10: {
5413                 struct scsi_reserve_10 *cdb;
5414
5415                 cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5416
5417                 if (cdb->byte2 & SR10_LONGID)
5418                         longid = 1;
5419                 else
5420                         thirdparty_id = cdb->thirdparty_id;
5421
5422                 resv_id = cdb->resv_id;
5423                 length = scsi_2btoul(cdb->length);
5424                 break;
5425         }
5426         }
5427
5428         /*
5429          * XXX KDM right now, we only support LUN reservation.  We don't
5430          * support 3rd party reservations, or extent reservations, which
5431          * might actually need the parameter list.  If we've gotten this
5432          * far, we've got a LUN reservation.  Anything else got kicked out
5433          * above.  So, according to SPC, ignore the length.
5434          */
5435         length = 0;
5436
5437         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5438          && (length > 0)) {
5439                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5440                 ctsio->kern_data_len = length;
5441                 ctsio->kern_total_len = length;
5442                 ctsio->kern_data_resid = 0;
5443                 ctsio->kern_rel_offset = 0;
5444                 ctsio->kern_sg_entries = 0;
5445                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5446                 ctsio->be_move_done = ctl_config_move_done;
5447                 ctl_datamove((union ctl_io *)ctsio);
5448
5449                 return (CTL_RETVAL_COMPLETE);
5450         }
5451
5452         if (length > 0)
5453                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5454
5455         mtx_lock(&lun->lun_lock);
5456         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5457                 ctl_set_reservation_conflict(ctsio);
5458                 goto bailout;
5459         }
5460
5461         lun->flags |= CTL_LUN_RESERVED;
5462         lun->res_idx = residx;
5463
5464         ctl_set_success(ctsio);
5465
5466 bailout:
5467         mtx_unlock(&lun->lun_lock);
5468
5469         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5470                 free(ctsio->kern_data_ptr, M_CTL);
5471                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5472         }
5473
5474         ctl_done((union ctl_io *)ctsio);
5475         return (CTL_RETVAL_COMPLETE);
5476 }
5477
5478 int
5479 ctl_start_stop(struct ctl_scsiio *ctsio)
5480 {
5481         struct scsi_start_stop_unit *cdb;
5482         struct ctl_lun *lun;
5483         int retval;
5484
5485         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5486
5487         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5488         retval = 0;
5489
5490         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5491
5492         /*
5493          * XXX KDM
5494          * We don't support the immediate bit on a stop unit.  In order to
5495          * do that, we would need to code up a way to know that a stop is
5496          * pending, and hold off any new commands until it completes, one
5497          * way or another.  Then we could accept or reject those commands
5498          * depending on its status.  We would almost need to do the reverse
5499          * of what we do below for an immediate start -- return the copy of
5500          * the ctl_io to the FETD with status to send to the host (and to
5501          * free the copy!) and then free the original I/O once the stop
5502          * actually completes.  That way, the OOA queue mechanism can work
5503          * to block commands that shouldn't proceed.  Another alternative
5504          * would be to put the copy in the queue in place of the original,
5505          * and return the original back to the caller.  That could be
5506          * slightly safer..
5507          */
5508         if ((cdb->byte2 & SSS_IMMED)
5509          && ((cdb->how & SSS_START) == 0)) {
5510                 ctl_set_invalid_field(ctsio,
5511                                       /*sks_valid*/ 1,
5512                                       /*command*/ 1,
5513                                       /*field*/ 1,
5514                                       /*bit_valid*/ 1,
5515                                       /*bit*/ 0);
5516                 ctl_done((union ctl_io *)ctsio);
5517                 return (CTL_RETVAL_COMPLETE);
5518         }
5519
5520         if ((lun->flags & CTL_LUN_PR_RESERVED)
5521          && ((cdb->how & SSS_START)==0)) {
5522                 uint32_t residx;
5523
5524                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5525                 if (ctl_get_prkey(lun, residx) == 0
5526                  || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5527
5528                         ctl_set_reservation_conflict(ctsio);
5529                         ctl_done((union ctl_io *)ctsio);
5530                         return (CTL_RETVAL_COMPLETE);
5531                 }
5532         }
5533
5534         /*
5535          * If there is no backend on this device, we can't start or stop
5536          * it.  In theory we shouldn't get any start/stop commands in the
5537          * first place at this level if the LUN doesn't have a backend.
5538          * That should get stopped by the command decode code.
5539          */
5540         if (lun->backend == NULL) {
5541                 ctl_set_invalid_opcode(ctsio);
5542                 ctl_done((union ctl_io *)ctsio);
5543                 return (CTL_RETVAL_COMPLETE);
5544         }
5545
5546         /*
5547          * XXX KDM Copan-specific offline behavior.
5548          * Figure out a reasonable way to port this?
5549          */
5550 #ifdef NEEDTOPORT
5551         mtx_lock(&lun->lun_lock);
5552
5553         if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5554          && (lun->flags & CTL_LUN_OFFLINE)) {
5555                 /*
5556                  * If the LUN is offline, and the on/offline bit isn't set,
5557                  * reject the start or stop.  Otherwise, let it through.
5558                  */
5559                 mtx_unlock(&lun->lun_lock);
5560                 ctl_set_lun_not_ready(ctsio);
5561                 ctl_done((union ctl_io *)ctsio);
5562         } else {
5563                 mtx_unlock(&lun->lun_lock);
5564 #endif /* NEEDTOPORT */
5565                 /*
5566                  * This could be a start or a stop when we're online,
5567                  * or a stop/offline or start/online.  A start or stop when
5568                  * we're offline is covered in the case above.
5569                  */
5570                 /*
5571                  * In the non-immediate case, we send the request to
5572                  * the backend and return status to the user when
5573                  * it is done.
5574                  *
5575                  * In the immediate case, we allocate a new ctl_io
5576                  * to hold a copy of the request, and send that to
5577                  * the backend.  We then set good status on the
5578                  * user's request and return it immediately.
5579                  */
5580                 if (cdb->byte2 & SSS_IMMED) {
5581                         union ctl_io *new_io;
5582
5583                         new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5584                         ctl_copy_io((union ctl_io *)ctsio, new_io);
5585                         retval = lun->backend->config_write(new_io);
5586                         ctl_set_success(ctsio);
5587                         ctl_done((union ctl_io *)ctsio);
5588                 } else {
5589                         retval = lun->backend->config_write(
5590                                 (union ctl_io *)ctsio);
5591                 }
5592 #ifdef NEEDTOPORT
5593         }
5594 #endif
5595         return (retval);
5596 }
5597
5598 /*
5599  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5600  * we don't really do anything with the LBA and length fields if the user
5601  * passes them in.  Instead we'll just flush out the cache for the entire
5602  * LUN.
5603  */
5604 int
5605 ctl_sync_cache(struct ctl_scsiio *ctsio)
5606 {
5607         struct ctl_lun *lun;
5608         struct ctl_softc *softc;
5609         uint64_t starting_lba;
5610         uint32_t block_count;
5611         int retval;
5612
5613         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5614
5615         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5616         softc = lun->ctl_softc;
5617         retval = 0;
5618
5619         switch (ctsio->cdb[0]) {
5620         case SYNCHRONIZE_CACHE: {
5621                 struct scsi_sync_cache *cdb;
5622                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5623
5624                 starting_lba = scsi_4btoul(cdb->begin_lba);
5625                 block_count = scsi_2btoul(cdb->lb_count);
5626                 break;
5627         }
5628         case SYNCHRONIZE_CACHE_16: {
5629                 struct scsi_sync_cache_16 *cdb;
5630                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5631
5632                 starting_lba = scsi_8btou64(cdb->begin_lba);
5633                 block_count = scsi_4btoul(cdb->lb_count);
5634                 break;
5635         }
5636         default:
5637                 ctl_set_invalid_opcode(ctsio);
5638                 ctl_done((union ctl_io *)ctsio);
5639                 goto bailout;
5640                 break; /* NOTREACHED */
5641         }
5642
5643         /*
5644          * We check the LBA and length, but don't do anything with them.
5645          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5646          * get flushed.  This check will just help satisfy anyone who wants
5647          * to see an error for an out of range LBA.
5648          */
5649         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5650                 ctl_set_lba_out_of_range(ctsio);
5651                 ctl_done((union ctl_io *)ctsio);
5652                 goto bailout;
5653         }
5654
5655         /*
5656          * If this LUN has no backend, we can't flush the cache anyway.
5657          */
5658         if (lun->backend == NULL) {
5659                 ctl_set_invalid_opcode(ctsio);
5660                 ctl_done((union ctl_io *)ctsio);
5661                 goto bailout;
5662         }
5663
5664         /*
5665          * Check to see whether we're configured to send the SYNCHRONIZE
5666          * CACHE command directly to the back end.
5667          */
5668         mtx_lock(&lun->lun_lock);
5669         if ((softc->flags & CTL_FLAG_REAL_SYNC)
5670          && (++(lun->sync_count) >= lun->sync_interval)) {
5671                 lun->sync_count = 0;
5672                 mtx_unlock(&lun->lun_lock);
5673                 retval = lun->backend->config_write((union ctl_io *)ctsio);
5674         } else {
5675                 mtx_unlock(&lun->lun_lock);
5676                 ctl_set_success(ctsio);
5677                 ctl_done((union ctl_io *)ctsio);
5678         }
5679
5680 bailout:
5681
5682         return (retval);
5683 }
5684
5685 int
5686 ctl_format(struct ctl_scsiio *ctsio)
5687 {
5688         struct scsi_format *cdb;
5689         struct ctl_lun *lun;
5690         int length, defect_list_len;
5691
5692         CTL_DEBUG_PRINT(("ctl_format\n"));
5693
5694         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5695
5696         cdb = (struct scsi_format *)ctsio->cdb;
5697
5698         length = 0;
5699         if (cdb->byte2 & SF_FMTDATA) {
5700                 if (cdb->byte2 & SF_LONGLIST)
5701                         length = sizeof(struct scsi_format_header_long);
5702                 else
5703                         length = sizeof(struct scsi_format_header_short);
5704         }
5705
5706         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5707          && (length > 0)) {
5708                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5709                 ctsio->kern_data_len = length;
5710                 ctsio->kern_total_len = length;
5711                 ctsio->kern_data_resid = 0;
5712                 ctsio->kern_rel_offset = 0;
5713                 ctsio->kern_sg_entries = 0;
5714                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5715                 ctsio->be_move_done = ctl_config_move_done;
5716                 ctl_datamove((union ctl_io *)ctsio);
5717
5718                 return (CTL_RETVAL_COMPLETE);
5719         }
5720
5721         defect_list_len = 0;
5722
5723         if (cdb->byte2 & SF_FMTDATA) {
5724                 if (cdb->byte2 & SF_LONGLIST) {
5725                         struct scsi_format_header_long *header;
5726
5727                         header = (struct scsi_format_header_long *)
5728                                 ctsio->kern_data_ptr;
5729
5730                         defect_list_len = scsi_4btoul(header->defect_list_len);
5731                         if (defect_list_len != 0) {
5732                                 ctl_set_invalid_field(ctsio,
5733                                                       /*sks_valid*/ 1,
5734                                                       /*command*/ 0,
5735                                                       /*field*/ 2,
5736                                                       /*bit_valid*/ 0,
5737                                                       /*bit*/ 0);
5738                                 goto bailout;
5739                         }
5740                 } else {
5741                         struct scsi_format_header_short *header;
5742
5743                         header = (struct scsi_format_header_short *)
5744                                 ctsio->kern_data_ptr;
5745
5746                         defect_list_len = scsi_2btoul(header->defect_list_len);
5747                         if (defect_list_len != 0) {
5748                                 ctl_set_invalid_field(ctsio,
5749                                                       /*sks_valid*/ 1,
5750                                                       /*command*/ 0,
5751                                                       /*field*/ 2,
5752                                                       /*bit_valid*/ 0,
5753                                                       /*bit*/ 0);
5754                                 goto bailout;
5755                         }
5756                 }
5757         }
5758
5759         /*
5760          * The format command will clear out the "Medium format corrupted"
5761          * status if set by the configuration code.  That status is really
5762          * just a way to notify the host that we have lost the media, and
5763          * get them to issue a command that will basically make them think
5764          * they're blowing away the media.
5765          */
5766         mtx_lock(&lun->lun_lock);
5767         lun->flags &= ~CTL_LUN_INOPERABLE;
5768         mtx_unlock(&lun->lun_lock);
5769
5770         ctl_set_success(ctsio);
5771 bailout:
5772
5773         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5774                 free(ctsio->kern_data_ptr, M_CTL);
5775                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5776         }
5777
5778         ctl_done((union ctl_io *)ctsio);
5779         return (CTL_RETVAL_COMPLETE);
5780 }
5781
5782 int
5783 ctl_read_buffer(struct ctl_scsiio *ctsio)
5784 {
5785         struct scsi_read_buffer *cdb;
5786         struct ctl_lun *lun;
5787         int buffer_offset, len;
5788         static uint8_t descr[4];
5789         static uint8_t echo_descr[4] = { 0 };
5790
5791         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5792
5793         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5794         cdb = (struct scsi_read_buffer *)ctsio->cdb;
5795
5796         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5797             (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5798             (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5799                 ctl_set_invalid_field(ctsio,
5800                                       /*sks_valid*/ 1,
5801                                       /*command*/ 1,
5802                                       /*field*/ 1,
5803                                       /*bit_valid*/ 1,
5804                                       /*bit*/ 4);
5805                 ctl_done((union ctl_io *)ctsio);
5806                 return (CTL_RETVAL_COMPLETE);
5807         }
5808
5809         len = scsi_3btoul(cdb->length);
5810         buffer_offset = scsi_3btoul(cdb->offset);
5811
5812         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5813                 ctl_set_invalid_field(ctsio,
5814                                       /*sks_valid*/ 1,
5815                                       /*command*/ 1,
5816                                       /*field*/ 6,
5817                                       /*bit_valid*/ 0,
5818                                       /*bit*/ 0);
5819                 ctl_done((union ctl_io *)ctsio);
5820                 return (CTL_RETVAL_COMPLETE);
5821         }
5822
5823         if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5824                 descr[0] = 0;
5825                 scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5826                 ctsio->kern_data_ptr = descr;
5827                 len = min(len, sizeof(descr));
5828         } else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5829                 ctsio->kern_data_ptr = echo_descr;
5830                 len = min(len, sizeof(echo_descr));
5831         } else {
5832                 if (lun->write_buffer == NULL) {
5833                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5834                             M_CTL, M_WAITOK);
5835                 }
5836                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5837         }
5838         ctsio->kern_data_len = len;
5839         ctsio->kern_total_len = len;
5840         ctsio->kern_data_resid = 0;
5841         ctsio->kern_rel_offset = 0;
5842         ctsio->kern_sg_entries = 0;
5843         ctl_set_success(ctsio);
5844         ctsio->be_move_done = ctl_config_move_done;
5845         ctl_datamove((union ctl_io *)ctsio);
5846         return (CTL_RETVAL_COMPLETE);
5847 }
5848
5849 int
5850 ctl_write_buffer(struct ctl_scsiio *ctsio)
5851 {
5852         struct scsi_write_buffer *cdb;
5853         struct ctl_lun *lun;
5854         int buffer_offset, len;
5855
5856         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5857
5858         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5859         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5860
5861         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5862                 ctl_set_invalid_field(ctsio,
5863                                       /*sks_valid*/ 1,
5864                                       /*command*/ 1,
5865                                       /*field*/ 1,
5866                                       /*bit_valid*/ 1,
5867                                       /*bit*/ 4);
5868                 ctl_done((union ctl_io *)ctsio);
5869                 return (CTL_RETVAL_COMPLETE);
5870         }
5871
5872         len = scsi_3btoul(cdb->length);
5873         buffer_offset = scsi_3btoul(cdb->offset);
5874
5875         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5876                 ctl_set_invalid_field(ctsio,
5877                                       /*sks_valid*/ 1,
5878                                       /*command*/ 1,
5879                                       /*field*/ 6,
5880                                       /*bit_valid*/ 0,
5881                                       /*bit*/ 0);
5882                 ctl_done((union ctl_io *)ctsio);
5883                 return (CTL_RETVAL_COMPLETE);
5884         }
5885
5886         /*
5887          * If we've got a kernel request that hasn't been malloced yet,
5888          * malloc it and tell the caller the data buffer is here.
5889          */
5890         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5891                 if (lun->write_buffer == NULL) {
5892                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5893                             M_CTL, M_WAITOK);
5894                 }
5895                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5896                 ctsio->kern_data_len = len;
5897                 ctsio->kern_total_len = len;
5898                 ctsio->kern_data_resid = 0;
5899                 ctsio->kern_rel_offset = 0;
5900                 ctsio->kern_sg_entries = 0;
5901                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5902                 ctsio->be_move_done = ctl_config_move_done;
5903                 ctl_datamove((union ctl_io *)ctsio);
5904
5905                 return (CTL_RETVAL_COMPLETE);
5906         }
5907
5908         ctl_set_success(ctsio);
5909         ctl_done((union ctl_io *)ctsio);
5910         return (CTL_RETVAL_COMPLETE);
5911 }
5912
5913 int
5914 ctl_write_same(struct ctl_scsiio *ctsio)
5915 {
5916         struct ctl_lun *lun;
5917         struct ctl_lba_len_flags *lbalen;
5918         uint64_t lba;
5919         uint32_t num_blocks;
5920         int len, retval;
5921         uint8_t byte2;
5922
5923         retval = CTL_RETVAL_COMPLETE;
5924
5925         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5926
5927         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5928
5929         switch (ctsio->cdb[0]) {
5930         case WRITE_SAME_10: {
5931                 struct scsi_write_same_10 *cdb;
5932
5933                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5934
5935                 lba = scsi_4btoul(cdb->addr);
5936                 num_blocks = scsi_2btoul(cdb->length);
5937                 byte2 = cdb->byte2;
5938                 break;
5939         }
5940         case WRITE_SAME_16: {
5941                 struct scsi_write_same_16 *cdb;
5942
5943                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5944
5945                 lba = scsi_8btou64(cdb->addr);
5946                 num_blocks = scsi_4btoul(cdb->length);
5947                 byte2 = cdb->byte2;
5948                 break;
5949         }
5950         default:
5951                 /*
5952                  * We got a command we don't support.  This shouldn't
5953                  * happen, commands should be filtered out above us.
5954                  */
5955                 ctl_set_invalid_opcode(ctsio);
5956                 ctl_done((union ctl_io *)ctsio);
5957
5958                 return (CTL_RETVAL_COMPLETE);
5959                 break; /* NOTREACHED */
5960         }
5961
5962         /* NDOB and ANCHOR flags can be used only together with UNMAP */
5963         if ((byte2 & SWS_UNMAP) == 0 &&
5964             (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5965                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5966                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5967                 ctl_done((union ctl_io *)ctsio);
5968                 return (CTL_RETVAL_COMPLETE);
5969         }
5970
5971         /*
5972          * The first check is to make sure we're in bounds, the second
5973          * check is to catch wrap-around problems.  If the lba + num blocks
5974          * is less than the lba, then we've wrapped around and the block
5975          * range is invalid anyway.
5976          */
5977         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5978          || ((lba + num_blocks) < lba)) {
5979                 ctl_set_lba_out_of_range(ctsio);
5980                 ctl_done((union ctl_io *)ctsio);
5981                 return (CTL_RETVAL_COMPLETE);
5982         }
5983
5984         /* Zero number of blocks means "to the last logical block" */
5985         if (num_blocks == 0) {
5986                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5987                         ctl_set_invalid_field(ctsio,
5988                                               /*sks_valid*/ 0,
5989                                               /*command*/ 1,
5990                                               /*field*/ 0,
5991                                               /*bit_valid*/ 0,
5992                                               /*bit*/ 0);
5993                         ctl_done((union ctl_io *)ctsio);
5994                         return (CTL_RETVAL_COMPLETE);
5995                 }
5996                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
5997         }
5998
5999         len = lun->be_lun->blocksize;
6000
6001         /*
6002          * If we've got a kernel request that hasn't been malloced yet,
6003          * malloc it and tell the caller the data buffer is here.
6004          */
6005         if ((byte2 & SWS_NDOB) == 0 &&
6006             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6007                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6008                 ctsio->kern_data_len = len;
6009                 ctsio->kern_total_len = len;
6010                 ctsio->kern_data_resid = 0;
6011                 ctsio->kern_rel_offset = 0;
6012                 ctsio->kern_sg_entries = 0;
6013                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6014                 ctsio->be_move_done = ctl_config_move_done;
6015                 ctl_datamove((union ctl_io *)ctsio);
6016
6017                 return (CTL_RETVAL_COMPLETE);
6018         }
6019
6020         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6021         lbalen->lba = lba;
6022         lbalen->len = num_blocks;
6023         lbalen->flags = byte2;
6024         retval = lun->backend->config_write((union ctl_io *)ctsio);
6025
6026         return (retval);
6027 }
6028
6029 int
6030 ctl_unmap(struct ctl_scsiio *ctsio)
6031 {
6032         struct ctl_lun *lun;
6033         struct scsi_unmap *cdb;
6034         struct ctl_ptr_len_flags *ptrlen;
6035         struct scsi_unmap_header *hdr;
6036         struct scsi_unmap_desc *buf, *end, *endnz, *range;
6037         uint64_t lba;
6038         uint32_t num_blocks;
6039         int len, retval;
6040         uint8_t byte2;
6041
6042         retval = CTL_RETVAL_COMPLETE;
6043
6044         CTL_DEBUG_PRINT(("ctl_unmap\n"));
6045
6046         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6047         cdb = (struct scsi_unmap *)ctsio->cdb;
6048
6049         len = scsi_2btoul(cdb->length);
6050         byte2 = cdb->byte2;
6051
6052         /*
6053          * If we've got a kernel request that hasn't been malloced yet,
6054          * malloc it and tell the caller the data buffer is here.
6055          */
6056         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6057                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6058                 ctsio->kern_data_len = len;
6059                 ctsio->kern_total_len = len;
6060                 ctsio->kern_data_resid = 0;
6061                 ctsio->kern_rel_offset = 0;
6062                 ctsio->kern_sg_entries = 0;
6063                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6064                 ctsio->be_move_done = ctl_config_move_done;
6065                 ctl_datamove((union ctl_io *)ctsio);
6066
6067                 return (CTL_RETVAL_COMPLETE);
6068         }
6069
6070         len = ctsio->kern_total_len - ctsio->kern_data_resid;
6071         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
6072         if (len < sizeof (*hdr) ||
6073             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
6074             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
6075             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
6076                 ctl_set_invalid_field(ctsio,
6077                                       /*sks_valid*/ 0,
6078                                       /*command*/ 0,
6079                                       /*field*/ 0,
6080                                       /*bit_valid*/ 0,
6081                                       /*bit*/ 0);
6082                 goto done;
6083         }
6084         len = scsi_2btoul(hdr->desc_length);
6085         buf = (struct scsi_unmap_desc *)(hdr + 1);
6086         end = buf + len / sizeof(*buf);
6087
6088         endnz = buf;
6089         for (range = buf; range < end; range++) {
6090                 lba = scsi_8btou64(range->lba);
6091                 num_blocks = scsi_4btoul(range->length);
6092                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6093                  || ((lba + num_blocks) < lba)) {
6094                         ctl_set_lba_out_of_range(ctsio);
6095                         ctl_done((union ctl_io *)ctsio);
6096                         return (CTL_RETVAL_COMPLETE);
6097                 }
6098                 if (num_blocks != 0)
6099                         endnz = range + 1;
6100         }
6101
6102         /*
6103          * Block backend can not handle zero last range.
6104          * Filter it out and return if there is nothing left.
6105          */
6106         len = (uint8_t *)endnz - (uint8_t *)buf;
6107         if (len == 0) {
6108                 ctl_set_success(ctsio);
6109                 goto done;
6110         }
6111
6112         mtx_lock(&lun->lun_lock);
6113         ptrlen = (struct ctl_ptr_len_flags *)
6114             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6115         ptrlen->ptr = (void *)buf;
6116         ptrlen->len = len;
6117         ptrlen->flags = byte2;
6118         ctl_check_blocked(lun);
6119         mtx_unlock(&lun->lun_lock);
6120
6121         retval = lun->backend->config_write((union ctl_io *)ctsio);
6122         return (retval);
6123
6124 done:
6125         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
6126                 free(ctsio->kern_data_ptr, M_CTL);
6127                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
6128         }
6129         ctl_done((union ctl_io *)ctsio);
6130         return (CTL_RETVAL_COMPLETE);
6131 }
6132
6133 /*
6134  * Note that this function currently doesn't actually do anything inside
6135  * CTL to enforce things if the DQue bit is turned on.
6136  *
6137  * Also note that this function can't be used in the default case, because
6138  * the DQue bit isn't set in the changeable mask for the control mode page
6139  * anyway.  This is just here as an example for how to implement a page
6140  * handler, and a placeholder in case we want to allow the user to turn
6141  * tagged queueing on and off.
6142  *
6143  * The D_SENSE bit handling is functional, however, and will turn
6144  * descriptor sense on and off for a given LUN.
6145  */
6146 int
6147 ctl_control_page_handler(struct ctl_scsiio *ctsio,
6148                          struct ctl_page_index *page_index, uint8_t *page_ptr)
6149 {
6150         struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6151         struct ctl_lun *lun;
6152         int set_ua;
6153         uint32_t initidx;
6154
6155         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6156         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6157         set_ua = 0;
6158
6159         user_cp = (struct scsi_control_page *)page_ptr;
6160         current_cp = (struct scsi_control_page *)
6161                 (page_index->page_data + (page_index->page_len *
6162                 CTL_PAGE_CURRENT));
6163         saved_cp = (struct scsi_control_page *)
6164                 (page_index->page_data + (page_index->page_len *
6165                 CTL_PAGE_SAVED));
6166
6167         mtx_lock(&lun->lun_lock);
6168         if (((current_cp->rlec & SCP_DSENSE) == 0)
6169          && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6170                 /*
6171                  * Descriptor sense is currently turned off and the user
6172                  * wants to turn it on.
6173                  */
6174                 current_cp->rlec |= SCP_DSENSE;
6175                 saved_cp->rlec |= SCP_DSENSE;
6176                 lun->flags |= CTL_LUN_SENSE_DESC;
6177                 set_ua = 1;
6178         } else if (((current_cp->rlec & SCP_DSENSE) != 0)
6179                 && ((user_cp->rlec & SCP_DSENSE) == 0)) {
6180                 /*
6181                  * Descriptor sense is currently turned on, and the user
6182                  * wants to turn it off.
6183                  */
6184                 current_cp->rlec &= ~SCP_DSENSE;
6185                 saved_cp->rlec &= ~SCP_DSENSE;
6186                 lun->flags &= ~CTL_LUN_SENSE_DESC;
6187                 set_ua = 1;
6188         }
6189         if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6190             (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6191                 current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6192                 current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6193                 saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6194                 saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6195                 set_ua = 1;
6196         }
6197         if ((current_cp->eca_and_aen & SCP_SWP) !=
6198             (user_cp->eca_and_aen & SCP_SWP)) {
6199                 current_cp->eca_and_aen &= ~SCP_SWP;
6200                 current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6201                 saved_cp->eca_and_aen &= ~SCP_SWP;
6202                 saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6203                 set_ua = 1;
6204         }
6205         if (set_ua != 0)
6206                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6207         mtx_unlock(&lun->lun_lock);
6208
6209         return (0);
6210 }
6211
6212 int
6213 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6214                      struct ctl_page_index *page_index, uint8_t *page_ptr)
6215 {
6216         struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6217         struct ctl_lun *lun;
6218         int set_ua;
6219         uint32_t initidx;
6220
6221         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6222         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6223         set_ua = 0;
6224
6225         user_cp = (struct scsi_caching_page *)page_ptr;
6226         current_cp = (struct scsi_caching_page *)
6227                 (page_index->page_data + (page_index->page_len *
6228                 CTL_PAGE_CURRENT));
6229         saved_cp = (struct scsi_caching_page *)
6230                 (page_index->page_data + (page_index->page_len *
6231                 CTL_PAGE_SAVED));
6232
6233         mtx_lock(&lun->lun_lock);
6234         if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6235             (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6236                 current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6237                 current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6238                 saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6239                 saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6240                 set_ua = 1;
6241         }
6242         if (set_ua != 0)
6243                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6244         mtx_unlock(&lun->lun_lock);
6245
6246         return (0);
6247 }
6248
6249 int
6250 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6251                                 struct ctl_page_index *page_index,
6252                                 uint8_t *page_ptr)
6253 {
6254         uint8_t *c;
6255         int i;
6256
6257         c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6258         ctl_time_io_secs =
6259                 (c[0] << 8) |
6260                 (c[1] << 0) |
6261                 0;
6262         CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6263         printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6264         printf("page data:");
6265         for (i=0; i<8; i++)
6266                 printf(" %.2x",page_ptr[i]);
6267         printf("\n");
6268         return (0);
6269 }
6270
6271 int
6272 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6273                                struct ctl_page_index *page_index,
6274                                int pc)
6275 {
6276         struct copan_debugconf_subpage *page;
6277
6278         page = (struct copan_debugconf_subpage *)page_index->page_data +
6279                 (page_index->page_len * pc);
6280
6281         switch (pc) {
6282         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6283         case SMS_PAGE_CTRL_DEFAULT >> 6:
6284         case SMS_PAGE_CTRL_SAVED >> 6:
6285                 /*
6286                  * We don't update the changable or default bits for this page.
6287                  */
6288                 break;
6289         case SMS_PAGE_CTRL_CURRENT >> 6:
6290                 page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6291                 page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6292                 break;
6293         default:
6294 #ifdef NEEDTOPORT
6295                 EPRINT(0, "Invalid PC %d!!", pc);
6296 #endif /* NEEDTOPORT */
6297                 break;
6298         }
6299         return (0);
6300 }
6301
6302
6303 static int
6304 ctl_do_mode_select(union ctl_io *io)
6305 {
6306         struct scsi_mode_page_header *page_header;
6307         struct ctl_page_index *page_index;
6308         struct ctl_scsiio *ctsio;
6309         int control_dev, page_len;
6310         int page_len_offset, page_len_size;
6311         union ctl_modepage_info *modepage_info;
6312         struct ctl_lun *lun;
6313         int *len_left, *len_used;
6314         int retval, i;
6315
6316         ctsio = &io->scsiio;
6317         page_index = NULL;
6318         page_len = 0;
6319         retval = CTL_RETVAL_COMPLETE;
6320
6321         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6322
6323         if (lun->be_lun->lun_type != T_DIRECT)
6324                 control_dev = 1;
6325         else
6326                 control_dev = 0;
6327
6328         modepage_info = (union ctl_modepage_info *)
6329                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6330         len_left = &modepage_info->header.len_left;
6331         len_used = &modepage_info->header.len_used;
6332
6333 do_next_page:
6334
6335         page_header = (struct scsi_mode_page_header *)
6336                 (ctsio->kern_data_ptr + *len_used);
6337
6338         if (*len_left == 0) {
6339                 free(ctsio->kern_data_ptr, M_CTL);
6340                 ctl_set_success(ctsio);
6341                 ctl_done((union ctl_io *)ctsio);
6342                 return (CTL_RETVAL_COMPLETE);
6343         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6344
6345                 free(ctsio->kern_data_ptr, M_CTL);
6346                 ctl_set_param_len_error(ctsio);
6347                 ctl_done((union ctl_io *)ctsio);
6348                 return (CTL_RETVAL_COMPLETE);
6349
6350         } else if ((page_header->page_code & SMPH_SPF)
6351                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6352
6353                 free(ctsio->kern_data_ptr, M_CTL);
6354                 ctl_set_param_len_error(ctsio);
6355                 ctl_done((union ctl_io *)ctsio);
6356                 return (CTL_RETVAL_COMPLETE);
6357         }
6358
6359
6360         /*
6361          * XXX KDM should we do something with the block descriptor?
6362          */
6363         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6364
6365                 if ((control_dev != 0)
6366                  && (lun->mode_pages.index[i].page_flags &
6367                      CTL_PAGE_FLAG_DISK_ONLY))
6368                         continue;
6369
6370                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6371                     (page_header->page_code & SMPH_PC_MASK))
6372                         continue;
6373
6374                 /*
6375                  * If neither page has a subpage code, then we've got a
6376                  * match.
6377                  */
6378                 if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6379                  && ((page_header->page_code & SMPH_SPF) == 0)) {
6380                         page_index = &lun->mode_pages.index[i];
6381                         page_len = page_header->page_length;
6382                         break;
6383                 }
6384
6385                 /*
6386                  * If both pages have subpages, then the subpage numbers
6387                  * have to match.
6388                  */
6389                 if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6390                   && (page_header->page_code & SMPH_SPF)) {
6391                         struct scsi_mode_page_header_sp *sph;
6392
6393                         sph = (struct scsi_mode_page_header_sp *)page_header;
6394
6395                         if (lun->mode_pages.index[i].subpage ==
6396                             sph->subpage) {
6397                                 page_index = &lun->mode_pages.index[i];
6398                                 page_len = scsi_2btoul(sph->page_length);
6399                                 break;
6400                         }
6401                 }
6402         }
6403
6404         /*
6405          * If we couldn't find the page, or if we don't have a mode select
6406          * handler for it, send back an error to the user.
6407          */
6408         if ((page_index == NULL)
6409          || (page_index->select_handler == NULL)) {
6410                 ctl_set_invalid_field(ctsio,
6411                                       /*sks_valid*/ 1,
6412                                       /*command*/ 0,
6413                                       /*field*/ *len_used,
6414                                       /*bit_valid*/ 0,
6415                                       /*bit*/ 0);
6416                 free(ctsio->kern_data_ptr, M_CTL);
6417                 ctl_done((union ctl_io *)ctsio);
6418                 return (CTL_RETVAL_COMPLETE);
6419         }
6420
6421         if (page_index->page_code & SMPH_SPF) {
6422                 page_len_offset = 2;
6423                 page_len_size = 2;
6424         } else {
6425                 page_len_size = 1;
6426                 page_len_offset = 1;
6427         }
6428
6429         /*
6430          * If the length the initiator gives us isn't the one we specify in
6431          * the mode page header, or if they didn't specify enough data in
6432          * the CDB to avoid truncating this page, kick out the request.
6433          */
6434         if ((page_len != (page_index->page_len - page_len_offset -
6435                           page_len_size))
6436          || (*len_left < page_index->page_len)) {
6437
6438
6439                 ctl_set_invalid_field(ctsio,
6440                                       /*sks_valid*/ 1,
6441                                       /*command*/ 0,
6442                                       /*field*/ *len_used + page_len_offset,
6443                                       /*bit_valid*/ 0,
6444                                       /*bit*/ 0);
6445                 free(ctsio->kern_data_ptr, M_CTL);
6446                 ctl_done((union ctl_io *)ctsio);
6447                 return (CTL_RETVAL_COMPLETE);
6448         }
6449
6450         /*
6451          * Run through the mode page, checking to make sure that the bits
6452          * the user changed are actually legal for him to change.
6453          */
6454         for (i = 0; i < page_index->page_len; i++) {
6455                 uint8_t *user_byte, *change_mask, *current_byte;
6456                 int bad_bit;
6457                 int j;
6458
6459                 user_byte = (uint8_t *)page_header + i;
6460                 change_mask = page_index->page_data +
6461                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6462                 current_byte = page_index->page_data +
6463                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6464
6465                 /*
6466                  * Check to see whether the user set any bits in this byte
6467                  * that he is not allowed to set.
6468                  */
6469                 if ((*user_byte & ~(*change_mask)) ==
6470                     (*current_byte & ~(*change_mask)))
6471                         continue;
6472
6473                 /*
6474                  * Go through bit by bit to determine which one is illegal.
6475                  */
6476                 bad_bit = 0;
6477                 for (j = 7; j >= 0; j--) {
6478                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6479                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6480                                 bad_bit = i;
6481                                 break;
6482                         }
6483                 }
6484                 ctl_set_invalid_field(ctsio,
6485                                       /*sks_valid*/ 1,
6486                                       /*command*/ 0,
6487                                       /*field*/ *len_used + i,
6488                                       /*bit_valid*/ 1,
6489                                       /*bit*/ bad_bit);
6490                 free(ctsio->kern_data_ptr, M_CTL);
6491                 ctl_done((union ctl_io *)ctsio);
6492                 return (CTL_RETVAL_COMPLETE);
6493         }
6494
6495         /*
6496          * Decrement these before we call the page handler, since we may
6497          * end up getting called back one way or another before the handler
6498          * returns to this context.
6499          */
6500         *len_left -= page_index->page_len;
6501         *len_used += page_index->page_len;
6502
6503         retval = page_index->select_handler(ctsio, page_index,
6504                                             (uint8_t *)page_header);
6505
6506         /*
6507          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6508          * wait until this queued command completes to finish processing
6509          * the mode page.  If it returns anything other than
6510          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6511          * already set the sense information, freed the data pointer, and
6512          * completed the io for us.
6513          */
6514         if (retval != CTL_RETVAL_COMPLETE)
6515                 goto bailout_no_done;
6516
6517         /*
6518          * If the initiator sent us more than one page, parse the next one.
6519          */
6520         if (*len_left > 0)
6521                 goto do_next_page;
6522
6523         ctl_set_success(ctsio);
6524         free(ctsio->kern_data_ptr, M_CTL);
6525         ctl_done((union ctl_io *)ctsio);
6526
6527 bailout_no_done:
6528
6529         return (CTL_RETVAL_COMPLETE);
6530
6531 }
6532
6533 int
6534 ctl_mode_select(struct ctl_scsiio *ctsio)
6535 {
6536         int param_len, pf, sp;
6537         int header_size, bd_len;
6538         int len_left, len_used;
6539         struct ctl_page_index *page_index;
6540         struct ctl_lun *lun;
6541         int control_dev, page_len;
6542         union ctl_modepage_info *modepage_info;
6543         int retval;
6544
6545         pf = 0;
6546         sp = 0;
6547         page_len = 0;
6548         len_used = 0;
6549         len_left = 0;
6550         retval = 0;
6551         bd_len = 0;
6552         page_index = NULL;
6553
6554         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6555
6556         if (lun->be_lun->lun_type != T_DIRECT)
6557                 control_dev = 1;
6558         else
6559                 control_dev = 0;
6560
6561         switch (ctsio->cdb[0]) {
6562         case MODE_SELECT_6: {
6563                 struct scsi_mode_select_6 *cdb;
6564
6565                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6566
6567                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6568                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6569
6570                 param_len = cdb->length;
6571                 header_size = sizeof(struct scsi_mode_header_6);
6572                 break;
6573         }
6574         case MODE_SELECT_10: {
6575                 struct scsi_mode_select_10 *cdb;
6576
6577                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6578
6579                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6580                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6581
6582                 param_len = scsi_2btoul(cdb->length);
6583                 header_size = sizeof(struct scsi_mode_header_10);
6584                 break;
6585         }
6586         default:
6587                 ctl_set_invalid_opcode(ctsio);
6588                 ctl_done((union ctl_io *)ctsio);
6589                 return (CTL_RETVAL_COMPLETE);
6590                 break; /* NOTREACHED */
6591         }
6592
6593         /*
6594          * From SPC-3:
6595          * "A parameter list length of zero indicates that the Data-Out Buffer
6596          * shall be empty. This condition shall not be considered as an error."
6597          */
6598         if (param_len == 0) {
6599                 ctl_set_success(ctsio);
6600                 ctl_done((union ctl_io *)ctsio);
6601                 return (CTL_RETVAL_COMPLETE);
6602         }
6603
6604         /*
6605          * Since we'll hit this the first time through, prior to
6606          * allocation, we don't need to free a data buffer here.
6607          */
6608         if (param_len < header_size) {
6609                 ctl_set_param_len_error(ctsio);
6610                 ctl_done((union ctl_io *)ctsio);
6611                 return (CTL_RETVAL_COMPLETE);
6612         }
6613
6614         /*
6615          * Allocate the data buffer and grab the user's data.  In theory,
6616          * we shouldn't have to sanity check the parameter list length here
6617          * because the maximum size is 64K.  We should be able to malloc
6618          * that much without too many problems.
6619          */
6620         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6621                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6622                 ctsio->kern_data_len = param_len;
6623                 ctsio->kern_total_len = param_len;
6624                 ctsio->kern_data_resid = 0;
6625                 ctsio->kern_rel_offset = 0;
6626                 ctsio->kern_sg_entries = 0;
6627                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6628                 ctsio->be_move_done = ctl_config_move_done;
6629                 ctl_datamove((union ctl_io *)ctsio);
6630
6631                 return (CTL_RETVAL_COMPLETE);
6632         }
6633
6634         switch (ctsio->cdb[0]) {
6635         case MODE_SELECT_6: {
6636                 struct scsi_mode_header_6 *mh6;
6637
6638                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6639                 bd_len = mh6->blk_desc_len;
6640                 break;
6641         }
6642         case MODE_SELECT_10: {
6643                 struct scsi_mode_header_10 *mh10;
6644
6645                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6646                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6647                 break;
6648         }
6649         default:
6650                 panic("Invalid CDB type %#x", ctsio->cdb[0]);
6651                 break;
6652         }
6653
6654         if (param_len < (header_size + bd_len)) {
6655                 free(ctsio->kern_data_ptr, M_CTL);
6656                 ctl_set_param_len_error(ctsio);
6657                 ctl_done((union ctl_io *)ctsio);
6658                 return (CTL_RETVAL_COMPLETE);
6659         }
6660
6661         /*
6662          * Set the IO_CONT flag, so that if this I/O gets passed to
6663          * ctl_config_write_done(), it'll get passed back to
6664          * ctl_do_mode_select() for further processing, or completion if
6665          * we're all done.
6666          */
6667         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6668         ctsio->io_cont = ctl_do_mode_select;
6669
6670         modepage_info = (union ctl_modepage_info *)
6671                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6672
6673         memset(modepage_info, 0, sizeof(*modepage_info));
6674
6675         len_left = param_len - header_size - bd_len;
6676         len_used = header_size + bd_len;
6677
6678         modepage_info->header.len_left = len_left;
6679         modepage_info->header.len_used = len_used;
6680
6681         return (ctl_do_mode_select((union ctl_io *)ctsio));
6682 }
6683
6684 int
6685 ctl_mode_sense(struct ctl_scsiio *ctsio)
6686 {
6687         struct ctl_lun *lun;
6688         int pc, page_code, dbd, llba, subpage;
6689         int alloc_len, page_len, header_len, total_len;
6690         struct scsi_mode_block_descr *block_desc;
6691         struct ctl_page_index *page_index;
6692         int control_dev;
6693
6694         dbd = 0;
6695         llba = 0;
6696         block_desc = NULL;
6697         page_index = NULL;
6698
6699         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6700
6701         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6702
6703         if (lun->be_lun->lun_type != T_DIRECT)
6704                 control_dev = 1;
6705         else
6706                 control_dev = 0;
6707
6708         switch (ctsio->cdb[0]) {
6709         case MODE_SENSE_6: {
6710                 struct scsi_mode_sense_6 *cdb;
6711
6712                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6713
6714                 header_len = sizeof(struct scsi_mode_hdr_6);
6715                 if (cdb->byte2 & SMS_DBD)
6716                         dbd = 1;
6717                 else
6718                         header_len += sizeof(struct scsi_mode_block_descr);
6719
6720                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6721                 page_code = cdb->page & SMS_PAGE_CODE;
6722                 subpage = cdb->subpage;
6723                 alloc_len = cdb->length;
6724                 break;
6725         }
6726         case MODE_SENSE_10: {
6727                 struct scsi_mode_sense_10 *cdb;
6728
6729                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6730
6731                 header_len = sizeof(struct scsi_mode_hdr_10);
6732
6733                 if (cdb->byte2 & SMS_DBD)
6734                         dbd = 1;
6735                 else
6736                         header_len += sizeof(struct scsi_mode_block_descr);
6737                 if (cdb->byte2 & SMS10_LLBAA)
6738                         llba = 1;
6739                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6740                 page_code = cdb->page & SMS_PAGE_CODE;
6741                 subpage = cdb->subpage;
6742                 alloc_len = scsi_2btoul(cdb->length);
6743                 break;
6744         }
6745         default:
6746                 ctl_set_invalid_opcode(ctsio);
6747                 ctl_done((union ctl_io *)ctsio);
6748                 return (CTL_RETVAL_COMPLETE);
6749                 break; /* NOTREACHED */
6750         }
6751
6752         /*
6753          * We have to make a first pass through to calculate the size of
6754          * the pages that match the user's query.  Then we allocate enough
6755          * memory to hold it, and actually copy the data into the buffer.
6756          */
6757         switch (page_code) {
6758         case SMS_ALL_PAGES_PAGE: {
6759                 int i;
6760
6761                 page_len = 0;
6762
6763                 /*
6764                  * At the moment, values other than 0 and 0xff here are
6765                  * reserved according to SPC-3.
6766                  */
6767                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6768                  && (subpage != SMS_SUBPAGE_ALL)) {
6769                         ctl_set_invalid_field(ctsio,
6770                                               /*sks_valid*/ 1,
6771                                               /*command*/ 1,
6772                                               /*field*/ 3,
6773                                               /*bit_valid*/ 0,
6774                                               /*bit*/ 0);
6775                         ctl_done((union ctl_io *)ctsio);
6776                         return (CTL_RETVAL_COMPLETE);
6777                 }
6778
6779                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6780                         if ((control_dev != 0)
6781                          && (lun->mode_pages.index[i].page_flags &
6782                              CTL_PAGE_FLAG_DISK_ONLY))
6783                                 continue;
6784
6785                         /*
6786                          * We don't use this subpage if the user didn't
6787                          * request all subpages.
6788                          */
6789                         if ((lun->mode_pages.index[i].subpage != 0)
6790                          && (subpage == SMS_SUBPAGE_PAGE_0))
6791                                 continue;
6792
6793 #if 0
6794                         printf("found page %#x len %d\n",
6795                                lun->mode_pages.index[i].page_code &
6796                                SMPH_PC_MASK,
6797                                lun->mode_pages.index[i].page_len);
6798 #endif
6799                         page_len += lun->mode_pages.index[i].page_len;
6800                 }
6801                 break;
6802         }
6803         default: {
6804                 int i;
6805
6806                 page_len = 0;
6807
6808                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6809                         /* Look for the right page code */
6810                         if ((lun->mode_pages.index[i].page_code &
6811                              SMPH_PC_MASK) != page_code)
6812                                 continue;
6813
6814                         /* Look for the right subpage or the subpage wildcard*/
6815                         if ((lun->mode_pages.index[i].subpage != subpage)
6816                          && (subpage != SMS_SUBPAGE_ALL))
6817                                 continue;
6818
6819                         /* Make sure the page is supported for this dev type */
6820                         if ((control_dev != 0)
6821                          && (lun->mode_pages.index[i].page_flags &
6822                              CTL_PAGE_FLAG_DISK_ONLY))
6823                                 continue;
6824
6825 #if 0
6826                         printf("found page %#x len %d\n",
6827                                lun->mode_pages.index[i].page_code &
6828                                SMPH_PC_MASK,
6829                                lun->mode_pages.index[i].page_len);
6830 #endif
6831
6832                         page_len += lun->mode_pages.index[i].page_len;
6833                 }
6834
6835                 if (page_len == 0) {
6836                         ctl_set_invalid_field(ctsio,
6837                                               /*sks_valid*/ 1,
6838                                               /*command*/ 1,
6839                                               /*field*/ 2,
6840                                               /*bit_valid*/ 1,
6841                                               /*bit*/ 5);
6842                         ctl_done((union ctl_io *)ctsio);
6843                         return (CTL_RETVAL_COMPLETE);
6844                 }
6845                 break;
6846         }
6847         }
6848
6849         total_len = header_len + page_len;
6850 #if 0
6851         printf("header_len = %d, page_len = %d, total_len = %d\n",
6852                header_len, page_len, total_len);
6853 #endif
6854
6855         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6856         ctsio->kern_sg_entries = 0;
6857         ctsio->kern_data_resid = 0;
6858         ctsio->kern_rel_offset = 0;
6859         if (total_len < alloc_len) {
6860                 ctsio->residual = alloc_len - total_len;
6861                 ctsio->kern_data_len = total_len;
6862                 ctsio->kern_total_len = total_len;
6863         } else {
6864                 ctsio->residual = 0;
6865                 ctsio->kern_data_len = alloc_len;
6866                 ctsio->kern_total_len = alloc_len;
6867         }
6868
6869         switch (ctsio->cdb[0]) {
6870         case MODE_SENSE_6: {
6871                 struct scsi_mode_hdr_6 *header;
6872
6873                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6874
6875                 header->datalen = MIN(total_len - 1, 254);
6876                 if (control_dev == 0) {
6877                         header->dev_specific = 0x10; /* DPOFUA */
6878                         if ((lun->flags & CTL_LUN_READONLY) ||
6879                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6880                             .eca_and_aen & SCP_SWP) != 0)
6881                                     header->dev_specific |= 0x80; /* WP */
6882                 }
6883                 if (dbd)
6884                         header->block_descr_len = 0;
6885                 else
6886                         header->block_descr_len =
6887                                 sizeof(struct scsi_mode_block_descr);
6888                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6889                 break;
6890         }
6891         case MODE_SENSE_10: {
6892                 struct scsi_mode_hdr_10 *header;
6893                 int datalen;
6894
6895                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6896
6897                 datalen = MIN(total_len - 2, 65533);
6898                 scsi_ulto2b(datalen, header->datalen);
6899                 if (control_dev == 0) {
6900                         header->dev_specific = 0x10; /* DPOFUA */
6901                         if ((lun->flags & CTL_LUN_READONLY) ||
6902                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6903                             .eca_and_aen & SCP_SWP) != 0)
6904                                     header->dev_specific |= 0x80; /* WP */
6905                 }
6906                 if (dbd)
6907                         scsi_ulto2b(0, header->block_descr_len);
6908                 else
6909                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6910                                     header->block_descr_len);
6911                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6912                 break;
6913         }
6914         default:
6915                 panic("invalid CDB type %#x", ctsio->cdb[0]);
6916                 break; /* NOTREACHED */
6917         }
6918
6919         /*
6920          * If we've got a disk, use its blocksize in the block
6921          * descriptor.  Otherwise, just set it to 0.
6922          */
6923         if (dbd == 0) {
6924                 if (control_dev == 0)
6925                         scsi_ulto3b(lun->be_lun->blocksize,
6926                                     block_desc->block_len);
6927                 else
6928                         scsi_ulto3b(0, block_desc->block_len);
6929         }
6930
6931         switch (page_code) {
6932         case SMS_ALL_PAGES_PAGE: {
6933                 int i, data_used;
6934
6935                 data_used = header_len;
6936                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6937                         struct ctl_page_index *page_index;
6938
6939                         page_index = &lun->mode_pages.index[i];
6940
6941                         if ((control_dev != 0)
6942                          && (page_index->page_flags &
6943                             CTL_PAGE_FLAG_DISK_ONLY))
6944                                 continue;
6945
6946                         /*
6947                          * We don't use this subpage if the user didn't
6948                          * request all subpages.  We already checked (above)
6949                          * to make sure the user only specified a subpage
6950                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6951                          */
6952                         if ((page_index->subpage != 0)
6953                          && (subpage == SMS_SUBPAGE_PAGE_0))
6954                                 continue;
6955
6956                         /*
6957                          * Call the handler, if it exists, to update the
6958                          * page to the latest values.
6959                          */
6960                         if (page_index->sense_handler != NULL)
6961                                 page_index->sense_handler(ctsio, page_index,pc);
6962
6963                         memcpy(ctsio->kern_data_ptr + data_used,
6964                                page_index->page_data +
6965                                (page_index->page_len * pc),
6966                                page_index->page_len);
6967                         data_used += page_index->page_len;
6968                 }
6969                 break;
6970         }
6971         default: {
6972                 int i, data_used;
6973
6974                 data_used = header_len;
6975
6976                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6977                         struct ctl_page_index *page_index;
6978
6979                         page_index = &lun->mode_pages.index[i];
6980
6981                         /* Look for the right page code */
6982                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6983                                 continue;
6984
6985                         /* Look for the right subpage or the subpage wildcard*/
6986                         if ((page_index->subpage != subpage)
6987                          && (subpage != SMS_SUBPAGE_ALL))
6988                                 continue;
6989
6990                         /* Make sure the page is supported for this dev type */
6991                         if ((control_dev != 0)
6992                          && (page_index->page_flags &
6993                              CTL_PAGE_FLAG_DISK_ONLY))
6994                                 continue;
6995
6996                         /*
6997                          * Call the handler, if it exists, to update the
6998                          * page to the latest values.
6999                          */
7000                         if (page_index->sense_handler != NULL)
7001                                 page_index->sense_handler(ctsio, page_index,pc);
7002
7003                         memcpy(ctsio->kern_data_ptr + data_used,
7004                                page_index->page_data +
7005                                (page_index->page_len * pc),
7006                                page_index->page_len);
7007                         data_used += page_index->page_len;
7008                 }
7009                 break;
7010         }
7011         }
7012
7013         ctl_set_success(ctsio);
7014         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7015         ctsio->be_move_done = ctl_config_move_done;
7016         ctl_datamove((union ctl_io *)ctsio);
7017         return (CTL_RETVAL_COMPLETE);
7018 }
7019
7020 int
7021 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
7022                                struct ctl_page_index *page_index,
7023                                int pc)
7024 {
7025         struct ctl_lun *lun;
7026         struct scsi_log_param_header *phdr;
7027         uint8_t *data;
7028         uint64_t val;
7029
7030         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7031         data = page_index->page_data;
7032
7033         if (lun->backend->lun_attr != NULL &&
7034             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
7035              != UINT64_MAX) {
7036                 phdr = (struct scsi_log_param_header *)data;
7037                 scsi_ulto2b(0x0001, phdr->param_code);
7038                 phdr->param_control = SLP_LBIN | SLP_LP;
7039                 phdr->param_len = 8;
7040                 data = (uint8_t *)(phdr + 1);
7041                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7042                 data[4] = 0x02; /* per-pool */
7043                 data += phdr->param_len;
7044         }
7045
7046         if (lun->backend->lun_attr != NULL &&
7047             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
7048              != UINT64_MAX) {
7049                 phdr = (struct scsi_log_param_header *)data;
7050                 scsi_ulto2b(0x0002, phdr->param_code);
7051                 phdr->param_control = SLP_LBIN | SLP_LP;
7052                 phdr->param_len = 8;
7053                 data = (uint8_t *)(phdr + 1);
7054                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7055                 data[4] = 0x01; /* per-LUN */
7056                 data += phdr->param_len;
7057         }
7058
7059         if (lun->backend->lun_attr != NULL &&
7060             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
7061              != UINT64_MAX) {
7062                 phdr = (struct scsi_log_param_header *)data;
7063                 scsi_ulto2b(0x00f1, phdr->param_code);
7064                 phdr->param_control = SLP_LBIN | SLP_LP;
7065                 phdr->param_len = 8;
7066                 data = (uint8_t *)(phdr + 1);
7067                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7068                 data[4] = 0x02; /* per-pool */
7069                 data += phdr->param_len;
7070         }
7071
7072         if (lun->backend->lun_attr != NULL &&
7073             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
7074              != UINT64_MAX) {
7075                 phdr = (struct scsi_log_param_header *)data;
7076                 scsi_ulto2b(0x00f2, phdr->param_code);
7077                 phdr->param_control = SLP_LBIN | SLP_LP;
7078                 phdr->param_len = 8;
7079                 data = (uint8_t *)(phdr + 1);
7080                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7081                 data[4] = 0x02; /* per-pool */
7082                 data += phdr->param_len;
7083         }
7084
7085         page_index->page_len = data - page_index->page_data;
7086         return (0);
7087 }
7088
7089 int
7090 ctl_log_sense(struct ctl_scsiio *ctsio)
7091 {
7092         struct ctl_lun *lun;
7093         int i, pc, page_code, subpage;
7094         int alloc_len, total_len;
7095         struct ctl_page_index *page_index;
7096         struct scsi_log_sense *cdb;
7097         struct scsi_log_header *header;
7098
7099         CTL_DEBUG_PRINT(("ctl_log_sense\n"));
7100
7101         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7102         cdb = (struct scsi_log_sense *)ctsio->cdb;
7103         pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
7104         page_code = cdb->page & SLS_PAGE_CODE;
7105         subpage = cdb->subpage;
7106         alloc_len = scsi_2btoul(cdb->length);
7107
7108         page_index = NULL;
7109         for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
7110                 page_index = &lun->log_pages.index[i];
7111
7112                 /* Look for the right page code */
7113                 if ((page_index->page_code & SL_PAGE_CODE) != page_code)
7114                         continue;
7115
7116                 /* Look for the right subpage or the subpage wildcard*/
7117                 if (page_index->subpage != subpage)
7118                         continue;
7119
7120                 break;
7121         }
7122         if (i >= CTL_NUM_LOG_PAGES) {
7123                 ctl_set_invalid_field(ctsio,
7124                                       /*sks_valid*/ 1,
7125                                       /*command*/ 1,
7126                                       /*field*/ 2,
7127                                       /*bit_valid*/ 0,
7128                                       /*bit*/ 0);
7129                 ctl_done((union ctl_io *)ctsio);
7130                 return (CTL_RETVAL_COMPLETE);
7131         }
7132
7133         total_len = sizeof(struct scsi_log_header) + page_index->page_len;
7134
7135         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7136         ctsio->kern_sg_entries = 0;
7137         ctsio->kern_data_resid = 0;
7138         ctsio->kern_rel_offset = 0;
7139         if (total_len < alloc_len) {
7140                 ctsio->residual = alloc_len - total_len;
7141                 ctsio->kern_data_len = total_len;
7142                 ctsio->kern_total_len = total_len;
7143         } else {
7144                 ctsio->residual = 0;
7145                 ctsio->kern_data_len = alloc_len;
7146                 ctsio->kern_total_len = alloc_len;
7147         }
7148
7149         header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7150         header->page = page_index->page_code;
7151         if (page_index->subpage) {
7152                 header->page |= SL_SPF;
7153                 header->subpage = page_index->subpage;
7154         }
7155         scsi_ulto2b(page_index->page_len, header->datalen);
7156
7157         /*
7158          * Call the handler, if it exists, to update the
7159          * page to the latest values.
7160          */
7161         if (page_index->sense_handler != NULL)
7162                 page_index->sense_handler(ctsio, page_index, pc);
7163
7164         memcpy(header + 1, page_index->page_data, page_index->page_len);
7165
7166         ctl_set_success(ctsio);
7167         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7168         ctsio->be_move_done = ctl_config_move_done;
7169         ctl_datamove((union ctl_io *)ctsio);
7170         return (CTL_RETVAL_COMPLETE);
7171 }
7172
7173 int
7174 ctl_read_capacity(struct ctl_scsiio *ctsio)
7175 {
7176         struct scsi_read_capacity *cdb;
7177         struct scsi_read_capacity_data *data;
7178         struct ctl_lun *lun;
7179         uint32_t lba;
7180
7181         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7182
7183         cdb = (struct scsi_read_capacity *)ctsio->cdb;
7184
7185         lba = scsi_4btoul(cdb->addr);
7186         if (((cdb->pmi & SRC_PMI) == 0)
7187          && (lba != 0)) {
7188                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7189                                       /*sks_valid*/ 1,
7190                                       /*command*/ 1,
7191                                       /*field*/ 2,
7192                                       /*bit_valid*/ 0,
7193                                       /*bit*/ 0);
7194                 ctl_done((union ctl_io *)ctsio);
7195                 return (CTL_RETVAL_COMPLETE);
7196         }
7197
7198         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7199
7200         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7201         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7202         ctsio->residual = 0;
7203         ctsio->kern_data_len = sizeof(*data);
7204         ctsio->kern_total_len = sizeof(*data);
7205         ctsio->kern_data_resid = 0;
7206         ctsio->kern_rel_offset = 0;
7207         ctsio->kern_sg_entries = 0;
7208
7209         /*
7210          * If the maximum LBA is greater than 0xfffffffe, the user must
7211          * issue a SERVICE ACTION IN (16) command, with the read capacity
7212          * serivce action set.
7213          */
7214         if (lun->be_lun->maxlba > 0xfffffffe)
7215                 scsi_ulto4b(0xffffffff, data->addr);
7216         else
7217                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7218
7219         /*
7220          * XXX KDM this may not be 512 bytes...
7221          */
7222         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7223
7224         ctl_set_success(ctsio);
7225         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7226         ctsio->be_move_done = ctl_config_move_done;
7227         ctl_datamove((union ctl_io *)ctsio);
7228         return (CTL_RETVAL_COMPLETE);
7229 }
7230
7231 int
7232 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7233 {
7234         struct scsi_read_capacity_16 *cdb;
7235         struct scsi_read_capacity_data_long *data;
7236         struct ctl_lun *lun;
7237         uint64_t lba;
7238         uint32_t alloc_len;
7239
7240         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7241
7242         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7243
7244         alloc_len = scsi_4btoul(cdb->alloc_len);
7245         lba = scsi_8btou64(cdb->addr);
7246
7247         if ((cdb->reladr & SRC16_PMI)
7248          && (lba != 0)) {
7249                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7250                                       /*sks_valid*/ 1,
7251                                       /*command*/ 1,
7252                                       /*field*/ 2,
7253                                       /*bit_valid*/ 0,
7254                                       /*bit*/ 0);
7255                 ctl_done((union ctl_io *)ctsio);
7256                 return (CTL_RETVAL_COMPLETE);
7257         }
7258
7259         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7260
7261         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7262         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7263
7264         if (sizeof(*data) < alloc_len) {
7265                 ctsio->residual = alloc_len - sizeof(*data);
7266                 ctsio->kern_data_len = sizeof(*data);
7267                 ctsio->kern_total_len = sizeof(*data);
7268         } else {
7269                 ctsio->residual = 0;
7270                 ctsio->kern_data_len = alloc_len;
7271                 ctsio->kern_total_len = alloc_len;
7272         }
7273         ctsio->kern_data_resid = 0;
7274         ctsio->kern_rel_offset = 0;
7275         ctsio->kern_sg_entries = 0;
7276
7277         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7278         /* XXX KDM this may not be 512 bytes... */
7279         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7280         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7281         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7282         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7283                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7284
7285         ctl_set_success(ctsio);
7286         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7287         ctsio->be_move_done = ctl_config_move_done;
7288         ctl_datamove((union ctl_io *)ctsio);
7289         return (CTL_RETVAL_COMPLETE);
7290 }
7291
7292 int
7293 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7294 {
7295         struct scsi_get_lba_status *cdb;
7296         struct scsi_get_lba_status_data *data;
7297         struct ctl_lun *lun;
7298         struct ctl_lba_len_flags *lbalen;
7299         uint64_t lba;
7300         uint32_t alloc_len, total_len;
7301         int retval;
7302
7303         CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7304
7305         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7306         cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7307         lba = scsi_8btou64(cdb->addr);
7308         alloc_len = scsi_4btoul(cdb->alloc_len);
7309
7310         if (lba > lun->be_lun->maxlba) {
7311                 ctl_set_lba_out_of_range(ctsio);
7312                 ctl_done((union ctl_io *)ctsio);
7313                 return (CTL_RETVAL_COMPLETE);
7314         }
7315
7316         total_len = sizeof(*data) + sizeof(data->descr[0]);
7317         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7318         data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7319
7320         if (total_len < alloc_len) {
7321                 ctsio->residual = alloc_len - total_len;
7322                 ctsio->kern_data_len = total_len;
7323                 ctsio->kern_total_len = total_len;
7324         } else {
7325                 ctsio->residual = 0;
7326                 ctsio->kern_data_len = alloc_len;
7327                 ctsio->kern_total_len = alloc_len;
7328         }
7329         ctsio->kern_data_resid = 0;
7330         ctsio->kern_rel_offset = 0;
7331         ctsio->kern_sg_entries = 0;
7332
7333         /* Fill dummy data in case backend can't tell anything. */
7334         scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7335         scsi_u64to8b(lba, data->descr[0].addr);
7336         scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7337             data->descr[0].length);
7338         data->descr[0].status = 0; /* Mapped or unknown. */
7339
7340         ctl_set_success(ctsio);
7341         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7342         ctsio->be_move_done = ctl_config_move_done;
7343
7344         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7345         lbalen->lba = lba;
7346         lbalen->len = total_len;
7347         lbalen->flags = 0;
7348         retval = lun->backend->config_read((union ctl_io *)ctsio);
7349         return (CTL_RETVAL_COMPLETE);
7350 }
7351
7352 int
7353 ctl_read_defect(struct ctl_scsiio *ctsio)
7354 {
7355         struct scsi_read_defect_data_10 *ccb10;
7356         struct scsi_read_defect_data_12 *ccb12;
7357         struct scsi_read_defect_data_hdr_10 *data10;
7358         struct scsi_read_defect_data_hdr_12 *data12;
7359         uint32_t alloc_len, data_len;
7360         uint8_t format;
7361
7362         CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7363
7364         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7365                 ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7366                 format = ccb10->format;
7367                 alloc_len = scsi_2btoul(ccb10->alloc_length);
7368                 data_len = sizeof(*data10);
7369         } else {
7370                 ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7371                 format = ccb12->format;
7372                 alloc_len = scsi_4btoul(ccb12->alloc_length);
7373                 data_len = sizeof(*data12);
7374         }
7375         if (alloc_len == 0) {
7376                 ctl_set_success(ctsio);
7377                 ctl_done((union ctl_io *)ctsio);
7378                 return (CTL_RETVAL_COMPLETE);
7379         }
7380
7381         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7382         if (data_len < alloc_len) {
7383                 ctsio->residual = alloc_len - data_len;
7384                 ctsio->kern_data_len = data_len;
7385                 ctsio->kern_total_len = data_len;
7386         } else {
7387                 ctsio->residual = 0;
7388                 ctsio->kern_data_len = alloc_len;
7389                 ctsio->kern_total_len = alloc_len;
7390         }
7391         ctsio->kern_data_resid = 0;
7392         ctsio->kern_rel_offset = 0;
7393         ctsio->kern_sg_entries = 0;
7394
7395         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7396                 data10 = (struct scsi_read_defect_data_hdr_10 *)
7397                     ctsio->kern_data_ptr;
7398                 data10->format = format;
7399                 scsi_ulto2b(0, data10->length);
7400         } else {
7401                 data12 = (struct scsi_read_defect_data_hdr_12 *)
7402                     ctsio->kern_data_ptr;
7403                 data12->format = format;
7404                 scsi_ulto2b(0, data12->generation);
7405                 scsi_ulto4b(0, data12->length);
7406         }
7407
7408         ctl_set_success(ctsio);
7409         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7410         ctsio->be_move_done = ctl_config_move_done;
7411         ctl_datamove((union ctl_io *)ctsio);
7412         return (CTL_RETVAL_COMPLETE);
7413 }
7414
7415 int
7416 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7417 {
7418         struct scsi_maintenance_in *cdb;
7419         int retval;
7420         int alloc_len, ext, total_len = 0, g, p, pc, pg, gs, os;
7421         int num_target_port_groups, num_target_ports;
7422         struct ctl_lun *lun;
7423         struct ctl_softc *softc;
7424         struct ctl_port *port;
7425         struct scsi_target_group_data *rtg_ptr;
7426         struct scsi_target_group_data_extended *rtg_ext_ptr;
7427         struct scsi_target_port_group_descriptor *tpg_desc;
7428
7429         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7430
7431         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7432         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7433         softc = lun->ctl_softc;
7434
7435         retval = CTL_RETVAL_COMPLETE;
7436
7437         switch (cdb->byte2 & STG_PDF_MASK) {
7438         case STG_PDF_LENGTH:
7439                 ext = 0;
7440                 break;
7441         case STG_PDF_EXTENDED:
7442                 ext = 1;
7443                 break;
7444         default:
7445                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7446                                       /*sks_valid*/ 1,
7447                                       /*command*/ 1,
7448                                       /*field*/ 2,
7449                                       /*bit_valid*/ 1,
7450                                       /*bit*/ 5);
7451                 ctl_done((union ctl_io *)ctsio);
7452                 return(retval);
7453         }
7454
7455         if (softc->is_single)
7456                 num_target_port_groups = 1;
7457         else
7458                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7459         num_target_ports = 0;
7460         mtx_lock(&softc->ctl_lock);
7461         STAILQ_FOREACH(port, &softc->port_list, links) {
7462                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7463                         continue;
7464                 if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7465                         continue;
7466                 num_target_ports++;
7467         }
7468         mtx_unlock(&softc->ctl_lock);
7469
7470         if (ext)
7471                 total_len = sizeof(struct scsi_target_group_data_extended);
7472         else
7473                 total_len = sizeof(struct scsi_target_group_data);
7474         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7475                 num_target_port_groups +
7476             sizeof(struct scsi_target_port_descriptor) *
7477                 num_target_ports * num_target_port_groups;
7478
7479         alloc_len = scsi_4btoul(cdb->length);
7480
7481         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7482
7483         ctsio->kern_sg_entries = 0;
7484
7485         if (total_len < alloc_len) {
7486                 ctsio->residual = alloc_len - total_len;
7487                 ctsio->kern_data_len = total_len;
7488                 ctsio->kern_total_len = total_len;
7489         } else {
7490                 ctsio->residual = 0;
7491                 ctsio->kern_data_len = alloc_len;
7492                 ctsio->kern_total_len = alloc_len;
7493         }
7494         ctsio->kern_data_resid = 0;
7495         ctsio->kern_rel_offset = 0;
7496
7497         if (ext) {
7498                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7499                     ctsio->kern_data_ptr;
7500                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7501                 rtg_ext_ptr->format_type = 0x10;
7502                 rtg_ext_ptr->implicit_transition_time = 0;
7503                 tpg_desc = &rtg_ext_ptr->groups[0];
7504         } else {
7505                 rtg_ptr = (struct scsi_target_group_data *)
7506                     ctsio->kern_data_ptr;
7507                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7508                 tpg_desc = &rtg_ptr->groups[0];
7509         }
7510
7511         mtx_lock(&softc->ctl_lock);
7512         pg = softc->port_offset / CTL_MAX_PORTS;
7513         if (softc->flags & CTL_FLAG_ACTIVE_SHELF) {
7514                 if (softc->ha_mode == CTL_HA_MODE_ACT_STBY) {
7515                         gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7516                         os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7517                 } else if (lun->flags & CTL_LUN_PRIMARY_SC) {
7518                         gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7519                         os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7520                 } else {
7521                         gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7522                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7523                 }
7524         } else {
7525                 gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7526                 os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7527         }
7528         for (g = 0; g < num_target_port_groups; g++) {
7529                 tpg_desc->pref_state = (g == pg) ? gs : os;
7530                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP;
7531                 scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7532                 tpg_desc->status = TPG_IMPLICIT;
7533                 pc = 0;
7534                 STAILQ_FOREACH(port, &softc->port_list, links) {
7535                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7536                                 continue;
7537                         if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7538                                 continue;
7539                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7540                         scsi_ulto2b(p, tpg_desc->descriptors[pc].
7541                             relative_target_port_identifier);
7542                         pc++;
7543                 }
7544                 tpg_desc->target_port_count = pc;
7545                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7546                     &tpg_desc->descriptors[pc];
7547         }
7548         mtx_unlock(&softc->ctl_lock);
7549
7550         ctl_set_success(ctsio);
7551         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7552         ctsio->be_move_done = ctl_config_move_done;
7553         ctl_datamove((union ctl_io *)ctsio);
7554         return(retval);
7555 }
7556
7557 int
7558 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7559 {
7560         struct ctl_lun *lun;
7561         struct scsi_report_supported_opcodes *cdb;
7562         const struct ctl_cmd_entry *entry, *sentry;
7563         struct scsi_report_supported_opcodes_all *all;
7564         struct scsi_report_supported_opcodes_descr *descr;
7565         struct scsi_report_supported_opcodes_one *one;
7566         int retval;
7567         int alloc_len, total_len;
7568         int opcode, service_action, i, j, num;
7569
7570         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7571
7572         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7573         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7574
7575         retval = CTL_RETVAL_COMPLETE;
7576
7577         opcode = cdb->requested_opcode;
7578         service_action = scsi_2btoul(cdb->requested_service_action);
7579         switch (cdb->options & RSO_OPTIONS_MASK) {
7580         case RSO_OPTIONS_ALL:
7581                 num = 0;
7582                 for (i = 0; i < 256; i++) {
7583                         entry = &ctl_cmd_table[i];
7584                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7585                                 for (j = 0; j < 32; j++) {
7586                                         sentry = &((const struct ctl_cmd_entry *)
7587                                             entry->execute)[j];
7588                                         if (ctl_cmd_applicable(
7589                                             lun->be_lun->lun_type, sentry))
7590                                                 num++;
7591                                 }
7592                         } else {
7593                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7594                                     entry))
7595                                         num++;
7596                         }
7597                 }
7598                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7599                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7600                 break;
7601         case RSO_OPTIONS_OC:
7602                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7603                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7604                                               /*sks_valid*/ 1,
7605                                               /*command*/ 1,
7606                                               /*field*/ 2,
7607                                               /*bit_valid*/ 1,
7608                                               /*bit*/ 2);
7609                         ctl_done((union ctl_io *)ctsio);
7610                         return (CTL_RETVAL_COMPLETE);
7611                 }
7612                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7613                 break;
7614         case RSO_OPTIONS_OC_SA:
7615                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7616                     service_action >= 32) {
7617                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7618                                               /*sks_valid*/ 1,
7619                                               /*command*/ 1,
7620                                               /*field*/ 2,
7621                                               /*bit_valid*/ 1,
7622                                               /*bit*/ 2);
7623                         ctl_done((union ctl_io *)ctsio);
7624                         return (CTL_RETVAL_COMPLETE);
7625                 }
7626                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7627                 break;
7628         default:
7629                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7630                                       /*sks_valid*/ 1,
7631                                       /*command*/ 1,
7632                                       /*field*/ 2,
7633                                       /*bit_valid*/ 1,
7634                                       /*bit*/ 2);
7635                 ctl_done((union ctl_io *)ctsio);
7636                 return (CTL_RETVAL_COMPLETE);
7637         }
7638
7639         alloc_len = scsi_4btoul(cdb->length);
7640
7641         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7642
7643         ctsio->kern_sg_entries = 0;
7644
7645         if (total_len < alloc_len) {
7646                 ctsio->residual = alloc_len - total_len;
7647                 ctsio->kern_data_len = total_len;
7648                 ctsio->kern_total_len = total_len;
7649         } else {
7650                 ctsio->residual = 0;
7651                 ctsio->kern_data_len = alloc_len;
7652                 ctsio->kern_total_len = alloc_len;
7653         }
7654         ctsio->kern_data_resid = 0;
7655         ctsio->kern_rel_offset = 0;
7656
7657         switch (cdb->options & RSO_OPTIONS_MASK) {
7658         case RSO_OPTIONS_ALL:
7659                 all = (struct scsi_report_supported_opcodes_all *)
7660                     ctsio->kern_data_ptr;
7661                 num = 0;
7662                 for (i = 0; i < 256; i++) {
7663                         entry = &ctl_cmd_table[i];
7664                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7665                                 for (j = 0; j < 32; j++) {
7666                                         sentry = &((const struct ctl_cmd_entry *)
7667                                             entry->execute)[j];
7668                                         if (!ctl_cmd_applicable(
7669                                             lun->be_lun->lun_type, sentry))
7670                                                 continue;
7671                                         descr = &all->descr[num++];
7672                                         descr->opcode = i;
7673                                         scsi_ulto2b(j, descr->service_action);
7674                                         descr->flags = RSO_SERVACTV;
7675                                         scsi_ulto2b(sentry->length,
7676                                             descr->cdb_length);
7677                                 }
7678                         } else {
7679                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7680                                     entry))
7681                                         continue;
7682                                 descr = &all->descr[num++];
7683                                 descr->opcode = i;
7684                                 scsi_ulto2b(0, descr->service_action);
7685                                 descr->flags = 0;
7686                                 scsi_ulto2b(entry->length, descr->cdb_length);
7687                         }
7688                 }
7689                 scsi_ulto4b(
7690                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7691                     all->length);
7692                 break;
7693         case RSO_OPTIONS_OC:
7694                 one = (struct scsi_report_supported_opcodes_one *)
7695                     ctsio->kern_data_ptr;
7696                 entry = &ctl_cmd_table[opcode];
7697                 goto fill_one;
7698         case RSO_OPTIONS_OC_SA:
7699                 one = (struct scsi_report_supported_opcodes_one *)
7700                     ctsio->kern_data_ptr;
7701                 entry = &ctl_cmd_table[opcode];
7702                 entry = &((const struct ctl_cmd_entry *)
7703                     entry->execute)[service_action];
7704 fill_one:
7705                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7706                         one->support = 3;
7707                         scsi_ulto2b(entry->length, one->cdb_length);
7708                         one->cdb_usage[0] = opcode;
7709                         memcpy(&one->cdb_usage[1], entry->usage,
7710                             entry->length - 1);
7711                 } else
7712                         one->support = 1;
7713                 break;
7714         }
7715
7716         ctl_set_success(ctsio);
7717         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7718         ctsio->be_move_done = ctl_config_move_done;
7719         ctl_datamove((union ctl_io *)ctsio);
7720         return(retval);
7721 }
7722
7723 int
7724 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7725 {
7726         struct scsi_report_supported_tmf *cdb;
7727         struct scsi_report_supported_tmf_data *data;
7728         int retval;
7729         int alloc_len, total_len;
7730
7731         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7732
7733         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7734
7735         retval = CTL_RETVAL_COMPLETE;
7736
7737         total_len = sizeof(struct scsi_report_supported_tmf_data);
7738         alloc_len = scsi_4btoul(cdb->length);
7739
7740         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7741
7742         ctsio->kern_sg_entries = 0;
7743
7744         if (total_len < alloc_len) {
7745                 ctsio->residual = alloc_len - total_len;
7746                 ctsio->kern_data_len = total_len;
7747                 ctsio->kern_total_len = total_len;
7748         } else {
7749                 ctsio->residual = 0;
7750                 ctsio->kern_data_len = alloc_len;
7751                 ctsio->kern_total_len = alloc_len;
7752         }
7753         ctsio->kern_data_resid = 0;
7754         ctsio->kern_rel_offset = 0;
7755
7756         data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7757         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7758         data->byte2 |= RST_ITNRS;
7759
7760         ctl_set_success(ctsio);
7761         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7762         ctsio->be_move_done = ctl_config_move_done;
7763         ctl_datamove((union ctl_io *)ctsio);
7764         return (retval);
7765 }
7766
7767 int
7768 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7769 {
7770         struct scsi_report_timestamp *cdb;
7771         struct scsi_report_timestamp_data *data;
7772         struct timeval tv;
7773         int64_t timestamp;
7774         int retval;
7775         int alloc_len, total_len;
7776
7777         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7778
7779         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7780
7781         retval = CTL_RETVAL_COMPLETE;
7782
7783         total_len = sizeof(struct scsi_report_timestamp_data);
7784         alloc_len = scsi_4btoul(cdb->length);
7785
7786         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7787
7788         ctsio->kern_sg_entries = 0;
7789
7790         if (total_len < alloc_len) {
7791                 ctsio->residual = alloc_len - total_len;
7792                 ctsio->kern_data_len = total_len;
7793                 ctsio->kern_total_len = total_len;
7794         } else {
7795                 ctsio->residual = 0;
7796                 ctsio->kern_data_len = alloc_len;
7797                 ctsio->kern_total_len = alloc_len;
7798         }
7799         ctsio->kern_data_resid = 0;
7800         ctsio->kern_rel_offset = 0;
7801
7802         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7803         scsi_ulto2b(sizeof(*data) - 2, data->length);
7804         data->origin = RTS_ORIG_OUTSIDE;
7805         getmicrotime(&tv);
7806         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7807         scsi_ulto4b(timestamp >> 16, data->timestamp);
7808         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7809
7810         ctl_set_success(ctsio);
7811         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7812         ctsio->be_move_done = ctl_config_move_done;
7813         ctl_datamove((union ctl_io *)ctsio);
7814         return (retval);
7815 }
7816
7817 int
7818 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7819 {
7820         struct scsi_per_res_in *cdb;
7821         int alloc_len, total_len = 0;
7822         /* struct scsi_per_res_in_rsrv in_data; */
7823         struct ctl_lun *lun;
7824         struct ctl_softc *softc;
7825         uint64_t key;
7826
7827         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7828
7829         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7830
7831         alloc_len = scsi_2btoul(cdb->length);
7832
7833         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7834         softc = lun->ctl_softc;
7835
7836 retry:
7837         mtx_lock(&lun->lun_lock);
7838         switch (cdb->action) {
7839         case SPRI_RK: /* read keys */
7840                 total_len = sizeof(struct scsi_per_res_in_keys) +
7841                         lun->pr_key_count *
7842                         sizeof(struct scsi_per_res_key);
7843                 break;
7844         case SPRI_RR: /* read reservation */
7845                 if (lun->flags & CTL_LUN_PR_RESERVED)
7846                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7847                 else
7848                         total_len = sizeof(struct scsi_per_res_in_header);
7849                 break;
7850         case SPRI_RC: /* report capabilities */
7851                 total_len = sizeof(struct scsi_per_res_cap);
7852                 break;
7853         case SPRI_RS: /* read full status */
7854                 total_len = sizeof(struct scsi_per_res_in_header) +
7855                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7856                     lun->pr_key_count;
7857                 break;
7858         default:
7859                 panic("Invalid PR type %x", cdb->action);
7860         }
7861         mtx_unlock(&lun->lun_lock);
7862
7863         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7864
7865         if (total_len < alloc_len) {
7866                 ctsio->residual = alloc_len - total_len;
7867                 ctsio->kern_data_len = total_len;
7868                 ctsio->kern_total_len = total_len;
7869         } else {
7870                 ctsio->residual = 0;
7871                 ctsio->kern_data_len = alloc_len;
7872                 ctsio->kern_total_len = alloc_len;
7873         }
7874
7875         ctsio->kern_data_resid = 0;
7876         ctsio->kern_rel_offset = 0;
7877         ctsio->kern_sg_entries = 0;
7878
7879         mtx_lock(&lun->lun_lock);
7880         switch (cdb->action) {
7881         case SPRI_RK: { // read keys
7882         struct scsi_per_res_in_keys *res_keys;
7883                 int i, key_count;
7884
7885                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7886
7887                 /*
7888                  * We had to drop the lock to allocate our buffer, which
7889                  * leaves time for someone to come in with another
7890                  * persistent reservation.  (That is unlikely, though,
7891                  * since this should be the only persistent reservation
7892                  * command active right now.)
7893                  */
7894                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7895                     (lun->pr_key_count *
7896                      sizeof(struct scsi_per_res_key)))){
7897                         mtx_unlock(&lun->lun_lock);
7898                         free(ctsio->kern_data_ptr, M_CTL);
7899                         printf("%s: reservation length changed, retrying\n",
7900                                __func__);
7901                         goto retry;
7902                 }
7903
7904                 scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7905
7906                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7907                              lun->pr_key_count, res_keys->header.length);
7908
7909                 for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7910                         if ((key = ctl_get_prkey(lun, i)) == 0)
7911                                 continue;
7912
7913                         /*
7914                          * We used lun->pr_key_count to calculate the
7915                          * size to allocate.  If it turns out the number of
7916                          * initiators with the registered flag set is
7917                          * larger than that (i.e. they haven't been kept in
7918                          * sync), we've got a problem.
7919                          */
7920                         if (key_count >= lun->pr_key_count) {
7921 #ifdef NEEDTOPORT
7922                                 csevent_log(CSC_CTL | CSC_SHELF_SW |
7923                                             CTL_PR_ERROR,
7924                                             csevent_LogType_Fault,
7925                                             csevent_AlertLevel_Yellow,
7926                                             csevent_FRU_ShelfController,
7927                                             csevent_FRU_Firmware,
7928                                         csevent_FRU_Unknown,
7929                                             "registered keys %d >= key "
7930                                             "count %d", key_count,
7931                                             lun->pr_key_count);
7932 #endif
7933                                 key_count++;
7934                                 continue;
7935                         }
7936                         scsi_u64to8b(key, res_keys->keys[key_count].key);
7937                         key_count++;
7938                 }
7939                 break;
7940         }
7941         case SPRI_RR: { // read reservation
7942                 struct scsi_per_res_in_rsrv *res;
7943                 int tmp_len, header_only;
7944
7945                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7946
7947                 scsi_ulto4b(lun->PRGeneration, res->header.generation);
7948
7949                 if (lun->flags & CTL_LUN_PR_RESERVED)
7950                 {
7951                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7952                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7953                                     res->header.length);
7954                         header_only = 0;
7955                 } else {
7956                         tmp_len = sizeof(struct scsi_per_res_in_header);
7957                         scsi_ulto4b(0, res->header.length);
7958                         header_only = 1;
7959                 }
7960
7961                 /*
7962                  * We had to drop the lock to allocate our buffer, which
7963                  * leaves time for someone to come in with another
7964                  * persistent reservation.  (That is unlikely, though,
7965                  * since this should be the only persistent reservation
7966                  * command active right now.)
7967                  */
7968                 if (tmp_len != total_len) {
7969                         mtx_unlock(&lun->lun_lock);
7970                         free(ctsio->kern_data_ptr, M_CTL);
7971                         printf("%s: reservation status changed, retrying\n",
7972                                __func__);
7973                         goto retry;
7974                 }
7975
7976                 /*
7977                  * No reservation held, so we're done.
7978                  */
7979                 if (header_only != 0)
7980                         break;
7981
7982                 /*
7983                  * If the registration is an All Registrants type, the key
7984                  * is 0, since it doesn't really matter.
7985                  */
7986                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7987                         scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7988                             res->data.reservation);
7989                 }
7990                 res->data.scopetype = lun->res_type;
7991                 break;
7992         }
7993         case SPRI_RC:     //report capabilities
7994         {
7995                 struct scsi_per_res_cap *res_cap;
7996                 uint16_t type_mask;
7997
7998                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7999                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
8000                 res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
8001                 type_mask = SPRI_TM_WR_EX_AR |
8002                             SPRI_TM_EX_AC_RO |
8003                             SPRI_TM_WR_EX_RO |
8004                             SPRI_TM_EX_AC |
8005                             SPRI_TM_WR_EX |
8006                             SPRI_TM_EX_AC_AR;
8007                 scsi_ulto2b(type_mask, res_cap->type_mask);
8008                 break;
8009         }
8010         case SPRI_RS: { // read full status
8011                 struct scsi_per_res_in_full *res_status;
8012                 struct scsi_per_res_in_full_desc *res_desc;
8013                 struct ctl_port *port;
8014                 int i, len;
8015
8016                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
8017
8018                 /*
8019                  * We had to drop the lock to allocate our buffer, which
8020                  * leaves time for someone to come in with another
8021                  * persistent reservation.  (That is unlikely, though,
8022                  * since this should be the only persistent reservation
8023                  * command active right now.)
8024                  */
8025                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
8026                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
8027                      lun->pr_key_count)){
8028                         mtx_unlock(&lun->lun_lock);
8029                         free(ctsio->kern_data_ptr, M_CTL);
8030                         printf("%s: reservation length changed, retrying\n",
8031                                __func__);
8032                         goto retry;
8033                 }
8034
8035                 scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
8036
8037                 res_desc = &res_status->desc[0];
8038                 for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
8039                         if ((key = ctl_get_prkey(lun, i)) == 0)
8040                                 continue;
8041
8042                         scsi_u64to8b(key, res_desc->res_key.key);
8043                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
8044                             (lun->pr_res_idx == i ||
8045                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
8046                                 res_desc->flags = SPRI_FULL_R_HOLDER;
8047                                 res_desc->scopetype = lun->res_type;
8048                         }
8049                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
8050                             res_desc->rel_trgt_port_id);
8051                         len = 0;
8052                         port = softc->ctl_ports[
8053                             ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
8054                         if (port != NULL)
8055                                 len = ctl_create_iid(port,
8056                                     i % CTL_MAX_INIT_PER_PORT,
8057                                     res_desc->transport_id);
8058                         scsi_ulto4b(len, res_desc->additional_length);
8059                         res_desc = (struct scsi_per_res_in_full_desc *)
8060                             &res_desc->transport_id[len];
8061                 }
8062                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
8063                     res_status->header.length);
8064                 break;
8065         }
8066         default:
8067                 /*
8068                  * This is a bug, because we just checked for this above,
8069                  * and should have returned an error.
8070                  */
8071                 panic("Invalid PR type %x", cdb->action);
8072                 break; /* NOTREACHED */
8073         }
8074         mtx_unlock(&lun->lun_lock);
8075
8076         ctl_set_success(ctsio);
8077         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8078         ctsio->be_move_done = ctl_config_move_done;
8079         ctl_datamove((union ctl_io *)ctsio);
8080         return (CTL_RETVAL_COMPLETE);
8081 }
8082
8083 static void
8084 ctl_est_res_ua(struct ctl_lun *lun, uint32_t residx, ctl_ua_type ua)
8085 {
8086         int off = lun->ctl_softc->persis_offset;
8087
8088         if (residx >= off && residx < off + CTL_MAX_INITIATORS)
8089                 ctl_est_ua(lun, residx - off, ua);
8090 }
8091
8092 /*
8093  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
8094  * it should return.
8095  */
8096 static int
8097 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
8098                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
8099                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
8100                 struct scsi_per_res_out_parms* param)
8101 {
8102         union ctl_ha_msg persis_io;
8103         int retval, i;
8104         int isc_retval;
8105
8106         retval = 0;
8107
8108         mtx_lock(&lun->lun_lock);
8109         if (sa_res_key == 0) {
8110                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8111                         /* validate scope and type */
8112                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8113                              SPR_LU_SCOPE) {
8114                                 mtx_unlock(&lun->lun_lock);
8115                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8116                                                       /*sks_valid*/ 1,
8117                                                       /*command*/ 1,
8118                                                       /*field*/ 2,
8119                                                       /*bit_valid*/ 1,
8120                                                       /*bit*/ 4);
8121                                 ctl_done((union ctl_io *)ctsio);
8122                                 return (1);
8123                         }
8124
8125                         if (type>8 || type==2 || type==4 || type==0) {
8126                                 mtx_unlock(&lun->lun_lock);
8127                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8128                                                       /*sks_valid*/ 1,
8129                                                       /*command*/ 1,
8130                                                       /*field*/ 2,
8131                                                       /*bit_valid*/ 1,
8132                                                       /*bit*/ 0);
8133                                 ctl_done((union ctl_io *)ctsio);
8134                                 return (1);
8135                         }
8136
8137                         /*
8138                          * Unregister everybody else and build UA for
8139                          * them
8140                          */
8141                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8142                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8143                                         continue;
8144
8145                                 ctl_clr_prkey(lun, i);
8146                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8147                         }
8148                         lun->pr_key_count = 1;
8149                         lun->res_type = type;
8150                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8151                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8152                                 lun->pr_res_idx = residx;
8153
8154                         /* send msg to other side */
8155                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8156                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8157                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8158                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8159                         persis_io.pr.pr_info.res_type = type;
8160                         memcpy(persis_io.pr.pr_info.sa_res_key,
8161                                param->serv_act_res_key,
8162                                sizeof(param->serv_act_res_key));
8163                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8164                              &persis_io, sizeof(persis_io), 0)) >
8165                              CTL_HA_STATUS_SUCCESS) {
8166                                 printf("CTL:Persis Out error returned "
8167                                        "from ctl_ha_msg_send %d\n",
8168                                        isc_retval);
8169                         }
8170                 } else {
8171                         /* not all registrants */
8172                         mtx_unlock(&lun->lun_lock);
8173                         free(ctsio->kern_data_ptr, M_CTL);
8174                         ctl_set_invalid_field(ctsio,
8175                                               /*sks_valid*/ 1,
8176                                               /*command*/ 0,
8177                                               /*field*/ 8,
8178                                               /*bit_valid*/ 0,
8179                                               /*bit*/ 0);
8180                         ctl_done((union ctl_io *)ctsio);
8181                         return (1);
8182                 }
8183         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8184                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
8185                 int found = 0;
8186
8187                 if (res_key == sa_res_key) {
8188                         /* special case */
8189                         /*
8190                          * The spec implies this is not good but doesn't
8191                          * say what to do. There are two choices either
8192                          * generate a res conflict or check condition
8193                          * with illegal field in parameter data. Since
8194                          * that is what is done when the sa_res_key is
8195                          * zero I'll take that approach since this has
8196                          * to do with the sa_res_key.
8197                          */
8198                         mtx_unlock(&lun->lun_lock);
8199                         free(ctsio->kern_data_ptr, M_CTL);
8200                         ctl_set_invalid_field(ctsio,
8201                                               /*sks_valid*/ 1,
8202                                               /*command*/ 0,
8203                                               /*field*/ 8,
8204                                               /*bit_valid*/ 0,
8205                                               /*bit*/ 0);
8206                         ctl_done((union ctl_io *)ctsio);
8207                         return (1);
8208                 }
8209
8210                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8211                         if (ctl_get_prkey(lun, i) != sa_res_key)
8212                                 continue;
8213
8214                         found = 1;
8215                         ctl_clr_prkey(lun, i);
8216                         lun->pr_key_count--;
8217                         ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8218                 }
8219                 if (!found) {
8220                         mtx_unlock(&lun->lun_lock);
8221                         free(ctsio->kern_data_ptr, M_CTL);
8222                         ctl_set_reservation_conflict(ctsio);
8223                         ctl_done((union ctl_io *)ctsio);
8224                         return (CTL_RETVAL_COMPLETE);
8225                 }
8226                 /* send msg to other side */
8227                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8228                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8229                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8230                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
8231                 persis_io.pr.pr_info.res_type = type;
8232                 memcpy(persis_io.pr.pr_info.sa_res_key,
8233                        param->serv_act_res_key,
8234                        sizeof(param->serv_act_res_key));
8235                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8236                      &persis_io, sizeof(persis_io), 0)) >
8237                      CTL_HA_STATUS_SUCCESS) {
8238                         printf("CTL:Persis Out error returned from "
8239                                "ctl_ha_msg_send %d\n", isc_retval);
8240                 }
8241         } else {
8242                 /* Reserved but not all registrants */
8243                 /* sa_res_key is res holder */
8244                 if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8245                         /* validate scope and type */
8246                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8247                              SPR_LU_SCOPE) {
8248                                 mtx_unlock(&lun->lun_lock);
8249                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8250                                                       /*sks_valid*/ 1,
8251                                                       /*command*/ 1,
8252                                                       /*field*/ 2,
8253                                                       /*bit_valid*/ 1,
8254                                                       /*bit*/ 4);
8255                                 ctl_done((union ctl_io *)ctsio);
8256                                 return (1);
8257                         }
8258
8259                         if (type>8 || type==2 || type==4 || type==0) {
8260                                 mtx_unlock(&lun->lun_lock);
8261                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8262                                                       /*sks_valid*/ 1,
8263                                                       /*command*/ 1,
8264                                                       /*field*/ 2,
8265                                                       /*bit_valid*/ 1,
8266                                                       /*bit*/ 0);
8267                                 ctl_done((union ctl_io *)ctsio);
8268                                 return (1);
8269                         }
8270
8271                         /*
8272                          * Do the following:
8273                          * if sa_res_key != res_key remove all
8274                          * registrants w/sa_res_key and generate UA
8275                          * for these registrants(Registrations
8276                          * Preempted) if it wasn't an exclusive
8277                          * reservation generate UA(Reservations
8278                          * Preempted) for all other registered nexuses
8279                          * if the type has changed. Establish the new
8280                          * reservation and holder. If res_key and
8281                          * sa_res_key are the same do the above
8282                          * except don't unregister the res holder.
8283                          */
8284
8285                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8286                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8287                                         continue;
8288
8289                                 if (sa_res_key == ctl_get_prkey(lun, i)) {
8290                                         ctl_clr_prkey(lun, i);
8291                                         lun->pr_key_count--;
8292                                         ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8293                                 } else if (type != lun->res_type
8294                                         && (lun->res_type == SPR_TYPE_WR_EX_RO
8295                                          || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8296                                         ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
8297                                 }
8298                         }
8299                         lun->res_type = type;
8300                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8301                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8302                                 lun->pr_res_idx = residx;
8303                         else
8304                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8305
8306                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8307                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8308                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8309                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8310                         persis_io.pr.pr_info.res_type = type;
8311                         memcpy(persis_io.pr.pr_info.sa_res_key,
8312                                param->serv_act_res_key,
8313                                sizeof(param->serv_act_res_key));
8314                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8315                              &persis_io, sizeof(persis_io), 0)) >
8316                              CTL_HA_STATUS_SUCCESS) {
8317                                 printf("CTL:Persis Out error returned "
8318                                        "from ctl_ha_msg_send %d\n",
8319                                        isc_retval);
8320                         }
8321                 } else {
8322                         /*
8323                          * sa_res_key is not the res holder just
8324                          * remove registrants
8325                          */
8326                         int found=0;
8327
8328                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8329                                 if (sa_res_key != ctl_get_prkey(lun, i))
8330                                         continue;
8331
8332                                 found = 1;
8333                                 ctl_clr_prkey(lun, i);
8334                                 lun->pr_key_count--;
8335                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8336                         }
8337
8338                         if (!found) {
8339                                 mtx_unlock(&lun->lun_lock);
8340                                 free(ctsio->kern_data_ptr, M_CTL);
8341                                 ctl_set_reservation_conflict(ctsio);
8342                                 ctl_done((union ctl_io *)ctsio);
8343                                 return (1);
8344                         }
8345                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8346                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8347                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8348                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8349                         persis_io.pr.pr_info.res_type = type;
8350                         memcpy(persis_io.pr.pr_info.sa_res_key,
8351                                param->serv_act_res_key,
8352                                sizeof(param->serv_act_res_key));
8353                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8354                              &persis_io, sizeof(persis_io), 0)) >
8355                              CTL_HA_STATUS_SUCCESS) {
8356                                 printf("CTL:Persis Out error returned "
8357                                        "from ctl_ha_msg_send %d\n",
8358                                 isc_retval);
8359                         }
8360                 }
8361         }
8362
8363         lun->PRGeneration++;
8364         mtx_unlock(&lun->lun_lock);
8365
8366         return (retval);
8367 }
8368
8369 static void
8370 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8371 {
8372         uint64_t sa_res_key;
8373         int i;
8374
8375         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8376
8377         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8378          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8379          || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8380                 if (sa_res_key == 0) {
8381                         /*
8382                          * Unregister everybody else and build UA for
8383                          * them
8384                          */
8385                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8386                                 if (i == msg->pr.pr_info.residx ||
8387                                     ctl_get_prkey(lun, i) == 0)
8388                                         continue;
8389
8390                                 ctl_clr_prkey(lun, i);
8391                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8392                         }
8393
8394                         lun->pr_key_count = 1;
8395                         lun->res_type = msg->pr.pr_info.res_type;
8396                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8397                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8398                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8399                 } else {
8400                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8401                                 if (sa_res_key == ctl_get_prkey(lun, i))
8402                                         continue;
8403
8404                                 ctl_clr_prkey(lun, i);
8405                                 lun->pr_key_count--;
8406                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8407                         }
8408                 }
8409         } else {
8410                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8411                         if (i == msg->pr.pr_info.residx ||
8412                             ctl_get_prkey(lun, i) == 0)
8413                                 continue;
8414
8415                         if (sa_res_key == ctl_get_prkey(lun, i)) {
8416                                 ctl_clr_prkey(lun, i);
8417                                 lun->pr_key_count--;
8418                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8419                         } else if (msg->pr.pr_info.res_type != lun->res_type
8420                                 && (lun->res_type == SPR_TYPE_WR_EX_RO
8421                                  || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8422                                 ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
8423                         }
8424                 }
8425                 lun->res_type = msg->pr.pr_info.res_type;
8426                 if (lun->res_type != SPR_TYPE_WR_EX_AR
8427                  && lun->res_type != SPR_TYPE_EX_AC_AR)
8428                         lun->pr_res_idx = msg->pr.pr_info.residx;
8429                 else
8430                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8431         }
8432         lun->PRGeneration++;
8433
8434 }
8435
8436
8437 int
8438 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8439 {
8440         int retval;
8441         int isc_retval;
8442         u_int32_t param_len;
8443         struct scsi_per_res_out *cdb;
8444         struct ctl_lun *lun;
8445         struct scsi_per_res_out_parms* param;
8446         struct ctl_softc *softc;
8447         uint32_t residx;
8448         uint64_t res_key, sa_res_key, key;
8449         uint8_t type;
8450         union ctl_ha_msg persis_io;
8451         int    i;
8452
8453         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8454
8455         retval = CTL_RETVAL_COMPLETE;
8456
8457         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8458         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8459         softc = lun->ctl_softc;
8460
8461         /*
8462          * We only support whole-LUN scope.  The scope & type are ignored for
8463          * register, register and ignore existing key and clear.
8464          * We sometimes ignore scope and type on preempts too!!
8465          * Verify reservation type here as well.
8466          */
8467         type = cdb->scope_type & SPR_TYPE_MASK;
8468         if ((cdb->action == SPRO_RESERVE)
8469          || (cdb->action == SPRO_RELEASE)) {
8470                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8471                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8472                                               /*sks_valid*/ 1,
8473                                               /*command*/ 1,
8474                                               /*field*/ 2,
8475                                               /*bit_valid*/ 1,
8476                                               /*bit*/ 4);
8477                         ctl_done((union ctl_io *)ctsio);
8478                         return (CTL_RETVAL_COMPLETE);
8479                 }
8480
8481                 if (type>8 || type==2 || type==4 || type==0) {
8482                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8483                                               /*sks_valid*/ 1,
8484                                               /*command*/ 1,
8485                                               /*field*/ 2,
8486                                               /*bit_valid*/ 1,
8487                                               /*bit*/ 0);
8488                         ctl_done((union ctl_io *)ctsio);
8489                         return (CTL_RETVAL_COMPLETE);
8490                 }
8491         }
8492
8493         param_len = scsi_4btoul(cdb->length);
8494
8495         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8496                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8497                 ctsio->kern_data_len = param_len;
8498                 ctsio->kern_total_len = param_len;
8499                 ctsio->kern_data_resid = 0;
8500                 ctsio->kern_rel_offset = 0;
8501                 ctsio->kern_sg_entries = 0;
8502                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8503                 ctsio->be_move_done = ctl_config_move_done;
8504                 ctl_datamove((union ctl_io *)ctsio);
8505
8506                 return (CTL_RETVAL_COMPLETE);
8507         }
8508
8509         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8510
8511         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8512         res_key = scsi_8btou64(param->res_key.key);
8513         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8514
8515         /*
8516          * Validate the reservation key here except for SPRO_REG_IGNO
8517          * This must be done for all other service actions
8518          */
8519         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8520                 mtx_lock(&lun->lun_lock);
8521                 if ((key = ctl_get_prkey(lun, residx)) != 0) {
8522                         if (res_key != key) {
8523                                 /*
8524                                  * The current key passed in doesn't match
8525                                  * the one the initiator previously
8526                                  * registered.
8527                                  */
8528                                 mtx_unlock(&lun->lun_lock);
8529                                 free(ctsio->kern_data_ptr, M_CTL);
8530                                 ctl_set_reservation_conflict(ctsio);
8531                                 ctl_done((union ctl_io *)ctsio);
8532                                 return (CTL_RETVAL_COMPLETE);
8533                         }
8534                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8535                         /*
8536                          * We are not registered
8537                          */
8538                         mtx_unlock(&lun->lun_lock);
8539                         free(ctsio->kern_data_ptr, M_CTL);
8540                         ctl_set_reservation_conflict(ctsio);
8541                         ctl_done((union ctl_io *)ctsio);
8542                         return (CTL_RETVAL_COMPLETE);
8543                 } else if (res_key != 0) {
8544                         /*
8545                          * We are not registered and trying to register but
8546                          * the register key isn't zero.
8547                          */
8548                         mtx_unlock(&lun->lun_lock);
8549                         free(ctsio->kern_data_ptr, M_CTL);
8550                         ctl_set_reservation_conflict(ctsio);
8551                         ctl_done((union ctl_io *)ctsio);
8552                         return (CTL_RETVAL_COMPLETE);
8553                 }
8554                 mtx_unlock(&lun->lun_lock);
8555         }
8556
8557         switch (cdb->action & SPRO_ACTION_MASK) {
8558         case SPRO_REGISTER:
8559         case SPRO_REG_IGNO: {
8560
8561 #if 0
8562                 printf("Registration received\n");
8563 #endif
8564
8565                 /*
8566                  * We don't support any of these options, as we report in
8567                  * the read capabilities request (see
8568                  * ctl_persistent_reserve_in(), above).
8569                  */
8570                 if ((param->flags & SPR_SPEC_I_PT)
8571                  || (param->flags & SPR_ALL_TG_PT)
8572                  || (param->flags & SPR_APTPL)) {
8573                         int bit_ptr;
8574
8575                         if (param->flags & SPR_APTPL)
8576                                 bit_ptr = 0;
8577                         else if (param->flags & SPR_ALL_TG_PT)
8578                                 bit_ptr = 2;
8579                         else /* SPR_SPEC_I_PT */
8580                                 bit_ptr = 3;
8581
8582                         free(ctsio->kern_data_ptr, M_CTL);
8583                         ctl_set_invalid_field(ctsio,
8584                                               /*sks_valid*/ 1,
8585                                               /*command*/ 0,
8586                                               /*field*/ 20,
8587                                               /*bit_valid*/ 1,
8588                                               /*bit*/ bit_ptr);
8589                         ctl_done((union ctl_io *)ctsio);
8590                         return (CTL_RETVAL_COMPLETE);
8591                 }
8592
8593                 mtx_lock(&lun->lun_lock);
8594
8595                 /*
8596                  * The initiator wants to clear the
8597                  * key/unregister.
8598                  */
8599                 if (sa_res_key == 0) {
8600                         if ((res_key == 0
8601                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8602                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8603                           && ctl_get_prkey(lun, residx) == 0)) {
8604                                 mtx_unlock(&lun->lun_lock);
8605                                 goto done;
8606                         }
8607
8608                         ctl_clr_prkey(lun, residx);
8609                         lun->pr_key_count--;
8610
8611                         if (residx == lun->pr_res_idx) {
8612                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8613                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8614
8615                                 if ((lun->res_type == SPR_TYPE_WR_EX_RO
8616                                   || lun->res_type == SPR_TYPE_EX_AC_RO)
8617                                  && lun->pr_key_count) {
8618                                         /*
8619                                          * If the reservation is a registrants
8620                                          * only type we need to generate a UA
8621                                          * for other registered inits.  The
8622                                          * sense code should be RESERVATIONS
8623                                          * RELEASED
8624                                          */
8625
8626                                         for (i = 0; i < CTL_MAX_INITIATORS;i++){
8627                                                 if (ctl_get_prkey(lun, i +
8628                                                     softc->persis_offset) == 0)
8629                                                         continue;
8630                                                 ctl_est_ua(lun, i,
8631                                                     CTL_UA_RES_RELEASE);
8632                                         }
8633                                 }
8634                                 lun->res_type = 0;
8635                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8636                                 if (lun->pr_key_count==0) {
8637                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8638                                         lun->res_type = 0;
8639                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8640                                 }
8641                         }
8642                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8643                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8644                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8645                         persis_io.pr.pr_info.residx = residx;
8646                         if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8647                              &persis_io, sizeof(persis_io), 0 )) >
8648                              CTL_HA_STATUS_SUCCESS) {
8649                                 printf("CTL:Persis Out error returned from "
8650                                        "ctl_ha_msg_send %d\n", isc_retval);
8651                         }
8652                 } else /* sa_res_key != 0 */ {
8653
8654                         /*
8655                          * If we aren't registered currently then increment
8656                          * the key count and set the registered flag.
8657                          */
8658                         ctl_alloc_prkey(lun, residx);
8659                         if (ctl_get_prkey(lun, residx) == 0)
8660                                 lun->pr_key_count++;
8661                         ctl_set_prkey(lun, residx, sa_res_key);
8662
8663                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8664                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8665                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8666                         persis_io.pr.pr_info.residx = residx;
8667                         memcpy(persis_io.pr.pr_info.sa_res_key,
8668                                param->serv_act_res_key,
8669                                sizeof(param->serv_act_res_key));
8670                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8671                              &persis_io, sizeof(persis_io), 0)) >
8672                              CTL_HA_STATUS_SUCCESS) {
8673                                 printf("CTL:Persis Out error returned from "
8674                                        "ctl_ha_msg_send %d\n", isc_retval);
8675                         }
8676                 }
8677                 lun->PRGeneration++;
8678                 mtx_unlock(&lun->lun_lock);
8679
8680                 break;
8681         }
8682         case SPRO_RESERVE:
8683 #if 0
8684                 printf("Reserve executed type %d\n", type);
8685 #endif
8686                 mtx_lock(&lun->lun_lock);
8687                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8688                         /*
8689                          * if this isn't the reservation holder and it's
8690                          * not a "all registrants" type or if the type is
8691                          * different then we have a conflict
8692                          */
8693                         if ((lun->pr_res_idx != residx
8694                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8695                          || lun->res_type != type) {
8696                                 mtx_unlock(&lun->lun_lock);
8697                                 free(ctsio->kern_data_ptr, M_CTL);
8698                                 ctl_set_reservation_conflict(ctsio);
8699                                 ctl_done((union ctl_io *)ctsio);
8700                                 return (CTL_RETVAL_COMPLETE);
8701                         }
8702                         mtx_unlock(&lun->lun_lock);
8703                 } else /* create a reservation */ {
8704                         /*
8705                          * If it's not an "all registrants" type record
8706                          * reservation holder
8707                          */
8708                         if (type != SPR_TYPE_WR_EX_AR
8709                          && type != SPR_TYPE_EX_AC_AR)
8710                                 lun->pr_res_idx = residx; /* Res holder */
8711                         else
8712                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8713
8714                         lun->flags |= CTL_LUN_PR_RESERVED;
8715                         lun->res_type = type;
8716
8717                         mtx_unlock(&lun->lun_lock);
8718
8719                         /* send msg to other side */
8720                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8721                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8722                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8723                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8724                         persis_io.pr.pr_info.res_type = type;
8725                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8726                              &persis_io, sizeof(persis_io), 0)) >
8727                              CTL_HA_STATUS_SUCCESS) {
8728                                 printf("CTL:Persis Out error returned from "
8729                                        "ctl_ha_msg_send %d\n", isc_retval);
8730                         }
8731                 }
8732                 break;
8733
8734         case SPRO_RELEASE:
8735                 mtx_lock(&lun->lun_lock);
8736                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8737                         /* No reservation exists return good status */
8738                         mtx_unlock(&lun->lun_lock);
8739                         goto done;
8740                 }
8741                 /*
8742                  * Is this nexus a reservation holder?
8743                  */
8744                 if (lun->pr_res_idx != residx
8745                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8746                         /*
8747                          * not a res holder return good status but
8748                          * do nothing
8749                          */
8750                         mtx_unlock(&lun->lun_lock);
8751                         goto done;
8752                 }
8753
8754                 if (lun->res_type != type) {
8755                         mtx_unlock(&lun->lun_lock);
8756                         free(ctsio->kern_data_ptr, M_CTL);
8757                         ctl_set_illegal_pr_release(ctsio);
8758                         ctl_done((union ctl_io *)ctsio);
8759                         return (CTL_RETVAL_COMPLETE);
8760                 }
8761
8762                 /* okay to release */
8763                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8764                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8765                 lun->res_type = 0;
8766
8767                 /*
8768                  * if this isn't an exclusive access
8769                  * res generate UA for all other
8770                  * registrants.
8771                  */
8772                 if (type != SPR_TYPE_EX_AC
8773                  && type != SPR_TYPE_WR_EX) {
8774                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8775                                 if (i == residx ||
8776                                     ctl_get_prkey(lun,
8777                                      i + softc->persis_offset) == 0)
8778                                         continue;
8779                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8780                         }
8781                 }
8782                 mtx_unlock(&lun->lun_lock);
8783                 /* Send msg to other side */
8784                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8785                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8786                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8787                 if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8788                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8789                         printf("CTL:Persis Out error returned from "
8790                                "ctl_ha_msg_send %d\n", isc_retval);
8791                 }
8792                 break;
8793
8794         case SPRO_CLEAR:
8795                 /* send msg to other side */
8796
8797                 mtx_lock(&lun->lun_lock);
8798                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8799                 lun->res_type = 0;
8800                 lun->pr_key_count = 0;
8801                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8802
8803                 ctl_clr_prkey(lun, residx);
8804                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8805                         if (ctl_get_prkey(lun, i) != 0) {
8806                                 ctl_clr_prkey(lun, i);
8807                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8808                         }
8809                 lun->PRGeneration++;
8810                 mtx_unlock(&lun->lun_lock);
8811                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8812                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8813                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8814                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8815                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8816                         printf("CTL:Persis Out error returned from "
8817                                "ctl_ha_msg_send %d\n", isc_retval);
8818                 }
8819                 break;
8820
8821         case SPRO_PREEMPT:
8822         case SPRO_PRE_ABO: {
8823                 int nretval;
8824
8825                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8826                                           residx, ctsio, cdb, param);
8827                 if (nretval != 0)
8828                         return (CTL_RETVAL_COMPLETE);
8829                 break;
8830         }
8831         default:
8832                 panic("Invalid PR type %x", cdb->action);
8833         }
8834
8835 done:
8836         free(ctsio->kern_data_ptr, M_CTL);
8837         ctl_set_success(ctsio);
8838         ctl_done((union ctl_io *)ctsio);
8839
8840         return (retval);
8841 }
8842
8843 /*
8844  * This routine is for handling a message from the other SC pertaining to
8845  * persistent reserve out. All the error checking will have been done
8846  * so only perorming the action need be done here to keep the two
8847  * in sync.
8848  */
8849 static void
8850 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8851 {
8852         struct ctl_lun *lun;
8853         struct ctl_softc *softc;
8854         int i;
8855         uint32_t targ_lun;
8856
8857         softc = control_softc;
8858
8859         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8860         lun = softc->ctl_luns[targ_lun];
8861         mtx_lock(&lun->lun_lock);
8862         switch(msg->pr.pr_info.action) {
8863         case CTL_PR_REG_KEY:
8864                 ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8865                 if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8866                         lun->pr_key_count++;
8867                 ctl_set_prkey(lun, msg->pr.pr_info.residx,
8868                     scsi_8btou64(msg->pr.pr_info.sa_res_key));
8869                 lun->PRGeneration++;
8870                 break;
8871
8872         case CTL_PR_UNREG_KEY:
8873                 ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8874                 lun->pr_key_count--;
8875
8876                 /* XXX Need to see if the reservation has been released */
8877                 /* if so do we need to generate UA? */
8878                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8879                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8880                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8881
8882                         if ((lun->res_type == SPR_TYPE_WR_EX_RO
8883                           || lun->res_type == SPR_TYPE_EX_AC_RO)
8884                          && lun->pr_key_count) {
8885                                 /*
8886                                  * If the reservation is a registrants
8887                                  * only type we need to generate a UA
8888                                  * for other registered inits.  The
8889                                  * sense code should be RESERVATIONS
8890                                  * RELEASED
8891                                  */
8892
8893                                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8894                                         if (ctl_get_prkey(lun, i +
8895                                             softc->persis_offset) == 0)
8896                                                 continue;
8897
8898                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8899                                 }
8900                         }
8901                         lun->res_type = 0;
8902                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8903                         if (lun->pr_key_count==0) {
8904                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8905                                 lun->res_type = 0;
8906                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8907                         }
8908                 }
8909                 lun->PRGeneration++;
8910                 break;
8911
8912         case CTL_PR_RESERVE:
8913                 lun->flags |= CTL_LUN_PR_RESERVED;
8914                 lun->res_type = msg->pr.pr_info.res_type;
8915                 lun->pr_res_idx = msg->pr.pr_info.residx;
8916
8917                 break;
8918
8919         case CTL_PR_RELEASE:
8920                 /*
8921                  * if this isn't an exclusive access res generate UA for all
8922                  * other registrants.
8923                  */
8924                 if (lun->res_type != SPR_TYPE_EX_AC
8925                  && lun->res_type != SPR_TYPE_WR_EX) {
8926                         for (i = 0; i < CTL_MAX_INITIATORS; i++)
8927                                 if (ctl_get_prkey(lun, i + softc->persis_offset) != 0)
8928                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8929                 }
8930
8931                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8932                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8933                 lun->res_type = 0;
8934                 break;
8935
8936         case CTL_PR_PREEMPT:
8937                 ctl_pro_preempt_other(lun, msg);
8938                 break;
8939         case CTL_PR_CLEAR:
8940                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8941                 lun->res_type = 0;
8942                 lun->pr_key_count = 0;
8943                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8944
8945                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8946                         if (ctl_get_prkey(lun, i) == 0)
8947                                 continue;
8948                         ctl_clr_prkey(lun, i);
8949                         ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8950                 }
8951                 lun->PRGeneration++;
8952                 break;
8953         }
8954
8955         mtx_unlock(&lun->lun_lock);
8956 }
8957
8958 int
8959 ctl_read_write(struct ctl_scsiio *ctsio)
8960 {
8961         struct ctl_lun *lun;
8962         struct ctl_lba_len_flags *lbalen;
8963         uint64_t lba;
8964         uint32_t num_blocks;
8965         int flags, retval;
8966         int isread;
8967
8968         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8969
8970         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8971
8972         flags = 0;
8973         retval = CTL_RETVAL_COMPLETE;
8974
8975         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8976               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8977         switch (ctsio->cdb[0]) {
8978         case READ_6:
8979         case WRITE_6: {
8980                 struct scsi_rw_6 *cdb;
8981
8982                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
8983
8984                 lba = scsi_3btoul(cdb->addr);
8985                 /* only 5 bits are valid in the most significant address byte */
8986                 lba &= 0x1fffff;
8987                 num_blocks = cdb->length;
8988                 /*
8989                  * This is correct according to SBC-2.
8990                  */
8991                 if (num_blocks == 0)
8992                         num_blocks = 256;
8993                 break;
8994         }
8995         case READ_10:
8996         case WRITE_10: {
8997                 struct scsi_rw_10 *cdb;
8998
8999                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
9000                 if (cdb->byte2 & SRW10_FUA)
9001                         flags |= CTL_LLF_FUA;
9002                 if (cdb->byte2 & SRW10_DPO)
9003                         flags |= CTL_LLF_DPO;
9004                 lba = scsi_4btoul(cdb->addr);
9005                 num_blocks = scsi_2btoul(cdb->length);
9006                 break;
9007         }
9008         case WRITE_VERIFY_10: {
9009                 struct scsi_write_verify_10 *cdb;
9010
9011                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
9012                 flags |= CTL_LLF_FUA;
9013                 if (cdb->byte2 & SWV_DPO)
9014                         flags |= CTL_LLF_DPO;
9015                 lba = scsi_4btoul(cdb->addr);
9016                 num_blocks = scsi_2btoul(cdb->length);
9017                 break;
9018         }
9019         case READ_12:
9020         case WRITE_12: {
9021                 struct scsi_rw_12 *cdb;
9022
9023                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
9024                 if (cdb->byte2 & SRW12_FUA)
9025                         flags |= CTL_LLF_FUA;
9026                 if (cdb->byte2 & SRW12_DPO)
9027                         flags |= CTL_LLF_DPO;
9028                 lba = scsi_4btoul(cdb->addr);
9029                 num_blocks = scsi_4btoul(cdb->length);
9030                 break;
9031         }
9032         case WRITE_VERIFY_12: {
9033                 struct scsi_write_verify_12 *cdb;
9034
9035                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
9036                 flags |= CTL_LLF_FUA;
9037                 if (cdb->byte2 & SWV_DPO)
9038                         flags |= CTL_LLF_DPO;
9039                 lba = scsi_4btoul(cdb->addr);
9040                 num_blocks = scsi_4btoul(cdb->length);
9041                 break;
9042         }
9043         case READ_16:
9044         case WRITE_16: {
9045                 struct scsi_rw_16 *cdb;
9046
9047                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9048                 if (cdb->byte2 & SRW12_FUA)
9049                         flags |= CTL_LLF_FUA;
9050                 if (cdb->byte2 & SRW12_DPO)
9051                         flags |= CTL_LLF_DPO;
9052                 lba = scsi_8btou64(cdb->addr);
9053                 num_blocks = scsi_4btoul(cdb->length);
9054                 break;
9055         }
9056         case WRITE_ATOMIC_16: {
9057                 struct scsi_rw_16 *cdb;
9058
9059                 if (lun->be_lun->atomicblock == 0) {
9060                         ctl_set_invalid_opcode(ctsio);
9061                         ctl_done((union ctl_io *)ctsio);
9062                         return (CTL_RETVAL_COMPLETE);
9063                 }
9064
9065                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9066                 if (cdb->byte2 & SRW12_FUA)
9067                         flags |= CTL_LLF_FUA;
9068                 if (cdb->byte2 & SRW12_DPO)
9069                         flags |= CTL_LLF_DPO;
9070                 lba = scsi_8btou64(cdb->addr);
9071                 num_blocks = scsi_4btoul(cdb->length);
9072                 if (num_blocks > lun->be_lun->atomicblock) {
9073                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
9074                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
9075                             /*bit*/ 0);
9076                         ctl_done((union ctl_io *)ctsio);
9077                         return (CTL_RETVAL_COMPLETE);
9078                 }
9079                 break;
9080         }
9081         case WRITE_VERIFY_16: {
9082                 struct scsi_write_verify_16 *cdb;
9083
9084                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9085                 flags |= CTL_LLF_FUA;
9086                 if (cdb->byte2 & SWV_DPO)
9087                         flags |= CTL_LLF_DPO;
9088                 lba = scsi_8btou64(cdb->addr);
9089                 num_blocks = scsi_4btoul(cdb->length);
9090                 break;
9091         }
9092         default:
9093                 /*
9094                  * We got a command we don't support.  This shouldn't
9095                  * happen, commands should be filtered out above us.
9096                  */
9097                 ctl_set_invalid_opcode(ctsio);
9098                 ctl_done((union ctl_io *)ctsio);
9099
9100                 return (CTL_RETVAL_COMPLETE);
9101                 break; /* NOTREACHED */
9102         }
9103
9104         /*
9105          * The first check is to make sure we're in bounds, the second
9106          * check is to catch wrap-around problems.  If the lba + num blocks
9107          * is less than the lba, then we've wrapped around and the block
9108          * range is invalid anyway.
9109          */
9110         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9111          || ((lba + num_blocks) < lba)) {
9112                 ctl_set_lba_out_of_range(ctsio);
9113                 ctl_done((union ctl_io *)ctsio);
9114                 return (CTL_RETVAL_COMPLETE);
9115         }
9116
9117         /*
9118          * According to SBC-3, a transfer length of 0 is not an error.
9119          * Note that this cannot happen with WRITE(6) or READ(6), since 0
9120          * translates to 256 blocks for those commands.
9121          */
9122         if (num_blocks == 0) {
9123                 ctl_set_success(ctsio);
9124                 ctl_done((union ctl_io *)ctsio);
9125                 return (CTL_RETVAL_COMPLETE);
9126         }
9127
9128         /* Set FUA and/or DPO if caches are disabled. */
9129         if (isread) {
9130                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9131                     SCP_RCD) != 0)
9132                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9133         } else {
9134                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9135                     SCP_WCE) == 0)
9136                         flags |= CTL_LLF_FUA;
9137         }
9138
9139         lbalen = (struct ctl_lba_len_flags *)
9140             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9141         lbalen->lba = lba;
9142         lbalen->len = num_blocks;
9143         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9144
9145         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9146         ctsio->kern_rel_offset = 0;
9147
9148         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9149
9150         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9151
9152         return (retval);
9153 }
9154
9155 static int
9156 ctl_cnw_cont(union ctl_io *io)
9157 {
9158         struct ctl_scsiio *ctsio;
9159         struct ctl_lun *lun;
9160         struct ctl_lba_len_flags *lbalen;
9161         int retval;
9162
9163         ctsio = &io->scsiio;
9164         ctsio->io_hdr.status = CTL_STATUS_NONE;
9165         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9166         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9167         lbalen = (struct ctl_lba_len_flags *)
9168             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9169         lbalen->flags &= ~CTL_LLF_COMPARE;
9170         lbalen->flags |= CTL_LLF_WRITE;
9171
9172         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9173         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9174         return (retval);
9175 }
9176
9177 int
9178 ctl_cnw(struct ctl_scsiio *ctsio)
9179 {
9180         struct ctl_lun *lun;
9181         struct ctl_lba_len_flags *lbalen;
9182         uint64_t lba;
9183         uint32_t num_blocks;
9184         int flags, retval;
9185
9186         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9187
9188         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9189
9190         flags = 0;
9191         retval = CTL_RETVAL_COMPLETE;
9192
9193         switch (ctsio->cdb[0]) {
9194         case COMPARE_AND_WRITE: {
9195                 struct scsi_compare_and_write *cdb;
9196
9197                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9198                 if (cdb->byte2 & SRW10_FUA)
9199                         flags |= CTL_LLF_FUA;
9200                 if (cdb->byte2 & SRW10_DPO)
9201                         flags |= CTL_LLF_DPO;
9202                 lba = scsi_8btou64(cdb->addr);
9203                 num_blocks = cdb->length;
9204                 break;
9205         }
9206         default:
9207                 /*
9208                  * We got a command we don't support.  This shouldn't
9209                  * happen, commands should be filtered out above us.
9210                  */
9211                 ctl_set_invalid_opcode(ctsio);
9212                 ctl_done((union ctl_io *)ctsio);
9213
9214                 return (CTL_RETVAL_COMPLETE);
9215                 break; /* NOTREACHED */
9216         }
9217
9218         /*
9219          * The first check is to make sure we're in bounds, the second
9220          * check is to catch wrap-around problems.  If the lba + num blocks
9221          * is less than the lba, then we've wrapped around and the block
9222          * range is invalid anyway.
9223          */
9224         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9225          || ((lba + num_blocks) < lba)) {
9226                 ctl_set_lba_out_of_range(ctsio);
9227                 ctl_done((union ctl_io *)ctsio);
9228                 return (CTL_RETVAL_COMPLETE);
9229         }
9230
9231         /*
9232          * According to SBC-3, a transfer length of 0 is not an error.
9233          */
9234         if (num_blocks == 0) {
9235                 ctl_set_success(ctsio);
9236                 ctl_done((union ctl_io *)ctsio);
9237                 return (CTL_RETVAL_COMPLETE);
9238         }
9239
9240         /* Set FUA if write cache is disabled. */
9241         if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9242             SCP_WCE) == 0)
9243                 flags |= CTL_LLF_FUA;
9244
9245         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9246         ctsio->kern_rel_offset = 0;
9247
9248         /*
9249          * Set the IO_CONT flag, so that if this I/O gets passed to
9250          * ctl_data_submit_done(), it'll get passed back to
9251          * ctl_ctl_cnw_cont() for further processing.
9252          */
9253         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9254         ctsio->io_cont = ctl_cnw_cont;
9255
9256         lbalen = (struct ctl_lba_len_flags *)
9257             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9258         lbalen->lba = lba;
9259         lbalen->len = num_blocks;
9260         lbalen->flags = CTL_LLF_COMPARE | flags;
9261
9262         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9263         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9264         return (retval);
9265 }
9266
9267 int
9268 ctl_verify(struct ctl_scsiio *ctsio)
9269 {
9270         struct ctl_lun *lun;
9271         struct ctl_lba_len_flags *lbalen;
9272         uint64_t lba;
9273         uint32_t num_blocks;
9274         int bytchk, flags;
9275         int retval;
9276
9277         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9278
9279         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9280
9281         bytchk = 0;
9282         flags = CTL_LLF_FUA;
9283         retval = CTL_RETVAL_COMPLETE;
9284
9285         switch (ctsio->cdb[0]) {
9286         case VERIFY_10: {
9287                 struct scsi_verify_10 *cdb;
9288
9289                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
9290                 if (cdb->byte2 & SVFY_BYTCHK)
9291                         bytchk = 1;
9292                 if (cdb->byte2 & SVFY_DPO)
9293                         flags |= CTL_LLF_DPO;
9294                 lba = scsi_4btoul(cdb->addr);
9295                 num_blocks = scsi_2btoul(cdb->length);
9296                 break;
9297         }
9298         case VERIFY_12: {
9299                 struct scsi_verify_12 *cdb;
9300
9301                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
9302                 if (cdb->byte2 & SVFY_BYTCHK)
9303                         bytchk = 1;
9304                 if (cdb->byte2 & SVFY_DPO)
9305                         flags |= CTL_LLF_DPO;
9306                 lba = scsi_4btoul(cdb->addr);
9307                 num_blocks = scsi_4btoul(cdb->length);
9308                 break;
9309         }
9310         case VERIFY_16: {
9311                 struct scsi_rw_16 *cdb;
9312
9313                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9314                 if (cdb->byte2 & SVFY_BYTCHK)
9315                         bytchk = 1;
9316                 if (cdb->byte2 & SVFY_DPO)
9317                         flags |= CTL_LLF_DPO;
9318                 lba = scsi_8btou64(cdb->addr);
9319                 num_blocks = scsi_4btoul(cdb->length);
9320                 break;
9321         }
9322         default:
9323                 /*
9324                  * We got a command we don't support.  This shouldn't
9325                  * happen, commands should be filtered out above us.
9326                  */
9327                 ctl_set_invalid_opcode(ctsio);
9328                 ctl_done((union ctl_io *)ctsio);
9329                 return (CTL_RETVAL_COMPLETE);
9330         }
9331
9332         /*
9333          * The first check is to make sure we're in bounds, the second
9334          * check is to catch wrap-around problems.  If the lba + num blocks
9335          * is less than the lba, then we've wrapped around and the block
9336          * range is invalid anyway.
9337          */
9338         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9339          || ((lba + num_blocks) < lba)) {
9340                 ctl_set_lba_out_of_range(ctsio);
9341                 ctl_done((union ctl_io *)ctsio);
9342                 return (CTL_RETVAL_COMPLETE);
9343         }
9344
9345         /*
9346          * According to SBC-3, a transfer length of 0 is not an error.
9347          */
9348         if (num_blocks == 0) {
9349                 ctl_set_success(ctsio);
9350                 ctl_done((union ctl_io *)ctsio);
9351                 return (CTL_RETVAL_COMPLETE);
9352         }
9353
9354         lbalen = (struct ctl_lba_len_flags *)
9355             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9356         lbalen->lba = lba;
9357         lbalen->len = num_blocks;
9358         if (bytchk) {
9359                 lbalen->flags = CTL_LLF_COMPARE | flags;
9360                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9361         } else {
9362                 lbalen->flags = CTL_LLF_VERIFY | flags;
9363                 ctsio->kern_total_len = 0;
9364         }
9365         ctsio->kern_rel_offset = 0;
9366
9367         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9368         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9369         return (retval);
9370 }
9371
9372 int
9373 ctl_report_luns(struct ctl_scsiio *ctsio)
9374 {
9375         struct ctl_softc *softc = control_softc;
9376         struct scsi_report_luns *cdb;
9377         struct scsi_report_luns_data *lun_data;
9378         struct ctl_lun *lun, *request_lun;
9379         struct ctl_port *port;
9380         int num_luns, retval;
9381         uint32_t alloc_len, lun_datalen;
9382         int num_filled, well_known;
9383         uint32_t initidx, targ_lun_id, lun_id;
9384
9385         retval = CTL_RETVAL_COMPLETE;
9386         well_known = 0;
9387
9388         cdb = (struct scsi_report_luns *)ctsio->cdb;
9389
9390         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9391
9392         mtx_lock(&softc->ctl_lock);
9393         num_luns = softc->num_luns;
9394         mtx_unlock(&softc->ctl_lock);
9395
9396         switch (cdb->select_report) {
9397         case RPL_REPORT_DEFAULT:
9398         case RPL_REPORT_ALL:
9399                 break;
9400         case RPL_REPORT_WELLKNOWN:
9401                 well_known = 1;
9402                 num_luns = 0;
9403                 break;
9404         default:
9405                 ctl_set_invalid_field(ctsio,
9406                                       /*sks_valid*/ 1,
9407                                       /*command*/ 1,
9408                                       /*field*/ 2,
9409                                       /*bit_valid*/ 0,
9410                                       /*bit*/ 0);
9411                 ctl_done((union ctl_io *)ctsio);
9412                 return (retval);
9413                 break; /* NOTREACHED */
9414         }
9415
9416         alloc_len = scsi_4btoul(cdb->length);
9417         /*
9418          * The initiator has to allocate at least 16 bytes for this request,
9419          * so he can at least get the header and the first LUN.  Otherwise
9420          * we reject the request (per SPC-3 rev 14, section 6.21).
9421          */
9422         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9423             sizeof(struct scsi_report_luns_lundata))) {
9424                 ctl_set_invalid_field(ctsio,
9425                                       /*sks_valid*/ 1,
9426                                       /*command*/ 1,
9427                                       /*field*/ 6,
9428                                       /*bit_valid*/ 0,
9429                                       /*bit*/ 0);
9430                 ctl_done((union ctl_io *)ctsio);
9431                 return (retval);
9432         }
9433
9434         request_lun = (struct ctl_lun *)
9435                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9436         port = ctl_io_port(&ctsio->io_hdr);
9437
9438         lun_datalen = sizeof(*lun_data) +
9439                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9440
9441         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9442         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9443         ctsio->kern_sg_entries = 0;
9444
9445         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9446
9447         mtx_lock(&softc->ctl_lock);
9448         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9449                 lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9450                 if (lun_id >= CTL_MAX_LUNS)
9451                         continue;
9452                 lun = softc->ctl_luns[lun_id];
9453                 if (lun == NULL)
9454                         continue;
9455
9456                 if (targ_lun_id <= 0xff) {
9457                         /*
9458                          * Peripheral addressing method, bus number 0.
9459                          */
9460                         lun_data->luns[num_filled].lundata[0] =
9461                                 RPL_LUNDATA_ATYP_PERIPH;
9462                         lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9463                         num_filled++;
9464                 } else if (targ_lun_id <= 0x3fff) {
9465                         /*
9466                          * Flat addressing method.
9467                          */
9468                         lun_data->luns[num_filled].lundata[0] =
9469                                 RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9470                         lun_data->luns[num_filled].lundata[1] =
9471                                 (targ_lun_id & 0xff);
9472                         num_filled++;
9473                 } else if (targ_lun_id <= 0xffffff) {
9474                         /*
9475                          * Extended flat addressing method.
9476                          */
9477                         lun_data->luns[num_filled].lundata[0] =
9478                             RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9479                         scsi_ulto3b(targ_lun_id,
9480                             &lun_data->luns[num_filled].lundata[1]);
9481                         num_filled++;
9482                 } else {
9483                         printf("ctl_report_luns: bogus LUN number %jd, "
9484                                "skipping\n", (intmax_t)targ_lun_id);
9485                 }
9486                 /*
9487                  * According to SPC-3, rev 14 section 6.21:
9488                  *
9489                  * "The execution of a REPORT LUNS command to any valid and
9490                  * installed logical unit shall clear the REPORTED LUNS DATA
9491                  * HAS CHANGED unit attention condition for all logical
9492                  * units of that target with respect to the requesting
9493                  * initiator. A valid and installed logical unit is one
9494                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9495                  * INQUIRY data (see 6.4.2)."
9496                  *
9497                  * If request_lun is NULL, the LUN this report luns command
9498                  * was issued to is either disabled or doesn't exist. In that
9499                  * case, we shouldn't clear any pending lun change unit
9500                  * attention.
9501                  */
9502                 if (request_lun != NULL) {
9503                         mtx_lock(&lun->lun_lock);
9504                         ctl_clr_ua(lun, initidx, CTL_UA_RES_RELEASE);
9505                         mtx_unlock(&lun->lun_lock);
9506                 }
9507         }
9508         mtx_unlock(&softc->ctl_lock);
9509
9510         /*
9511          * It's quite possible that we've returned fewer LUNs than we allocated
9512          * space for.  Trim it.
9513          */
9514         lun_datalen = sizeof(*lun_data) +
9515                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9516
9517         if (lun_datalen < alloc_len) {
9518                 ctsio->residual = alloc_len - lun_datalen;
9519                 ctsio->kern_data_len = lun_datalen;
9520                 ctsio->kern_total_len = lun_datalen;
9521         } else {
9522                 ctsio->residual = 0;
9523                 ctsio->kern_data_len = alloc_len;
9524                 ctsio->kern_total_len = alloc_len;
9525         }
9526         ctsio->kern_data_resid = 0;
9527         ctsio->kern_rel_offset = 0;
9528         ctsio->kern_sg_entries = 0;
9529
9530         /*
9531          * We set this to the actual data length, regardless of how much
9532          * space we actually have to return results.  If the user looks at
9533          * this value, he'll know whether or not he allocated enough space
9534          * and reissue the command if necessary.  We don't support well
9535          * known logical units, so if the user asks for that, return none.
9536          */
9537         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9538
9539         /*
9540          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9541          * this request.
9542          */
9543         ctl_set_success(ctsio);
9544         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9545         ctsio->be_move_done = ctl_config_move_done;
9546         ctl_datamove((union ctl_io *)ctsio);
9547         return (retval);
9548 }
9549
9550 int
9551 ctl_request_sense(struct ctl_scsiio *ctsio)
9552 {
9553         struct scsi_request_sense *cdb;
9554         struct scsi_sense_data *sense_ptr;
9555         struct ctl_softc *ctl_softc;
9556         struct ctl_lun *lun;
9557         uint32_t initidx;
9558         int have_error;
9559         scsi_sense_data_type sense_format;
9560         ctl_ua_type ua_type;
9561
9562         cdb = (struct scsi_request_sense *)ctsio->cdb;
9563
9564         ctl_softc = control_softc;
9565         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9566
9567         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9568
9569         /*
9570          * Determine which sense format the user wants.
9571          */
9572         if (cdb->byte2 & SRS_DESC)
9573                 sense_format = SSD_TYPE_DESC;
9574         else
9575                 sense_format = SSD_TYPE_FIXED;
9576
9577         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9578         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9579         ctsio->kern_sg_entries = 0;
9580
9581         /*
9582          * struct scsi_sense_data, which is currently set to 256 bytes, is
9583          * larger than the largest allowed value for the length field in the
9584          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9585          */
9586         ctsio->residual = 0;
9587         ctsio->kern_data_len = cdb->length;
9588         ctsio->kern_total_len = cdb->length;
9589
9590         ctsio->kern_data_resid = 0;
9591         ctsio->kern_rel_offset = 0;
9592         ctsio->kern_sg_entries = 0;
9593
9594         /*
9595          * If we don't have a LUN, we don't have any pending sense.
9596          */
9597         if (lun == NULL)
9598                 goto no_sense;
9599
9600         have_error = 0;
9601         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9602         /*
9603          * Check for pending sense, and then for pending unit attentions.
9604          * Pending sense gets returned first, then pending unit attentions.
9605          */
9606         mtx_lock(&lun->lun_lock);
9607 #ifdef CTL_WITH_CA
9608         if (ctl_is_set(lun->have_ca, initidx)) {
9609                 scsi_sense_data_type stored_format;
9610
9611                 /*
9612                  * Check to see which sense format was used for the stored
9613                  * sense data.
9614                  */
9615                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9616
9617                 /*
9618                  * If the user requested a different sense format than the
9619                  * one we stored, then we need to convert it to the other
9620                  * format.  If we're going from descriptor to fixed format
9621                  * sense data, we may lose things in translation, depending
9622                  * on what options were used.
9623                  *
9624                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9625                  * for some reason we'll just copy it out as-is.
9626                  */
9627                 if ((stored_format == SSD_TYPE_FIXED)
9628                  && (sense_format == SSD_TYPE_DESC))
9629                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9630                             &lun->pending_sense[initidx],
9631                             (struct scsi_sense_data_desc *)sense_ptr);
9632                 else if ((stored_format == SSD_TYPE_DESC)
9633                       && (sense_format == SSD_TYPE_FIXED))
9634                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9635                             &lun->pending_sense[initidx],
9636                             (struct scsi_sense_data_fixed *)sense_ptr);
9637                 else
9638                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9639                                MIN(sizeof(*sense_ptr),
9640                                sizeof(lun->pending_sense[initidx])));
9641
9642                 ctl_clear_mask(lun->have_ca, initidx);
9643                 have_error = 1;
9644         } else
9645 #endif
9646         {
9647                 ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9648                 if (ua_type != CTL_UA_NONE)
9649                         have_error = 1;
9650                 if (ua_type == CTL_UA_LUN_CHANGE) {
9651                         mtx_unlock(&lun->lun_lock);
9652                         mtx_lock(&ctl_softc->ctl_lock);
9653                         ctl_clear_ua(ctl_softc, initidx, ua_type);
9654                         mtx_unlock(&ctl_softc->ctl_lock);
9655                         mtx_lock(&lun->lun_lock);
9656                 }
9657
9658         }
9659         mtx_unlock(&lun->lun_lock);
9660
9661         /*
9662          * We already have a pending error, return it.
9663          */
9664         if (have_error != 0) {
9665                 /*
9666                  * We report the SCSI status as OK, since the status of the
9667                  * request sense command itself is OK.
9668                  * We report 0 for the sense length, because we aren't doing
9669                  * autosense in this case.  We're reporting sense as
9670                  * parameter data.
9671                  */
9672                 ctl_set_success(ctsio);
9673                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9674                 ctsio->be_move_done = ctl_config_move_done;
9675                 ctl_datamove((union ctl_io *)ctsio);
9676                 return (CTL_RETVAL_COMPLETE);
9677         }
9678
9679 no_sense:
9680
9681         /*
9682          * No sense information to report, so we report that everything is
9683          * okay.
9684          */
9685         ctl_set_sense_data(sense_ptr,
9686                            lun,
9687                            sense_format,
9688                            /*current_error*/ 1,
9689                            /*sense_key*/ SSD_KEY_NO_SENSE,
9690                            /*asc*/ 0x00,
9691                            /*ascq*/ 0x00,
9692                            SSD_ELEM_NONE);
9693
9694         /*
9695          * We report 0 for the sense length, because we aren't doing
9696          * autosense in this case.  We're reporting sense as parameter data.
9697          */
9698         ctl_set_success(ctsio);
9699         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9700         ctsio->be_move_done = ctl_config_move_done;
9701         ctl_datamove((union ctl_io *)ctsio);
9702         return (CTL_RETVAL_COMPLETE);
9703 }
9704
9705 int
9706 ctl_tur(struct ctl_scsiio *ctsio)
9707 {
9708
9709         CTL_DEBUG_PRINT(("ctl_tur\n"));
9710
9711         ctl_set_success(ctsio);
9712         ctl_done((union ctl_io *)ctsio);
9713
9714         return (CTL_RETVAL_COMPLETE);
9715 }
9716
9717 #ifdef notyet
9718 static int
9719 ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9720 {
9721
9722 }
9723 #endif
9724
9725 /*
9726  * SCSI VPD page 0x00, the Supported VPD Pages page.
9727  */
9728 static int
9729 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9730 {
9731         struct scsi_vpd_supported_pages *pages;
9732         int sup_page_size;
9733         struct ctl_lun *lun;
9734         int p;
9735
9736         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9737
9738         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9739             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9740         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9741         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9742         ctsio->kern_sg_entries = 0;
9743
9744         if (sup_page_size < alloc_len) {
9745                 ctsio->residual = alloc_len - sup_page_size;
9746                 ctsio->kern_data_len = sup_page_size;
9747                 ctsio->kern_total_len = sup_page_size;
9748         } else {
9749                 ctsio->residual = 0;
9750                 ctsio->kern_data_len = alloc_len;
9751                 ctsio->kern_total_len = alloc_len;
9752         }
9753         ctsio->kern_data_resid = 0;
9754         ctsio->kern_rel_offset = 0;
9755         ctsio->kern_sg_entries = 0;
9756
9757         /*
9758          * The control device is always connected.  The disk device, on the
9759          * other hand, may not be online all the time.  Need to change this
9760          * to figure out whether the disk device is actually online or not.
9761          */
9762         if (lun != NULL)
9763                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9764                                 lun->be_lun->lun_type;
9765         else
9766                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9767
9768         p = 0;
9769         /* Supported VPD pages */
9770         pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9771         /* Serial Number */
9772         pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9773         /* Device Identification */
9774         pages->page_list[p++] = SVPD_DEVICE_ID;
9775         /* Extended INQUIRY Data */
9776         pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9777         /* Mode Page Policy */
9778         pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9779         /* SCSI Ports */
9780         pages->page_list[p++] = SVPD_SCSI_PORTS;
9781         /* Third-party Copy */
9782         pages->page_list[p++] = SVPD_SCSI_TPC;
9783         if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9784                 /* Block limits */
9785                 pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9786                 /* Block Device Characteristics */
9787                 pages->page_list[p++] = SVPD_BDC;
9788                 /* Logical Block Provisioning */
9789                 pages->page_list[p++] = SVPD_LBP;
9790         }
9791         pages->length = p;
9792
9793         ctl_set_success(ctsio);
9794         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9795         ctsio->be_move_done = ctl_config_move_done;
9796         ctl_datamove((union ctl_io *)ctsio);
9797         return (CTL_RETVAL_COMPLETE);
9798 }
9799
9800 /*
9801  * SCSI VPD page 0x80, the Unit Serial Number page.
9802  */
9803 static int
9804 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9805 {
9806         struct scsi_vpd_unit_serial_number *sn_ptr;
9807         struct ctl_lun *lun;
9808         int data_len;
9809
9810         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9811
9812         data_len = 4 + CTL_SN_LEN;
9813         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9814         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9815         if (data_len < alloc_len) {
9816                 ctsio->residual = alloc_len - data_len;
9817                 ctsio->kern_data_len = data_len;
9818                 ctsio->kern_total_len = data_len;
9819         } else {
9820                 ctsio->residual = 0;
9821                 ctsio->kern_data_len = alloc_len;
9822                 ctsio->kern_total_len = alloc_len;
9823         }
9824         ctsio->kern_data_resid = 0;
9825         ctsio->kern_rel_offset = 0;
9826         ctsio->kern_sg_entries = 0;
9827
9828         /*
9829          * The control device is always connected.  The disk device, on the
9830          * other hand, may not be online all the time.  Need to change this
9831          * to figure out whether the disk device is actually online or not.
9832          */
9833         if (lun != NULL)
9834                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9835                                   lun->be_lun->lun_type;
9836         else
9837                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9838
9839         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9840         sn_ptr->length = CTL_SN_LEN;
9841         /*
9842          * If we don't have a LUN, we just leave the serial number as
9843          * all spaces.
9844          */
9845         if (lun != NULL) {
9846                 strncpy((char *)sn_ptr->serial_num,
9847                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9848         } else
9849                 memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9850
9851         ctl_set_success(ctsio);
9852         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9853         ctsio->be_move_done = ctl_config_move_done;
9854         ctl_datamove((union ctl_io *)ctsio);
9855         return (CTL_RETVAL_COMPLETE);
9856 }
9857
9858
9859 /*
9860  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9861  */
9862 static int
9863 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9864 {
9865         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9866         struct ctl_lun *lun;
9867         int data_len;
9868
9869         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9870
9871         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9872         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9873         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9874         ctsio->kern_sg_entries = 0;
9875
9876         if (data_len < alloc_len) {
9877                 ctsio->residual = alloc_len - data_len;
9878                 ctsio->kern_data_len = data_len;
9879                 ctsio->kern_total_len = data_len;
9880         } else {
9881                 ctsio->residual = 0;
9882                 ctsio->kern_data_len = alloc_len;
9883                 ctsio->kern_total_len = alloc_len;
9884         }
9885         ctsio->kern_data_resid = 0;
9886         ctsio->kern_rel_offset = 0;
9887         ctsio->kern_sg_entries = 0;
9888
9889         /*
9890          * The control device is always connected.  The disk device, on the
9891          * other hand, may not be online all the time.
9892          */
9893         if (lun != NULL)
9894                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9895                                      lun->be_lun->lun_type;
9896         else
9897                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9898         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9899         scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9900         /*
9901          * We support head of queue, ordered and simple tags.
9902          */
9903         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9904         /*
9905          * Volatile cache supported.
9906          */
9907         eid_ptr->flags3 = SVPD_EID_V_SUP;
9908
9909         /*
9910          * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9911          * attention for a particular IT nexus on all LUNs once we report
9912          * it to that nexus once.  This bit is required as of SPC-4.
9913          */
9914         eid_ptr->flags4 = SVPD_EID_LUICLT;
9915
9916         /*
9917          * XXX KDM in order to correctly answer this, we would need
9918          * information from the SIM to determine how much sense data it
9919          * can send.  So this would really be a path inquiry field, most
9920          * likely.  This can be set to a maximum of 252 according to SPC-4,
9921          * but the hardware may or may not be able to support that much.
9922          * 0 just means that the maximum sense data length is not reported.
9923          */
9924         eid_ptr->max_sense_length = 0;
9925
9926         ctl_set_success(ctsio);
9927         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9928         ctsio->be_move_done = ctl_config_move_done;
9929         ctl_datamove((union ctl_io *)ctsio);
9930         return (CTL_RETVAL_COMPLETE);
9931 }
9932
9933 static int
9934 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9935 {
9936         struct scsi_vpd_mode_page_policy *mpp_ptr;
9937         struct ctl_lun *lun;
9938         int data_len;
9939
9940         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9941
9942         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9943             sizeof(struct scsi_vpd_mode_page_policy_descr);
9944
9945         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9946         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9947         ctsio->kern_sg_entries = 0;
9948
9949         if (data_len < alloc_len) {
9950                 ctsio->residual = alloc_len - data_len;
9951                 ctsio->kern_data_len = data_len;
9952                 ctsio->kern_total_len = data_len;
9953         } else {
9954                 ctsio->residual = 0;
9955                 ctsio->kern_data_len = alloc_len;
9956                 ctsio->kern_total_len = alloc_len;
9957         }
9958         ctsio->kern_data_resid = 0;
9959         ctsio->kern_rel_offset = 0;
9960         ctsio->kern_sg_entries = 0;
9961
9962         /*
9963          * The control device is always connected.  The disk device, on the
9964          * other hand, may not be online all the time.
9965          */
9966         if (lun != NULL)
9967                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9968                                      lun->be_lun->lun_type;
9969         else
9970                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9971         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9972         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9973         mpp_ptr->descr[0].page_code = 0x3f;
9974         mpp_ptr->descr[0].subpage_code = 0xff;
9975         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9976
9977         ctl_set_success(ctsio);
9978         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9979         ctsio->be_move_done = ctl_config_move_done;
9980         ctl_datamove((union ctl_io *)ctsio);
9981         return (CTL_RETVAL_COMPLETE);
9982 }
9983
9984 /*
9985  * SCSI VPD page 0x83, the Device Identification page.
9986  */
9987 static int
9988 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9989 {
9990         struct scsi_vpd_device_id *devid_ptr;
9991         struct scsi_vpd_id_descriptor *desc;
9992         struct ctl_softc *softc;
9993         struct ctl_lun *lun;
9994         struct ctl_port *port;
9995         int data_len;
9996         uint8_t proto;
9997
9998         softc = control_softc;
9999
10000         port = softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
10001         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10002
10003         data_len = sizeof(struct scsi_vpd_device_id) +
10004             sizeof(struct scsi_vpd_id_descriptor) +
10005                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
10006             sizeof(struct scsi_vpd_id_descriptor) +
10007                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
10008         if (lun && lun->lun_devid)
10009                 data_len += lun->lun_devid->len;
10010         if (port->port_devid)
10011                 data_len += port->port_devid->len;
10012         if (port->target_devid)
10013                 data_len += port->target_devid->len;
10014
10015         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10016         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
10017         ctsio->kern_sg_entries = 0;
10018
10019         if (data_len < alloc_len) {
10020                 ctsio->residual = alloc_len - data_len;
10021                 ctsio->kern_data_len = data_len;
10022                 ctsio->kern_total_len = data_len;
10023         } else {
10024                 ctsio->residual = 0;
10025                 ctsio->kern_data_len = alloc_len;
10026                 ctsio->kern_total_len = alloc_len;
10027         }
10028         ctsio->kern_data_resid = 0;
10029         ctsio->kern_rel_offset = 0;
10030         ctsio->kern_sg_entries = 0;
10031
10032         /*
10033          * The control device is always connected.  The disk device, on the
10034          * other hand, may not be online all the time.
10035          */
10036         if (lun != NULL)
10037                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10038                                      lun->be_lun->lun_type;
10039         else
10040                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10041         devid_ptr->page_code = SVPD_DEVICE_ID;
10042         scsi_ulto2b(data_len - 4, devid_ptr->length);
10043
10044         if (port->port_type == CTL_PORT_FC)
10045                 proto = SCSI_PROTO_FC << 4;
10046         else if (port->port_type == CTL_PORT_ISCSI)
10047                 proto = SCSI_PROTO_ISCSI << 4;
10048         else
10049                 proto = SCSI_PROTO_SPI << 4;
10050         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
10051
10052         /*
10053          * We're using a LUN association here.  i.e., this device ID is a
10054          * per-LUN identifier.
10055          */
10056         if (lun && lun->lun_devid) {
10057                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
10058                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10059                     lun->lun_devid->len);
10060         }
10061
10062         /*
10063          * This is for the WWPN which is a port association.
10064          */
10065         if (port->port_devid) {
10066                 memcpy(desc, port->port_devid->data, port->port_devid->len);
10067                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10068                     port->port_devid->len);
10069         }
10070
10071         /*
10072          * This is for the Relative Target Port(type 4h) identifier
10073          */
10074         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10075         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10076             SVPD_ID_TYPE_RELTARG;
10077         desc->length = 4;
10078         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
10079         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10080             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
10081
10082         /*
10083          * This is for the Target Port Group(type 5h) identifier
10084          */
10085         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10086         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10087             SVPD_ID_TYPE_TPORTGRP;
10088         desc->length = 4;
10089         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
10090             &desc->identifier[2]);
10091         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10092             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
10093
10094         /*
10095          * This is for the Target identifier
10096          */
10097         if (port->target_devid) {
10098                 memcpy(desc, port->target_devid->data, port->target_devid->len);
10099         }
10100
10101         ctl_set_success(ctsio);
10102         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10103         ctsio->be_move_done = ctl_config_move_done;
10104         ctl_datamove((union ctl_io *)ctsio);
10105         return (CTL_RETVAL_COMPLETE);
10106 }
10107
10108 static int
10109 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
10110 {
10111         struct ctl_softc *softc = control_softc;
10112         struct scsi_vpd_scsi_ports *sp;
10113         struct scsi_vpd_port_designation *pd;
10114         struct scsi_vpd_port_designation_cont *pdc;
10115         struct ctl_lun *lun;
10116         struct ctl_port *port;
10117         int data_len, num_target_ports, iid_len, id_len, g, pg, p;
10118         int num_target_port_groups;
10119
10120         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10121
10122         if (softc->is_single)
10123                 num_target_port_groups = 1;
10124         else
10125                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10126         num_target_ports = 0;
10127         iid_len = 0;
10128         id_len = 0;
10129         mtx_lock(&softc->ctl_lock);
10130         STAILQ_FOREACH(port, &softc->port_list, links) {
10131                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10132                         continue;
10133                 if (lun != NULL &&
10134                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
10135                         continue;
10136                 num_target_ports++;
10137                 if (port->init_devid)
10138                         iid_len += port->init_devid->len;
10139                 if (port->port_devid)
10140                         id_len += port->port_devid->len;
10141         }
10142         mtx_unlock(&softc->ctl_lock);
10143
10144         data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10145             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10146              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10147         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10148         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10149         ctsio->kern_sg_entries = 0;
10150
10151         if (data_len < alloc_len) {
10152                 ctsio->residual = alloc_len - data_len;
10153                 ctsio->kern_data_len = data_len;
10154                 ctsio->kern_total_len = data_len;
10155         } else {
10156                 ctsio->residual = 0;
10157                 ctsio->kern_data_len = alloc_len;
10158                 ctsio->kern_total_len = alloc_len;
10159         }
10160         ctsio->kern_data_resid = 0;
10161         ctsio->kern_rel_offset = 0;
10162         ctsio->kern_sg_entries = 0;
10163
10164         /*
10165          * The control device is always connected.  The disk device, on the
10166          * other hand, may not be online all the time.  Need to change this
10167          * to figure out whether the disk device is actually online or not.
10168          */
10169         if (lun != NULL)
10170                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10171                                   lun->be_lun->lun_type;
10172         else
10173                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10174
10175         sp->page_code = SVPD_SCSI_PORTS;
10176         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10177             sp->page_length);
10178         pd = &sp->design[0];
10179
10180         mtx_lock(&softc->ctl_lock);
10181         pg = softc->port_offset / CTL_MAX_PORTS;
10182         for (g = 0; g < num_target_port_groups; g++) {
10183                 STAILQ_FOREACH(port, &softc->port_list, links) {
10184                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10185                                 continue;
10186                         if (lun != NULL &&
10187                             ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
10188                                 continue;
10189                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10190                         scsi_ulto2b(p, pd->relative_port_id);
10191                         if (port->init_devid && g == pg) {
10192                                 iid_len = port->init_devid->len;
10193                                 memcpy(pd->initiator_transportid,
10194                                     port->init_devid->data, port->init_devid->len);
10195                         } else
10196                                 iid_len = 0;
10197                         scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10198                         pdc = (struct scsi_vpd_port_designation_cont *)
10199                             (&pd->initiator_transportid[iid_len]);
10200                         if (port->port_devid && g == pg) {
10201                                 id_len = port->port_devid->len;
10202                                 memcpy(pdc->target_port_descriptors,
10203                                     port->port_devid->data, port->port_devid->len);
10204                         } else
10205                                 id_len = 0;
10206                         scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10207                         pd = (struct scsi_vpd_port_designation *)
10208                             ((uint8_t *)pdc->target_port_descriptors + id_len);
10209                 }
10210         }
10211         mtx_unlock(&softc->ctl_lock);
10212
10213         ctl_set_success(ctsio);
10214         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10215         ctsio->be_move_done = ctl_config_move_done;
10216         ctl_datamove((union ctl_io *)ctsio);
10217         return (CTL_RETVAL_COMPLETE);
10218 }
10219
10220 static int
10221 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10222 {
10223         struct scsi_vpd_block_limits *bl_ptr;
10224         struct ctl_lun *lun;
10225         int bs;
10226
10227         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10228
10229         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10230         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10231         ctsio->kern_sg_entries = 0;
10232
10233         if (sizeof(*bl_ptr) < alloc_len) {
10234                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
10235                 ctsio->kern_data_len = sizeof(*bl_ptr);
10236                 ctsio->kern_total_len = sizeof(*bl_ptr);
10237         } else {
10238                 ctsio->residual = 0;
10239                 ctsio->kern_data_len = alloc_len;
10240                 ctsio->kern_total_len = alloc_len;
10241         }
10242         ctsio->kern_data_resid = 0;
10243         ctsio->kern_rel_offset = 0;
10244         ctsio->kern_sg_entries = 0;
10245
10246         /*
10247          * The control device is always connected.  The disk device, on the
10248          * other hand, may not be online all the time.  Need to change this
10249          * to figure out whether the disk device is actually online or not.
10250          */
10251         if (lun != NULL)
10252                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10253                                   lun->be_lun->lun_type;
10254         else
10255                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10256
10257         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10258         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10259         bl_ptr->max_cmp_write_len = 0xff;
10260         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10261         if (lun != NULL) {
10262                 bs = lun->be_lun->blocksize;
10263                 scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
10264                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10265                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10266                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10267                         if (lun->be_lun->ublockexp != 0) {
10268                                 scsi_ulto4b((1 << lun->be_lun->ublockexp),
10269                                     bl_ptr->opt_unmap_grain);
10270                                 scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
10271                                     bl_ptr->unmap_grain_align);
10272                         }
10273                 }
10274                 scsi_ulto4b(lun->be_lun->atomicblock,
10275                     bl_ptr->max_atomic_transfer_length);
10276                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
10277                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10278         }
10279         scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10280
10281         ctl_set_success(ctsio);
10282         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10283         ctsio->be_move_done = ctl_config_move_done;
10284         ctl_datamove((union ctl_io *)ctsio);
10285         return (CTL_RETVAL_COMPLETE);
10286 }
10287
10288 static int
10289 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10290 {
10291         struct scsi_vpd_block_device_characteristics *bdc_ptr;
10292         struct ctl_lun *lun;
10293         const char *value;
10294         u_int i;
10295
10296         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10297
10298         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10299         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10300         ctsio->kern_sg_entries = 0;
10301
10302         if (sizeof(*bdc_ptr) < alloc_len) {
10303                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10304                 ctsio->kern_data_len = sizeof(*bdc_ptr);
10305                 ctsio->kern_total_len = sizeof(*bdc_ptr);
10306         } else {
10307                 ctsio->residual = 0;
10308                 ctsio->kern_data_len = alloc_len;
10309                 ctsio->kern_total_len = alloc_len;
10310         }
10311         ctsio->kern_data_resid = 0;
10312         ctsio->kern_rel_offset = 0;
10313         ctsio->kern_sg_entries = 0;
10314
10315         /*
10316          * The control device is always connected.  The disk device, on the
10317          * other hand, may not be online all the time.  Need to change this
10318          * to figure out whether the disk device is actually online or not.
10319          */
10320         if (lun != NULL)
10321                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10322                                   lun->be_lun->lun_type;
10323         else
10324                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10325         bdc_ptr->page_code = SVPD_BDC;
10326         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10327         if (lun != NULL &&
10328             (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10329                 i = strtol(value, NULL, 0);
10330         else
10331                 i = CTL_DEFAULT_ROTATION_RATE;
10332         scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10333         if (lun != NULL &&
10334             (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10335                 i = strtol(value, NULL, 0);
10336         else
10337                 i = 0;
10338         bdc_ptr->wab_wac_ff = (i & 0x0f);
10339         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10340
10341         ctl_set_success(ctsio);
10342         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10343         ctsio->be_move_done = ctl_config_move_done;
10344         ctl_datamove((union ctl_io *)ctsio);
10345         return (CTL_RETVAL_COMPLETE);
10346 }
10347
10348 static int
10349 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10350 {
10351         struct scsi_vpd_logical_block_prov *lbp_ptr;
10352         struct ctl_lun *lun;
10353
10354         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10355
10356         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10357         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10358         ctsio->kern_sg_entries = 0;
10359
10360         if (sizeof(*lbp_ptr) < alloc_len) {
10361                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10362                 ctsio->kern_data_len = sizeof(*lbp_ptr);
10363                 ctsio->kern_total_len = sizeof(*lbp_ptr);
10364         } else {
10365                 ctsio->residual = 0;
10366                 ctsio->kern_data_len = alloc_len;
10367                 ctsio->kern_total_len = alloc_len;
10368         }
10369         ctsio->kern_data_resid = 0;
10370         ctsio->kern_rel_offset = 0;
10371         ctsio->kern_sg_entries = 0;
10372
10373         /*
10374          * The control device is always connected.  The disk device, on the
10375          * other hand, may not be online all the time.  Need to change this
10376          * to figure out whether the disk device is actually online or not.
10377          */
10378         if (lun != NULL)
10379                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10380                                   lun->be_lun->lun_type;
10381         else
10382                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10383
10384         lbp_ptr->page_code = SVPD_LBP;
10385         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10386         lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10387         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10388                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10389                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10390                 lbp_ptr->prov_type = SVPD_LBP_THIN;
10391         }
10392
10393         ctl_set_success(ctsio);
10394         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10395         ctsio->be_move_done = ctl_config_move_done;
10396         ctl_datamove((union ctl_io *)ctsio);
10397         return (CTL_RETVAL_COMPLETE);
10398 }
10399
10400 /*
10401  * INQUIRY with the EVPD bit set.
10402  */
10403 static int
10404 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10405 {
10406         struct ctl_lun *lun;
10407         struct scsi_inquiry *cdb;
10408         int alloc_len, retval;
10409
10410         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10411         cdb = (struct scsi_inquiry *)ctsio->cdb;
10412         alloc_len = scsi_2btoul(cdb->length);
10413
10414         switch (cdb->page_code) {
10415         case SVPD_SUPPORTED_PAGES:
10416                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10417                 break;
10418         case SVPD_UNIT_SERIAL_NUMBER:
10419                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10420                 break;
10421         case SVPD_DEVICE_ID:
10422                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10423                 break;
10424         case SVPD_EXTENDED_INQUIRY_DATA:
10425                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10426                 break;
10427         case SVPD_MODE_PAGE_POLICY:
10428                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10429                 break;
10430         case SVPD_SCSI_PORTS:
10431                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10432                 break;
10433         case SVPD_SCSI_TPC:
10434                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10435                 break;
10436         case SVPD_BLOCK_LIMITS:
10437                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10438                         goto err;
10439                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10440                 break;
10441         case SVPD_BDC:
10442                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10443                         goto err;
10444                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10445                 break;
10446         case SVPD_LBP:
10447                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10448                         goto err;
10449                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10450                 break;
10451         default:
10452 err:
10453                 ctl_set_invalid_field(ctsio,
10454                                       /*sks_valid*/ 1,
10455                                       /*command*/ 1,
10456                                       /*field*/ 2,
10457                                       /*bit_valid*/ 0,
10458                                       /*bit*/ 0);
10459                 ctl_done((union ctl_io *)ctsio);
10460                 retval = CTL_RETVAL_COMPLETE;
10461                 break;
10462         }
10463
10464         return (retval);
10465 }
10466
10467 /*
10468  * Standard INQUIRY data.
10469  */
10470 static int
10471 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10472 {
10473         struct scsi_inquiry_data *inq_ptr;
10474         struct scsi_inquiry *cdb;
10475         struct ctl_softc *softc;
10476         struct ctl_lun *lun;
10477         char *val;
10478         uint32_t alloc_len, data_len;
10479         ctl_port_type port_type;
10480
10481         softc = control_softc;
10482
10483         /*
10484          * Figure out whether we're talking to a Fibre Channel port or not.
10485          * We treat the ioctl front end, and any SCSI adapters, as packetized
10486          * SCSI front ends.
10487          */
10488         port_type = softc->ctl_ports[
10489             ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10490         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10491                 port_type = CTL_PORT_SCSI;
10492
10493         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10494         cdb = (struct scsi_inquiry *)ctsio->cdb;
10495         alloc_len = scsi_2btoul(cdb->length);
10496
10497         /*
10498          * We malloc the full inquiry data size here and fill it
10499          * in.  If the user only asks for less, we'll give him
10500          * that much.
10501          */
10502         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10503         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10504         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10505         ctsio->kern_sg_entries = 0;
10506         ctsio->kern_data_resid = 0;
10507         ctsio->kern_rel_offset = 0;
10508
10509         if (data_len < alloc_len) {
10510                 ctsio->residual = alloc_len - data_len;
10511                 ctsio->kern_data_len = data_len;
10512                 ctsio->kern_total_len = data_len;
10513         } else {
10514                 ctsio->residual = 0;
10515                 ctsio->kern_data_len = alloc_len;
10516                 ctsio->kern_total_len = alloc_len;
10517         }
10518
10519         /*
10520          * If we have a LUN configured, report it as connected.  Otherwise,
10521          * report that it is offline or no device is supported, depending 
10522          * on the value of inquiry_pq_no_lun.
10523          *
10524          * According to the spec (SPC-4 r34), the peripheral qualifier
10525          * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10526          *
10527          * "A peripheral device having the specified peripheral device type 
10528          * is not connected to this logical unit. However, the device
10529          * server is capable of supporting the specified peripheral device
10530          * type on this logical unit."
10531          *
10532          * According to the same spec, the peripheral qualifier
10533          * SID_QUAL_BAD_LU (011b) is used in this scenario:
10534          *
10535          * "The device server is not capable of supporting a peripheral
10536          * device on this logical unit. For this peripheral qualifier the
10537          * peripheral device type shall be set to 1Fh. All other peripheral
10538          * device type values are reserved for this peripheral qualifier."
10539          *
10540          * Given the text, it would seem that we probably want to report that
10541          * the LUN is offline here.  There is no LUN connected, but we can
10542          * support a LUN at the given LUN number.
10543          *
10544          * In the real world, though, it sounds like things are a little
10545          * different:
10546          *
10547          * - Linux, when presented with a LUN with the offline peripheral
10548          *   qualifier, will create an sg driver instance for it.  So when
10549          *   you attach it to CTL, you wind up with a ton of sg driver
10550          *   instances.  (One for every LUN that Linux bothered to probe.)
10551          *   Linux does this despite the fact that it issues a REPORT LUNs
10552          *   to LUN 0 to get the inventory of supported LUNs.
10553          *
10554          * - There is other anecdotal evidence (from Emulex folks) about
10555          *   arrays that use the offline peripheral qualifier for LUNs that
10556          *   are on the "passive" path in an active/passive array.
10557          *
10558          * So the solution is provide a hopefully reasonable default
10559          * (return bad/no LUN) and allow the user to change the behavior
10560          * with a tunable/sysctl variable.
10561          */
10562         if (lun != NULL)
10563                 inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10564                                   lun->be_lun->lun_type;
10565         else if (softc->inquiry_pq_no_lun == 0)
10566                 inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10567         else
10568                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10569
10570         /* RMB in byte 2 is 0 */
10571         inq_ptr->version = SCSI_REV_SPC4;
10572
10573         /*
10574          * According to SAM-3, even if a device only supports a single
10575          * level of LUN addressing, it should still set the HISUP bit:
10576          *
10577          * 4.9.1 Logical unit numbers overview
10578          *
10579          * All logical unit number formats described in this standard are
10580          * hierarchical in structure even when only a single level in that
10581          * hierarchy is used. The HISUP bit shall be set to one in the
10582          * standard INQUIRY data (see SPC-2) when any logical unit number
10583          * format described in this standard is used.  Non-hierarchical
10584          * formats are outside the scope of this standard.
10585          *
10586          * Therefore we set the HiSup bit here.
10587          *
10588          * The reponse format is 2, per SPC-3.
10589          */
10590         inq_ptr->response_format = SID_HiSup | 2;
10591
10592         inq_ptr->additional_length = data_len -
10593             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10594         CTL_DEBUG_PRINT(("additional_length = %d\n",
10595                          inq_ptr->additional_length));
10596
10597         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10598         /* 16 bit addressing */
10599         if (port_type == CTL_PORT_SCSI)
10600                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10601         /* XXX set the SID_MultiP bit here if we're actually going to
10602            respond on multiple ports */
10603         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10604
10605         /* 16 bit data bus, synchronous transfers */
10606         if (port_type == CTL_PORT_SCSI)
10607                 inq_ptr->flags = SID_WBus16 | SID_Sync;
10608         /*
10609          * XXX KDM do we want to support tagged queueing on the control
10610          * device at all?
10611          */
10612         if ((lun == NULL)
10613          || (lun->be_lun->lun_type != T_PROCESSOR))
10614                 inq_ptr->flags |= SID_CmdQue;
10615         /*
10616          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10617          * We have 8 bytes for the vendor name, and 16 bytes for the device
10618          * name and 4 bytes for the revision.
10619          */
10620         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10621             "vendor")) == NULL) {
10622                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10623         } else {
10624                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10625                 strncpy(inq_ptr->vendor, val,
10626                     min(sizeof(inq_ptr->vendor), strlen(val)));
10627         }
10628         if (lun == NULL) {
10629                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10630                     sizeof(inq_ptr->product));
10631         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10632                 switch (lun->be_lun->lun_type) {
10633                 case T_DIRECT:
10634                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10635                             sizeof(inq_ptr->product));
10636                         break;
10637                 case T_PROCESSOR:
10638                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10639                             sizeof(inq_ptr->product));
10640                         break;
10641                 default:
10642                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10643                             sizeof(inq_ptr->product));
10644                         break;
10645                 }
10646         } else {
10647                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10648                 strncpy(inq_ptr->product, val,
10649                     min(sizeof(inq_ptr->product), strlen(val)));
10650         }
10651
10652         /*
10653          * XXX make this a macro somewhere so it automatically gets
10654          * incremented when we make changes.
10655          */
10656         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10657             "revision")) == NULL) {
10658                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10659         } else {
10660                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10661                 strncpy(inq_ptr->revision, val,
10662                     min(sizeof(inq_ptr->revision), strlen(val)));
10663         }
10664
10665         /*
10666          * For parallel SCSI, we support double transition and single
10667          * transition clocking.  We also support QAS (Quick Arbitration
10668          * and Selection) and Information Unit transfers on both the
10669          * control and array devices.
10670          */
10671         if (port_type == CTL_PORT_SCSI)
10672                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10673                                     SID_SPI_IUS;
10674
10675         /* SAM-5 (no version claimed) */
10676         scsi_ulto2b(0x00A0, inq_ptr->version1);
10677         /* SPC-4 (no version claimed) */
10678         scsi_ulto2b(0x0460, inq_ptr->version2);
10679         if (port_type == CTL_PORT_FC) {
10680                 /* FCP-2 ANSI INCITS.350:2003 */
10681                 scsi_ulto2b(0x0917, inq_ptr->version3);
10682         } else if (port_type == CTL_PORT_SCSI) {
10683                 /* SPI-4 ANSI INCITS.362:200x */
10684                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10685         } else if (port_type == CTL_PORT_ISCSI) {
10686                 /* iSCSI (no version claimed) */
10687                 scsi_ulto2b(0x0960, inq_ptr->version3);
10688         } else if (port_type == CTL_PORT_SAS) {
10689                 /* SAS (no version claimed) */
10690                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10691         }
10692
10693         if (lun == NULL) {
10694                 /* SBC-4 (no version claimed) */
10695                 scsi_ulto2b(0x0600, inq_ptr->version4);
10696         } else {
10697                 switch (lun->be_lun->lun_type) {
10698                 case T_DIRECT:
10699                         /* SBC-4 (no version claimed) */
10700                         scsi_ulto2b(0x0600, inq_ptr->version4);
10701                         break;
10702                 case T_PROCESSOR:
10703                 default:
10704                         break;
10705                 }
10706         }
10707
10708         ctl_set_success(ctsio);
10709         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10710         ctsio->be_move_done = ctl_config_move_done;
10711         ctl_datamove((union ctl_io *)ctsio);
10712         return (CTL_RETVAL_COMPLETE);
10713 }
10714
10715 int
10716 ctl_inquiry(struct ctl_scsiio *ctsio)
10717 {
10718         struct scsi_inquiry *cdb;
10719         int retval;
10720
10721         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10722
10723         cdb = (struct scsi_inquiry *)ctsio->cdb;
10724         if (cdb->byte2 & SI_EVPD)
10725                 retval = ctl_inquiry_evpd(ctsio);
10726         else if (cdb->page_code == 0)
10727                 retval = ctl_inquiry_std(ctsio);
10728         else {
10729                 ctl_set_invalid_field(ctsio,
10730                                       /*sks_valid*/ 1,
10731                                       /*command*/ 1,
10732                                       /*field*/ 2,
10733                                       /*bit_valid*/ 0,
10734                                       /*bit*/ 0);
10735                 ctl_done((union ctl_io *)ctsio);
10736                 return (CTL_RETVAL_COMPLETE);
10737         }
10738
10739         return (retval);
10740 }
10741
10742 /*
10743  * For known CDB types, parse the LBA and length.
10744  */
10745 static int
10746 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10747 {
10748         if (io->io_hdr.io_type != CTL_IO_SCSI)
10749                 return (1);
10750
10751         switch (io->scsiio.cdb[0]) {
10752         case COMPARE_AND_WRITE: {
10753                 struct scsi_compare_and_write *cdb;
10754
10755                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10756
10757                 *lba = scsi_8btou64(cdb->addr);
10758                 *len = cdb->length;
10759                 break;
10760         }
10761         case READ_6:
10762         case WRITE_6: {
10763                 struct scsi_rw_6 *cdb;
10764
10765                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10766
10767                 *lba = scsi_3btoul(cdb->addr);
10768                 /* only 5 bits are valid in the most significant address byte */
10769                 *lba &= 0x1fffff;
10770                 *len = cdb->length;
10771                 break;
10772         }
10773         case READ_10:
10774         case WRITE_10: {
10775                 struct scsi_rw_10 *cdb;
10776
10777                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10778
10779                 *lba = scsi_4btoul(cdb->addr);
10780                 *len = scsi_2btoul(cdb->length);
10781                 break;
10782         }
10783         case WRITE_VERIFY_10: {
10784                 struct scsi_write_verify_10 *cdb;
10785
10786                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10787
10788                 *lba = scsi_4btoul(cdb->addr);
10789                 *len = scsi_2btoul(cdb->length);
10790                 break;
10791         }
10792         case READ_12:
10793         case WRITE_12: {
10794                 struct scsi_rw_12 *cdb;
10795
10796                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10797
10798                 *lba = scsi_4btoul(cdb->addr);
10799                 *len = scsi_4btoul(cdb->length);
10800                 break;
10801         }
10802         case WRITE_VERIFY_12: {
10803                 struct scsi_write_verify_12 *cdb;
10804
10805                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10806
10807                 *lba = scsi_4btoul(cdb->addr);
10808                 *len = scsi_4btoul(cdb->length);
10809                 break;
10810         }
10811         case READ_16:
10812         case WRITE_16:
10813         case WRITE_ATOMIC_16: {
10814                 struct scsi_rw_16 *cdb;
10815
10816                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10817
10818                 *lba = scsi_8btou64(cdb->addr);
10819                 *len = scsi_4btoul(cdb->length);
10820                 break;
10821         }
10822         case WRITE_VERIFY_16: {
10823                 struct scsi_write_verify_16 *cdb;
10824
10825                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10826
10827                 *lba = scsi_8btou64(cdb->addr);
10828                 *len = scsi_4btoul(cdb->length);
10829                 break;
10830         }
10831         case WRITE_SAME_10: {
10832                 struct scsi_write_same_10 *cdb;
10833
10834                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10835
10836                 *lba = scsi_4btoul(cdb->addr);
10837                 *len = scsi_2btoul(cdb->length);
10838                 break;
10839         }
10840         case WRITE_SAME_16: {
10841                 struct scsi_write_same_16 *cdb;
10842
10843                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10844
10845                 *lba = scsi_8btou64(cdb->addr);
10846                 *len = scsi_4btoul(cdb->length);
10847                 break;
10848         }
10849         case VERIFY_10: {
10850                 struct scsi_verify_10 *cdb;
10851
10852                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10853
10854                 *lba = scsi_4btoul(cdb->addr);
10855                 *len = scsi_2btoul(cdb->length);
10856                 break;
10857         }
10858         case VERIFY_12: {
10859                 struct scsi_verify_12 *cdb;
10860
10861                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10862
10863                 *lba = scsi_4btoul(cdb->addr);
10864                 *len = scsi_4btoul(cdb->length);
10865                 break;
10866         }
10867         case VERIFY_16: {
10868                 struct scsi_verify_16 *cdb;
10869
10870                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10871
10872                 *lba = scsi_8btou64(cdb->addr);
10873                 *len = scsi_4btoul(cdb->length);
10874                 break;
10875         }
10876         case UNMAP: {
10877                 *lba = 0;
10878                 *len = UINT64_MAX;
10879                 break;
10880         }
10881         case SERVICE_ACTION_IN: {       /* GET LBA STATUS */
10882                 struct scsi_get_lba_status *cdb;
10883
10884                 cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10885                 *lba = scsi_8btou64(cdb->addr);
10886                 *len = UINT32_MAX;
10887                 break;
10888         }
10889         default:
10890                 return (1);
10891                 break; /* NOTREACHED */
10892         }
10893
10894         return (0);
10895 }
10896
10897 static ctl_action
10898 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10899     bool seq)
10900 {
10901         uint64_t endlba1, endlba2;
10902
10903         endlba1 = lba1 + len1 - (seq ? 0 : 1);
10904         endlba2 = lba2 + len2 - 1;
10905
10906         if ((endlba1 < lba2) || (endlba2 < lba1))
10907                 return (CTL_ACTION_PASS);
10908         else
10909                 return (CTL_ACTION_BLOCK);
10910 }
10911
10912 static int
10913 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10914 {
10915         struct ctl_ptr_len_flags *ptrlen;
10916         struct scsi_unmap_desc *buf, *end, *range;
10917         uint64_t lba;
10918         uint32_t len;
10919
10920         /* If not UNMAP -- go other way. */
10921         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10922             io->scsiio.cdb[0] != UNMAP)
10923                 return (CTL_ACTION_ERROR);
10924
10925         /* If UNMAP without data -- block and wait for data. */
10926         ptrlen = (struct ctl_ptr_len_flags *)
10927             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10928         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10929             ptrlen->ptr == NULL)
10930                 return (CTL_ACTION_BLOCK);
10931
10932         /* UNMAP with data -- check for collision. */
10933         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10934         end = buf + ptrlen->len / sizeof(*buf);
10935         for (range = buf; range < end; range++) {
10936                 lba = scsi_8btou64(range->lba);
10937                 len = scsi_4btoul(range->length);
10938                 if ((lba < lba2 + len2) && (lba + len > lba2))
10939                         return (CTL_ACTION_BLOCK);
10940         }
10941         return (CTL_ACTION_PASS);
10942 }
10943
10944 static ctl_action
10945 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10946 {
10947         uint64_t lba1, lba2;
10948         uint64_t len1, len2;
10949         int retval;
10950
10951         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10952                 return (CTL_ACTION_ERROR);
10953
10954         retval = ctl_extent_check_unmap(io1, lba2, len2);
10955         if (retval != CTL_ACTION_ERROR)
10956                 return (retval);
10957
10958         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10959                 return (CTL_ACTION_ERROR);
10960
10961         return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10962 }
10963
10964 static ctl_action
10965 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10966 {
10967         uint64_t lba1, lba2;
10968         uint64_t len1, len2;
10969
10970         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10971                 return (CTL_ACTION_ERROR);
10972         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10973                 return (CTL_ACTION_ERROR);
10974
10975         if (lba1 + len1 == lba2)
10976                 return (CTL_ACTION_BLOCK);
10977         return (CTL_ACTION_PASS);
10978 }
10979
10980 static ctl_action
10981 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10982     union ctl_io *ooa_io)
10983 {
10984         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10985         ctl_serialize_action *serialize_row;
10986
10987         /*
10988          * The initiator attempted multiple untagged commands at the same
10989          * time.  Can't do that.
10990          */
10991         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10992          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10993          && ((pending_io->io_hdr.nexus.targ_port ==
10994               ooa_io->io_hdr.nexus.targ_port)
10995           && (pending_io->io_hdr.nexus.initid.id ==
10996               ooa_io->io_hdr.nexus.initid.id))
10997          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10998               CTL_FLAG_STATUS_SENT)) == 0))
10999                 return (CTL_ACTION_OVERLAP);
11000
11001         /*
11002          * The initiator attempted to send multiple tagged commands with
11003          * the same ID.  (It's fine if different initiators have the same
11004          * tag ID.)
11005          *
11006          * Even if all of those conditions are true, we don't kill the I/O
11007          * if the command ahead of us has been aborted.  We won't end up
11008          * sending it to the FETD, and it's perfectly legal to resend a
11009          * command with the same tag number as long as the previous
11010          * instance of this tag number has been aborted somehow.
11011          */
11012         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11013          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11014          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11015          && ((pending_io->io_hdr.nexus.targ_port ==
11016               ooa_io->io_hdr.nexus.targ_port)
11017           && (pending_io->io_hdr.nexus.initid.id ==
11018               ooa_io->io_hdr.nexus.initid.id))
11019          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11020               CTL_FLAG_STATUS_SENT)) == 0))
11021                 return (CTL_ACTION_OVERLAP_TAG);
11022
11023         /*
11024          * If we get a head of queue tag, SAM-3 says that we should
11025          * immediately execute it.
11026          *
11027          * What happens if this command would normally block for some other
11028          * reason?  e.g. a request sense with a head of queue tag
11029          * immediately after a write.  Normally that would block, but this
11030          * will result in its getting executed immediately...
11031          *
11032          * We currently return "pass" instead of "skip", so we'll end up
11033          * going through the rest of the queue to check for overlapped tags.
11034          *
11035          * XXX KDM check for other types of blockage first??
11036          */
11037         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11038                 return (CTL_ACTION_PASS);
11039
11040         /*
11041          * Ordered tags have to block until all items ahead of them
11042          * have completed.  If we get called with an ordered tag, we always
11043          * block, if something else is ahead of us in the queue.
11044          */
11045         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11046                 return (CTL_ACTION_BLOCK);
11047
11048         /*
11049          * Simple tags get blocked until all head of queue and ordered tags
11050          * ahead of them have completed.  I'm lumping untagged commands in
11051          * with simple tags here.  XXX KDM is that the right thing to do?
11052          */
11053         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11054           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11055          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11056           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11057                 return (CTL_ACTION_BLOCK);
11058
11059         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11060         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11061
11062         serialize_row = ctl_serialize_table[ooa_entry->seridx];
11063
11064         switch (serialize_row[pending_entry->seridx]) {
11065         case CTL_SER_BLOCK:
11066                 return (CTL_ACTION_BLOCK);
11067         case CTL_SER_EXTENT:
11068                 return (ctl_extent_check(ooa_io, pending_io,
11069                     (lun->serseq == CTL_LUN_SERSEQ_ON)));
11070         case CTL_SER_EXTENTOPT:
11071                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11072                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11073                         return (ctl_extent_check(ooa_io, pending_io,
11074                             (lun->serseq == CTL_LUN_SERSEQ_ON)));
11075                 return (CTL_ACTION_PASS);
11076         case CTL_SER_EXTENTSEQ:
11077                 if (lun->serseq != CTL_LUN_SERSEQ_OFF)
11078                         return (ctl_extent_check_seq(ooa_io, pending_io));
11079                 return (CTL_ACTION_PASS);
11080         case CTL_SER_PASS:
11081                 return (CTL_ACTION_PASS);
11082         case CTL_SER_BLOCKOPT:
11083                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11084                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11085                         return (CTL_ACTION_BLOCK);
11086                 return (CTL_ACTION_PASS);
11087         case CTL_SER_SKIP:
11088                 return (CTL_ACTION_SKIP);
11089         default:
11090                 panic("invalid serialization value %d",
11091                       serialize_row[pending_entry->seridx]);
11092         }
11093
11094         return (CTL_ACTION_ERROR);
11095 }
11096
11097 /*
11098  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11099  * Assumptions:
11100  * - pending_io is generally either incoming, or on the blocked queue
11101  * - starting I/O is the I/O we want to start the check with.
11102  */
11103 static ctl_action
11104 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11105               union ctl_io *starting_io)
11106 {
11107         union ctl_io *ooa_io;
11108         ctl_action action;
11109
11110         mtx_assert(&lun->lun_lock, MA_OWNED);
11111
11112         /*
11113          * Run back along the OOA queue, starting with the current
11114          * blocked I/O and going through every I/O before it on the
11115          * queue.  If starting_io is NULL, we'll just end up returning
11116          * CTL_ACTION_PASS.
11117          */
11118         for (ooa_io = starting_io; ooa_io != NULL;
11119              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11120              ooa_links)){
11121
11122                 /*
11123                  * This routine just checks to see whether
11124                  * cur_blocked is blocked by ooa_io, which is ahead
11125                  * of it in the queue.  It doesn't queue/dequeue
11126                  * cur_blocked.
11127                  */
11128                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11129                 switch (action) {
11130                 case CTL_ACTION_BLOCK:
11131                 case CTL_ACTION_OVERLAP:
11132                 case CTL_ACTION_OVERLAP_TAG:
11133                 case CTL_ACTION_SKIP:
11134                 case CTL_ACTION_ERROR:
11135                         return (action);
11136                         break; /* NOTREACHED */
11137                 case CTL_ACTION_PASS:
11138                         break;
11139                 default:
11140                         panic("invalid action %d", action);
11141                         break;  /* NOTREACHED */
11142                 }
11143         }
11144
11145         return (CTL_ACTION_PASS);
11146 }
11147
11148 /*
11149  * Assumptions:
11150  * - An I/O has just completed, and has been removed from the per-LUN OOA
11151  *   queue, so some items on the blocked queue may now be unblocked.
11152  */
11153 static int
11154 ctl_check_blocked(struct ctl_lun *lun)
11155 {
11156         union ctl_io *cur_blocked, *next_blocked;
11157
11158         mtx_assert(&lun->lun_lock, MA_OWNED);
11159
11160         /*
11161          * Run forward from the head of the blocked queue, checking each
11162          * entry against the I/Os prior to it on the OOA queue to see if
11163          * there is still any blockage.
11164          *
11165          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11166          * with our removing a variable on it while it is traversing the
11167          * list.
11168          */
11169         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11170              cur_blocked != NULL; cur_blocked = next_blocked) {
11171                 union ctl_io *prev_ooa;
11172                 ctl_action action;
11173
11174                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11175                                                           blocked_links);
11176
11177                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11178                                                       ctl_ooaq, ooa_links);
11179
11180                 /*
11181                  * If cur_blocked happens to be the first item in the OOA
11182                  * queue now, prev_ooa will be NULL, and the action
11183                  * returned will just be CTL_ACTION_PASS.
11184                  */
11185                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11186
11187                 switch (action) {
11188                 case CTL_ACTION_BLOCK:
11189                         /* Nothing to do here, still blocked */
11190                         break;
11191                 case CTL_ACTION_OVERLAP:
11192                 case CTL_ACTION_OVERLAP_TAG:
11193                         /*
11194                          * This shouldn't happen!  In theory we've already
11195                          * checked this command for overlap...
11196                          */
11197                         break;
11198                 case CTL_ACTION_PASS:
11199                 case CTL_ACTION_SKIP: {
11200                         const struct ctl_cmd_entry *entry;
11201                         int isc_retval;
11202
11203                         /*
11204                          * The skip case shouldn't happen, this transaction
11205                          * should have never made it onto the blocked queue.
11206                          */
11207                         /*
11208                          * This I/O is no longer blocked, we can remove it
11209                          * from the blocked queue.  Since this is a TAILQ
11210                          * (doubly linked list), we can do O(1) removals
11211                          * from any place on the list.
11212                          */
11213                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11214                                      blocked_links);
11215                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11216
11217                         if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11218                                 /*
11219                                  * Need to send IO back to original side to
11220                                  * run
11221                                  */
11222                                 union ctl_ha_msg msg_info;
11223
11224                                 msg_info.hdr.original_sc =
11225                                         cur_blocked->io_hdr.original_sc;
11226                                 msg_info.hdr.serializing_sc = cur_blocked;
11227                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
11228                                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11229                                      &msg_info, sizeof(msg_info), 0)) >
11230                                      CTL_HA_STATUS_SUCCESS) {
11231                                         printf("CTL:Check Blocked error from "
11232                                                "ctl_ha_msg_send %d\n",
11233                                                isc_retval);
11234                                 }
11235                                 break;
11236                         }
11237                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11238
11239                         /*
11240                          * Check this I/O for LUN state changes that may
11241                          * have happened while this command was blocked.
11242                          * The LUN state may have been changed by a command
11243                          * ahead of us in the queue, so we need to re-check
11244                          * for any states that can be caused by SCSI
11245                          * commands.
11246                          */
11247                         if (ctl_scsiio_lun_check(lun, entry,
11248                                                  &cur_blocked->scsiio) == 0) {
11249                                 cur_blocked->io_hdr.flags |=
11250                                                       CTL_FLAG_IS_WAS_ON_RTR;
11251                                 ctl_enqueue_rtr(cur_blocked);
11252                         } else
11253                                 ctl_done(cur_blocked);
11254                         break;
11255                 }
11256                 default:
11257                         /*
11258                          * This probably shouldn't happen -- we shouldn't
11259                          * get CTL_ACTION_ERROR, or anything else.
11260                          */
11261                         break;
11262                 }
11263         }
11264
11265         return (CTL_RETVAL_COMPLETE);
11266 }
11267
11268 /*
11269  * This routine (with one exception) checks LUN flags that can be set by
11270  * commands ahead of us in the OOA queue.  These flags have to be checked
11271  * when a command initially comes in, and when we pull a command off the
11272  * blocked queue and are preparing to execute it.  The reason we have to
11273  * check these flags for commands on the blocked queue is that the LUN
11274  * state may have been changed by a command ahead of us while we're on the
11275  * blocked queue.
11276  *
11277  * Ordering is somewhat important with these checks, so please pay
11278  * careful attention to the placement of any new checks.
11279  */
11280 static int
11281 ctl_scsiio_lun_check(struct ctl_lun *lun,
11282     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11283 {
11284         struct ctl_softc *softc = lun->ctl_softc;
11285         int retval;
11286         uint32_t residx;
11287
11288         retval = 0;
11289
11290         mtx_assert(&lun->lun_lock, MA_OWNED);
11291
11292         /*
11293          * If this shelf is a secondary shelf controller, we have to reject
11294          * any media access commands.
11295          */
11296         if ((softc->flags & CTL_FLAG_ACTIVE_SHELF) == 0 &&
11297             (entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0) {
11298                 ctl_set_lun_standby(ctsio);
11299                 retval = 1;
11300                 goto bailout;
11301         }
11302
11303         if (entry->pattern & CTL_LUN_PAT_WRITE) {
11304                 if (lun->flags & CTL_LUN_READONLY) {
11305                         ctl_set_sense(ctsio, /*current_error*/ 1,
11306                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11307                             /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11308                         retval = 1;
11309                         goto bailout;
11310                 }
11311                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11312                     .eca_and_aen & SCP_SWP) != 0) {
11313                         ctl_set_sense(ctsio, /*current_error*/ 1,
11314                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11315                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11316                         retval = 1;
11317                         goto bailout;
11318                 }
11319         }
11320
11321         /*
11322          * Check for a reservation conflict.  If this command isn't allowed
11323          * even on reserved LUNs, and if this initiator isn't the one who
11324          * reserved us, reject the command with a reservation conflict.
11325          */
11326         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11327         if ((lun->flags & CTL_LUN_RESERVED)
11328          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11329                 if (lun->res_idx != residx) {
11330                         ctl_set_reservation_conflict(ctsio);
11331                         retval = 1;
11332                         goto bailout;
11333                 }
11334         }
11335
11336         if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11337             (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11338                 /* No reservation or command is allowed. */;
11339         } else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11340             (lun->res_type == SPR_TYPE_WR_EX ||
11341              lun->res_type == SPR_TYPE_WR_EX_RO ||
11342              lun->res_type == SPR_TYPE_WR_EX_AR)) {
11343                 /* The command is allowed for Write Exclusive resv. */;
11344         } else {
11345                 /*
11346                  * if we aren't registered or it's a res holder type
11347                  * reservation and this isn't the res holder then set a
11348                  * conflict.
11349                  */
11350                 if (ctl_get_prkey(lun, residx) == 0
11351                  || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11352                         ctl_set_reservation_conflict(ctsio);
11353                         retval = 1;
11354                         goto bailout;
11355                 }
11356
11357         }
11358
11359         if ((lun->flags & CTL_LUN_OFFLINE)
11360          && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11361                 ctl_set_lun_not_ready(ctsio);
11362                 retval = 1;
11363                 goto bailout;
11364         }
11365
11366         /*
11367          * If the LUN is stopped, see if this particular command is allowed
11368          * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11369          */
11370         if ((lun->flags & CTL_LUN_STOPPED)
11371          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11372                 /* "Logical unit not ready, initializing cmd. required" */
11373                 ctl_set_lun_stopped(ctsio);
11374                 retval = 1;
11375                 goto bailout;
11376         }
11377
11378         if ((lun->flags & CTL_LUN_INOPERABLE)
11379          && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11380                 /* "Medium format corrupted" */
11381                 ctl_set_medium_format_corrupted(ctsio);
11382                 retval = 1;
11383                 goto bailout;
11384         }
11385
11386 bailout:
11387         return (retval);
11388
11389 }
11390
11391 static void
11392 ctl_failover_io(union ctl_io *io, int have_lock)
11393 {
11394         ctl_set_busy(&io->scsiio);
11395         ctl_done(io);
11396 }
11397
11398 static void
11399 ctl_failover(void)
11400 {
11401         struct ctl_lun *lun;
11402         struct ctl_softc *softc;
11403         union ctl_io *next_io, *pending_io;
11404         union ctl_io *io;
11405         int lun_idx;
11406
11407         softc = control_softc;
11408
11409         mtx_lock(&softc->ctl_lock);
11410         /*
11411          * Remove any cmds from the other SC from the rtr queue.  These
11412          * will obviously only be for LUNs for which we're the primary.
11413          * We can't send status or get/send data for these commands.
11414          * Since they haven't been executed yet, we can just remove them.
11415          * We'll either abort them or delete them below, depending on
11416          * which HA mode we're in.
11417          */
11418 #ifdef notyet
11419         mtx_lock(&softc->queue_lock);
11420         for (io = (union ctl_io *)STAILQ_FIRST(&softc->rtr_queue);
11421              io != NULL; io = next_io) {
11422                 next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11423                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11424                         STAILQ_REMOVE(&softc->rtr_queue, &io->io_hdr,
11425                                       ctl_io_hdr, links);
11426         }
11427         mtx_unlock(&softc->queue_lock);
11428 #endif
11429
11430         for (lun_idx=0; lun_idx < softc->num_luns; lun_idx++) {
11431                 lun = softc->ctl_luns[lun_idx];
11432                 if (lun==NULL)
11433                         continue;
11434
11435                 /*
11436                  * Processor LUNs are primary on both sides.
11437                  * XXX will this always be true?
11438                  */
11439                 if (lun->be_lun->lun_type == T_PROCESSOR)
11440                         continue;
11441
11442                 if ((lun->flags & CTL_LUN_PRIMARY_SC)
11443                  && (softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11444                         printf("FAILOVER: primary lun %d\n", lun_idx);
11445                         /*
11446                          * Remove all commands from the other SC. First from the
11447                          * blocked queue then from the ooa queue. Once we have
11448                          * removed them. Call ctl_check_blocked to see if there
11449                          * is anything that can run.
11450                          */
11451                         for (io = (union ctl_io *)TAILQ_FIRST(
11452                              &lun->blocked_queue); io != NULL; io = next_io) {
11453
11454                                 next_io = (union ctl_io *)TAILQ_NEXT(
11455                                     &io->io_hdr, blocked_links);
11456
11457                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11458                                         TAILQ_REMOVE(&lun->blocked_queue,
11459                                                      &io->io_hdr,blocked_links);
11460                                         io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11461                                         TAILQ_REMOVE(&lun->ooa_queue,
11462                                                      &io->io_hdr, ooa_links);
11463
11464                                         ctl_free_io(io);
11465                                 }
11466                         }
11467
11468                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11469                              io != NULL; io = next_io) {
11470
11471                                 next_io = (union ctl_io *)TAILQ_NEXT(
11472                                     &io->io_hdr, ooa_links);
11473
11474                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11475
11476                                         TAILQ_REMOVE(&lun->ooa_queue,
11477                                                 &io->io_hdr,
11478                                                 ooa_links);
11479
11480                                         ctl_free_io(io);
11481                                 }
11482                         }
11483                         ctl_check_blocked(lun);
11484                 } else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11485                         && (softc->ha_mode == CTL_HA_MODE_XFER)) {
11486
11487                         printf("FAILOVER: primary lun %d\n", lun_idx);
11488                         /*
11489                          * Abort all commands from the other SC.  We can't
11490                          * send status back for them now.  These should get
11491                          * cleaned up when they are completed or come out
11492                          * for a datamove operation.
11493                          */
11494                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11495                              io != NULL; io = next_io) {
11496                                 next_io = (union ctl_io *)TAILQ_NEXT(
11497                                         &io->io_hdr, ooa_links);
11498
11499                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11500                                         io->io_hdr.flags |= CTL_FLAG_ABORT;
11501                         }
11502                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11503                         && (softc->ha_mode == CTL_HA_MODE_XFER)) {
11504
11505                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11506
11507                         lun->flags |= CTL_LUN_PRIMARY_SC;
11508
11509                         /*
11510                          * We send all I/O that was sent to this controller
11511                          * and redirected to the other side back with
11512                          * busy status, and have the initiator retry it.
11513                          * Figuring out how much data has been transferred,
11514                          * etc. and picking up where we left off would be 
11515                          * very tricky.
11516                          *
11517                          * XXX KDM need to remove I/O from the blocked
11518                          * queue as well!
11519                          */
11520                         for (pending_io = (union ctl_io *)TAILQ_FIRST(
11521                              &lun->ooa_queue); pending_io != NULL;
11522                              pending_io = next_io) {
11523
11524                                 next_io =  (union ctl_io *)TAILQ_NEXT(
11525                                         &pending_io->io_hdr, ooa_links);
11526
11527                                 pending_io->io_hdr.flags &=
11528                                         ~CTL_FLAG_SENT_2OTHER_SC;
11529
11530                                 if (pending_io->io_hdr.flags &
11531                                     CTL_FLAG_IO_ACTIVE) {
11532                                         pending_io->io_hdr.flags |=
11533                                                 CTL_FLAG_FAILOVER;
11534                                 } else {
11535                                         ctl_set_busy(&pending_io->scsiio);
11536                                         ctl_done(pending_io);
11537                                 }
11538                         }
11539
11540                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11541                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11542                         && (softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11543                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11544                         /*
11545                          * if the first io on the OOA is not on the RtR queue
11546                          * add it.
11547                          */
11548                         lun->flags |= CTL_LUN_PRIMARY_SC;
11549
11550                         pending_io = (union ctl_io *)TAILQ_FIRST(
11551                             &lun->ooa_queue);
11552                         if (pending_io==NULL) {
11553                                 printf("Nothing on OOA queue\n");
11554                                 continue;
11555                         }
11556
11557                         pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11558                         if ((pending_io->io_hdr.flags &
11559                              CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11560                                 pending_io->io_hdr.flags |=
11561                                     CTL_FLAG_IS_WAS_ON_RTR;
11562                                 ctl_enqueue_rtr(pending_io);
11563                         }
11564 #if 0
11565                         else
11566                         {
11567                                 printf("Tag 0x%04x is running\n",
11568                                       pending_io->scsiio.tag_num);
11569                         }
11570 #endif
11571
11572                         next_io = (union ctl_io *)TAILQ_NEXT(
11573                             &pending_io->io_hdr, ooa_links);
11574                         for (pending_io=next_io; pending_io != NULL;
11575                              pending_io = next_io) {
11576                                 pending_io->io_hdr.flags &=
11577                                     ~CTL_FLAG_SENT_2OTHER_SC;
11578                                 next_io = (union ctl_io *)TAILQ_NEXT(
11579                                         &pending_io->io_hdr, ooa_links);
11580                                 if (pending_io->io_hdr.flags &
11581                                     CTL_FLAG_IS_WAS_ON_RTR) {
11582 #if 0
11583                                         printf("Tag 0x%04x is running\n",
11584                                                 pending_io->scsiio.tag_num);
11585 #endif
11586                                         continue;
11587                                 }
11588
11589                                 switch (ctl_check_ooa(lun, pending_io,
11590                                     (union ctl_io *)TAILQ_PREV(
11591                                     &pending_io->io_hdr, ctl_ooaq,
11592                                     ooa_links))) {
11593
11594                                 case CTL_ACTION_BLOCK:
11595                                         TAILQ_INSERT_TAIL(&lun->blocked_queue,
11596                                                           &pending_io->io_hdr,
11597                                                           blocked_links);
11598                                         pending_io->io_hdr.flags |=
11599                                             CTL_FLAG_BLOCKED;
11600                                         break;
11601                                 case CTL_ACTION_PASS:
11602                                 case CTL_ACTION_SKIP:
11603                                         pending_io->io_hdr.flags |=
11604                                             CTL_FLAG_IS_WAS_ON_RTR;
11605                                         ctl_enqueue_rtr(pending_io);
11606                                         break;
11607                                 case CTL_ACTION_OVERLAP:
11608                                         ctl_set_overlapped_cmd(
11609                                             (struct ctl_scsiio *)pending_io);
11610                                         ctl_done(pending_io);
11611                                         break;
11612                                 case CTL_ACTION_OVERLAP_TAG:
11613                                         ctl_set_overlapped_tag(
11614                                             (struct ctl_scsiio *)pending_io,
11615                                             pending_io->scsiio.tag_num & 0xff);
11616                                         ctl_done(pending_io);
11617                                         break;
11618                                 case CTL_ACTION_ERROR:
11619                                 default:
11620                                         ctl_set_internal_failure(
11621                                                 (struct ctl_scsiio *)pending_io,
11622                                                 0,  // sks_valid
11623                                                 0); //retry count
11624                                         ctl_done(pending_io);
11625                                         break;
11626                                 }
11627                         }
11628
11629                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11630                 } else {
11631                         panic("Unhandled HA mode failover, LUN flags = %#x, "
11632                               "ha_mode = #%x", lun->flags, softc->ha_mode);
11633                 }
11634         }
11635         ctl_pause_rtr = 0;
11636         mtx_unlock(&softc->ctl_lock);
11637 }
11638
11639 static void
11640 ctl_clear_ua(struct ctl_softc *ctl_softc, uint32_t initidx,
11641              ctl_ua_type ua_type)
11642 {
11643         struct ctl_lun *lun;
11644         ctl_ua_type *pu;
11645
11646         mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
11647
11648         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
11649                 mtx_lock(&lun->lun_lock);
11650                 pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
11651                 if (pu != NULL)
11652                         pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua_type;
11653                 mtx_unlock(&lun->lun_lock);
11654         }
11655 }
11656
11657 static int
11658 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11659 {
11660         struct ctl_lun *lun;
11661         const struct ctl_cmd_entry *entry;
11662         uint32_t initidx, targ_lun;
11663         int retval;
11664
11665         retval = 0;
11666
11667         lun = NULL;
11668
11669         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11670         if ((targ_lun < CTL_MAX_LUNS)
11671          && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11672                 /*
11673                  * If the LUN is invalid, pretend that it doesn't exist.
11674                  * It will go away as soon as all pending I/O has been
11675                  * completed.
11676                  */
11677                 mtx_lock(&lun->lun_lock);
11678                 if (lun->flags & CTL_LUN_DISABLED) {
11679                         mtx_unlock(&lun->lun_lock);
11680                         lun = NULL;
11681                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11682                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11683                 } else {
11684                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11685                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11686                                 lun->be_lun;
11687                         if (lun->be_lun->lun_type == T_PROCESSOR) {
11688                                 ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11689                         }
11690
11691                         /*
11692                          * Every I/O goes into the OOA queue for a
11693                          * particular LUN, and stays there until completion.
11694                          */
11695                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11696                             ooa_links);
11697                 }
11698         } else {
11699                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11700                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11701         }
11702
11703         /* Get command entry and return error if it is unsuppotyed. */
11704         entry = ctl_validate_command(ctsio);
11705         if (entry == NULL) {
11706                 if (lun)
11707                         mtx_unlock(&lun->lun_lock);
11708                 return (retval);
11709         }
11710
11711         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11712         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11713
11714         /*
11715          * Check to see whether we can send this command to LUNs that don't
11716          * exist.  This should pretty much only be the case for inquiry
11717          * and request sense.  Further checks, below, really require having
11718          * a LUN, so we can't really check the command anymore.  Just put
11719          * it on the rtr queue.
11720          */
11721         if (lun == NULL) {
11722                 if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11723                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11724                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11725                         return (retval);
11726                 }
11727
11728                 ctl_set_unsupported_lun(ctsio);
11729                 ctl_done((union ctl_io *)ctsio);
11730                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11731                 return (retval);
11732         } else {
11733                 /*
11734                  * Make sure we support this particular command on this LUN.
11735                  * e.g., we don't support writes to the control LUN.
11736                  */
11737                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11738                         mtx_unlock(&lun->lun_lock);
11739                         ctl_set_invalid_opcode(ctsio);
11740                         ctl_done((union ctl_io *)ctsio);
11741                         return (retval);
11742                 }
11743         }
11744
11745         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11746
11747 #ifdef CTL_WITH_CA
11748         /*
11749          * If we've got a request sense, it'll clear the contingent
11750          * allegiance condition.  Otherwise, if we have a CA condition for
11751          * this initiator, clear it, because it sent down a command other
11752          * than request sense.
11753          */
11754         if ((ctsio->cdb[0] != REQUEST_SENSE)
11755          && (ctl_is_set(lun->have_ca, initidx)))
11756                 ctl_clear_mask(lun->have_ca, initidx);
11757 #endif
11758
11759         /*
11760          * If the command has this flag set, it handles its own unit
11761          * attention reporting, we shouldn't do anything.  Otherwise we
11762          * check for any pending unit attentions, and send them back to the
11763          * initiator.  We only do this when a command initially comes in,
11764          * not when we pull it off the blocked queue.
11765          *
11766          * According to SAM-3, section 5.3.2, the order that things get
11767          * presented back to the host is basically unit attentions caused
11768          * by some sort of reset event, busy status, reservation conflicts
11769          * or task set full, and finally any other status.
11770          *
11771          * One issue here is that some of the unit attentions we report
11772          * don't fall into the "reset" category (e.g. "reported luns data
11773          * has changed").  So reporting it here, before the reservation
11774          * check, may be technically wrong.  I guess the only thing to do
11775          * would be to check for and report the reset events here, and then
11776          * check for the other unit attention types after we check for a
11777          * reservation conflict.
11778          *
11779          * XXX KDM need to fix this
11780          */
11781         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11782                 ctl_ua_type ua_type;
11783                 scsi_sense_data_type sense_format;
11784
11785                 if (lun->flags & CTL_LUN_SENSE_DESC)
11786                         sense_format = SSD_TYPE_DESC;
11787                 else
11788                         sense_format = SSD_TYPE_FIXED;
11789
11790                 ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11791                     sense_format);
11792                 if (ua_type != CTL_UA_NONE) {
11793                         mtx_unlock(&lun->lun_lock);
11794                         ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11795                         ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11796                         ctsio->sense_len = SSD_FULL_SIZE;
11797                         ctl_done((union ctl_io *)ctsio);
11798                         return (retval);
11799                 }
11800         }
11801
11802
11803         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11804                 mtx_unlock(&lun->lun_lock);
11805                 ctl_done((union ctl_io *)ctsio);
11806                 return (retval);
11807         }
11808
11809         /*
11810          * XXX CHD this is where we want to send IO to other side if
11811          * this LUN is secondary on this SC. We will need to make a copy
11812          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11813          * the copy we send as FROM_OTHER.
11814          * We also need to stuff the address of the original IO so we can
11815          * find it easily. Something similar will need be done on the other
11816          * side so when we are done we can find the copy.
11817          */
11818         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11819                 union ctl_ha_msg msg_info;
11820                 int isc_retval;
11821
11822                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11823
11824                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11825                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11826 #if 0
11827                 printf("1. ctsio %p\n", ctsio);
11828 #endif
11829                 msg_info.hdr.serializing_sc = NULL;
11830                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11831                 msg_info.scsi.tag_num = ctsio->tag_num;
11832                 msg_info.scsi.tag_type = ctsio->tag_type;
11833                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11834
11835                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11836
11837                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11838                     (void *)&msg_info, sizeof(msg_info), 0)) >
11839                     CTL_HA_STATUS_SUCCESS) {
11840                         printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11841                                isc_retval);
11842                         printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11843                 } else {
11844 #if 0
11845                         printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11846 #endif
11847                 }
11848
11849                 /*
11850                  * XXX KDM this I/O is off the incoming queue, but hasn't
11851                  * been inserted on any other queue.  We may need to come
11852                  * up with a holding queue while we wait for serialization
11853                  * so that we have an idea of what we're waiting for from
11854                  * the other side.
11855                  */
11856                 mtx_unlock(&lun->lun_lock);
11857                 return (retval);
11858         }
11859
11860         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11861                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11862                               ctl_ooaq, ooa_links))) {
11863         case CTL_ACTION_BLOCK:
11864                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11865                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11866                                   blocked_links);
11867                 mtx_unlock(&lun->lun_lock);
11868                 return (retval);
11869         case CTL_ACTION_PASS:
11870         case CTL_ACTION_SKIP:
11871                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11872                 mtx_unlock(&lun->lun_lock);
11873                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11874                 break;
11875         case CTL_ACTION_OVERLAP:
11876                 mtx_unlock(&lun->lun_lock);
11877                 ctl_set_overlapped_cmd(ctsio);
11878                 ctl_done((union ctl_io *)ctsio);
11879                 break;
11880         case CTL_ACTION_OVERLAP_TAG:
11881                 mtx_unlock(&lun->lun_lock);
11882                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11883                 ctl_done((union ctl_io *)ctsio);
11884                 break;
11885         case CTL_ACTION_ERROR:
11886         default:
11887                 mtx_unlock(&lun->lun_lock);
11888                 ctl_set_internal_failure(ctsio,
11889                                          /*sks_valid*/ 0,
11890                                          /*retry_count*/ 0);
11891                 ctl_done((union ctl_io *)ctsio);
11892                 break;
11893         }
11894         return (retval);
11895 }
11896
11897 const struct ctl_cmd_entry *
11898 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11899 {
11900         const struct ctl_cmd_entry *entry;
11901         int service_action;
11902
11903         entry = &ctl_cmd_table[ctsio->cdb[0]];
11904         if (sa)
11905                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11906         if (entry->flags & CTL_CMD_FLAG_SA5) {
11907                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11908                 entry = &((const struct ctl_cmd_entry *)
11909                     entry->execute)[service_action];
11910         }
11911         return (entry);
11912 }
11913
11914 const struct ctl_cmd_entry *
11915 ctl_validate_command(struct ctl_scsiio *ctsio)
11916 {
11917         const struct ctl_cmd_entry *entry;
11918         int i, sa;
11919         uint8_t diff;
11920
11921         entry = ctl_get_cmd_entry(ctsio, &sa);
11922         if (entry->execute == NULL) {
11923                 if (sa)
11924                         ctl_set_invalid_field(ctsio,
11925                                               /*sks_valid*/ 1,
11926                                               /*command*/ 1,
11927                                               /*field*/ 1,
11928                                               /*bit_valid*/ 1,
11929                                               /*bit*/ 4);
11930                 else
11931                         ctl_set_invalid_opcode(ctsio);
11932                 ctl_done((union ctl_io *)ctsio);
11933                 return (NULL);
11934         }
11935         KASSERT(entry->length > 0,
11936             ("Not defined length for command 0x%02x/0x%02x",
11937              ctsio->cdb[0], ctsio->cdb[1]));
11938         for (i = 1; i < entry->length; i++) {
11939                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11940                 if (diff == 0)
11941                         continue;
11942                 ctl_set_invalid_field(ctsio,
11943                                       /*sks_valid*/ 1,
11944                                       /*command*/ 1,
11945                                       /*field*/ i,
11946                                       /*bit_valid*/ 1,
11947                                       /*bit*/ fls(diff) - 1);
11948                 ctl_done((union ctl_io *)ctsio);
11949                 return (NULL);
11950         }
11951         return (entry);
11952 }
11953
11954 static int
11955 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11956 {
11957
11958         switch (lun_type) {
11959         case T_PROCESSOR:
11960                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11961                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11962                         return (0);
11963                 break;
11964         case T_DIRECT:
11965                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11966                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11967                         return (0);
11968                 break;
11969         default:
11970                 return (0);
11971         }
11972         return (1);
11973 }
11974
11975 static int
11976 ctl_scsiio(struct ctl_scsiio *ctsio)
11977 {
11978         int retval;
11979         const struct ctl_cmd_entry *entry;
11980
11981         retval = CTL_RETVAL_COMPLETE;
11982
11983         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11984
11985         entry = ctl_get_cmd_entry(ctsio, NULL);
11986
11987         /*
11988          * If this I/O has been aborted, just send it straight to
11989          * ctl_done() without executing it.
11990          */
11991         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11992                 ctl_done((union ctl_io *)ctsio);
11993                 goto bailout;
11994         }
11995
11996         /*
11997          * All the checks should have been handled by ctl_scsiio_precheck().
11998          * We should be clear now to just execute the I/O.
11999          */
12000         retval = entry->execute(ctsio);
12001
12002 bailout:
12003         return (retval);
12004 }
12005
12006 /*
12007  * Since we only implement one target right now, a bus reset simply resets
12008  * our single target.
12009  */
12010 static int
12011 ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
12012 {
12013         return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
12014 }
12015
12016 static int
12017 ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
12018                  ctl_ua_type ua_type)
12019 {
12020         struct ctl_lun *lun;
12021         int retval;
12022
12023         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12024                 union ctl_ha_msg msg_info;
12025
12026                 io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
12027                 msg_info.hdr.nexus = io->io_hdr.nexus;
12028                 if (ua_type==CTL_UA_TARG_RESET)
12029                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
12030                 else
12031                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
12032                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12033                 msg_info.hdr.original_sc = NULL;
12034                 msg_info.hdr.serializing_sc = NULL;
12035                 if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12036                     (void *)&msg_info, sizeof(msg_info), 0)) {
12037                 }
12038         }
12039         retval = 0;
12040
12041         mtx_lock(&softc->ctl_lock);
12042         STAILQ_FOREACH(lun, &softc->lun_list, links)
12043                 retval += ctl_lun_reset(lun, io, ua_type);
12044         mtx_unlock(&softc->ctl_lock);
12045
12046         return (retval);
12047 }
12048
12049 /*
12050  * The LUN should always be set.  The I/O is optional, and is used to
12051  * distinguish between I/Os sent by this initiator, and by other
12052  * initiators.  We set unit attention for initiators other than this one.
12053  * SAM-3 is vague on this point.  It does say that a unit attention should
12054  * be established for other initiators when a LUN is reset (see section
12055  * 5.7.3), but it doesn't specifically say that the unit attention should
12056  * be established for this particular initiator when a LUN is reset.  Here
12057  * is the relevant text, from SAM-3 rev 8:
12058  *
12059  * 5.7.2 When a SCSI initiator port aborts its own tasks
12060  *
12061  * When a SCSI initiator port causes its own task(s) to be aborted, no
12062  * notification that the task(s) have been aborted shall be returned to
12063  * the SCSI initiator port other than the completion response for the
12064  * command or task management function action that caused the task(s) to
12065  * be aborted and notification(s) associated with related effects of the
12066  * action (e.g., a reset unit attention condition).
12067  *
12068  * XXX KDM for now, we're setting unit attention for all initiators.
12069  */
12070 static int
12071 ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
12072 {
12073         union ctl_io *xio;
12074 #if 0
12075         uint32_t initidx;
12076 #endif
12077 #ifdef CTL_WITH_CA
12078         int i;
12079 #endif
12080
12081         mtx_lock(&lun->lun_lock);
12082         /*
12083          * Run through the OOA queue and abort each I/O.
12084          */
12085 #if 0
12086         TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12087 #endif
12088         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12089              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12090                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
12091         }
12092
12093         /*
12094          * This version sets unit attention for every
12095          */
12096 #if 0
12097         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12098         ctl_est_ua_all(lun, initidx, ua_type);
12099 #else
12100         ctl_est_ua_all(lun, -1, ua_type);
12101 #endif
12102
12103         /*
12104          * A reset (any kind, really) clears reservations established with
12105          * RESERVE/RELEASE.  It does not clear reservations established
12106          * with PERSISTENT RESERVE OUT, but we don't support that at the
12107          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
12108          * reservations made with the RESERVE/RELEASE commands, because
12109          * those commands are obsolete in SPC-3.
12110          */
12111         lun->flags &= ~CTL_LUN_RESERVED;
12112
12113 #ifdef CTL_WITH_CA
12114         for (i = 0; i < CTL_MAX_INITIATORS; i++)
12115                 ctl_clear_mask(lun->have_ca, i);
12116 #endif
12117         mtx_unlock(&lun->lun_lock);
12118
12119         return (0);
12120 }
12121
12122 static void
12123 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
12124     int other_sc)
12125 {
12126         union ctl_io *xio;
12127
12128         mtx_assert(&lun->lun_lock, MA_OWNED);
12129
12130         /*
12131          * Run through the OOA queue and attempt to find the given I/O.
12132          * The target port, initiator ID, tag type and tag number have to
12133          * match the values that we got from the initiator.  If we have an
12134          * untagged command to abort, simply abort the first untagged command
12135          * we come to.  We only allow one untagged command at a time of course.
12136          */
12137         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12138              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12139
12140                 if ((targ_port == UINT32_MAX ||
12141                      targ_port == xio->io_hdr.nexus.targ_port) &&
12142                     (init_id == UINT32_MAX ||
12143                      init_id == xio->io_hdr.nexus.initid.id)) {
12144                         if (targ_port != xio->io_hdr.nexus.targ_port ||
12145                             init_id != xio->io_hdr.nexus.initid.id)
12146                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12147                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12148                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12149                                 union ctl_ha_msg msg_info;
12150
12151                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
12152                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12153                                 msg_info.task.tag_num = xio->scsiio.tag_num;
12154                                 msg_info.task.tag_type = xio->scsiio.tag_type;
12155                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12156                                 msg_info.hdr.original_sc = NULL;
12157                                 msg_info.hdr.serializing_sc = NULL;
12158                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12159                                     (void *)&msg_info, sizeof(msg_info), 0);
12160                         }
12161                 }
12162         }
12163 }
12164
12165 static int
12166 ctl_abort_task_set(union ctl_io *io)
12167 {
12168         struct ctl_softc *softc = control_softc;
12169         struct ctl_lun *lun;
12170         uint32_t targ_lun;
12171
12172         /*
12173          * Look up the LUN.
12174          */
12175         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12176         mtx_lock(&softc->ctl_lock);
12177         if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
12178                 lun = softc->ctl_luns[targ_lun];
12179         else {
12180                 mtx_unlock(&softc->ctl_lock);
12181                 return (1);
12182         }
12183
12184         mtx_lock(&lun->lun_lock);
12185         mtx_unlock(&softc->ctl_lock);
12186         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12187                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12188                     io->io_hdr.nexus.initid.id,
12189                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12190         } else { /* CTL_TASK_CLEAR_TASK_SET */
12191                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12192                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12193         }
12194         mtx_unlock(&lun->lun_lock);
12195         return (0);
12196 }
12197
12198 static int
12199 ctl_i_t_nexus_reset(union ctl_io *io)
12200 {
12201         struct ctl_softc *softc = control_softc;
12202         struct ctl_lun *lun;
12203         uint32_t initidx, residx;
12204
12205         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12206         residx = ctl_get_resindex(&io->io_hdr.nexus);
12207         mtx_lock(&softc->ctl_lock);
12208         STAILQ_FOREACH(lun, &softc->lun_list, links) {
12209                 mtx_lock(&lun->lun_lock);
12210                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12211                     io->io_hdr.nexus.initid.id,
12212                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12213 #ifdef CTL_WITH_CA
12214                 ctl_clear_mask(lun->have_ca, initidx);
12215 #endif
12216                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
12217                         lun->flags &= ~CTL_LUN_RESERVED;
12218                 ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12219                 mtx_unlock(&lun->lun_lock);
12220         }
12221         mtx_unlock(&softc->ctl_lock);
12222         return (0);
12223 }
12224
12225 static int
12226 ctl_abort_task(union ctl_io *io)
12227 {
12228         union ctl_io *xio;
12229         struct ctl_lun *lun;
12230         struct ctl_softc *softc;
12231 #if 0
12232         struct sbuf sb;
12233         char printbuf[128];
12234 #endif
12235         int found;
12236         uint32_t targ_lun;
12237
12238         softc = control_softc;
12239         found = 0;
12240
12241         /*
12242          * Look up the LUN.
12243          */
12244         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12245         mtx_lock(&softc->ctl_lock);
12246         if ((targ_lun < CTL_MAX_LUNS)
12247          && (softc->ctl_luns[targ_lun] != NULL))
12248                 lun = softc->ctl_luns[targ_lun];
12249         else {
12250                 mtx_unlock(&softc->ctl_lock);
12251                 return (1);
12252         }
12253
12254 #if 0
12255         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12256                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12257 #endif
12258
12259         mtx_lock(&lun->lun_lock);
12260         mtx_unlock(&softc->ctl_lock);
12261         /*
12262          * Run through the OOA queue and attempt to find the given I/O.
12263          * The target port, initiator ID, tag type and tag number have to
12264          * match the values that we got from the initiator.  If we have an
12265          * untagged command to abort, simply abort the first untagged command
12266          * we come to.  We only allow one untagged command at a time of course.
12267          */
12268 #if 0
12269         TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12270 #endif
12271         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12272              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12273 #if 0
12274                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12275
12276                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12277                             lun->lun, xio->scsiio.tag_num,
12278                             xio->scsiio.tag_type,
12279                             (xio->io_hdr.blocked_links.tqe_prev
12280                             == NULL) ? "" : " BLOCKED",
12281                             (xio->io_hdr.flags &
12282                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12283                             (xio->io_hdr.flags &
12284                             CTL_FLAG_ABORT) ? " ABORT" : "",
12285                             (xio->io_hdr.flags &
12286                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12287                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12288                 sbuf_finish(&sb);
12289                 printf("%s\n", sbuf_data(&sb));
12290 #endif
12291
12292                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12293                  || (xio->io_hdr.nexus.initid.id != io->io_hdr.nexus.initid.id)
12294                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12295                         continue;
12296
12297                 /*
12298                  * If the abort says that the task is untagged, the
12299                  * task in the queue must be untagged.  Otherwise,
12300                  * we just check to see whether the tag numbers
12301                  * match.  This is because the QLogic firmware
12302                  * doesn't pass back the tag type in an abort
12303                  * request.
12304                  */
12305 #if 0
12306                 if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12307                   && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12308                  || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12309 #endif
12310                 /*
12311                  * XXX KDM we've got problems with FC, because it
12312                  * doesn't send down a tag type with aborts.  So we
12313                  * can only really go by the tag number...
12314                  * This may cause problems with parallel SCSI.
12315                  * Need to figure that out!!
12316                  */
12317                 if (xio->scsiio.tag_num == io->taskio.tag_num) {
12318                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12319                         found = 1;
12320                         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12321                             !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12322                                 union ctl_ha_msg msg_info;
12323
12324                                 io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
12325                                 msg_info.hdr.nexus = io->io_hdr.nexus;
12326                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12327                                 msg_info.task.tag_num = io->taskio.tag_num;
12328                                 msg_info.task.tag_type = io->taskio.tag_type;
12329                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12330                                 msg_info.hdr.original_sc = NULL;
12331                                 msg_info.hdr.serializing_sc = NULL;
12332 #if 0
12333                                 printf("Sent Abort to other side\n");
12334 #endif
12335                                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12336                                     (void *)&msg_info, sizeof(msg_info), 0) !=
12337                                     CTL_HA_STATUS_SUCCESS) {
12338                                 }
12339                         }
12340 #if 0
12341                         printf("ctl_abort_task: found I/O to abort\n");
12342 #endif
12343                 }
12344         }
12345         mtx_unlock(&lun->lun_lock);
12346
12347         if (found == 0) {
12348                 /*
12349                  * This isn't really an error.  It's entirely possible for
12350                  * the abort and command completion to cross on the wire.
12351                  * This is more of an informative/diagnostic error.
12352                  */
12353 #if 0
12354                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12355                        "%d:%d:%d:%d tag %d type %d\n",
12356                        io->io_hdr.nexus.initid.id,
12357                        io->io_hdr.nexus.targ_port,
12358                        io->io_hdr.nexus.targ_target.id,
12359                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12360                        io->taskio.tag_type);
12361 #endif
12362         }
12363         return (0);
12364 }
12365
12366 static void
12367 ctl_run_task(union ctl_io *io)
12368 {
12369         struct ctl_softc *softc = control_softc;
12370         int retval = 1;
12371         const char *task_desc;
12372
12373         CTL_DEBUG_PRINT(("ctl_run_task\n"));
12374
12375         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12376             ("ctl_run_task: Unextected io_type %d\n",
12377              io->io_hdr.io_type));
12378
12379         task_desc = ctl_scsi_task_string(&io->taskio);
12380         if (task_desc != NULL) {
12381 #ifdef NEEDTOPORT
12382                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12383                             CTL_TASK_REPORT,
12384                             csevent_LogType_Trace,
12385                             csevent_Severity_Information,
12386                             csevent_AlertLevel_Green,
12387                             csevent_FRU_Firmware,
12388                             csevent_FRU_Unknown,
12389                             "CTL: received task: %s",task_desc);
12390 #endif
12391         } else {
12392 #ifdef NEEDTOPORT
12393                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12394                             CTL_TASK_REPORT,
12395                             csevent_LogType_Trace,
12396                             csevent_Severity_Information,
12397                             csevent_AlertLevel_Green,
12398                             csevent_FRU_Firmware,
12399                             csevent_FRU_Unknown,
12400                             "CTL: received unknown task "
12401                             "type: %d (%#x)",
12402                             io->taskio.task_action,
12403                             io->taskio.task_action);
12404 #endif
12405         }
12406         switch (io->taskio.task_action) {
12407         case CTL_TASK_ABORT_TASK:
12408                 retval = ctl_abort_task(io);
12409                 break;
12410         case CTL_TASK_ABORT_TASK_SET:
12411         case CTL_TASK_CLEAR_TASK_SET:
12412                 retval = ctl_abort_task_set(io);
12413                 break;
12414         case CTL_TASK_CLEAR_ACA:
12415                 break;
12416         case CTL_TASK_I_T_NEXUS_RESET:
12417                 retval = ctl_i_t_nexus_reset(io);
12418                 break;
12419         case CTL_TASK_LUN_RESET: {
12420                 struct ctl_lun *lun;
12421                 uint32_t targ_lun;
12422
12423                 targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12424                 mtx_lock(&softc->ctl_lock);
12425                 if ((targ_lun < CTL_MAX_LUNS)
12426                  && (softc->ctl_luns[targ_lun] != NULL))
12427                         lun = softc->ctl_luns[targ_lun];
12428                 else {
12429                         mtx_unlock(&softc->ctl_lock);
12430                         retval = 1;
12431                         break;
12432                 }
12433
12434                 if (!(io->io_hdr.flags &
12435                     CTL_FLAG_FROM_OTHER_SC)) {
12436                         union ctl_ha_msg msg_info;
12437
12438                         io->io_hdr.flags |=
12439                                 CTL_FLAG_SENT_2OTHER_SC;
12440                         msg_info.hdr.msg_type =
12441                                 CTL_MSG_MANAGE_TASKS;
12442                         msg_info.hdr.nexus = io->io_hdr.nexus;
12443                         msg_info.task.task_action =
12444                                 CTL_TASK_LUN_RESET;
12445                         msg_info.hdr.original_sc = NULL;
12446                         msg_info.hdr.serializing_sc = NULL;
12447                         if (CTL_HA_STATUS_SUCCESS !=
12448                             ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12449                             (void *)&msg_info,
12450                             sizeof(msg_info), 0)) {
12451                         }
12452                 }
12453
12454                 retval = ctl_lun_reset(lun, io,
12455                                        CTL_UA_LUN_RESET);
12456                 mtx_unlock(&softc->ctl_lock);
12457                 break;
12458         }
12459         case CTL_TASK_TARGET_RESET:
12460                 retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12461                 break;
12462         case CTL_TASK_BUS_RESET:
12463                 retval = ctl_bus_reset(softc, io);
12464                 break;
12465         case CTL_TASK_PORT_LOGIN:
12466                 break;
12467         case CTL_TASK_PORT_LOGOUT:
12468                 break;
12469         default:
12470                 printf("ctl_run_task: got unknown task management event %d\n",
12471                        io->taskio.task_action);
12472                 break;
12473         }
12474         if (retval == 0)
12475                 io->io_hdr.status = CTL_SUCCESS;
12476         else
12477                 io->io_hdr.status = CTL_ERROR;
12478         ctl_done(io);
12479 }
12480
12481 /*
12482  * For HA operation.  Handle commands that come in from the other
12483  * controller.
12484  */
12485 static void
12486 ctl_handle_isc(union ctl_io *io)
12487 {
12488         int free_io;
12489         struct ctl_lun *lun;
12490         struct ctl_softc *softc;
12491         uint32_t targ_lun;
12492
12493         softc = control_softc;
12494
12495         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12496         lun = softc->ctl_luns[targ_lun];
12497
12498         switch (io->io_hdr.msg_type) {
12499         case CTL_MSG_SERIALIZE:
12500                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12501                 break;
12502         case CTL_MSG_R2R: {
12503                 const struct ctl_cmd_entry *entry;
12504
12505                 /*
12506                  * This is only used in SER_ONLY mode.
12507                  */
12508                 free_io = 0;
12509                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12510                 mtx_lock(&lun->lun_lock);
12511                 if (ctl_scsiio_lun_check(lun,
12512                     entry, (struct ctl_scsiio *)io) != 0) {
12513                         mtx_unlock(&lun->lun_lock);
12514                         ctl_done(io);
12515                         break;
12516                 }
12517                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12518                 mtx_unlock(&lun->lun_lock);
12519                 ctl_enqueue_rtr(io);
12520                 break;
12521         }
12522         case CTL_MSG_FINISH_IO:
12523                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
12524                         free_io = 0;
12525                         ctl_done(io);
12526                 } else {
12527                         free_io = 1;
12528                         mtx_lock(&lun->lun_lock);
12529                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12530                                      ooa_links);
12531                         ctl_check_blocked(lun);
12532                         mtx_unlock(&lun->lun_lock);
12533                 }
12534                 break;
12535         case CTL_MSG_PERS_ACTION:
12536                 ctl_hndl_per_res_out_on_other_sc(
12537                         (union ctl_ha_msg *)&io->presio.pr_msg);
12538                 free_io = 1;
12539                 break;
12540         case CTL_MSG_BAD_JUJU:
12541                 free_io = 0;
12542                 ctl_done(io);
12543                 break;
12544         case CTL_MSG_DATAMOVE:
12545                 /* Only used in XFER mode */
12546                 free_io = 0;
12547                 ctl_datamove_remote(io);
12548                 break;
12549         case CTL_MSG_DATAMOVE_DONE:
12550                 /* Only used in XFER mode */
12551                 free_io = 0;
12552                 io->scsiio.be_move_done(io);
12553                 break;
12554         default:
12555                 free_io = 1;
12556                 printf("%s: Invalid message type %d\n",
12557                        __func__, io->io_hdr.msg_type);
12558                 break;
12559         }
12560         if (free_io)
12561                 ctl_free_io(io);
12562
12563 }
12564
12565
12566 /*
12567  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12568  * there is no match.
12569  */
12570 static ctl_lun_error_pattern
12571 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12572 {
12573         const struct ctl_cmd_entry *entry;
12574         ctl_lun_error_pattern filtered_pattern, pattern;
12575
12576         pattern = desc->error_pattern;
12577
12578         /*
12579          * XXX KDM we need more data passed into this function to match a
12580          * custom pattern, and we actually need to implement custom pattern
12581          * matching.
12582          */
12583         if (pattern & CTL_LUN_PAT_CMD)
12584                 return (CTL_LUN_PAT_CMD);
12585
12586         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12587                 return (CTL_LUN_PAT_ANY);
12588
12589         entry = ctl_get_cmd_entry(ctsio, NULL);
12590
12591         filtered_pattern = entry->pattern & pattern;
12592
12593         /*
12594          * If the user requested specific flags in the pattern (e.g.
12595          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12596          * flags.
12597          *
12598          * If the user did not specify any flags, it doesn't matter whether
12599          * or not the command supports the flags.
12600          */
12601         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12602              (pattern & ~CTL_LUN_PAT_MASK))
12603                 return (CTL_LUN_PAT_NONE);
12604
12605         /*
12606          * If the user asked for a range check, see if the requested LBA
12607          * range overlaps with this command's LBA range.
12608          */
12609         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12610                 uint64_t lba1;
12611                 uint64_t len1;
12612                 ctl_action action;
12613                 int retval;
12614
12615                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12616                 if (retval != 0)
12617                         return (CTL_LUN_PAT_NONE);
12618
12619                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12620                                               desc->lba_range.len, FALSE);
12621                 /*
12622                  * A "pass" means that the LBA ranges don't overlap, so
12623                  * this doesn't match the user's range criteria.
12624                  */
12625                 if (action == CTL_ACTION_PASS)
12626                         return (CTL_LUN_PAT_NONE);
12627         }
12628
12629         return (filtered_pattern);
12630 }
12631
12632 static void
12633 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12634 {
12635         struct ctl_error_desc *desc, *desc2;
12636
12637         mtx_assert(&lun->lun_lock, MA_OWNED);
12638
12639         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12640                 ctl_lun_error_pattern pattern;
12641                 /*
12642                  * Check to see whether this particular command matches
12643                  * the pattern in the descriptor.
12644                  */
12645                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12646                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12647                         continue;
12648
12649                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12650                 case CTL_LUN_INJ_ABORTED:
12651                         ctl_set_aborted(&io->scsiio);
12652                         break;
12653                 case CTL_LUN_INJ_MEDIUM_ERR:
12654                         ctl_set_medium_error(&io->scsiio);
12655                         break;
12656                 case CTL_LUN_INJ_UA:
12657                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12658                          * OCCURRED */
12659                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12660                         break;
12661                 case CTL_LUN_INJ_CUSTOM:
12662                         /*
12663                          * We're assuming the user knows what he is doing.
12664                          * Just copy the sense information without doing
12665                          * checks.
12666                          */
12667                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12668                               MIN(sizeof(desc->custom_sense),
12669                                   sizeof(io->scsiio.sense_data)));
12670                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12671                         io->scsiio.sense_len = SSD_FULL_SIZE;
12672                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12673                         break;
12674                 case CTL_LUN_INJ_NONE:
12675                 default:
12676                         /*
12677                          * If this is an error injection type we don't know
12678                          * about, clear the continuous flag (if it is set)
12679                          * so it will get deleted below.
12680                          */
12681                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12682                         break;
12683                 }
12684                 /*
12685                  * By default, each error injection action is a one-shot
12686                  */
12687                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12688                         continue;
12689
12690                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12691
12692                 free(desc, M_CTL);
12693         }
12694 }
12695
12696 #ifdef CTL_IO_DELAY
12697 static void
12698 ctl_datamove_timer_wakeup(void *arg)
12699 {
12700         union ctl_io *io;
12701
12702         io = (union ctl_io *)arg;
12703
12704         ctl_datamove(io);
12705 }
12706 #endif /* CTL_IO_DELAY */
12707
12708 void
12709 ctl_datamove(union ctl_io *io)
12710 {
12711         void (*fe_datamove)(union ctl_io *io);
12712
12713         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12714
12715         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12716
12717 #ifdef CTL_TIME_IO
12718         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12719                 char str[256];
12720                 char path_str[64];
12721                 struct sbuf sb;
12722
12723                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12724                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12725
12726                 sbuf_cat(&sb, path_str);
12727                 switch (io->io_hdr.io_type) {
12728                 case CTL_IO_SCSI:
12729                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12730                         sbuf_printf(&sb, "\n");
12731                         sbuf_cat(&sb, path_str);
12732                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12733                                     io->scsiio.tag_num, io->scsiio.tag_type);
12734                         break;
12735                 case CTL_IO_TASK:
12736                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12737                                     "Tag Type: %d\n", io->taskio.task_action,
12738                                     io->taskio.tag_num, io->taskio.tag_type);
12739                         break;
12740                 default:
12741                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12742                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12743                         break;
12744                 }
12745                 sbuf_cat(&sb, path_str);
12746                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12747                             (intmax_t)time_uptime - io->io_hdr.start_time);
12748                 sbuf_finish(&sb);
12749                 printf("%s", sbuf_data(&sb));
12750         }
12751 #endif /* CTL_TIME_IO */
12752
12753 #ifdef CTL_IO_DELAY
12754         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12755                 struct ctl_lun *lun;
12756
12757                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12758
12759                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12760         } else {
12761                 struct ctl_lun *lun;
12762
12763                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12764                 if ((lun != NULL)
12765                  && (lun->delay_info.datamove_delay > 0)) {
12766                         struct callout *callout;
12767
12768                         callout = (struct callout *)&io->io_hdr.timer_bytes;
12769                         callout_init(callout, /*mpsafe*/ 1);
12770                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12771                         callout_reset(callout,
12772                                       lun->delay_info.datamove_delay * hz,
12773                                       ctl_datamove_timer_wakeup, io);
12774                         if (lun->delay_info.datamove_type ==
12775                             CTL_DELAY_TYPE_ONESHOT)
12776                                 lun->delay_info.datamove_delay = 0;
12777                         return;
12778                 }
12779         }
12780 #endif
12781
12782         /*
12783          * This command has been aborted.  Set the port status, so we fail
12784          * the data move.
12785          */
12786         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12787                 printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12788                        io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12789                        io->io_hdr.nexus.targ_port,
12790                        (uintmax_t)io->io_hdr.nexus.targ_target.id,
12791                        io->io_hdr.nexus.targ_lun);
12792                 io->io_hdr.port_status = 31337;
12793                 /*
12794                  * Note that the backend, in this case, will get the
12795                  * callback in its context.  In other cases it may get
12796                  * called in the frontend's interrupt thread context.
12797                  */
12798                 io->scsiio.be_move_done(io);
12799                 return;
12800         }
12801
12802         /* Don't confuse frontend with zero length data move. */
12803         if (io->scsiio.kern_data_len == 0) {
12804                 io->scsiio.be_move_done(io);
12805                 return;
12806         }
12807
12808         /*
12809          * If we're in XFER mode and this I/O is from the other shelf
12810          * controller, we need to send the DMA to the other side to
12811          * actually transfer the data to/from the host.  In serialize only
12812          * mode the transfer happens below CTL and ctl_datamove() is only
12813          * called on the machine that originally received the I/O.
12814          */
12815         if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12816          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12817                 union ctl_ha_msg msg;
12818                 uint32_t sg_entries_sent;
12819                 int do_sg_copy;
12820                 int i;
12821
12822                 memset(&msg, 0, sizeof(msg));
12823                 msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12824                 msg.hdr.original_sc = io->io_hdr.original_sc;
12825                 msg.hdr.serializing_sc = io;
12826                 msg.hdr.nexus = io->io_hdr.nexus;
12827                 msg.dt.flags = io->io_hdr.flags;
12828                 /*
12829                  * We convert everything into a S/G list here.  We can't
12830                  * pass by reference, only by value between controllers.
12831                  * So we can't pass a pointer to the S/G list, only as many
12832                  * S/G entries as we can fit in here.  If it's possible for
12833                  * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12834                  * then we need to break this up into multiple transfers.
12835                  */
12836                 if (io->scsiio.kern_sg_entries == 0) {
12837                         msg.dt.kern_sg_entries = 1;
12838                         /*
12839                          * If this is in cached memory, flush the cache
12840                          * before we send the DMA request to the other
12841                          * controller.  We want to do this in either the
12842                          * read or the write case.  The read case is
12843                          * straightforward.  In the write case, we want to
12844                          * make sure nothing is in the local cache that
12845                          * could overwrite the DMAed data.
12846                          */
12847                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12848                                 /*
12849                                  * XXX KDM use bus_dmamap_sync() here.
12850                                  */
12851                         }
12852
12853                         /*
12854                          * Convert to a physical address if this is a
12855                          * virtual address.
12856                          */
12857                         if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12858                                 msg.dt.sg_list[0].addr =
12859                                         io->scsiio.kern_data_ptr;
12860                         } else {
12861                                 /*
12862                                  * XXX KDM use busdma here!
12863                                  */
12864 #if 0
12865                                 msg.dt.sg_list[0].addr = (void *)
12866                                         vtophys(io->scsiio.kern_data_ptr);
12867 #endif
12868                         }
12869
12870                         msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12871                         do_sg_copy = 0;
12872                 } else {
12873                         struct ctl_sg_entry *sgl;
12874
12875                         do_sg_copy = 1;
12876                         msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12877                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12878                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12879                                 /*
12880                                  * XXX KDM use bus_dmamap_sync() here.
12881                                  */
12882                         }
12883                 }
12884
12885                 msg.dt.kern_data_len = io->scsiio.kern_data_len;
12886                 msg.dt.kern_total_len = io->scsiio.kern_total_len;
12887                 msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12888                 msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12889                 msg.dt.sg_sequence = 0;
12890
12891                 /*
12892                  * Loop until we've sent all of the S/G entries.  On the
12893                  * other end, we'll recompose these S/G entries into one
12894                  * contiguous list before passing it to the
12895                  */
12896                 for (sg_entries_sent = 0; sg_entries_sent <
12897                      msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12898                         msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list)/
12899                                 sizeof(msg.dt.sg_list[0])),
12900                                 msg.dt.kern_sg_entries - sg_entries_sent);
12901
12902                         if (do_sg_copy != 0) {
12903                                 struct ctl_sg_entry *sgl;
12904                                 int j;
12905
12906                                 sgl = (struct ctl_sg_entry *)
12907                                         io->scsiio.kern_data_ptr;
12908                                 /*
12909                                  * If this is in cached memory, flush the cache
12910                                  * before we send the DMA request to the other
12911                                  * controller.  We want to do this in either
12912                                  * the * read or the write case.  The read
12913                                  * case is straightforward.  In the write
12914                                  * case, we want to make sure nothing is
12915                                  * in the local cache that could overwrite
12916                                  * the DMAed data.
12917                                  */
12918
12919                                 for (i = sg_entries_sent, j = 0;
12920                                      i < msg.dt.cur_sg_entries; i++, j++) {
12921                                         if ((io->io_hdr.flags &
12922                                              CTL_FLAG_NO_DATASYNC) == 0) {
12923                                                 /*
12924                                                  * XXX KDM use bus_dmamap_sync()
12925                                                  */
12926                                         }
12927                                         if ((io->io_hdr.flags &
12928                                              CTL_FLAG_BUS_ADDR) == 0) {
12929                                                 /*
12930                                                  * XXX KDM use busdma.
12931                                                  */
12932 #if 0
12933                                                 msg.dt.sg_list[j].addr =(void *)
12934                                                        vtophys(sgl[i].addr);
12935 #endif
12936                                         } else {
12937                                                 msg.dt.sg_list[j].addr =
12938                                                         sgl[i].addr;
12939                                         }
12940                                         msg.dt.sg_list[j].len = sgl[i].len;
12941                                 }
12942                         }
12943
12944                         sg_entries_sent += msg.dt.cur_sg_entries;
12945                         if (sg_entries_sent >= msg.dt.kern_sg_entries)
12946                                 msg.dt.sg_last = 1;
12947                         else
12948                                 msg.dt.sg_last = 0;
12949
12950                         /*
12951                          * XXX KDM drop and reacquire the lock here?
12952                          */
12953                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12954                             sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12955                                 /*
12956                                  * XXX do something here.
12957                                  */
12958                         }
12959
12960                         msg.dt.sent_sg_entries = sg_entries_sent;
12961                 }
12962                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12963                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12964                         ctl_failover_io(io, /*have_lock*/ 0);
12965
12966         } else {
12967
12968                 /*
12969                  * Lookup the fe_datamove() function for this particular
12970                  * front end.
12971                  */
12972                 fe_datamove =
12973                     control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12974
12975                 fe_datamove(io);
12976         }
12977 }
12978
12979 static void
12980 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12981 {
12982         union ctl_ha_msg msg;
12983         int isc_status;
12984
12985         memset(&msg, 0, sizeof(msg));
12986
12987         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12988         msg.hdr.original_sc = io;
12989         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12990         msg.hdr.nexus = io->io_hdr.nexus;
12991         msg.hdr.status = io->io_hdr.status;
12992         msg.scsi.tag_num = io->scsiio.tag_num;
12993         msg.scsi.tag_type = io->scsiio.tag_type;
12994         msg.scsi.scsi_status = io->scsiio.scsi_status;
12995         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12996                sizeof(io->scsiio.sense_data));
12997         msg.scsi.sense_len = io->scsiio.sense_len;
12998         msg.scsi.sense_residual = io->scsiio.sense_residual;
12999         msg.scsi.fetd_status = io->io_hdr.port_status;
13000         msg.scsi.residual = io->scsiio.residual;
13001         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13002
13003         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13004                 ctl_failover_io(io, /*have_lock*/ have_lock);
13005                 return;
13006         }
13007
13008         isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
13009         if (isc_status > CTL_HA_STATUS_SUCCESS) {
13010                 /* XXX do something if this fails */
13011         }
13012
13013 }
13014
13015 /*
13016  * The DMA to the remote side is done, now we need to tell the other side
13017  * we're done so it can continue with its data movement.
13018  */
13019 static void
13020 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
13021 {
13022         union ctl_io *io;
13023
13024         io = rq->context;
13025
13026         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13027                 printf("%s: ISC DMA write failed with error %d", __func__,
13028                        rq->ret);
13029                 ctl_set_internal_failure(&io->scsiio,
13030                                          /*sks_valid*/ 1,
13031                                          /*retry_count*/ rq->ret);
13032         }
13033
13034         ctl_dt_req_free(rq);
13035
13036         /*
13037          * In this case, we had to malloc the memory locally.  Free it.
13038          */
13039         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13040                 int i;
13041                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13042                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13043         }
13044         /*
13045          * The data is in local and remote memory, so now we need to send
13046          * status (good or back) back to the other side.
13047          */
13048         ctl_send_datamove_done(io, /*have_lock*/ 0);
13049 }
13050
13051 /*
13052  * We've moved the data from the host/controller into local memory.  Now we
13053  * need to push it over to the remote controller's memory.
13054  */
13055 static int
13056 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
13057 {
13058         int retval;
13059
13060         retval = 0;
13061
13062         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
13063                                           ctl_datamove_remote_write_cb);
13064
13065         return (retval);
13066 }
13067
13068 static void
13069 ctl_datamove_remote_write(union ctl_io *io)
13070 {
13071         int retval;
13072         void (*fe_datamove)(union ctl_io *io);
13073
13074         /*
13075          * - Get the data from the host/HBA into local memory.
13076          * - DMA memory from the local controller to the remote controller.
13077          * - Send status back to the remote controller.
13078          */
13079
13080         retval = ctl_datamove_remote_sgl_setup(io);
13081         if (retval != 0)
13082                 return;
13083
13084         /* Switch the pointer over so the FETD knows what to do */
13085         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13086
13087         /*
13088          * Use a custom move done callback, since we need to send completion
13089          * back to the other controller, not to the backend on this side.
13090          */
13091         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
13092
13093         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13094
13095         fe_datamove(io);
13096
13097         return;
13098
13099 }
13100
13101 static int
13102 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
13103 {
13104 #if 0
13105         char str[256];
13106         char path_str[64];
13107         struct sbuf sb;
13108 #endif
13109
13110         /*
13111          * In this case, we had to malloc the memory locally.  Free it.
13112          */
13113         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13114                 int i;
13115                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13116                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13117         }
13118
13119 #if 0
13120         scsi_path_string(io, path_str, sizeof(path_str));
13121         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13122         sbuf_cat(&sb, path_str);
13123         scsi_command_string(&io->scsiio, NULL, &sb);
13124         sbuf_printf(&sb, "\n");
13125         sbuf_cat(&sb, path_str);
13126         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13127                     io->scsiio.tag_num, io->scsiio.tag_type);
13128         sbuf_cat(&sb, path_str);
13129         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
13130                     io->io_hdr.flags, io->io_hdr.status);
13131         sbuf_finish(&sb);
13132         printk("%s", sbuf_data(&sb));
13133 #endif
13134
13135
13136         /*
13137          * The read is done, now we need to send status (good or bad) back
13138          * to the other side.
13139          */
13140         ctl_send_datamove_done(io, /*have_lock*/ 0);
13141
13142         return (0);
13143 }
13144
13145 static void
13146 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
13147 {
13148         union ctl_io *io;
13149         void (*fe_datamove)(union ctl_io *io);
13150
13151         io = rq->context;
13152
13153         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13154                 printf("%s: ISC DMA read failed with error %d", __func__,
13155                        rq->ret);
13156                 ctl_set_internal_failure(&io->scsiio,
13157                                          /*sks_valid*/ 1,
13158                                          /*retry_count*/ rq->ret);
13159         }
13160
13161         ctl_dt_req_free(rq);
13162
13163         /* Switch the pointer over so the FETD knows what to do */
13164         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13165
13166         /*
13167          * Use a custom move done callback, since we need to send completion
13168          * back to the other controller, not to the backend on this side.
13169          */
13170         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13171
13172         /* XXX KDM add checks like the ones in ctl_datamove? */
13173
13174         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13175
13176         fe_datamove(io);
13177 }
13178
13179 static int
13180 ctl_datamove_remote_sgl_setup(union ctl_io *io)
13181 {
13182         struct ctl_sg_entry *local_sglist, *remote_sglist;
13183         struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13184         struct ctl_softc *softc;
13185         int retval;
13186         int i;
13187
13188         retval = 0;
13189         softc = control_softc;
13190
13191         local_sglist = io->io_hdr.local_sglist;
13192         local_dma_sglist = io->io_hdr.local_dma_sglist;
13193         remote_sglist = io->io_hdr.remote_sglist;
13194         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13195
13196         if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13197                 for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13198                         local_sglist[i].len = remote_sglist[i].len;
13199
13200                         /*
13201                          * XXX Detect the situation where the RS-level I/O
13202                          * redirector on the other side has already read the
13203                          * data off of the AOR RS on this side, and
13204                          * transferred it to remote (mirror) memory on the
13205                          * other side.  Since we already have the data in
13206                          * memory here, we just need to use it.
13207                          *
13208                          * XXX KDM this can probably be removed once we
13209                          * get the cache device code in and take the
13210                          * current AOR implementation out.
13211                          */
13212 #ifdef NEEDTOPORT
13213                         if ((remote_sglist[i].addr >=
13214                              (void *)vtophys(softc->mirr->addr))
13215                          && (remote_sglist[i].addr <
13216                              ((void *)vtophys(softc->mirr->addr) +
13217                              CacheMirrorOffset))) {
13218                                 local_sglist[i].addr = remote_sglist[i].addr -
13219                                         CacheMirrorOffset;
13220                                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13221                                      CTL_FLAG_DATA_IN)
13222                                         io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13223                         } else {
13224                                 local_sglist[i].addr = remote_sglist[i].addr +
13225                                         CacheMirrorOffset;
13226                         }
13227 #endif
13228 #if 0
13229                         printf("%s: local %p, remote %p, len %d\n",
13230                                __func__, local_sglist[i].addr,
13231                                remote_sglist[i].addr, local_sglist[i].len);
13232 #endif
13233                 }
13234         } else {
13235                 uint32_t len_to_go;
13236
13237                 /*
13238                  * In this case, we don't have automatically allocated
13239                  * memory for this I/O on this controller.  This typically
13240                  * happens with internal CTL I/O -- e.g. inquiry, mode
13241                  * sense, etc.  Anything coming from RAIDCore will have
13242                  * a mirror area available.
13243                  */
13244                 len_to_go = io->scsiio.kern_data_len;
13245
13246                 /*
13247                  * Clear the no datasync flag, we have to use malloced
13248                  * buffers.
13249                  */
13250                 io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13251
13252                 /*
13253                  * The difficult thing here is that the size of the various
13254                  * S/G segments may be different than the size from the
13255                  * remote controller.  That'll make it harder when DMAing
13256                  * the data back to the other side.
13257                  */
13258                 for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13259                      sizeof(io->io_hdr.remote_sglist[0])) &&
13260                      (len_to_go > 0); i++) {
13261                         local_sglist[i].len = MIN(len_to_go, 131072);
13262                         CTL_SIZE_8B(local_dma_sglist[i].len,
13263                                     local_sglist[i].len);
13264                         local_sglist[i].addr =
13265                                 malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13266
13267                         local_dma_sglist[i].addr = local_sglist[i].addr;
13268
13269                         if (local_sglist[i].addr == NULL) {
13270                                 int j;
13271
13272                                 printf("malloc failed for %zd bytes!",
13273                                        local_dma_sglist[i].len);
13274                                 for (j = 0; j < i; j++) {
13275                                         free(local_sglist[j].addr, M_CTL);
13276                                 }
13277                                 ctl_set_internal_failure(&io->scsiio,
13278                                                          /*sks_valid*/ 1,
13279                                                          /*retry_count*/ 4857);
13280                                 retval = 1;
13281                                 goto bailout_error;
13282                                 
13283                         }
13284                         /* XXX KDM do we need a sync here? */
13285
13286                         len_to_go -= local_sglist[i].len;
13287                 }
13288                 /*
13289                  * Reset the number of S/G entries accordingly.  The
13290                  * original number of S/G entries is available in
13291                  * rem_sg_entries.
13292                  */
13293                 io->scsiio.kern_sg_entries = i;
13294
13295 #if 0
13296                 printf("%s: kern_sg_entries = %d\n", __func__,
13297                        io->scsiio.kern_sg_entries);
13298                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13299                         printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13300                                local_sglist[i].addr, local_sglist[i].len,
13301                                local_dma_sglist[i].len);
13302 #endif
13303         }
13304
13305
13306         return (retval);
13307
13308 bailout_error:
13309
13310         ctl_send_datamove_done(io, /*have_lock*/ 0);
13311
13312         return (retval);
13313 }
13314
13315 static int
13316 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13317                          ctl_ha_dt_cb callback)
13318 {
13319         struct ctl_ha_dt_req *rq;
13320         struct ctl_sg_entry *remote_sglist, *local_sglist;
13321         struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13322         uint32_t local_used, remote_used, total_used;
13323         int retval;
13324         int i, j;
13325
13326         retval = 0;
13327
13328         rq = ctl_dt_req_alloc();
13329
13330         /*
13331          * If we failed to allocate the request, and if the DMA didn't fail
13332          * anyway, set busy status.  This is just a resource allocation
13333          * failure.
13334          */
13335         if ((rq == NULL)
13336          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13337                 ctl_set_busy(&io->scsiio);
13338
13339         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13340
13341                 if (rq != NULL)
13342                         ctl_dt_req_free(rq);
13343
13344                 /*
13345                  * The data move failed.  We need to return status back
13346                  * to the other controller.  No point in trying to DMA
13347                  * data to the remote controller.
13348                  */
13349
13350                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13351
13352                 retval = 1;
13353
13354                 goto bailout;
13355         }
13356
13357         local_sglist = io->io_hdr.local_sglist;
13358         local_dma_sglist = io->io_hdr.local_dma_sglist;
13359         remote_sglist = io->io_hdr.remote_sglist;
13360         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13361         local_used = 0;
13362         remote_used = 0;
13363         total_used = 0;
13364
13365         if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13366                 rq->ret = CTL_HA_STATUS_SUCCESS;
13367                 rq->context = io;
13368                 callback(rq);
13369                 goto bailout;
13370         }
13371
13372         /*
13373          * Pull/push the data over the wire from/to the other controller.
13374          * This takes into account the possibility that the local and
13375          * remote sglists may not be identical in terms of the size of
13376          * the elements and the number of elements.
13377          *
13378          * One fundamental assumption here is that the length allocated for
13379          * both the local and remote sglists is identical.  Otherwise, we've
13380          * essentially got a coding error of some sort.
13381          */
13382         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13383                 int isc_ret;
13384                 uint32_t cur_len, dma_length;
13385                 uint8_t *tmp_ptr;
13386
13387                 rq->id = CTL_HA_DATA_CTL;
13388                 rq->command = command;
13389                 rq->context = io;
13390
13391                 /*
13392                  * Both pointers should be aligned.  But it is possible
13393                  * that the allocation length is not.  They should both
13394                  * also have enough slack left over at the end, though,
13395                  * to round up to the next 8 byte boundary.
13396                  */
13397                 cur_len = MIN(local_sglist[i].len - local_used,
13398                               remote_sglist[j].len - remote_used);
13399
13400                 /*
13401                  * In this case, we have a size issue and need to decrease
13402                  * the size, except in the case where we actually have less
13403                  * than 8 bytes left.  In that case, we need to increase
13404                  * the DMA length to get the last bit.
13405                  */
13406                 if ((cur_len & 0x7) != 0) {
13407                         if (cur_len > 0x7) {
13408                                 cur_len = cur_len - (cur_len & 0x7);
13409                                 dma_length = cur_len;
13410                         } else {
13411                                 CTL_SIZE_8B(dma_length, cur_len);
13412                         }
13413
13414                 } else
13415                         dma_length = cur_len;
13416
13417                 /*
13418                  * If we had to allocate memory for this I/O, instead of using
13419                  * the non-cached mirror memory, we'll need to flush the cache
13420                  * before trying to DMA to the other controller.
13421                  *
13422                  * We could end up doing this multiple times for the same
13423                  * segment if we have a larger local segment than remote
13424                  * segment.  That shouldn't be an issue.
13425                  */
13426                 if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13427                         /*
13428                          * XXX KDM use bus_dmamap_sync() here.
13429                          */
13430                 }
13431
13432                 rq->size = dma_length;
13433
13434                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
13435                 tmp_ptr += local_used;
13436
13437                 /* Use physical addresses when talking to ISC hardware */
13438                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13439                         /* XXX KDM use busdma */
13440 #if 0
13441                         rq->local = vtophys(tmp_ptr);
13442 #endif
13443                 } else
13444                         rq->local = tmp_ptr;
13445
13446                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13447                 tmp_ptr += remote_used;
13448                 rq->remote = tmp_ptr;
13449
13450                 rq->callback = NULL;
13451
13452                 local_used += cur_len;
13453                 if (local_used >= local_sglist[i].len) {
13454                         i++;
13455                         local_used = 0;
13456                 }
13457
13458                 remote_used += cur_len;
13459                 if (remote_used >= remote_sglist[j].len) {
13460                         j++;
13461                         remote_used = 0;
13462                 }
13463                 total_used += cur_len;
13464
13465                 if (total_used >= io->scsiio.kern_data_len)
13466                         rq->callback = callback;
13467
13468                 if ((rq->size & 0x7) != 0) {
13469                         printf("%s: warning: size %d is not on 8b boundary\n",
13470                                __func__, rq->size);
13471                 }
13472                 if (((uintptr_t)rq->local & 0x7) != 0) {
13473                         printf("%s: warning: local %p not on 8b boundary\n",
13474                                __func__, rq->local);
13475                 }
13476                 if (((uintptr_t)rq->remote & 0x7) != 0) {
13477                         printf("%s: warning: remote %p not on 8b boundary\n",
13478                                __func__, rq->local);
13479                 }
13480 #if 0
13481                 printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13482                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13483                        rq->local, rq->remote, rq->size);
13484 #endif
13485
13486                 isc_ret = ctl_dt_single(rq);
13487                 if (isc_ret == CTL_HA_STATUS_WAIT)
13488                         continue;
13489
13490                 if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13491                         rq->ret = CTL_HA_STATUS_SUCCESS;
13492                 } else {
13493                         rq->ret = isc_ret;
13494                 }
13495                 callback(rq);
13496                 goto bailout;
13497         }
13498
13499 bailout:
13500         return (retval);
13501
13502 }
13503
13504 static void
13505 ctl_datamove_remote_read(union ctl_io *io)
13506 {
13507         int retval;
13508         int i;
13509
13510         /*
13511          * This will send an error to the other controller in the case of a
13512          * failure.
13513          */
13514         retval = ctl_datamove_remote_sgl_setup(io);
13515         if (retval != 0)
13516                 return;
13517
13518         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13519                                           ctl_datamove_remote_read_cb);
13520         if ((retval != 0)
13521          && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13522                 /*
13523                  * Make sure we free memory if there was an error..  The
13524                  * ctl_datamove_remote_xfer() function will send the
13525                  * datamove done message, or call the callback with an
13526                  * error if there is a problem.
13527                  */
13528                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13529                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13530         }
13531
13532         return;
13533 }
13534
13535 /*
13536  * Process a datamove request from the other controller.  This is used for
13537  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13538  * first.  Once that is complete, the data gets DMAed into the remote
13539  * controller's memory.  For reads, we DMA from the remote controller's
13540  * memory into our memory first, and then move it out to the FETD.
13541  */
13542 static void
13543 ctl_datamove_remote(union ctl_io *io)
13544 {
13545         struct ctl_softc *softc;
13546
13547         softc = control_softc;
13548
13549         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13550
13551         /*
13552          * Note that we look for an aborted I/O here, but don't do some of
13553          * the other checks that ctl_datamove() normally does.
13554          * We don't need to run the datamove delay code, since that should
13555          * have been done if need be on the other controller.
13556          */
13557         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13558                 printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13559                        io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13560                        io->io_hdr.nexus.targ_port,
13561                        io->io_hdr.nexus.targ_target.id,
13562                        io->io_hdr.nexus.targ_lun);
13563                 io->io_hdr.port_status = 31338;
13564                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13565                 return;
13566         }
13567
13568         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13569                 ctl_datamove_remote_write(io);
13570         } else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13571                 ctl_datamove_remote_read(io);
13572         } else {
13573                 union ctl_ha_msg msg;
13574                 struct scsi_sense_data *sense;
13575                 uint8_t sks[3];
13576                 int retry_count;
13577
13578                 memset(&msg, 0, sizeof(msg));
13579
13580                 msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13581                 msg.hdr.status = CTL_SCSI_ERROR;
13582                 msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13583
13584                 retry_count = 4243;
13585
13586                 sense = &msg.scsi.sense_data;
13587                 sks[0] = SSD_SCS_VALID;
13588                 sks[1] = (retry_count >> 8) & 0xff;
13589                 sks[2] = retry_count & 0xff;
13590
13591                 /* "Internal target failure" */
13592                 scsi_set_sense_data(sense,
13593                                     /*sense_format*/ SSD_TYPE_NONE,
13594                                     /*current_error*/ 1,
13595                                     /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13596                                     /*asc*/ 0x44,
13597                                     /*ascq*/ 0x00,
13598                                     /*type*/ SSD_ELEM_SKS,
13599                                     /*size*/ sizeof(sks),
13600                                     /*data*/ sks,
13601                                     SSD_ELEM_NONE);
13602
13603                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13604                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13605                         ctl_failover_io(io, /*have_lock*/ 1);
13606                         return;
13607                 }
13608
13609                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13610                     CTL_HA_STATUS_SUCCESS) {
13611                         /* XXX KDM what to do if this fails? */
13612                 }
13613                 return;
13614         }
13615         
13616 }
13617
13618 static int
13619 ctl_process_done(union ctl_io *io)
13620 {
13621         struct ctl_lun *lun;
13622         struct ctl_softc *softc = control_softc;
13623         void (*fe_done)(union ctl_io *io);
13624         uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13625
13626         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13627
13628         fe_done = softc->ctl_ports[targ_port]->fe_done;
13629
13630 #ifdef CTL_TIME_IO
13631         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13632                 char str[256];
13633                 char path_str[64];
13634                 struct sbuf sb;
13635
13636                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13637                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13638
13639                 sbuf_cat(&sb, path_str);
13640                 switch (io->io_hdr.io_type) {
13641                 case CTL_IO_SCSI:
13642                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13643                         sbuf_printf(&sb, "\n");
13644                         sbuf_cat(&sb, path_str);
13645                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13646                                     io->scsiio.tag_num, io->scsiio.tag_type);
13647                         break;
13648                 case CTL_IO_TASK:
13649                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13650                                     "Tag Type: %d\n", io->taskio.task_action,
13651                                     io->taskio.tag_num, io->taskio.tag_type);
13652                         break;
13653                 default:
13654                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13655                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13656                         break;
13657                 }
13658                 sbuf_cat(&sb, path_str);
13659                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13660                             (intmax_t)time_uptime - io->io_hdr.start_time);
13661                 sbuf_finish(&sb);
13662                 printf("%s", sbuf_data(&sb));
13663         }
13664 #endif /* CTL_TIME_IO */
13665
13666         switch (io->io_hdr.io_type) {
13667         case CTL_IO_SCSI:
13668                 break;
13669         case CTL_IO_TASK:
13670                 if (bootverbose || (ctl_debug & CTL_DEBUG_INFO))
13671                         ctl_io_error_print(io, NULL);
13672                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13673                         ctl_free_io(io);
13674                 else
13675                         fe_done(io);
13676                 return (CTL_RETVAL_COMPLETE);
13677         default:
13678                 panic("ctl_process_done: invalid io type %d\n",
13679                       io->io_hdr.io_type);
13680                 break; /* NOTREACHED */
13681         }
13682
13683         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13684         if (lun == NULL) {
13685                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13686                                  io->io_hdr.nexus.targ_mapped_lun));
13687                 goto bailout;
13688         }
13689
13690         mtx_lock(&lun->lun_lock);
13691
13692         /*
13693          * Check to see if we have any errors to inject here.  We only
13694          * inject errors for commands that don't already have errors set.
13695          */
13696         if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13697             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13698             ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13699                 ctl_inject_error(lun, io);
13700
13701         /*
13702          * XXX KDM how do we treat commands that aren't completed
13703          * successfully?
13704          *
13705          * XXX KDM should we also track I/O latency?
13706          */
13707         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13708             io->io_hdr.io_type == CTL_IO_SCSI) {
13709 #ifdef CTL_TIME_IO
13710                 struct bintime cur_bt;
13711 #endif
13712                 int type;
13713
13714                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13715                     CTL_FLAG_DATA_IN)
13716                         type = CTL_STATS_READ;
13717                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13718                     CTL_FLAG_DATA_OUT)
13719                         type = CTL_STATS_WRITE;
13720                 else
13721                         type = CTL_STATS_NO_IO;
13722
13723                 lun->stats.ports[targ_port].bytes[type] +=
13724                     io->scsiio.kern_total_len;
13725                 lun->stats.ports[targ_port].operations[type]++;
13726 #ifdef CTL_TIME_IO
13727                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13728                    &io->io_hdr.dma_bt);
13729                 lun->stats.ports[targ_port].num_dmas[type] +=
13730                     io->io_hdr.num_dmas;
13731                 getbintime(&cur_bt);
13732                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13733                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13734 #endif
13735         }
13736
13737         /*
13738          * Remove this from the OOA queue.
13739          */
13740         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13741
13742         /*
13743          * Run through the blocked queue on this LUN and see if anything
13744          * has become unblocked, now that this transaction is done.
13745          */
13746         ctl_check_blocked(lun);
13747
13748         /*
13749          * If the LUN has been invalidated, free it if there is nothing
13750          * left on its OOA queue.
13751          */
13752         if ((lun->flags & CTL_LUN_INVALID)
13753          && TAILQ_EMPTY(&lun->ooa_queue)) {
13754                 mtx_unlock(&lun->lun_lock);
13755                 mtx_lock(&softc->ctl_lock);
13756                 ctl_free_lun(lun);
13757                 mtx_unlock(&softc->ctl_lock);
13758         } else
13759                 mtx_unlock(&lun->lun_lock);
13760
13761 bailout:
13762
13763         /*
13764          * If this command has been aborted, make sure we set the status
13765          * properly.  The FETD is responsible for freeing the I/O and doing
13766          * whatever it needs to do to clean up its state.
13767          */
13768         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13769                 ctl_set_task_aborted(&io->scsiio);
13770
13771         /*
13772          * If enabled, print command error status.
13773          * We don't print UAs unless debugging was enabled explicitly.
13774          */
13775         do {
13776                 if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)
13777                         break;
13778                 if (!bootverbose && (ctl_debug & CTL_DEBUG_INFO) == 0)
13779                         break;
13780                 if ((ctl_debug & CTL_DEBUG_INFO) == 0 &&
13781                     ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR) &&
13782                      (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13783                         int error_code, sense_key, asc, ascq;
13784
13785                         scsi_extract_sense_len(&io->scsiio.sense_data,
13786                             io->scsiio.sense_len, &error_code, &sense_key,
13787                             &asc, &ascq, /*show_errors*/ 0);
13788                         if (sense_key == SSD_KEY_UNIT_ATTENTION)
13789                                 break;
13790                 }
13791
13792                 ctl_io_error_print(io, NULL);
13793         } while (0);
13794
13795         /*
13796          * Tell the FETD or the other shelf controller we're done with this
13797          * command.  Note that only SCSI commands get to this point.  Task
13798          * management commands are completed above.
13799          *
13800          * We only send status to the other controller if we're in XFER
13801          * mode.  In SER_ONLY mode, the I/O is done on the controller that
13802          * received the I/O (from CTL's perspective), and so the status is
13803          * generated there.
13804          * 
13805          * XXX KDM if we hold the lock here, we could cause a deadlock
13806          * if the frontend comes back in in this context to queue
13807          * something.
13808          */
13809         if ((softc->ha_mode == CTL_HA_MODE_XFER)
13810          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13811                 union ctl_ha_msg msg;
13812
13813                 memset(&msg, 0, sizeof(msg));
13814                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13815                 msg.hdr.original_sc = io->io_hdr.original_sc;
13816                 msg.hdr.nexus = io->io_hdr.nexus;
13817                 msg.hdr.status = io->io_hdr.status;
13818                 msg.scsi.scsi_status = io->scsiio.scsi_status;
13819                 msg.scsi.tag_num = io->scsiio.tag_num;
13820                 msg.scsi.tag_type = io->scsiio.tag_type;
13821                 msg.scsi.sense_len = io->scsiio.sense_len;
13822                 msg.scsi.sense_residual = io->scsiio.sense_residual;
13823                 msg.scsi.residual = io->scsiio.residual;
13824                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13825                        sizeof(io->scsiio.sense_data));
13826                 /*
13827                  * We copy this whether or not this is an I/O-related
13828                  * command.  Otherwise, we'd have to go and check to see
13829                  * whether it's a read/write command, and it really isn't
13830                  * worth it.
13831                  */
13832                 memcpy(&msg.scsi.lbalen,
13833                        &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13834                        sizeof(msg.scsi.lbalen));
13835
13836                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13837                                 sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13838                         /* XXX do something here */
13839                 }
13840
13841                 ctl_free_io(io);
13842         } else 
13843                 fe_done(io);
13844
13845         return (CTL_RETVAL_COMPLETE);
13846 }
13847
13848 #ifdef CTL_WITH_CA
13849 /*
13850  * Front end should call this if it doesn't do autosense.  When the request
13851  * sense comes back in from the initiator, we'll dequeue this and send it.
13852  */
13853 int
13854 ctl_queue_sense(union ctl_io *io)
13855 {
13856         struct ctl_lun *lun;
13857         struct ctl_port *port;
13858         struct ctl_softc *softc;
13859         uint32_t initidx, targ_lun;
13860
13861         softc = control_softc;
13862
13863         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13864
13865         /*
13866          * LUN lookup will likely move to the ctl_work_thread() once we
13867          * have our new queueing infrastructure (that doesn't put things on
13868          * a per-LUN queue initially).  That is so that we can handle
13869          * things like an INQUIRY to a LUN that we don't have enabled.  We
13870          * can't deal with that right now.
13871          */
13872         mtx_lock(&softc->ctl_lock);
13873
13874         /*
13875          * If we don't have a LUN for this, just toss the sense
13876          * information.
13877          */
13878         port = ctl_io_port(&ctsio->io_hdr);
13879         targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13880         if ((targ_lun < CTL_MAX_LUNS)
13881          && (softc->ctl_luns[targ_lun] != NULL))
13882                 lun = softc->ctl_luns[targ_lun];
13883         else
13884                 goto bailout;
13885
13886         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13887
13888         mtx_lock(&lun->lun_lock);
13889         /*
13890          * Already have CA set for this LUN...toss the sense information.
13891          */
13892         if (ctl_is_set(lun->have_ca, initidx)) {
13893                 mtx_unlock(&lun->lun_lock);
13894                 goto bailout;
13895         }
13896
13897         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13898                MIN(sizeof(lun->pending_sense[initidx]),
13899                sizeof(io->scsiio.sense_data)));
13900         ctl_set_mask(lun->have_ca, initidx);
13901         mtx_unlock(&lun->lun_lock);
13902
13903 bailout:
13904         mtx_unlock(&softc->ctl_lock);
13905
13906         ctl_free_io(io);
13907
13908         return (CTL_RETVAL_COMPLETE);
13909 }
13910 #endif
13911
13912 /*
13913  * Primary command inlet from frontend ports.  All SCSI and task I/O
13914  * requests must go through this function.
13915  */
13916 int
13917 ctl_queue(union ctl_io *io)
13918 {
13919         struct ctl_port *port;
13920
13921         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13922
13923 #ifdef CTL_TIME_IO
13924         io->io_hdr.start_time = time_uptime;
13925         getbintime(&io->io_hdr.start_bt);
13926 #endif /* CTL_TIME_IO */
13927
13928         /* Map FE-specific LUN ID into global one. */
13929         port = ctl_io_port(&io->io_hdr);
13930         io->io_hdr.nexus.targ_mapped_lun =
13931             ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13932
13933         switch (io->io_hdr.io_type) {
13934         case CTL_IO_SCSI:
13935         case CTL_IO_TASK:
13936                 if (ctl_debug & CTL_DEBUG_CDB)
13937                         ctl_io_print(io);
13938                 ctl_enqueue_incoming(io);
13939                 break;
13940         default:
13941                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13942                 return (EINVAL);
13943         }
13944
13945         return (CTL_RETVAL_COMPLETE);
13946 }
13947
13948 #ifdef CTL_IO_DELAY
13949 static void
13950 ctl_done_timer_wakeup(void *arg)
13951 {
13952         union ctl_io *io;
13953
13954         io = (union ctl_io *)arg;
13955         ctl_done(io);
13956 }
13957 #endif /* CTL_IO_DELAY */
13958
13959 void
13960 ctl_done(union ctl_io *io)
13961 {
13962
13963         /*
13964          * Enable this to catch duplicate completion issues.
13965          */
13966 #if 0
13967         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13968                 printf("%s: type %d msg %d cdb %x iptl: "
13969                        "%d:%d:%d:%d tag 0x%04x "
13970                        "flag %#x status %x\n",
13971                         __func__,
13972                         io->io_hdr.io_type,
13973                         io->io_hdr.msg_type,
13974                         io->scsiio.cdb[0],
13975                         io->io_hdr.nexus.initid.id,
13976                         io->io_hdr.nexus.targ_port,
13977                         io->io_hdr.nexus.targ_target.id,
13978                         io->io_hdr.nexus.targ_lun,
13979                         (io->io_hdr.io_type ==
13980                         CTL_IO_TASK) ?
13981                         io->taskio.tag_num :
13982                         io->scsiio.tag_num,
13983                         io->io_hdr.flags,
13984                         io->io_hdr.status);
13985         } else
13986                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13987 #endif
13988
13989         /*
13990          * This is an internal copy of an I/O, and should not go through
13991          * the normal done processing logic.
13992          */
13993         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13994                 return;
13995
13996         /*
13997          * We need to send a msg to the serializing shelf to finish the IO
13998          * as well.  We don't send a finish message to the other shelf if
13999          * this is a task management command.  Task management commands
14000          * aren't serialized in the OOA queue, but rather just executed on
14001          * both shelf controllers for commands that originated on that
14002          * controller.
14003          */
14004         if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
14005          && (io->io_hdr.io_type != CTL_IO_TASK)) {
14006                 union ctl_ha_msg msg_io;
14007
14008                 msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
14009                 msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
14010                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
14011                     sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
14012                 }
14013                 /* continue on to finish IO */
14014         }
14015 #ifdef CTL_IO_DELAY
14016         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
14017                 struct ctl_lun *lun;
14018
14019                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14020
14021                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
14022         } else {
14023                 struct ctl_lun *lun;
14024
14025                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14026
14027                 if ((lun != NULL)
14028                  && (lun->delay_info.done_delay > 0)) {
14029                         struct callout *callout;
14030
14031                         callout = (struct callout *)&io->io_hdr.timer_bytes;
14032                         callout_init(callout, /*mpsafe*/ 1);
14033                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
14034                         callout_reset(callout,
14035                                       lun->delay_info.done_delay * hz,
14036                                       ctl_done_timer_wakeup, io);
14037                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
14038                                 lun->delay_info.done_delay = 0;
14039                         return;
14040                 }
14041         }
14042 #endif /* CTL_IO_DELAY */
14043
14044         ctl_enqueue_done(io);
14045 }
14046
14047 int
14048 ctl_isc(struct ctl_scsiio *ctsio)
14049 {
14050         struct ctl_lun *lun;
14051         int retval;
14052
14053         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14054
14055         CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
14056
14057         CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
14058
14059         retval = lun->backend->data_submit((union ctl_io *)ctsio);
14060
14061         return (retval);
14062 }
14063
14064
14065 static void
14066 ctl_work_thread(void *arg)
14067 {
14068         struct ctl_thread *thr = (struct ctl_thread *)arg;
14069         struct ctl_softc *softc = thr->ctl_softc;
14070         union ctl_io *io;
14071         int retval;
14072
14073         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
14074
14075         for (;;) {
14076                 retval = 0;
14077
14078                 /*
14079                  * We handle the queues in this order:
14080                  * - ISC
14081                  * - done queue (to free up resources, unblock other commands)
14082                  * - RtR queue
14083                  * - incoming queue
14084                  *
14085                  * If those queues are empty, we break out of the loop and
14086                  * go to sleep.
14087                  */
14088                 mtx_lock(&thr->queue_lock);
14089                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
14090                 if (io != NULL) {
14091                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
14092                         mtx_unlock(&thr->queue_lock);
14093                         ctl_handle_isc(io);
14094                         continue;
14095                 }
14096                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
14097                 if (io != NULL) {
14098                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
14099                         /* clear any blocked commands, call fe_done */
14100                         mtx_unlock(&thr->queue_lock);
14101                         retval = ctl_process_done(io);
14102                         continue;
14103                 }
14104                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
14105                 if (io != NULL) {
14106                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
14107                         mtx_unlock(&thr->queue_lock);
14108                         if (io->io_hdr.io_type == CTL_IO_TASK)
14109                                 ctl_run_task(io);
14110                         else
14111                                 ctl_scsiio_precheck(softc, &io->scsiio);
14112                         continue;
14113                 }
14114                 if (!ctl_pause_rtr) {
14115                         io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
14116                         if (io != NULL) {
14117                                 STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
14118                                 mtx_unlock(&thr->queue_lock);
14119                                 retval = ctl_scsiio(&io->scsiio);
14120                                 if (retval != CTL_RETVAL_COMPLETE)
14121                                         CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
14122                                 continue;
14123                         }
14124                 }
14125
14126                 /* Sleep until we have something to do. */
14127                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
14128         }
14129 }
14130
14131 static void
14132 ctl_lun_thread(void *arg)
14133 {
14134         struct ctl_softc *softc = (struct ctl_softc *)arg;
14135         struct ctl_be_lun *be_lun;
14136         int retval;
14137
14138         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
14139
14140         for (;;) {
14141                 retval = 0;
14142                 mtx_lock(&softc->ctl_lock);
14143                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
14144                 if (be_lun != NULL) {
14145                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
14146                         mtx_unlock(&softc->ctl_lock);
14147                         ctl_create_lun(be_lun);
14148                         continue;
14149                 }
14150
14151                 /* Sleep until we have something to do. */
14152                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
14153                     PDROP | PRIBIO, "-", 0);
14154         }
14155 }
14156
14157 static void
14158 ctl_thresh_thread(void *arg)
14159 {
14160         struct ctl_softc *softc = (struct ctl_softc *)arg;
14161         struct ctl_lun *lun;
14162         struct ctl_be_lun *be_lun;
14163         struct scsi_da_rw_recovery_page *rwpage;
14164         struct ctl_logical_block_provisioning_page *page;
14165         const char *attr;
14166         uint64_t thres, val;
14167         int i, e;
14168
14169         CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
14170
14171         for (;;) {
14172                 mtx_lock(&softc->ctl_lock);
14173                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
14174                         be_lun = lun->be_lun;
14175                         if ((lun->flags & CTL_LUN_DISABLED) ||
14176                             (lun->flags & CTL_LUN_OFFLINE) ||
14177                             lun->backend->lun_attr == NULL)
14178                                 continue;
14179                         rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
14180                         if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
14181                                 continue;
14182                         e = 0;
14183                         page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
14184                         for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
14185                                 if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
14186                                         continue;
14187                                 thres = scsi_4btoul(page->descr[i].count);
14188                                 thres <<= CTL_LBP_EXPONENT;
14189                                 switch (page->descr[i].resource) {
14190                                 case 0x01:
14191                                         attr = "blocksavail";
14192                                         break;
14193                                 case 0x02:
14194                                         attr = "blocksused";
14195                                         break;
14196                                 case 0xf1:
14197                                         attr = "poolblocksavail";
14198                                         break;
14199                                 case 0xf2:
14200                                         attr = "poolblocksused";
14201                                         break;
14202                                 default:
14203                                         continue;
14204                                 }
14205                                 mtx_unlock(&softc->ctl_lock); // XXX
14206                                 val = lun->backend->lun_attr(
14207                                     lun->be_lun->be_lun, attr);
14208                                 mtx_lock(&softc->ctl_lock);
14209                                 if (val == UINT64_MAX)
14210                                         continue;
14211                                 if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
14212                                     == SLBPPD_ARMING_INC)
14213                                         e |= (val >= thres);
14214                                 else
14215                                         e |= (val <= thres);
14216                         }
14217                         mtx_lock(&lun->lun_lock);
14218                         if (e) {
14219                                 if (lun->lasttpt == 0 ||
14220                                     time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
14221                                         lun->lasttpt = time_uptime;
14222                                         ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14223                                 }
14224                         } else {
14225                                 lun->lasttpt = 0;
14226                                 ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14227                         }
14228                         mtx_unlock(&lun->lun_lock);
14229                 }
14230                 mtx_unlock(&softc->ctl_lock);
14231                 pause("-", CTL_LBP_PERIOD * hz);
14232         }
14233 }
14234
14235 static void
14236 ctl_enqueue_incoming(union ctl_io *io)
14237 {
14238         struct ctl_softc *softc = control_softc;
14239         struct ctl_thread *thr;
14240         u_int idx;
14241
14242         idx = (io->io_hdr.nexus.targ_port * 127 +
14243                io->io_hdr.nexus.initid.id) % worker_threads;
14244         thr = &softc->threads[idx];
14245         mtx_lock(&thr->queue_lock);
14246         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14247         mtx_unlock(&thr->queue_lock);
14248         wakeup(thr);
14249 }
14250
14251 static void
14252 ctl_enqueue_rtr(union ctl_io *io)
14253 {
14254         struct ctl_softc *softc = control_softc;
14255         struct ctl_thread *thr;
14256
14257         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14258         mtx_lock(&thr->queue_lock);
14259         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14260         mtx_unlock(&thr->queue_lock);
14261         wakeup(thr);
14262 }
14263
14264 static void
14265 ctl_enqueue_done(union ctl_io *io)
14266 {
14267         struct ctl_softc *softc = control_softc;
14268         struct ctl_thread *thr;
14269
14270         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14271         mtx_lock(&thr->queue_lock);
14272         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14273         mtx_unlock(&thr->queue_lock);
14274         wakeup(thr);
14275 }
14276
14277 static void
14278 ctl_enqueue_isc(union ctl_io *io)
14279 {
14280         struct ctl_softc *softc = control_softc;
14281         struct ctl_thread *thr;
14282
14283         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14284         mtx_lock(&thr->queue_lock);
14285         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14286         mtx_unlock(&thr->queue_lock);
14287         wakeup(thr);
14288 }
14289
14290 /* Initialization and failover */
14291
14292 void
14293 ctl_init_isc_msg(void)
14294 {
14295         printf("CTL: Still calling this thing\n");
14296 }
14297
14298 /*
14299  * Init component
14300  *      Initializes component into configuration defined by bootMode
14301  *      (see hasc-sv.c)
14302  *      returns hasc_Status:
14303  *              OK
14304  *              ERROR - fatal error
14305  */
14306 static ctl_ha_comp_status
14307 ctl_isc_init(struct ctl_ha_component *c)
14308 {
14309         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14310
14311         c->status = ret;
14312         return ret;
14313 }
14314
14315 /* Start component
14316  *      Starts component in state requested. If component starts successfully,
14317  *      it must set its own state to the requestrd state
14318  *      When requested state is HASC_STATE_HA, the component may refine it
14319  *      by adding _SLAVE or _MASTER flags.
14320  *      Currently allowed state transitions are:
14321  *      UNKNOWN->HA             - initial startup
14322  *      UNKNOWN->SINGLE - initial startup when no parter detected
14323  *      HA->SINGLE              - failover
14324  * returns ctl_ha_comp_status:
14325  *              OK      - component successfully started in requested state
14326  *              FAILED  - could not start the requested state, failover may
14327  *                        be possible
14328  *              ERROR   - fatal error detected, no future startup possible
14329  */
14330 static ctl_ha_comp_status
14331 ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14332 {
14333         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14334
14335         printf("%s: go\n", __func__);
14336
14337         // UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14338         if (c->state == CTL_HA_STATE_UNKNOWN ) {
14339                 control_softc->is_single = 0;
14340                 if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14341                     != CTL_HA_STATUS_SUCCESS) {
14342                         printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14343                         ret = CTL_HA_COMP_STATUS_ERROR;
14344                 }
14345         } else if (CTL_HA_STATE_IS_HA(c->state)
14346                 && CTL_HA_STATE_IS_SINGLE(state)){
14347                 // HA->SINGLE transition
14348                 ctl_failover();
14349                 control_softc->is_single = 1;
14350         } else {
14351                 printf("ctl_isc_start:Invalid state transition %X->%X\n",
14352                        c->state, state);
14353                 ret = CTL_HA_COMP_STATUS_ERROR;
14354         }
14355         if (CTL_HA_STATE_IS_SINGLE(state))
14356                 control_softc->is_single = 1;
14357
14358         c->state = state;
14359         c->status = ret;
14360         return ret;
14361 }
14362
14363 /*
14364  * Quiesce component
14365  * The component must clear any error conditions (set status to OK) and
14366  * prepare itself to another Start call
14367  * returns ctl_ha_comp_status:
14368  *      OK
14369  *      ERROR
14370  */
14371 static ctl_ha_comp_status
14372 ctl_isc_quiesce(struct ctl_ha_component *c)
14373 {
14374         int ret = CTL_HA_COMP_STATUS_OK;
14375
14376         ctl_pause_rtr = 1;
14377         c->status = ret;
14378         return ret;
14379 }
14380
14381 struct ctl_ha_component ctl_ha_component_ctlisc =
14382 {
14383         .name = "CTL ISC",
14384         .state = CTL_HA_STATE_UNKNOWN,
14385         .init = ctl_isc_init,
14386         .start = ctl_isc_start,
14387         .quiesce = ctl_isc_quiesce
14388 };
14389
14390 /*
14391  *  vim: ts=8
14392  */