]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/ctl.c
MFC r286406, r286414:
[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 #ifdef notyet
380 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
381                                   int param);
382 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
383 #endif
384 static int ctl_init(void);
385 void ctl_shutdown(void);
386 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
387 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
388 static void ctl_ioctl_online(void *arg);
389 static void ctl_ioctl_offline(void *arg);
390 static int ctl_ioctl_lun_enable(void *arg, int lun_id);
391 static int ctl_ioctl_lun_disable(void *arg, int lun_id);
392 static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
393 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
394 static int ctl_ioctl_submit_wait(union ctl_io *io);
395 static void ctl_ioctl_datamove(union ctl_io *io);
396 static void ctl_ioctl_done(union ctl_io *io);
397 static void ctl_ioctl_hard_startstop_callback(void *arg,
398                                               struct cfi_metatask *metatask);
399 static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
400 static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
401                               struct ctl_ooa *ooa_hdr,
402                               struct ctl_ooa_entry *kern_entries);
403 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
404                      struct thread *td);
405 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
406                          struct ctl_be_lun *be_lun);
407 static int ctl_free_lun(struct ctl_lun *lun);
408 static void ctl_create_lun(struct ctl_be_lun *be_lun);
409 static struct ctl_port * ctl_io_port(struct ctl_io_hdr *io_hdr);
410 /**
411 static void ctl_failover_change_pages(struct ctl_softc *softc,
412                                       struct ctl_scsiio *ctsio, int master);
413 **/
414
415 static int ctl_do_mode_select(union ctl_io *io);
416 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
417                            uint64_t res_key, uint64_t sa_res_key,
418                            uint8_t type, uint32_t residx,
419                            struct ctl_scsiio *ctsio,
420                            struct scsi_per_res_out *cdb,
421                            struct scsi_per_res_out_parms* param);
422 static void ctl_pro_preempt_other(struct ctl_lun *lun,
423                                   union ctl_ha_msg *msg);
424 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
425 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
426 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
427 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
428 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
429 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
430 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
431                                          int alloc_len);
432 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
433                                          int alloc_len);
434 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
435 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
436 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
437 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
438 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
439 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
440     bool seq);
441 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
442 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
443     union ctl_io *pending_io, union ctl_io *ooa_io);
444 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
445                                 union ctl_io *starting_io);
446 static int ctl_check_blocked(struct ctl_lun *lun);
447 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
448                                 const struct ctl_cmd_entry *entry,
449                                 struct ctl_scsiio *ctsio);
450 //static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
451 #ifdef notyet
452 static void ctl_failover(void);
453 #endif
454 static void ctl_clear_ua(struct ctl_softc *ctl_softc, uint32_t initidx,
455                          ctl_ua_type ua_type);
456 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
457                                struct ctl_scsiio *ctsio);
458 static int ctl_scsiio(struct ctl_scsiio *ctsio);
459
460 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
461 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
462                             ctl_ua_type ua_type);
463 static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
464                          ctl_ua_type ua_type);
465 static int ctl_abort_task(union ctl_io *io);
466 static int ctl_abort_task_set(union ctl_io *io);
467 static int ctl_i_t_nexus_reset(union ctl_io *io);
468 static void ctl_run_task(union ctl_io *io);
469 #ifdef CTL_IO_DELAY
470 static void ctl_datamove_timer_wakeup(void *arg);
471 static void ctl_done_timer_wakeup(void *arg);
472 #endif /* CTL_IO_DELAY */
473
474 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
475 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
476 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
477 static void ctl_datamove_remote_write(union ctl_io *io);
478 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
479 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
480 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
481 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
482                                     ctl_ha_dt_cb callback);
483 static void ctl_datamove_remote_read(union ctl_io *io);
484 static void ctl_datamove_remote(union ctl_io *io);
485 static int ctl_process_done(union ctl_io *io);
486 static void ctl_lun_thread(void *arg);
487 static void ctl_thresh_thread(void *arg);
488 static void ctl_work_thread(void *arg);
489 static void ctl_enqueue_incoming(union ctl_io *io);
490 static void ctl_enqueue_rtr(union ctl_io *io);
491 static void ctl_enqueue_done(union ctl_io *io);
492 #ifdef notyet
493 static void ctl_enqueue_isc(union ctl_io *io);
494 #endif
495 static const struct ctl_cmd_entry *
496     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
497 static const struct ctl_cmd_entry *
498     ctl_validate_command(struct ctl_scsiio *ctsio);
499 static int ctl_cmd_applicable(uint8_t lun_type,
500     const struct ctl_cmd_entry *entry);
501
502 /*
503  * Load the serialization table.  This isn't very pretty, but is probably
504  * the easiest way to do it.
505  */
506 #include "ctl_ser_table.c"
507
508 /*
509  * We only need to define open, close and ioctl routines for this driver.
510  */
511 static struct cdevsw ctl_cdevsw = {
512         .d_version =    D_VERSION,
513         .d_flags =      0,
514         .d_open =       ctl_open,
515         .d_close =      ctl_close,
516         .d_ioctl =      ctl_ioctl,
517         .d_name =       "ctl",
518 };
519
520
521 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
522
523 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
524
525 static moduledata_t ctl_moduledata = {
526         "ctl",
527         ctl_module_event_handler,
528         NULL
529 };
530
531 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
532 MODULE_VERSION(ctl, 1);
533
534 static struct ctl_frontend ioctl_frontend =
535 {
536         .name = "ioctl",
537 };
538
539 #ifdef notyet
540 static void
541 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
542                             union ctl_ha_msg *msg_info)
543 {
544         struct ctl_scsiio *ctsio;
545
546         if (msg_info->hdr.original_sc == NULL) {
547                 printf("%s: original_sc == NULL!\n", __func__);
548                 /* XXX KDM now what? */
549                 return;
550         }
551
552         ctsio = &msg_info->hdr.original_sc->scsiio;
553         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
554         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
555         ctsio->io_hdr.status = msg_info->hdr.status;
556         ctsio->scsi_status = msg_info->scsi.scsi_status;
557         ctsio->sense_len = msg_info->scsi.sense_len;
558         ctsio->sense_residual = msg_info->scsi.sense_residual;
559         ctsio->residual = msg_info->scsi.residual;
560         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
561                sizeof(ctsio->sense_data));
562         memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
563                &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
564         ctl_enqueue_isc((union ctl_io *)ctsio);
565 }
566
567 static void
568 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
569                                 union ctl_ha_msg *msg_info)
570 {
571         struct ctl_scsiio *ctsio;
572
573         if (msg_info->hdr.serializing_sc == NULL) {
574                 printf("%s: serializing_sc == NULL!\n", __func__);
575                 /* XXX KDM now what? */
576                 return;
577         }
578
579         ctsio = &msg_info->hdr.serializing_sc->scsiio;
580 #if 0
581         /*
582          * Attempt to catch the situation where an I/O has
583          * been freed, and we're using it again.
584          */
585         if (ctsio->io_hdr.io_type == 0xff) {
586                 union ctl_io *tmp_io;
587                 tmp_io = (union ctl_io *)ctsio;
588                 printf("%s: %p use after free!\n", __func__,
589                        ctsio);
590                 printf("%s: type %d msg %d cdb %x iptl: "
591                        "%d:%d:%d:%d tag 0x%04x "
592                        "flag %#x status %x\n",
593                         __func__,
594                         tmp_io->io_hdr.io_type,
595                         tmp_io->io_hdr.msg_type,
596                         tmp_io->scsiio.cdb[0],
597                         tmp_io->io_hdr.nexus.initid.id,
598                         tmp_io->io_hdr.nexus.targ_port,
599                         tmp_io->io_hdr.nexus.targ_target.id,
600                         tmp_io->io_hdr.nexus.targ_lun,
601                         (tmp_io->io_hdr.io_type ==
602                         CTL_IO_TASK) ?
603                         tmp_io->taskio.tag_num :
604                         tmp_io->scsiio.tag_num,
605                         tmp_io->io_hdr.flags,
606                         tmp_io->io_hdr.status);
607         }
608 #endif
609         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
610         ctl_enqueue_isc((union ctl_io *)ctsio);
611 }
612
613 /*
614  * ISC (Inter Shelf Communication) event handler.  Events from the HA
615  * subsystem come in here.
616  */
617 static void
618 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
619 {
620         struct ctl_softc *softc;
621         union ctl_io *io;
622         struct ctl_prio *presio;
623         ctl_ha_status isc_status;
624
625         softc = control_softc;
626         io = NULL;
627
628
629 #if 0
630         printf("CTL: Isc Msg event %d\n", event);
631 #endif
632         if (event == CTL_HA_EVT_MSG_RECV) {
633                 union ctl_ha_msg msg_info;
634
635                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
636                                              sizeof(msg_info), /*wait*/ 0);
637 #if 0
638                 printf("CTL: msg_type %d\n", msg_info.msg_type);
639 #endif
640                 if (isc_status != 0) {
641                         printf("Error receiving message, status = %d\n",
642                                isc_status);
643                         return;
644                 }
645
646                 switch (msg_info.hdr.msg_type) {
647                 case CTL_MSG_SERIALIZE:
648 #if 0
649                         printf("Serialize\n");
650 #endif
651                         io = ctl_alloc_io_nowait(softc->othersc_pool);
652                         if (io == NULL) {
653                                 printf("ctl_isc_event_handler: can't allocate "
654                                        "ctl_io!\n");
655                                 /* Bad Juju */
656                                 /* Need to set busy and send msg back */
657                                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
658                                 msg_info.hdr.status = CTL_SCSI_ERROR;
659                                 msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
660                                 msg_info.scsi.sense_len = 0;
661                                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
662                                     sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
663                                 }
664                                 goto bailout;
665                         }
666                         ctl_zero_io(io);
667                         // populate ctsio from msg_info
668                         io->io_hdr.io_type = CTL_IO_SCSI;
669                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
670                         io->io_hdr.original_sc = msg_info.hdr.original_sc;
671 #if 0
672                         printf("pOrig %x\n", (int)msg_info.original_sc);
673 #endif
674                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
675                                             CTL_FLAG_IO_ACTIVE;
676                         /*
677                          * If we're in serialization-only mode, we don't
678                          * want to go through full done processing.  Thus
679                          * the COPY flag.
680                          *
681                          * XXX KDM add another flag that is more specific.
682                          */
683                         if (softc->ha_mode == CTL_HA_MODE_SER_ONLY)
684                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
685                         io->io_hdr.nexus = msg_info.hdr.nexus;
686 #if 0
687                         printf("targ %d, port %d, iid %d, lun %d\n",
688                                io->io_hdr.nexus.targ_target.id,
689                                io->io_hdr.nexus.targ_port,
690                                io->io_hdr.nexus.initid.id,
691                                io->io_hdr.nexus.targ_lun);
692 #endif
693                         io->scsiio.tag_num = msg_info.scsi.tag_num;
694                         io->scsiio.tag_type = msg_info.scsi.tag_type;
695                         memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
696                                CTL_MAX_CDBLEN);
697                         if (softc->ha_mode == CTL_HA_MODE_XFER) {
698                                 const struct ctl_cmd_entry *entry;
699
700                                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
701                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
702                                 io->io_hdr.flags |=
703                                         entry->flags & CTL_FLAG_DATA_MASK;
704                         }
705                         ctl_enqueue_isc(io);
706                         break;
707
708                 /* Performed on the Originating SC, XFER mode only */
709                 case CTL_MSG_DATAMOVE: {
710                         struct ctl_sg_entry *sgl;
711                         int i, j;
712
713                         io = msg_info.hdr.original_sc;
714                         if (io == NULL) {
715                                 printf("%s: original_sc == NULL!\n", __func__);
716                                 /* XXX KDM do something here */
717                                 break;
718                         }
719                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
720                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
721                         /*
722                          * Keep track of this, we need to send it back over
723                          * when the datamove is complete.
724                          */
725                         io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
726
727                         if (msg_info.dt.sg_sequence == 0) {
728                                 /*
729                                  * XXX KDM we use the preallocated S/G list
730                                  * here, but we'll need to change this to
731                                  * dynamic allocation if we need larger S/G
732                                  * lists.
733                                  */
734                                 if (msg_info.dt.kern_sg_entries >
735                                     sizeof(io->io_hdr.remote_sglist) /
736                                     sizeof(io->io_hdr.remote_sglist[0])) {
737                                         printf("%s: number of S/G entries "
738                                             "needed %u > allocated num %zd\n",
739                                             __func__,
740                                             msg_info.dt.kern_sg_entries,
741                                             sizeof(io->io_hdr.remote_sglist)/
742                                             sizeof(io->io_hdr.remote_sglist[0]));
743                                 
744                                         /*
745                                          * XXX KDM send a message back to
746                                          * the other side to shut down the
747                                          * DMA.  The error will come back
748                                          * through via the normal channel.
749                                          */
750                                         break;
751                                 }
752                                 sgl = io->io_hdr.remote_sglist;
753                                 memset(sgl, 0,
754                                        sizeof(io->io_hdr.remote_sglist));
755
756                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
757
758                                 io->scsiio.kern_sg_entries =
759                                         msg_info.dt.kern_sg_entries;
760                                 io->scsiio.rem_sg_entries =
761                                         msg_info.dt.kern_sg_entries;
762                                 io->scsiio.kern_data_len =
763                                         msg_info.dt.kern_data_len;
764                                 io->scsiio.kern_total_len =
765                                         msg_info.dt.kern_total_len;
766                                 io->scsiio.kern_data_resid =
767                                         msg_info.dt.kern_data_resid;
768                                 io->scsiio.kern_rel_offset =
769                                         msg_info.dt.kern_rel_offset;
770                                 /*
771                                  * Clear out per-DMA flags.
772                                  */
773                                 io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
774                                 /*
775                                  * Add per-DMA flags that are set for this
776                                  * particular DMA request.
777                                  */
778                                 io->io_hdr.flags |= msg_info.dt.flags &
779                                                     CTL_FLAG_RDMA_MASK;
780                         } else
781                                 sgl = (struct ctl_sg_entry *)
782                                         io->scsiio.kern_data_ptr;
783
784                         for (i = msg_info.dt.sent_sg_entries, j = 0;
785                              i < (msg_info.dt.sent_sg_entries +
786                              msg_info.dt.cur_sg_entries); i++, j++) {
787                                 sgl[i].addr = msg_info.dt.sg_list[j].addr;
788                                 sgl[i].len = msg_info.dt.sg_list[j].len;
789
790 #if 0
791                                 printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
792                                        __func__,
793                                        msg_info.dt.sg_list[j].addr,
794                                        msg_info.dt.sg_list[j].len,
795                                        sgl[i].addr, sgl[i].len, j, i);
796 #endif
797                         }
798 #if 0
799                         memcpy(&sgl[msg_info.dt.sent_sg_entries],
800                                msg_info.dt.sg_list,
801                                sizeof(*sgl) * msg_info.dt.cur_sg_entries);
802 #endif
803
804                         /*
805                          * If this is the last piece of the I/O, we've got
806                          * the full S/G list.  Queue processing in the thread.
807                          * Otherwise wait for the next piece.
808                          */
809                         if (msg_info.dt.sg_last != 0)
810                                 ctl_enqueue_isc(io);
811                         break;
812                 }
813                 /* Performed on the Serializing (primary) SC, XFER mode only */
814                 case CTL_MSG_DATAMOVE_DONE: {
815                         if (msg_info.hdr.serializing_sc == NULL) {
816                                 printf("%s: serializing_sc == NULL!\n",
817                                        __func__);
818                                 /* XXX KDM now what? */
819                                 break;
820                         }
821                         /*
822                          * We grab the sense information here in case
823                          * there was a failure, so we can return status
824                          * back to the initiator.
825                          */
826                         io = msg_info.hdr.serializing_sc;
827                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
828                         io->io_hdr.status = msg_info.hdr.status;
829                         io->scsiio.scsi_status = msg_info.scsi.scsi_status;
830                         io->scsiio.sense_len = msg_info.scsi.sense_len;
831                         io->scsiio.sense_residual =msg_info.scsi.sense_residual;
832                         io->io_hdr.port_status = msg_info.scsi.fetd_status;
833                         io->scsiio.residual = msg_info.scsi.residual;
834                         memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
835                                sizeof(io->scsiio.sense_data));
836                         ctl_enqueue_isc(io);
837                         break;
838                 }
839
840                 /* Preformed on Originating SC, SER_ONLY mode */
841                 case CTL_MSG_R2R:
842                         io = msg_info.hdr.original_sc;
843                         if (io == NULL) {
844                                 printf("%s: Major Bummer\n", __func__);
845                                 return;
846                         } else {
847 #if 0
848                                 printf("pOrig %x\n",(int) ctsio);
849 #endif
850                         }
851                         io->io_hdr.msg_type = CTL_MSG_R2R;
852                         io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
853                         ctl_enqueue_isc(io);
854                         break;
855
856                 /*
857                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
858                  * mode.
859                  * Performed on the Originating (i.e. secondary) SC in XFER
860                  * mode
861                  */
862                 case CTL_MSG_FINISH_IO:
863                         if (softc->ha_mode == CTL_HA_MODE_XFER)
864                                 ctl_isc_handler_finish_xfer(softc,
865                                                             &msg_info);
866                         else
867                                 ctl_isc_handler_finish_ser_only(softc,
868                                                                 &msg_info);
869                         break;
870
871                 /* Preformed on Originating SC */
872                 case CTL_MSG_BAD_JUJU:
873                         io = msg_info.hdr.original_sc;
874                         if (io == NULL) {
875                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
876                                        __func__);
877                                 break;
878                         }
879                         ctl_copy_sense_data(&msg_info, io);
880                         /*
881                          * IO should have already been cleaned up on other
882                          * SC so clear this flag so we won't send a message
883                          * back to finish the IO there.
884                          */
885                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
886                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
887
888                         /* io = msg_info.hdr.serializing_sc; */
889                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
890                         ctl_enqueue_isc(io);
891                         break;
892
893                 /* Handle resets sent from the other side */
894                 case CTL_MSG_MANAGE_TASKS: {
895                         struct ctl_taskio *taskio;
896                         taskio = (struct ctl_taskio *)ctl_alloc_io_nowait(
897                             softc->othersc_pool);
898                         if (taskio == NULL) {
899                                 printf("ctl_isc_event_handler: can't allocate "
900                                        "ctl_io!\n");
901                                 /* Bad Juju */
902                                 /* should I just call the proper reset func
903                                    here??? */
904                                 goto bailout;
905                         }
906                         ctl_zero_io((union ctl_io *)taskio);
907                         taskio->io_hdr.io_type = CTL_IO_TASK;
908                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
909                         taskio->io_hdr.nexus = msg_info.hdr.nexus;
910                         taskio->task_action = msg_info.task.task_action;
911                         taskio->tag_num = msg_info.task.tag_num;
912                         taskio->tag_type = msg_info.task.tag_type;
913 #ifdef CTL_TIME_IO
914                         taskio->io_hdr.start_time = time_uptime;
915                         getbintime(&taskio->io_hdr.start_bt);
916 #if 0
917                         cs_prof_gettime(&taskio->io_hdr.start_ticks);
918 #endif
919 #endif /* CTL_TIME_IO */
920                         ctl_run_task((union ctl_io *)taskio);
921                         break;
922                 }
923                 /* Persistent Reserve action which needs attention */
924                 case CTL_MSG_PERS_ACTION:
925                         presio = (struct ctl_prio *)ctl_alloc_io_nowait(
926                             softc->othersc_pool);
927                         if (presio == NULL) {
928                                 printf("ctl_isc_event_handler: can't allocate "
929                                        "ctl_io!\n");
930                                 /* Bad Juju */
931                                 /* Need to set busy and send msg back */
932                                 goto bailout;
933                         }
934                         ctl_zero_io((union ctl_io *)presio);
935                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
936                         presio->pr_msg = msg_info.pr;
937                         ctl_enqueue_isc((union ctl_io *)presio);
938                         break;
939                 case CTL_MSG_SYNC_FE:
940                         rcv_sync_msg = 1;
941                         break;
942                 default:
943                         printf("How did I get here?\n");
944                 }
945         } else if (event == CTL_HA_EVT_MSG_SENT) {
946                 if (param != CTL_HA_STATUS_SUCCESS) {
947                         printf("Bad status from ctl_ha_msg_send status %d\n",
948                                param);
949                 }
950                 return;
951         } else if (event == CTL_HA_EVT_DISCONNECT) {
952                 printf("CTL: Got a disconnect from Isc\n");
953                 return;
954         } else {
955                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
956                 return;
957         }
958
959 bailout:
960         return;
961 }
962
963 static void
964 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
965 {
966         struct scsi_sense_data *sense;
967
968         sense = &dest->scsiio.sense_data;
969         bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
970         dest->scsiio.scsi_status = src->scsi.scsi_status;
971         dest->scsiio.sense_len = src->scsi.sense_len;
972         dest->io_hdr.status = src->hdr.status;
973 }
974 #endif
975
976 static void
977 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
978 {
979         ctl_ua_type *pu;
980
981         mtx_assert(&lun->lun_lock, MA_OWNED);
982         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
983         if (pu == NULL)
984                 return;
985         pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
986 }
987
988 static void
989 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
990 {
991         int i, j;
992
993         mtx_assert(&lun->lun_lock, MA_OWNED);
994         for (i = 0; i < CTL_MAX_PORTS; i++) {
995                 if (lun->pending_ua[i] == NULL)
996                         continue;
997                 for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
998                         if (i * CTL_MAX_INIT_PER_PORT + j == except)
999                                 continue;
1000                         lun->pending_ua[i][j] |= ua;
1001                 }
1002         }
1003 }
1004
1005 static void
1006 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1007 {
1008         ctl_ua_type *pu;
1009
1010         mtx_assert(&lun->lun_lock, MA_OWNED);
1011         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1012         if (pu == NULL)
1013                 return;
1014         pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1015 }
1016
1017 static void
1018 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1019 {
1020         int i, j;
1021
1022         mtx_assert(&lun->lun_lock, MA_OWNED);
1023         for (i = 0; i < CTL_MAX_PORTS; i++) {
1024                 if (lun->pending_ua[i] == NULL)
1025                         continue;
1026                 for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1027                         if (i * CTL_MAX_INIT_PER_PORT + j == except)
1028                                 continue;
1029                         lun->pending_ua[i][j] &= ~ua;
1030                 }
1031         }
1032 }
1033
1034 static int
1035 ctl_ha_state_sysctl(SYSCTL_HANDLER_ARGS)
1036 {
1037         struct ctl_softc *softc = (struct ctl_softc *)arg1;
1038         struct ctl_lun *lun;
1039         int error, value;
1040
1041         if (softc->flags & CTL_FLAG_ACTIVE_SHELF)
1042                 value = 0;
1043         else
1044                 value = 1;
1045
1046         error = sysctl_handle_int(oidp, &value, 0, req);
1047         if ((error != 0) || (req->newptr == NULL))
1048                 return (error);
1049
1050         mtx_lock(&softc->ctl_lock);
1051         if (value == 0)
1052                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1053         else
1054                 softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1055         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1056                 mtx_lock(&lun->lun_lock);
1057                 ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1058                 mtx_unlock(&lun->lun_lock);
1059         }
1060         mtx_unlock(&softc->ctl_lock);
1061         return (0);
1062 }
1063
1064 static int
1065 ctl_init(void)
1066 {
1067         struct ctl_softc *softc;
1068         void *other_pool;
1069         struct ctl_port *port;
1070         int i, error, retval;
1071         //int isc_retval;
1072
1073         retval = 0;
1074         ctl_pause_rtr = 0;
1075         rcv_sync_msg = 0;
1076
1077         control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1078                                M_WAITOK | M_ZERO);
1079         softc = control_softc;
1080
1081         softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1082                               "cam/ctl");
1083
1084         softc->dev->si_drv1 = softc;
1085
1086         /*
1087          * By default, return a "bad LUN" peripheral qualifier for unknown
1088          * LUNs.  The user can override this default using the tunable or
1089          * sysctl.  See the comment in ctl_inquiry_std() for more details.
1090          */
1091         softc->inquiry_pq_no_lun = 1;
1092         TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
1093                           &softc->inquiry_pq_no_lun);
1094         sysctl_ctx_init(&softc->sysctl_ctx);
1095         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1096                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1097                 CTLFLAG_RD, 0, "CAM Target Layer");
1098
1099         if (softc->sysctl_tree == NULL) {
1100                 printf("%s: unable to allocate sysctl tree\n", __func__);
1101                 destroy_dev(softc->dev);
1102                 free(control_softc, M_DEVBUF);
1103                 control_softc = NULL;
1104                 return (ENOMEM);
1105         }
1106
1107         SYSCTL_ADD_INT(&softc->sysctl_ctx,
1108                        SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1109                        "inquiry_pq_no_lun", CTLFLAG_RW,
1110                        &softc->inquiry_pq_no_lun, 0,
1111                        "Report no lun possible for invalid LUNs");
1112
1113         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1114         softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1115             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1116         softc->open_count = 0;
1117
1118         /*
1119          * Default to actually sending a SYNCHRONIZE CACHE command down to
1120          * the drive.
1121          */
1122         softc->flags = CTL_FLAG_REAL_SYNC;
1123
1124         /*
1125          * In Copan's HA scheme, the "master" and "slave" roles are
1126          * figured out through the slot the controller is in.  Although it
1127          * is an active/active system, someone has to be in charge.
1128          */
1129         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1130             OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1131             "HA head ID (0 - no HA)");
1132         if (softc->ha_id == 0) {
1133                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1134                 softc->is_single = 1;
1135                 softc->port_offset = 0;
1136         } else
1137                 softc->port_offset = (softc->ha_id - 1) * CTL_MAX_PORTS;
1138         softc->persis_offset = softc->port_offset * CTL_MAX_INIT_PER_PORT;
1139
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
1194         /*
1195          * Initialize the ioctl front end.
1196          */
1197         ctl_frontend_register(&ioctl_frontend);
1198         port = &softc->ioctl_info.port;
1199         port->frontend = &ioctl_frontend;
1200         sprintf(softc->ioctl_info.port_name, "ioctl");
1201         port->port_type = CTL_PORT_IOCTL;
1202         port->num_requested_ctl_io = 100;
1203         port->port_name = softc->ioctl_info.port_name;
1204         port->port_online = ctl_ioctl_online;
1205         port->port_offline = ctl_ioctl_offline;
1206         port->onoff_arg = &softc->ioctl_info;
1207         port->lun_enable = ctl_ioctl_lun_enable;
1208         port->lun_disable = ctl_ioctl_lun_disable;
1209         port->targ_lun_arg = &softc->ioctl_info;
1210         port->fe_datamove = ctl_ioctl_datamove;
1211         port->fe_done = ctl_ioctl_done;
1212         port->max_targets = 15;
1213         port->max_target_id = 15;
1214
1215         if (ctl_port_register(&softc->ioctl_info.port) != 0) {
1216                 printf("ctl: ioctl front end registration failed, will "
1217                        "continue anyway\n");
1218         }
1219
1220         SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1221             OID_AUTO, "ha_state", CTLTYPE_INT | CTLFLAG_RWTUN,
1222             softc, 0, ctl_ha_state_sysctl, "I", "HA state for this head");
1223
1224 #ifdef CTL_IO_DELAY
1225         if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1226                 printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1227                        sizeof(struct callout), CTL_TIMER_BYTES);
1228                 return (EINVAL);
1229         }
1230 #endif /* CTL_IO_DELAY */
1231
1232         return (0);
1233 }
1234
1235 void
1236 ctl_shutdown(void)
1237 {
1238         struct ctl_softc *softc;
1239         struct ctl_lun *lun, *next_lun;
1240
1241         softc = (struct ctl_softc *)control_softc;
1242
1243         if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1244                 printf("ctl: ioctl front end deregistration failed\n");
1245
1246         mtx_lock(&softc->ctl_lock);
1247
1248         /*
1249          * Free up each LUN.
1250          */
1251         for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1252                 next_lun = STAILQ_NEXT(lun, links);
1253                 ctl_free_lun(lun);
1254         }
1255
1256         mtx_unlock(&softc->ctl_lock);
1257
1258         ctl_frontend_deregister(&ioctl_frontend);
1259
1260 #if 0
1261         ctl_shutdown_thread(softc->work_thread);
1262         mtx_destroy(&softc->queue_lock);
1263 #endif
1264
1265         ctl_tpc_shutdown(softc);
1266         uma_zdestroy(softc->io_zone);
1267         mtx_destroy(&softc->ctl_lock);
1268
1269         destroy_dev(softc->dev);
1270
1271         sysctl_ctx_free(&softc->sysctl_ctx);
1272
1273         free(control_softc, M_DEVBUF);
1274         control_softc = NULL;
1275 }
1276
1277 static int
1278 ctl_module_event_handler(module_t mod, int what, void *arg)
1279 {
1280
1281         switch (what) {
1282         case MOD_LOAD:
1283                 return (ctl_init());
1284         case MOD_UNLOAD:
1285                 return (EBUSY);
1286         default:
1287                 return (EOPNOTSUPP);
1288         }
1289 }
1290
1291 /*
1292  * XXX KDM should we do some access checks here?  Bump a reference count to
1293  * prevent a CTL module from being unloaded while someone has it open?
1294  */
1295 static int
1296 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1297 {
1298         return (0);
1299 }
1300
1301 static int
1302 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1303 {
1304         return (0);
1305 }
1306
1307 int
1308 ctl_port_enable(ctl_port_type port_type)
1309 {
1310         struct ctl_softc *softc = control_softc;
1311         struct ctl_port *port;
1312
1313         if (softc->is_single == 0) {
1314                 union ctl_ha_msg msg_info;
1315                 int isc_retval;
1316
1317 #if 0
1318                 printf("%s: HA mode, synchronizing frontend enable\n",
1319                         __func__);
1320 #endif
1321                 msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1322                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1323                         sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1324                         printf("Sync msg send error retval %d\n", isc_retval);
1325                 }
1326                 if (!rcv_sync_msg) {
1327                         isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1328                                 sizeof(msg_info), 1);
1329                 }
1330 #if 0
1331                 printf("CTL:Frontend Enable\n");
1332         } else {
1333                 printf("%s: single mode, skipping frontend synchronization\n",
1334                         __func__);
1335 #endif
1336         }
1337
1338         STAILQ_FOREACH(port, &softc->port_list, links) {
1339                 if (port_type & port->port_type)
1340                 {
1341 #if 0
1342                         printf("port %d\n", port->targ_port);
1343 #endif
1344                         ctl_port_online(port);
1345                 }
1346         }
1347
1348         return (0);
1349 }
1350
1351 int
1352 ctl_port_disable(ctl_port_type port_type)
1353 {
1354         struct ctl_softc *softc;
1355         struct ctl_port *port;
1356
1357         softc = control_softc;
1358
1359         STAILQ_FOREACH(port, &softc->port_list, links) {
1360                 if (port_type & port->port_type)
1361                         ctl_port_offline(port);
1362         }
1363
1364         return (0);
1365 }
1366
1367 /*
1368  * Returns 0 for success, 1 for failure.
1369  * Currently the only failure mode is if there aren't enough entries
1370  * allocated.  So, in case of a failure, look at num_entries_dropped,
1371  * reallocate and try again.
1372  */
1373 int
1374 ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1375               int *num_entries_filled, int *num_entries_dropped,
1376               ctl_port_type port_type, int no_virtual)
1377 {
1378         struct ctl_softc *softc;
1379         struct ctl_port *port;
1380         int entries_dropped, entries_filled;
1381         int retval;
1382         int i;
1383
1384         softc = control_softc;
1385
1386         retval = 0;
1387         entries_filled = 0;
1388         entries_dropped = 0;
1389
1390         i = 0;
1391         mtx_lock(&softc->ctl_lock);
1392         STAILQ_FOREACH(port, &softc->port_list, links) {
1393                 struct ctl_port_entry *entry;
1394
1395                 if ((port->port_type & port_type) == 0)
1396                         continue;
1397
1398                 if ((no_virtual != 0)
1399                  && (port->virtual_port != 0))
1400                         continue;
1401
1402                 if (entries_filled >= num_entries_alloced) {
1403                         entries_dropped++;
1404                         continue;
1405                 }
1406                 entry = &entries[i];
1407
1408                 entry->port_type = port->port_type;
1409                 strlcpy(entry->port_name, port->port_name,
1410                         sizeof(entry->port_name));
1411                 entry->physical_port = port->physical_port;
1412                 entry->virtual_port = port->virtual_port;
1413                 entry->wwnn = port->wwnn;
1414                 entry->wwpn = port->wwpn;
1415
1416                 i++;
1417                 entries_filled++;
1418         }
1419
1420         mtx_unlock(&softc->ctl_lock);
1421
1422         if (entries_dropped > 0)
1423                 retval = 1;
1424
1425         *num_entries_dropped = entries_dropped;
1426         *num_entries_filled = entries_filled;
1427
1428         return (retval);
1429 }
1430
1431 static void
1432 ctl_ioctl_online(void *arg)
1433 {
1434         struct ctl_ioctl_info *ioctl_info;
1435
1436         ioctl_info = (struct ctl_ioctl_info *)arg;
1437
1438         ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1439 }
1440
1441 static void
1442 ctl_ioctl_offline(void *arg)
1443 {
1444         struct ctl_ioctl_info *ioctl_info;
1445
1446         ioctl_info = (struct ctl_ioctl_info *)arg;
1447
1448         ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1449 }
1450
1451 /*
1452  * Remove an initiator by port number and initiator ID.
1453  * Returns 0 for success, -1 for failure.
1454  */
1455 int
1456 ctl_remove_initiator(struct ctl_port *port, int iid)
1457 {
1458         struct ctl_softc *softc = control_softc;
1459
1460         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1461
1462         if (iid > CTL_MAX_INIT_PER_PORT) {
1463                 printf("%s: initiator ID %u > maximun %u!\n",
1464                        __func__, iid, CTL_MAX_INIT_PER_PORT);
1465                 return (-1);
1466         }
1467
1468         mtx_lock(&softc->ctl_lock);
1469         port->wwpn_iid[iid].in_use--;
1470         port->wwpn_iid[iid].last_use = time_uptime;
1471         mtx_unlock(&softc->ctl_lock);
1472
1473         return (0);
1474 }
1475
1476 /*
1477  * Add an initiator to the initiator map.
1478  * Returns iid for success, < 0 for failure.
1479  */
1480 int
1481 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1482 {
1483         struct ctl_softc *softc = control_softc;
1484         time_t best_time;
1485         int i, best;
1486
1487         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1488
1489         if (iid >= CTL_MAX_INIT_PER_PORT) {
1490                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1491                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1492                 free(name, M_CTL);
1493                 return (-1);
1494         }
1495
1496         mtx_lock(&softc->ctl_lock);
1497
1498         if (iid < 0 && (wwpn != 0 || name != NULL)) {
1499                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1500                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1501                                 iid = i;
1502                                 break;
1503                         }
1504                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
1505                             strcmp(name, port->wwpn_iid[i].name) == 0) {
1506                                 iid = i;
1507                                 break;
1508                         }
1509                 }
1510         }
1511
1512         if (iid < 0) {
1513                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1514                         if (port->wwpn_iid[i].in_use == 0 &&
1515                             port->wwpn_iid[i].wwpn == 0 &&
1516                             port->wwpn_iid[i].name == NULL) {
1517                                 iid = i;
1518                                 break;
1519                         }
1520                 }
1521         }
1522
1523         if (iid < 0) {
1524                 best = -1;
1525                 best_time = INT32_MAX;
1526                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1527                         if (port->wwpn_iid[i].in_use == 0) {
1528                                 if (port->wwpn_iid[i].last_use < best_time) {
1529                                         best = i;
1530                                         best_time = port->wwpn_iid[i].last_use;
1531                                 }
1532                         }
1533                 }
1534                 iid = best;
1535         }
1536
1537         if (iid < 0) {
1538                 mtx_unlock(&softc->ctl_lock);
1539                 free(name, M_CTL);
1540                 return (-2);
1541         }
1542
1543         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1544                 /*
1545                  * This is not an error yet.
1546                  */
1547                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1548 #if 0
1549                         printf("%s: port %d iid %u WWPN %#jx arrived"
1550                             " again\n", __func__, port->targ_port,
1551                             iid, (uintmax_t)wwpn);
1552 #endif
1553                         goto take;
1554                 }
1555                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1556                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
1557 #if 0
1558                         printf("%s: port %d iid %u name '%s' arrived"
1559                             " again\n", __func__, port->targ_port,
1560                             iid, name);
1561 #endif
1562                         goto take;
1563                 }
1564
1565                 /*
1566                  * This is an error, but what do we do about it?  The
1567                  * driver is telling us we have a new WWPN for this
1568                  * initiator ID, so we pretty much need to use it.
1569                  */
1570                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1571                     " but WWPN %#jx '%s' is still at that address\n",
1572                     __func__, port->targ_port, iid, wwpn, name,
1573                     (uintmax_t)port->wwpn_iid[iid].wwpn,
1574                     port->wwpn_iid[iid].name);
1575
1576                 /*
1577                  * XXX KDM clear have_ca and ua_pending on each LUN for
1578                  * this initiator.
1579                  */
1580         }
1581 take:
1582         free(port->wwpn_iid[iid].name, M_CTL);
1583         port->wwpn_iid[iid].name = name;
1584         port->wwpn_iid[iid].wwpn = wwpn;
1585         port->wwpn_iid[iid].in_use++;
1586         mtx_unlock(&softc->ctl_lock);
1587
1588         return (iid);
1589 }
1590
1591 static int
1592 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1593 {
1594         int len;
1595
1596         switch (port->port_type) {
1597         case CTL_PORT_FC:
1598         {
1599                 struct scsi_transportid_fcp *id =
1600                     (struct scsi_transportid_fcp *)buf;
1601                 if (port->wwpn_iid[iid].wwpn == 0)
1602                         return (0);
1603                 memset(id, 0, sizeof(*id));
1604                 id->format_protocol = SCSI_PROTO_FC;
1605                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1606                 return (sizeof(*id));
1607         }
1608         case CTL_PORT_ISCSI:
1609         {
1610                 struct scsi_transportid_iscsi_port *id =
1611                     (struct scsi_transportid_iscsi_port *)buf;
1612                 if (port->wwpn_iid[iid].name == NULL)
1613                         return (0);
1614                 memset(id, 0, 256);
1615                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1616                     SCSI_PROTO_ISCSI;
1617                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1618                 len = roundup2(min(len, 252), 4);
1619                 scsi_ulto2b(len, id->additional_length);
1620                 return (sizeof(*id) + len);
1621         }
1622         case CTL_PORT_SAS:
1623         {
1624                 struct scsi_transportid_sas *id =
1625                     (struct scsi_transportid_sas *)buf;
1626                 if (port->wwpn_iid[iid].wwpn == 0)
1627                         return (0);
1628                 memset(id, 0, sizeof(*id));
1629                 id->format_protocol = SCSI_PROTO_SAS;
1630                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1631                 return (sizeof(*id));
1632         }
1633         default:
1634         {
1635                 struct scsi_transportid_spi *id =
1636                     (struct scsi_transportid_spi *)buf;
1637                 memset(id, 0, sizeof(*id));
1638                 id->format_protocol = SCSI_PROTO_SPI;
1639                 scsi_ulto2b(iid, id->scsi_addr);
1640                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1641                 return (sizeof(*id));
1642         }
1643         }
1644 }
1645
1646 static int
1647 ctl_ioctl_lun_enable(void *arg, int lun_id)
1648 {
1649         return (0);
1650 }
1651
1652 static int
1653 ctl_ioctl_lun_disable(void *arg, int lun_id)
1654 {
1655         return (0);
1656 }
1657
1658 /*
1659  * Data movement routine for the CTL ioctl frontend port.
1660  */
1661 static int
1662 ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1663 {
1664         struct ctl_sg_entry *ext_sglist, *kern_sglist;
1665         struct ctl_sg_entry ext_entry, kern_entry;
1666         int ext_sglen, ext_sg_entries, kern_sg_entries;
1667         int ext_sg_start, ext_offset;
1668         int len_to_copy, len_copied;
1669         int kern_watermark, ext_watermark;
1670         int ext_sglist_malloced;
1671         int i, j;
1672
1673         ext_sglist_malloced = 0;
1674         ext_sg_start = 0;
1675         ext_offset = 0;
1676
1677         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1678
1679         /*
1680          * If this flag is set, fake the data transfer.
1681          */
1682         if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1683                 ctsio->ext_data_filled = ctsio->ext_data_len;
1684                 goto bailout;
1685         }
1686
1687         /*
1688          * To simplify things here, if we have a single buffer, stick it in
1689          * a S/G entry and just make it a single entry S/G list.
1690          */
1691         if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1692                 int len_seen;
1693
1694                 ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1695
1696                 ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1697                                                            M_WAITOK);
1698                 ext_sglist_malloced = 1;
1699                 if (copyin(ctsio->ext_data_ptr, ext_sglist,
1700                                    ext_sglen) != 0) {
1701                         ctl_set_internal_failure(ctsio,
1702                                                  /*sks_valid*/ 0,
1703                                                  /*retry_count*/ 0);
1704                         goto bailout;
1705                 }
1706                 ext_sg_entries = ctsio->ext_sg_entries;
1707                 len_seen = 0;
1708                 for (i = 0; i < ext_sg_entries; i++) {
1709                         if ((len_seen + ext_sglist[i].len) >=
1710                              ctsio->ext_data_filled) {
1711                                 ext_sg_start = i;
1712                                 ext_offset = ctsio->ext_data_filled - len_seen;
1713                                 break;
1714                         }
1715                         len_seen += ext_sglist[i].len;
1716                 }
1717         } else {
1718                 ext_sglist = &ext_entry;
1719                 ext_sglist->addr = ctsio->ext_data_ptr;
1720                 ext_sglist->len = ctsio->ext_data_len;
1721                 ext_sg_entries = 1;
1722                 ext_sg_start = 0;
1723                 ext_offset = ctsio->ext_data_filled;
1724         }
1725
1726         if (ctsio->kern_sg_entries > 0) {
1727                 kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1728                 kern_sg_entries = ctsio->kern_sg_entries;
1729         } else {
1730                 kern_sglist = &kern_entry;
1731                 kern_sglist->addr = ctsio->kern_data_ptr;
1732                 kern_sglist->len = ctsio->kern_data_len;
1733                 kern_sg_entries = 1;
1734         }
1735
1736
1737         kern_watermark = 0;
1738         ext_watermark = ext_offset;
1739         len_copied = 0;
1740         for (i = ext_sg_start, j = 0;
1741              i < ext_sg_entries && j < kern_sg_entries;) {
1742                 uint8_t *ext_ptr, *kern_ptr;
1743
1744                 len_to_copy = MIN(ext_sglist[i].len - ext_watermark,
1745                                   kern_sglist[j].len - kern_watermark);
1746
1747                 ext_ptr = (uint8_t *)ext_sglist[i].addr;
1748                 ext_ptr = ext_ptr + ext_watermark;
1749                 if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1750                         /*
1751                          * XXX KDM fix this!
1752                          */
1753                         panic("need to implement bus address support");
1754 #if 0
1755                         kern_ptr = bus_to_virt(kern_sglist[j].addr);
1756 #endif
1757                 } else
1758                         kern_ptr = (uint8_t *)kern_sglist[j].addr;
1759                 kern_ptr = kern_ptr + kern_watermark;
1760
1761                 kern_watermark += len_to_copy;
1762                 ext_watermark += len_to_copy;
1763
1764                 if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1765                      CTL_FLAG_DATA_IN) {
1766                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1767                                          "bytes to user\n", len_to_copy));
1768                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1769                                          "to %p\n", kern_ptr, ext_ptr));
1770                         if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1771                                 ctl_set_internal_failure(ctsio,
1772                                                          /*sks_valid*/ 0,
1773                                                          /*retry_count*/ 0);
1774                                 goto bailout;
1775                         }
1776                 } else {
1777                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1778                                          "bytes from user\n", len_to_copy));
1779                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1780                                          "to %p\n", ext_ptr, kern_ptr));
1781                         if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1782                                 ctl_set_internal_failure(ctsio,
1783                                                          /*sks_valid*/ 0,
1784                                                          /*retry_count*/0);
1785                                 goto bailout;
1786                         }
1787                 }
1788
1789                 len_copied += len_to_copy;
1790
1791                 if (ext_sglist[i].len == ext_watermark) {
1792                         i++;
1793                         ext_watermark = 0;
1794                 }
1795
1796                 if (kern_sglist[j].len == kern_watermark) {
1797                         j++;
1798                         kern_watermark = 0;
1799                 }
1800         }
1801
1802         ctsio->ext_data_filled += len_copied;
1803
1804         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1805                          "kern_sg_entries: %d\n", ext_sg_entries,
1806                          kern_sg_entries));
1807         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1808                          "kern_data_len = %d\n", ctsio->ext_data_len,
1809                          ctsio->kern_data_len));
1810
1811
1812         /* XXX KDM set residual?? */
1813 bailout:
1814
1815         if (ext_sglist_malloced != 0)
1816                 free(ext_sglist, M_CTL);
1817
1818         return (CTL_RETVAL_COMPLETE);
1819 }
1820
1821 /*
1822  * Serialize a command that went down the "wrong" side, and so was sent to
1823  * this controller for execution.  The logic is a little different than the
1824  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1825  * sent back to the other side, but in the success case, we execute the
1826  * command on this side (XFER mode) or tell the other side to execute it
1827  * (SER_ONLY mode).
1828  */
1829 static int
1830 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1831 {
1832         struct ctl_softc *softc;
1833         union ctl_ha_msg msg_info;
1834         struct ctl_lun *lun;
1835         int retval = 0;
1836         uint32_t targ_lun;
1837
1838         softc = control_softc;
1839
1840         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1841         lun = softc->ctl_luns[targ_lun];
1842         if (lun==NULL)
1843         {
1844                 /*
1845                  * Why isn't LUN defined? The other side wouldn't
1846                  * send a cmd if the LUN is undefined.
1847                  */
1848                 printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1849
1850                 /* "Logical unit not supported" */
1851                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1852                                    lun,
1853                                    /*sense_format*/SSD_TYPE_NONE,
1854                                    /*current_error*/ 1,
1855                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1856                                    /*asc*/ 0x25,
1857                                    /*ascq*/ 0x00,
1858                                    SSD_ELEM_NONE);
1859
1860                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1861                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1862                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1863                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1864                 msg_info.hdr.serializing_sc = NULL;
1865                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1866                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1867                                 sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1868                 }
1869                 return(1);
1870
1871         }
1872
1873         mtx_lock(&lun->lun_lock);
1874         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1875
1876         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1877                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1878                  ooa_links))) {
1879         case CTL_ACTION_BLOCK:
1880                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1881                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1882                                   blocked_links);
1883                 break;
1884         case CTL_ACTION_PASS:
1885         case CTL_ACTION_SKIP:
1886                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
1887                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1888                         ctl_enqueue_rtr((union ctl_io *)ctsio);
1889                 } else {
1890
1891                         /* send msg back to other side */
1892                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1893                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1894                         msg_info.hdr.msg_type = CTL_MSG_R2R;
1895 #if 0
1896                         printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1897 #endif
1898                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1899                             sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1900                         }
1901                 }
1902                 break;
1903         case CTL_ACTION_OVERLAP:
1904                 /* OVERLAPPED COMMANDS ATTEMPTED */
1905                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1906                                    lun,
1907                                    /*sense_format*/SSD_TYPE_NONE,
1908                                    /*current_error*/ 1,
1909                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1910                                    /*asc*/ 0x4E,
1911                                    /*ascq*/ 0x00,
1912                                    SSD_ELEM_NONE);
1913
1914                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1915                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1916                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1917                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1918                 msg_info.hdr.serializing_sc = NULL;
1919                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1920 #if 0
1921                 printf("BAD JUJU:Major Bummer Overlap\n");
1922 #endif
1923                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1924                 retval = 1;
1925                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1926                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1927                 }
1928                 break;
1929         case CTL_ACTION_OVERLAP_TAG:
1930                 /* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1931                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1932                                    lun,
1933                                    /*sense_format*/SSD_TYPE_NONE,
1934                                    /*current_error*/ 1,
1935                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1936                                    /*asc*/ 0x4D,
1937                                    /*ascq*/ ctsio->tag_num & 0xff,
1938                                    SSD_ELEM_NONE);
1939
1940                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1941                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1942                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1943                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1944                 msg_info.hdr.serializing_sc = NULL;
1945                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1946 #if 0
1947                 printf("BAD JUJU:Major Bummer Overlap Tag\n");
1948 #endif
1949                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1950                 retval = 1;
1951                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1952                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1953                 }
1954                 break;
1955         case CTL_ACTION_ERROR:
1956         default:
1957                 /* "Internal target failure" */
1958                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1959                                    lun,
1960                                    /*sense_format*/SSD_TYPE_NONE,
1961                                    /*current_error*/ 1,
1962                                    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1963                                    /*asc*/ 0x44,
1964                                    /*ascq*/ 0x00,
1965                                    SSD_ELEM_NONE);
1966
1967                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1968                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1969                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1970                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1971                 msg_info.hdr.serializing_sc = NULL;
1972                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1973 #if 0
1974                 printf("BAD JUJU:Major Bummer HW Error\n");
1975 #endif
1976                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1977                 retval = 1;
1978                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1979                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1980                 }
1981                 break;
1982         }
1983         mtx_unlock(&lun->lun_lock);
1984         return (retval);
1985 }
1986
1987 static int
1988 ctl_ioctl_submit_wait(union ctl_io *io)
1989 {
1990         struct ctl_fe_ioctl_params params;
1991         ctl_fe_ioctl_state last_state;
1992         int done, retval;
1993
1994         retval = 0;
1995
1996         bzero(&params, sizeof(params));
1997
1998         mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1999         cv_init(&params.sem, "ctlioccv");
2000         params.state = CTL_IOCTL_INPROG;
2001         last_state = params.state;
2002
2003         io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
2004
2005         CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
2006
2007         /* This shouldn't happen */
2008         if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
2009                 return (retval);
2010
2011         done = 0;
2012
2013         do {
2014                 mtx_lock(&params.ioctl_mtx);
2015                 /*
2016                  * Check the state here, and don't sleep if the state has
2017                  * already changed (i.e. wakeup has already occured, but we
2018                  * weren't waiting yet).
2019                  */
2020                 if (params.state == last_state) {
2021                         /* XXX KDM cv_wait_sig instead? */
2022                         cv_wait(&params.sem, &params.ioctl_mtx);
2023                 }
2024                 last_state = params.state;
2025
2026                 switch (params.state) {
2027                 case CTL_IOCTL_INPROG:
2028                         /* Why did we wake up? */
2029                         /* XXX KDM error here? */
2030                         mtx_unlock(&params.ioctl_mtx);
2031                         break;
2032                 case CTL_IOCTL_DATAMOVE:
2033                         CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
2034
2035                         /*
2036                          * change last_state back to INPROG to avoid
2037                          * deadlock on subsequent data moves.
2038                          */
2039                         params.state = last_state = CTL_IOCTL_INPROG;
2040
2041                         mtx_unlock(&params.ioctl_mtx);
2042                         ctl_ioctl_do_datamove(&io->scsiio);
2043                         /*
2044                          * Note that in some cases, most notably writes,
2045                          * this will queue the I/O and call us back later.
2046                          * In other cases, generally reads, this routine
2047                          * will immediately call back and wake us up,
2048                          * probably using our own context.
2049                          */
2050                         io->scsiio.be_move_done(io);
2051                         break;
2052                 case CTL_IOCTL_DONE:
2053                         mtx_unlock(&params.ioctl_mtx);
2054                         CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
2055                         done = 1;
2056                         break;
2057                 default:
2058                         mtx_unlock(&params.ioctl_mtx);
2059                         /* XXX KDM error here? */
2060                         break;
2061                 }
2062         } while (done == 0);
2063
2064         mtx_destroy(&params.ioctl_mtx);
2065         cv_destroy(&params.sem);
2066
2067         return (CTL_RETVAL_COMPLETE);
2068 }
2069
2070 static void
2071 ctl_ioctl_datamove(union ctl_io *io)
2072 {
2073         struct ctl_fe_ioctl_params *params;
2074
2075         params = (struct ctl_fe_ioctl_params *)
2076                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2077
2078         mtx_lock(&params->ioctl_mtx);
2079         params->state = CTL_IOCTL_DATAMOVE;
2080         cv_broadcast(&params->sem);
2081         mtx_unlock(&params->ioctl_mtx);
2082 }
2083
2084 static void
2085 ctl_ioctl_done(union ctl_io *io)
2086 {
2087         struct ctl_fe_ioctl_params *params;
2088
2089         params = (struct ctl_fe_ioctl_params *)
2090                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2091
2092         mtx_lock(&params->ioctl_mtx);
2093         params->state = CTL_IOCTL_DONE;
2094         cv_broadcast(&params->sem);
2095         mtx_unlock(&params->ioctl_mtx);
2096 }
2097
2098 static void
2099 ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2100 {
2101         struct ctl_fe_ioctl_startstop_info *sd_info;
2102
2103         sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2104
2105         sd_info->hs_info.status = metatask->status;
2106         sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2107         sd_info->hs_info.luns_complete =
2108                 metatask->taskinfo.startstop.luns_complete;
2109         sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2110
2111         cv_broadcast(&sd_info->sem);
2112 }
2113
2114 static void
2115 ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2116 {
2117         struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2118
2119         fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2120
2121         mtx_lock(fe_bbr_info->lock);
2122         fe_bbr_info->bbr_info->status = metatask->status;
2123         fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2124         fe_bbr_info->wakeup_done = 1;
2125         mtx_unlock(fe_bbr_info->lock);
2126
2127         cv_broadcast(&fe_bbr_info->sem);
2128 }
2129
2130 /*
2131  * Returns 0 for success, errno for failure.
2132  */
2133 static int
2134 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2135                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2136 {
2137         union ctl_io *io;
2138         int retval;
2139
2140         retval = 0;
2141
2142         mtx_lock(&lun->lun_lock);
2143         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2144              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2145              ooa_links)) {
2146                 struct ctl_ooa_entry *entry;
2147
2148                 /*
2149                  * If we've got more than we can fit, just count the
2150                  * remaining entries.
2151                  */
2152                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2153                         continue;
2154
2155                 entry = &kern_entries[*cur_fill_num];
2156
2157                 entry->tag_num = io->scsiio.tag_num;
2158                 entry->lun_num = lun->lun;
2159 #ifdef CTL_TIME_IO
2160                 entry->start_bt = io->io_hdr.start_bt;
2161 #endif
2162                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2163                 entry->cdb_len = io->scsiio.cdb_len;
2164                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2165                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2166
2167                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2168                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2169
2170                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2171                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2172
2173                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2174                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2175
2176                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2177                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2178         }
2179         mtx_unlock(&lun->lun_lock);
2180
2181         return (retval);
2182 }
2183
2184 static void *
2185 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2186                  size_t error_str_len)
2187 {
2188         void *kptr;
2189
2190         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2191
2192         if (copyin(user_addr, kptr, len) != 0) {
2193                 snprintf(error_str, error_str_len, "Error copying %d bytes "
2194                          "from user address %p to kernel address %p", len,
2195                          user_addr, kptr);
2196                 free(kptr, M_CTL);
2197                 return (NULL);
2198         }
2199
2200         return (kptr);
2201 }
2202
2203 static void
2204 ctl_free_args(int num_args, struct ctl_be_arg *args)
2205 {
2206         int i;
2207
2208         if (args == NULL)
2209                 return;
2210
2211         for (i = 0; i < num_args; i++) {
2212                 free(args[i].kname, M_CTL);
2213                 free(args[i].kvalue, M_CTL);
2214         }
2215
2216         free(args, M_CTL);
2217 }
2218
2219 static struct ctl_be_arg *
2220 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2221                 char *error_str, size_t error_str_len)
2222 {
2223         struct ctl_be_arg *args;
2224         int i;
2225
2226         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2227                                 error_str, error_str_len);
2228
2229         if (args == NULL)
2230                 goto bailout;
2231
2232         for (i = 0; i < num_args; i++) {
2233                 args[i].kname = NULL;
2234                 args[i].kvalue = NULL;
2235         }
2236
2237         for (i = 0; i < num_args; i++) {
2238                 uint8_t *tmpptr;
2239
2240                 args[i].kname = ctl_copyin_alloc(args[i].name,
2241                         args[i].namelen, error_str, error_str_len);
2242                 if (args[i].kname == NULL)
2243                         goto bailout;
2244
2245                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2246                         snprintf(error_str, error_str_len, "Argument %d "
2247                                  "name is not NUL-terminated", i);
2248                         goto bailout;
2249                 }
2250
2251                 if (args[i].flags & CTL_BEARG_RD) {
2252                         tmpptr = ctl_copyin_alloc(args[i].value,
2253                                 args[i].vallen, error_str, error_str_len);
2254                         if (tmpptr == NULL)
2255                                 goto bailout;
2256                         if ((args[i].flags & CTL_BEARG_ASCII)
2257                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2258                                 snprintf(error_str, error_str_len, "Argument "
2259                                     "%d value is not NUL-terminated", i);
2260                                 goto bailout;
2261                         }
2262                         args[i].kvalue = tmpptr;
2263                 } else {
2264                         args[i].kvalue = malloc(args[i].vallen,
2265                             M_CTL, M_WAITOK | M_ZERO);
2266                 }
2267         }
2268
2269         return (args);
2270 bailout:
2271
2272         ctl_free_args(num_args, args);
2273
2274         return (NULL);
2275 }
2276
2277 static void
2278 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2279 {
2280         int i;
2281
2282         for (i = 0; i < num_args; i++) {
2283                 if (args[i].flags & CTL_BEARG_WR)
2284                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2285         }
2286 }
2287
2288 /*
2289  * Escape characters that are illegal or not recommended in XML.
2290  */
2291 int
2292 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2293 {
2294         char *end = str + size;
2295         int retval;
2296
2297         retval = 0;
2298
2299         for (; *str && str < end; str++) {
2300                 switch (*str) {
2301                 case '&':
2302                         retval = sbuf_printf(sb, "&amp;");
2303                         break;
2304                 case '>':
2305                         retval = sbuf_printf(sb, "&gt;");
2306                         break;
2307                 case '<':
2308                         retval = sbuf_printf(sb, "&lt;");
2309                         break;
2310                 default:
2311                         retval = sbuf_putc(sb, *str);
2312                         break;
2313                 }
2314
2315                 if (retval != 0)
2316                         break;
2317
2318         }
2319
2320         return (retval);
2321 }
2322
2323 static void
2324 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2325 {
2326         struct scsi_vpd_id_descriptor *desc;
2327         int i;
2328
2329         if (id == NULL || id->len < 4)
2330                 return;
2331         desc = (struct scsi_vpd_id_descriptor *)id->data;
2332         switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2333         case SVPD_ID_TYPE_T10:
2334                 sbuf_printf(sb, "t10.");
2335                 break;
2336         case SVPD_ID_TYPE_EUI64:
2337                 sbuf_printf(sb, "eui.");
2338                 break;
2339         case SVPD_ID_TYPE_NAA:
2340                 sbuf_printf(sb, "naa.");
2341                 break;
2342         case SVPD_ID_TYPE_SCSI_NAME:
2343                 break;
2344         }
2345         switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2346         case SVPD_ID_CODESET_BINARY:
2347                 for (i = 0; i < desc->length; i++)
2348                         sbuf_printf(sb, "%02x", desc->identifier[i]);
2349                 break;
2350         case SVPD_ID_CODESET_ASCII:
2351                 sbuf_printf(sb, "%.*s", (int)desc->length,
2352                     (char *)desc->identifier);
2353                 break;
2354         case SVPD_ID_CODESET_UTF8:
2355                 sbuf_printf(sb, "%s", (char *)desc->identifier);
2356                 break;
2357         }
2358 }
2359
2360 static int
2361 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2362           struct thread *td)
2363 {
2364         struct ctl_softc *softc;
2365         int retval;
2366
2367         softc = control_softc;
2368
2369         retval = 0;
2370
2371         switch (cmd) {
2372         case CTL_IO: {
2373                 union ctl_io *io;
2374                 void *pool_tmp;
2375
2376                 /*
2377                  * If we haven't been "enabled", don't allow any SCSI I/O
2378                  * to this FETD.
2379                  */
2380                 if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2381                         retval = EPERM;
2382                         break;
2383                 }
2384
2385                 io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2386
2387                 /*
2388                  * Need to save the pool reference so it doesn't get
2389                  * spammed by the user's ctl_io.
2390                  */
2391                 pool_tmp = io->io_hdr.pool;
2392                 memcpy(io, (void *)addr, sizeof(*io));
2393                 io->io_hdr.pool = pool_tmp;
2394
2395                 /*
2396                  * No status yet, so make sure the status is set properly.
2397                  */
2398                 io->io_hdr.status = CTL_STATUS_NONE;
2399
2400                 /*
2401                  * The user sets the initiator ID, target and LUN IDs.
2402                  */
2403                 io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2404                 io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2405                 if ((io->io_hdr.io_type == CTL_IO_SCSI)
2406                  && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2407                         io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2408
2409                 retval = ctl_ioctl_submit_wait(io);
2410
2411                 if (retval != 0) {
2412                         ctl_free_io(io);
2413                         break;
2414                 }
2415
2416                 memcpy((void *)addr, io, sizeof(*io));
2417
2418                 /* return this to our pool */
2419                 ctl_free_io(io);
2420
2421                 break;
2422         }
2423         case CTL_ENABLE_PORT:
2424         case CTL_DISABLE_PORT:
2425         case CTL_SET_PORT_WWNS: {
2426                 struct ctl_port *port;
2427                 struct ctl_port_entry *entry;
2428
2429                 entry = (struct ctl_port_entry *)addr;
2430                 
2431                 mtx_lock(&softc->ctl_lock);
2432                 STAILQ_FOREACH(port, &softc->port_list, links) {
2433                         int action, done;
2434
2435                         action = 0;
2436                         done = 0;
2437
2438                         if ((entry->port_type == CTL_PORT_NONE)
2439                          && (entry->targ_port == port->targ_port)) {
2440                                 /*
2441                                  * If the user only wants to enable or
2442                                  * disable or set WWNs on a specific port,
2443                                  * do the operation and we're done.
2444                                  */
2445                                 action = 1;
2446                                 done = 1;
2447                         } else if (entry->port_type & port->port_type) {
2448                                 /*
2449                                  * Compare the user's type mask with the
2450                                  * particular frontend type to see if we
2451                                  * have a match.
2452                                  */
2453                                 action = 1;
2454                                 done = 0;
2455
2456                                 /*
2457                                  * Make sure the user isn't trying to set
2458                                  * WWNs on multiple ports at the same time.
2459                                  */
2460                                 if (cmd == CTL_SET_PORT_WWNS) {
2461                                         printf("%s: Can't set WWNs on "
2462                                                "multiple ports\n", __func__);
2463                                         retval = EINVAL;
2464                                         break;
2465                                 }
2466                         }
2467                         if (action != 0) {
2468                                 /*
2469                                  * XXX KDM we have to drop the lock here,
2470                                  * because the online/offline operations
2471                                  * can potentially block.  We need to
2472                                  * reference count the frontends so they
2473                                  * can't go away,
2474                                  */
2475                                 mtx_unlock(&softc->ctl_lock);
2476
2477                                 if (cmd == CTL_ENABLE_PORT) {
2478                                         ctl_port_online(port);
2479                                 } else if (cmd == CTL_DISABLE_PORT) {
2480                                         ctl_port_offline(port);
2481                                 }
2482
2483                                 mtx_lock(&softc->ctl_lock);
2484
2485                                 if (cmd == CTL_SET_PORT_WWNS)
2486                                         ctl_port_set_wwns(port,
2487                                             (entry->flags & CTL_PORT_WWNN_VALID) ?
2488                                             1 : 0, entry->wwnn,
2489                                             (entry->flags & CTL_PORT_WWPN_VALID) ?
2490                                             1 : 0, entry->wwpn);
2491                         }
2492                         if (done != 0)
2493                                 break;
2494                 }
2495                 mtx_unlock(&softc->ctl_lock);
2496                 break;
2497         }
2498         case CTL_GET_PORT_LIST: {
2499                 struct ctl_port *port;
2500                 struct ctl_port_list *list;
2501                 int i;
2502
2503                 list = (struct ctl_port_list *)addr;
2504
2505                 if (list->alloc_len != (list->alloc_num *
2506                     sizeof(struct ctl_port_entry))) {
2507                         printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2508                                "alloc_num %u * sizeof(struct ctl_port_entry) "
2509                                "%zu\n", __func__, list->alloc_len,
2510                                list->alloc_num, sizeof(struct ctl_port_entry));
2511                         retval = EINVAL;
2512                         break;
2513                 }
2514                 list->fill_len = 0;
2515                 list->fill_num = 0;
2516                 list->dropped_num = 0;
2517                 i = 0;
2518                 mtx_lock(&softc->ctl_lock);
2519                 STAILQ_FOREACH(port, &softc->port_list, links) {
2520                         struct ctl_port_entry entry, *list_entry;
2521
2522                         if (list->fill_num >= list->alloc_num) {
2523                                 list->dropped_num++;
2524                                 continue;
2525                         }
2526
2527                         entry.port_type = port->port_type;
2528                         strlcpy(entry.port_name, port->port_name,
2529                                 sizeof(entry.port_name));
2530                         entry.targ_port = port->targ_port;
2531                         entry.physical_port = port->physical_port;
2532                         entry.virtual_port = port->virtual_port;
2533                         entry.wwnn = port->wwnn;
2534                         entry.wwpn = port->wwpn;
2535                         if (port->status & CTL_PORT_STATUS_ONLINE)
2536                                 entry.online = 1;
2537                         else
2538                                 entry.online = 0;
2539
2540                         list_entry = &list->entries[i];
2541
2542                         retval = copyout(&entry, list_entry, sizeof(entry));
2543                         if (retval != 0) {
2544                                 printf("%s: CTL_GET_PORT_LIST: copyout "
2545                                        "returned %d\n", __func__, retval);
2546                                 break;
2547                         }
2548                         i++;
2549                         list->fill_num++;
2550                         list->fill_len += sizeof(entry);
2551                 }
2552                 mtx_unlock(&softc->ctl_lock);
2553
2554                 /*
2555                  * If this is non-zero, we had a copyout fault, so there's
2556                  * probably no point in attempting to set the status inside
2557                  * the structure.
2558                  */
2559                 if (retval != 0)
2560                         break;
2561
2562                 if (list->dropped_num > 0)
2563                         list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2564                 else
2565                         list->status = CTL_PORT_LIST_OK;
2566                 break;
2567         }
2568         case CTL_DUMP_OOA: {
2569                 struct ctl_lun *lun;
2570                 union ctl_io *io;
2571                 char printbuf[128];
2572                 struct sbuf sb;
2573
2574                 mtx_lock(&softc->ctl_lock);
2575                 printf("Dumping OOA queues:\n");
2576                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2577                         mtx_lock(&lun->lun_lock);
2578                         for (io = (union ctl_io *)TAILQ_FIRST(
2579                              &lun->ooa_queue); io != NULL;
2580                              io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2581                              ooa_links)) {
2582                                 sbuf_new(&sb, printbuf, sizeof(printbuf),
2583                                          SBUF_FIXEDLEN);
2584                                 sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2585                                             (intmax_t)lun->lun,
2586                                             io->scsiio.tag_num,
2587                                             (io->io_hdr.flags &
2588                                             CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2589                                             (io->io_hdr.flags &
2590                                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2591                                             (io->io_hdr.flags &
2592                                             CTL_FLAG_ABORT) ? " ABORT" : "",
2593                                             (io->io_hdr.flags &
2594                                         CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2595                                 ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2596                                 sbuf_finish(&sb);
2597                                 printf("%s\n", sbuf_data(&sb));
2598                         }
2599                         mtx_unlock(&lun->lun_lock);
2600                 }
2601                 printf("OOA queues dump done\n");
2602                 mtx_unlock(&softc->ctl_lock);
2603                 break;
2604         }
2605         case CTL_GET_OOA: {
2606                 struct ctl_lun *lun;
2607                 struct ctl_ooa *ooa_hdr;
2608                 struct ctl_ooa_entry *entries;
2609                 uint32_t cur_fill_num;
2610
2611                 ooa_hdr = (struct ctl_ooa *)addr;
2612
2613                 if ((ooa_hdr->alloc_len == 0)
2614                  || (ooa_hdr->alloc_num == 0)) {
2615                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2616                                "must be non-zero\n", __func__,
2617                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2618                         retval = EINVAL;
2619                         break;
2620                 }
2621
2622                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2623                     sizeof(struct ctl_ooa_entry))) {
2624                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2625                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2626                                __func__, ooa_hdr->alloc_len,
2627                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2628                         retval = EINVAL;
2629                         break;
2630                 }
2631
2632                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2633                 if (entries == NULL) {
2634                         printf("%s: could not allocate %d bytes for OOA "
2635                                "dump\n", __func__, ooa_hdr->alloc_len);
2636                         retval = ENOMEM;
2637                         break;
2638                 }
2639
2640                 mtx_lock(&softc->ctl_lock);
2641                 if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2642                  && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2643                   || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2644                         mtx_unlock(&softc->ctl_lock);
2645                         free(entries, M_CTL);
2646                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2647                                __func__, (uintmax_t)ooa_hdr->lun_num);
2648                         retval = EINVAL;
2649                         break;
2650                 }
2651
2652                 cur_fill_num = 0;
2653
2654                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2655                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2656                                 retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2657                                         ooa_hdr, entries);
2658                                 if (retval != 0)
2659                                         break;
2660                         }
2661                         if (retval != 0) {
2662                                 mtx_unlock(&softc->ctl_lock);
2663                                 free(entries, M_CTL);
2664                                 break;
2665                         }
2666                 } else {
2667                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2668
2669                         retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2670                                                     entries);
2671                 }
2672                 mtx_unlock(&softc->ctl_lock);
2673
2674                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2675                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2676                         sizeof(struct ctl_ooa_entry);
2677                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2678                 if (retval != 0) {
2679                         printf("%s: error copying out %d bytes for OOA dump\n", 
2680                                __func__, ooa_hdr->fill_len);
2681                 }
2682
2683                 getbintime(&ooa_hdr->cur_bt);
2684
2685                 if (cur_fill_num > ooa_hdr->alloc_num) {
2686                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2687                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2688                 } else {
2689                         ooa_hdr->dropped_num = 0;
2690                         ooa_hdr->status = CTL_OOA_OK;
2691                 }
2692
2693                 free(entries, M_CTL);
2694                 break;
2695         }
2696         case CTL_CHECK_OOA: {
2697                 union ctl_io *io;
2698                 struct ctl_lun *lun;
2699                 struct ctl_ooa_info *ooa_info;
2700
2701
2702                 ooa_info = (struct ctl_ooa_info *)addr;
2703
2704                 if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2705                         ooa_info->status = CTL_OOA_INVALID_LUN;
2706                         break;
2707                 }
2708                 mtx_lock(&softc->ctl_lock);
2709                 lun = softc->ctl_luns[ooa_info->lun_id];
2710                 if (lun == NULL) {
2711                         mtx_unlock(&softc->ctl_lock);
2712                         ooa_info->status = CTL_OOA_INVALID_LUN;
2713                         break;
2714                 }
2715                 mtx_lock(&lun->lun_lock);
2716                 mtx_unlock(&softc->ctl_lock);
2717                 ooa_info->num_entries = 0;
2718                 for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2719                      io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2720                      &io->io_hdr, ooa_links)) {
2721                         ooa_info->num_entries++;
2722                 }
2723                 mtx_unlock(&lun->lun_lock);
2724
2725                 ooa_info->status = CTL_OOA_SUCCESS;
2726
2727                 break;
2728         }
2729         case CTL_HARD_START:
2730         case CTL_HARD_STOP: {
2731                 struct ctl_fe_ioctl_startstop_info ss_info;
2732                 struct cfi_metatask *metatask;
2733                 struct mtx hs_mtx;
2734
2735                 mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2736
2737                 cv_init(&ss_info.sem, "hard start/stop cv" );
2738
2739                 metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2740                 if (metatask == NULL) {
2741                         retval = ENOMEM;
2742                         mtx_destroy(&hs_mtx);
2743                         break;
2744                 }
2745
2746                 if (cmd == CTL_HARD_START)
2747                         metatask->tasktype = CFI_TASK_STARTUP;
2748                 else
2749                         metatask->tasktype = CFI_TASK_SHUTDOWN;
2750
2751                 metatask->callback = ctl_ioctl_hard_startstop_callback;
2752                 metatask->callback_arg = &ss_info;
2753
2754                 cfi_action(metatask);
2755
2756                 /* Wait for the callback */
2757                 mtx_lock(&hs_mtx);
2758                 cv_wait_sig(&ss_info.sem, &hs_mtx);
2759                 mtx_unlock(&hs_mtx);
2760
2761                 /*
2762                  * All information has been copied from the metatask by the
2763                  * time cv_broadcast() is called, so we free the metatask here.
2764                  */
2765                 cfi_free_metatask(metatask);
2766
2767                 memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2768
2769                 mtx_destroy(&hs_mtx);
2770                 break;
2771         }
2772         case CTL_BBRREAD: {
2773                 struct ctl_bbrread_info *bbr_info;
2774                 struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2775                 struct mtx bbr_mtx;
2776                 struct cfi_metatask *metatask;
2777
2778                 bbr_info = (struct ctl_bbrread_info *)addr;
2779
2780                 bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2781
2782                 bzero(&bbr_mtx, sizeof(bbr_mtx));
2783                 mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2784
2785                 fe_bbr_info.bbr_info = bbr_info;
2786                 fe_bbr_info.lock = &bbr_mtx;
2787
2788                 cv_init(&fe_bbr_info.sem, "BBR read cv");
2789                 metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2790
2791                 if (metatask == NULL) {
2792                         mtx_destroy(&bbr_mtx);
2793                         cv_destroy(&fe_bbr_info.sem);
2794                         retval = ENOMEM;
2795                         break;
2796                 }
2797                 metatask->tasktype = CFI_TASK_BBRREAD;
2798                 metatask->callback = ctl_ioctl_bbrread_callback;
2799                 metatask->callback_arg = &fe_bbr_info;
2800                 metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2801                 metatask->taskinfo.bbrread.lba = bbr_info->lba;
2802                 metatask->taskinfo.bbrread.len = bbr_info->len;
2803
2804                 cfi_action(metatask);
2805
2806                 mtx_lock(&bbr_mtx);
2807                 while (fe_bbr_info.wakeup_done == 0)
2808                         cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2809                 mtx_unlock(&bbr_mtx);
2810
2811                 bbr_info->status = metatask->status;
2812                 bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2813                 bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2814                 memcpy(&bbr_info->sense_data,
2815                        &metatask->taskinfo.bbrread.sense_data,
2816                        MIN(sizeof(bbr_info->sense_data),
2817                            sizeof(metatask->taskinfo.bbrread.sense_data)));
2818
2819                 cfi_free_metatask(metatask);
2820
2821                 mtx_destroy(&bbr_mtx);
2822                 cv_destroy(&fe_bbr_info.sem);
2823
2824                 break;
2825         }
2826         case CTL_DELAY_IO: {
2827                 struct ctl_io_delay_info *delay_info;
2828 #ifdef CTL_IO_DELAY
2829                 struct ctl_lun *lun;
2830 #endif /* CTL_IO_DELAY */
2831
2832                 delay_info = (struct ctl_io_delay_info *)addr;
2833
2834 #ifdef CTL_IO_DELAY
2835                 mtx_lock(&softc->ctl_lock);
2836
2837                 if ((delay_info->lun_id >= CTL_MAX_LUNS)
2838                  || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2839                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2840                 } else {
2841                         lun = softc->ctl_luns[delay_info->lun_id];
2842                         mtx_lock(&lun->lun_lock);
2843
2844                         delay_info->status = CTL_DELAY_STATUS_OK;
2845
2846                         switch (delay_info->delay_type) {
2847                         case CTL_DELAY_TYPE_CONT:
2848                                 break;
2849                         case CTL_DELAY_TYPE_ONESHOT:
2850                                 break;
2851                         default:
2852                                 delay_info->status =
2853                                         CTL_DELAY_STATUS_INVALID_TYPE;
2854                                 break;
2855                         }
2856
2857                         switch (delay_info->delay_loc) {
2858                         case CTL_DELAY_LOC_DATAMOVE:
2859                                 lun->delay_info.datamove_type =
2860                                         delay_info->delay_type;
2861                                 lun->delay_info.datamove_delay =
2862                                         delay_info->delay_secs;
2863                                 break;
2864                         case CTL_DELAY_LOC_DONE:
2865                                 lun->delay_info.done_type =
2866                                         delay_info->delay_type;
2867                                 lun->delay_info.done_delay =
2868                                         delay_info->delay_secs;
2869                                 break;
2870                         default:
2871                                 delay_info->status =
2872                                         CTL_DELAY_STATUS_INVALID_LOC;
2873                                 break;
2874                         }
2875                         mtx_unlock(&lun->lun_lock);
2876                 }
2877
2878                 mtx_unlock(&softc->ctl_lock);
2879 #else
2880                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2881 #endif /* CTL_IO_DELAY */
2882                 break;
2883         }
2884         case CTL_REALSYNC_SET: {
2885                 int *syncstate;
2886
2887                 syncstate = (int *)addr;
2888
2889                 mtx_lock(&softc->ctl_lock);
2890                 switch (*syncstate) {
2891                 case 0:
2892                         softc->flags &= ~CTL_FLAG_REAL_SYNC;
2893                         break;
2894                 case 1:
2895                         softc->flags |= CTL_FLAG_REAL_SYNC;
2896                         break;
2897                 default:
2898                         retval = EINVAL;
2899                         break;
2900                 }
2901                 mtx_unlock(&softc->ctl_lock);
2902                 break;
2903         }
2904         case CTL_REALSYNC_GET: {
2905                 int *syncstate;
2906
2907                 syncstate = (int*)addr;
2908
2909                 mtx_lock(&softc->ctl_lock);
2910                 if (softc->flags & CTL_FLAG_REAL_SYNC)
2911                         *syncstate = 1;
2912                 else
2913                         *syncstate = 0;
2914                 mtx_unlock(&softc->ctl_lock);
2915
2916                 break;
2917         }
2918         case CTL_SETSYNC:
2919         case CTL_GETSYNC: {
2920                 struct ctl_sync_info *sync_info;
2921                 struct ctl_lun *lun;
2922
2923                 sync_info = (struct ctl_sync_info *)addr;
2924
2925                 mtx_lock(&softc->ctl_lock);
2926                 lun = softc->ctl_luns[sync_info->lun_id];
2927                 if (lun == NULL) {
2928                         mtx_unlock(&softc->ctl_lock);
2929                         sync_info->status = CTL_GS_SYNC_NO_LUN;
2930                 }
2931                 /*
2932                  * Get or set the sync interval.  We're not bounds checking
2933                  * in the set case, hopefully the user won't do something
2934                  * silly.
2935                  */
2936                 mtx_lock(&lun->lun_lock);
2937                 mtx_unlock(&softc->ctl_lock);
2938                 if (cmd == CTL_GETSYNC)
2939                         sync_info->sync_interval = lun->sync_interval;
2940                 else
2941                         lun->sync_interval = sync_info->sync_interval;
2942                 mtx_unlock(&lun->lun_lock);
2943
2944                 sync_info->status = CTL_GS_SYNC_OK;
2945
2946                 break;
2947         }
2948         case CTL_GETSTATS: {
2949                 struct ctl_stats *stats;
2950                 struct ctl_lun *lun;
2951                 int i;
2952
2953                 stats = (struct ctl_stats *)addr;
2954
2955                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2956                      stats->alloc_len) {
2957                         stats->status = CTL_SS_NEED_MORE_SPACE;
2958                         stats->num_luns = softc->num_luns;
2959                         break;
2960                 }
2961                 /*
2962                  * XXX KDM no locking here.  If the LUN list changes,
2963                  * things can blow up.
2964                  */
2965                 for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2966                      i++, lun = STAILQ_NEXT(lun, links)) {
2967                         retval = copyout(&lun->stats, &stats->lun_stats[i],
2968                                          sizeof(lun->stats));
2969                         if (retval != 0)
2970                                 break;
2971                 }
2972                 stats->num_luns = softc->num_luns;
2973                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2974                                  softc->num_luns;
2975                 stats->status = CTL_SS_OK;
2976 #ifdef CTL_TIME_IO
2977                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
2978 #else
2979                 stats->flags = CTL_STATS_FLAG_NONE;
2980 #endif
2981                 getnanouptime(&stats->timestamp);
2982                 break;
2983         }
2984         case CTL_ERROR_INJECT: {
2985                 struct ctl_error_desc *err_desc, *new_err_desc;
2986                 struct ctl_lun *lun;
2987
2988                 err_desc = (struct ctl_error_desc *)addr;
2989
2990                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2991                                       M_WAITOK | M_ZERO);
2992                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2993
2994                 mtx_lock(&softc->ctl_lock);
2995                 lun = softc->ctl_luns[err_desc->lun_id];
2996                 if (lun == NULL) {
2997                         mtx_unlock(&softc->ctl_lock);
2998                         free(new_err_desc, M_CTL);
2999                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
3000                                __func__, (uintmax_t)err_desc->lun_id);
3001                         retval = EINVAL;
3002                         break;
3003                 }
3004                 mtx_lock(&lun->lun_lock);
3005                 mtx_unlock(&softc->ctl_lock);
3006
3007                 /*
3008                  * We could do some checking here to verify the validity
3009                  * of the request, but given the complexity of error
3010                  * injection requests, the checking logic would be fairly
3011                  * complex.
3012                  *
3013                  * For now, if the request is invalid, it just won't get
3014                  * executed and might get deleted.
3015                  */
3016                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
3017
3018                 /*
3019                  * XXX KDM check to make sure the serial number is unique,
3020                  * in case we somehow manage to wrap.  That shouldn't
3021                  * happen for a very long time, but it's the right thing to
3022                  * do.
3023                  */
3024                 new_err_desc->serial = lun->error_serial;
3025                 err_desc->serial = lun->error_serial;
3026                 lun->error_serial++;
3027
3028                 mtx_unlock(&lun->lun_lock);
3029                 break;
3030         }
3031         case CTL_ERROR_INJECT_DELETE: {
3032                 struct ctl_error_desc *delete_desc, *desc, *desc2;
3033                 struct ctl_lun *lun;
3034                 int delete_done;
3035
3036                 delete_desc = (struct ctl_error_desc *)addr;
3037                 delete_done = 0;
3038
3039                 mtx_lock(&softc->ctl_lock);
3040                 lun = softc->ctl_luns[delete_desc->lun_id];
3041                 if (lun == NULL) {
3042                         mtx_unlock(&softc->ctl_lock);
3043                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
3044                                __func__, (uintmax_t)delete_desc->lun_id);
3045                         retval = EINVAL;
3046                         break;
3047                 }
3048                 mtx_lock(&lun->lun_lock);
3049                 mtx_unlock(&softc->ctl_lock);
3050                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
3051                         if (desc->serial != delete_desc->serial)
3052                                 continue;
3053
3054                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
3055                                       links);
3056                         free(desc, M_CTL);
3057                         delete_done = 1;
3058                 }
3059                 mtx_unlock(&lun->lun_lock);
3060                 if (delete_done == 0) {
3061                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
3062                                "error serial %ju on LUN %u\n", __func__, 
3063                                delete_desc->serial, delete_desc->lun_id);
3064                         retval = EINVAL;
3065                         break;
3066                 }
3067                 break;
3068         }
3069         case CTL_DUMP_STRUCTS: {
3070                 int i, j, k;
3071                 struct ctl_port *port;
3072                 struct ctl_frontend *fe;
3073
3074                 mtx_lock(&softc->ctl_lock);
3075                 printf("CTL Persistent Reservation information start:\n");
3076                 for (i = 0; i < CTL_MAX_LUNS; i++) {
3077                         struct ctl_lun *lun;
3078
3079                         lun = softc->ctl_luns[i];
3080
3081                         if ((lun == NULL)
3082                          || ((lun->flags & CTL_LUN_DISABLED) != 0))
3083                                 continue;
3084
3085                         for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
3086                                 if (lun->pr_keys[j] == NULL)
3087                                         continue;
3088                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3089                                         if (lun->pr_keys[j][k] == 0)
3090                                                 continue;
3091                                         printf("  LUN %d port %d iid %d key "
3092                                                "%#jx\n", i, j, k,
3093                                                (uintmax_t)lun->pr_keys[j][k]);
3094                                 }
3095                         }
3096                 }
3097                 printf("CTL Persistent Reservation information end\n");
3098                 printf("CTL Ports:\n");
3099                 STAILQ_FOREACH(port, &softc->port_list, links) {
3100                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3101                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3102                                port->frontend->name, port->port_type,
3103                                port->physical_port, port->virtual_port,
3104                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3105                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3106                                 if (port->wwpn_iid[j].in_use == 0 &&
3107                                     port->wwpn_iid[j].wwpn == 0 &&
3108                                     port->wwpn_iid[j].name == NULL)
3109                                         continue;
3110
3111                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
3112                                     j, port->wwpn_iid[j].in_use,
3113                                     (uintmax_t)port->wwpn_iid[j].wwpn,
3114                                     port->wwpn_iid[j].name);
3115                         }
3116                 }
3117                 printf("CTL Port information end\n");
3118                 mtx_unlock(&softc->ctl_lock);
3119                 /*
3120                  * XXX KDM calling this without a lock.  We'd likely want
3121                  * to drop the lock before calling the frontend's dump
3122                  * routine anyway.
3123                  */
3124                 printf("CTL Frontends:\n");
3125                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
3126                         printf("  Frontend '%s'\n", fe->name);
3127                         if (fe->fe_dump != NULL)
3128                                 fe->fe_dump();
3129                 }
3130                 printf("CTL Frontend information end\n");
3131                 break;
3132         }
3133         case CTL_LUN_REQ: {
3134                 struct ctl_lun_req *lun_req;
3135                 struct ctl_backend_driver *backend;
3136
3137                 lun_req = (struct ctl_lun_req *)addr;
3138
3139                 backend = ctl_backend_find(lun_req->backend);
3140                 if (backend == NULL) {
3141                         lun_req->status = CTL_LUN_ERROR;
3142                         snprintf(lun_req->error_str,
3143                                  sizeof(lun_req->error_str),
3144                                  "Backend \"%s\" not found.",
3145                                  lun_req->backend);
3146                         break;
3147                 }
3148                 if (lun_req->num_be_args > 0) {
3149                         lun_req->kern_be_args = ctl_copyin_args(
3150                                 lun_req->num_be_args,
3151                                 lun_req->be_args,
3152                                 lun_req->error_str,
3153                                 sizeof(lun_req->error_str));
3154                         if (lun_req->kern_be_args == NULL) {
3155                                 lun_req->status = CTL_LUN_ERROR;
3156                                 break;
3157                         }
3158                 }
3159
3160                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3161
3162                 if (lun_req->num_be_args > 0) {
3163                         ctl_copyout_args(lun_req->num_be_args,
3164                                       lun_req->kern_be_args);
3165                         ctl_free_args(lun_req->num_be_args,
3166                                       lun_req->kern_be_args);
3167                 }
3168                 break;
3169         }
3170         case CTL_LUN_LIST: {
3171                 struct sbuf *sb;
3172                 struct ctl_lun *lun;
3173                 struct ctl_lun_list *list;
3174                 struct ctl_option *opt;
3175
3176                 list = (struct ctl_lun_list *)addr;
3177
3178                 /*
3179                  * Allocate a fixed length sbuf here, based on the length
3180                  * of the user's buffer.  We could allocate an auto-extending
3181                  * buffer, and then tell the user how much larger our
3182                  * amount of data is than his buffer, but that presents
3183                  * some problems:
3184                  *
3185                  * 1.  The sbuf(9) routines use a blocking malloc, and so
3186                  *     we can't hold a lock while calling them with an
3187                  *     auto-extending buffer.
3188                  *
3189                  * 2.  There is not currently a LUN reference counting
3190                  *     mechanism, outside of outstanding transactions on
3191                  *     the LUN's OOA queue.  So a LUN could go away on us
3192                  *     while we're getting the LUN number, backend-specific
3193                  *     information, etc.  Thus, given the way things
3194                  *     currently work, we need to hold the CTL lock while
3195                  *     grabbing LUN information.
3196                  *
3197                  * So, from the user's standpoint, the best thing to do is
3198                  * allocate what he thinks is a reasonable buffer length,
3199                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3200                  * double the buffer length and try again.  (And repeat
3201                  * that until he succeeds.)
3202                  */
3203                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3204                 if (sb == NULL) {
3205                         list->status = CTL_LUN_LIST_ERROR;
3206                         snprintf(list->error_str, sizeof(list->error_str),
3207                                  "Unable to allocate %d bytes for LUN list",
3208                                  list->alloc_len);
3209                         break;
3210                 }
3211
3212                 sbuf_printf(sb, "<ctllunlist>\n");
3213
3214                 mtx_lock(&softc->ctl_lock);
3215                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3216                         mtx_lock(&lun->lun_lock);
3217                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3218                                              (uintmax_t)lun->lun);
3219
3220                         /*
3221                          * Bail out as soon as we see that we've overfilled
3222                          * the buffer.
3223                          */
3224                         if (retval != 0)
3225                                 break;
3226
3227                         retval = sbuf_printf(sb, "\t<backend_type>%s"
3228                                              "</backend_type>\n",
3229                                              (lun->backend == NULL) ?  "none" :
3230                                              lun->backend->name);
3231
3232                         if (retval != 0)
3233                                 break;
3234
3235                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3236                                              lun->be_lun->lun_type);
3237
3238                         if (retval != 0)
3239                                 break;
3240
3241                         if (lun->backend == NULL) {
3242                                 retval = sbuf_printf(sb, "</lun>\n");
3243                                 if (retval != 0)
3244                                         break;
3245                                 continue;
3246                         }
3247
3248                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3249                                              (lun->be_lun->maxlba > 0) ?
3250                                              lun->be_lun->maxlba + 1 : 0);
3251
3252                         if (retval != 0)
3253                                 break;
3254
3255                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3256                                              lun->be_lun->blocksize);
3257
3258                         if (retval != 0)
3259                                 break;
3260
3261                         retval = sbuf_printf(sb, "\t<serial_number>");
3262
3263                         if (retval != 0)
3264                                 break;
3265
3266                         retval = ctl_sbuf_printf_esc(sb,
3267                             lun->be_lun->serial_num,
3268                             sizeof(lun->be_lun->serial_num));
3269
3270                         if (retval != 0)
3271                                 break;
3272
3273                         retval = sbuf_printf(sb, "</serial_number>\n");
3274                 
3275                         if (retval != 0)
3276                                 break;
3277
3278                         retval = sbuf_printf(sb, "\t<device_id>");
3279
3280                         if (retval != 0)
3281                                 break;
3282
3283                         retval = ctl_sbuf_printf_esc(sb,
3284                             lun->be_lun->device_id,
3285                             sizeof(lun->be_lun->device_id));
3286
3287                         if (retval != 0)
3288                                 break;
3289
3290                         retval = sbuf_printf(sb, "</device_id>\n");
3291
3292                         if (retval != 0)
3293                                 break;
3294
3295                         if (lun->backend->lun_info != NULL) {
3296                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3297                                 if (retval != 0)
3298                                         break;
3299                         }
3300                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3301                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3302                                     opt->name, opt->value, opt->name);
3303                                 if (retval != 0)
3304                                         break;
3305                         }
3306
3307                         retval = sbuf_printf(sb, "</lun>\n");
3308
3309                         if (retval != 0)
3310                                 break;
3311                         mtx_unlock(&lun->lun_lock);
3312                 }
3313                 if (lun != NULL)
3314                         mtx_unlock(&lun->lun_lock);
3315                 mtx_unlock(&softc->ctl_lock);
3316
3317                 if ((retval != 0)
3318                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3319                         retval = 0;
3320                         sbuf_delete(sb);
3321                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3322                         snprintf(list->error_str, sizeof(list->error_str),
3323                                  "Out of space, %d bytes is too small",
3324                                  list->alloc_len);
3325                         break;
3326                 }
3327
3328                 sbuf_finish(sb);
3329
3330                 retval = copyout(sbuf_data(sb), list->lun_xml,
3331                                  sbuf_len(sb) + 1);
3332
3333                 list->fill_len = sbuf_len(sb) + 1;
3334                 list->status = CTL_LUN_LIST_OK;
3335                 sbuf_delete(sb);
3336                 break;
3337         }
3338         case CTL_ISCSI: {
3339                 struct ctl_iscsi *ci;
3340                 struct ctl_frontend *fe;
3341
3342                 ci = (struct ctl_iscsi *)addr;
3343
3344                 fe = ctl_frontend_find("iscsi");
3345                 if (fe == NULL) {
3346                         ci->status = CTL_ISCSI_ERROR;
3347                         snprintf(ci->error_str, sizeof(ci->error_str),
3348                             "Frontend \"iscsi\" not found.");
3349                         break;
3350                 }
3351
3352                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3353                 break;
3354         }
3355         case CTL_PORT_REQ: {
3356                 struct ctl_req *req;
3357                 struct ctl_frontend *fe;
3358
3359                 req = (struct ctl_req *)addr;
3360
3361                 fe = ctl_frontend_find(req->driver);
3362                 if (fe == NULL) {
3363                         req->status = CTL_LUN_ERROR;
3364                         snprintf(req->error_str, sizeof(req->error_str),
3365                             "Frontend \"%s\" not found.", req->driver);
3366                         break;
3367                 }
3368                 if (req->num_args > 0) {
3369                         req->kern_args = ctl_copyin_args(req->num_args,
3370                             req->args, req->error_str, sizeof(req->error_str));
3371                         if (req->kern_args == NULL) {
3372                                 req->status = CTL_LUN_ERROR;
3373                                 break;
3374                         }
3375                 }
3376
3377                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3378
3379                 if (req->num_args > 0) {
3380                         ctl_copyout_args(req->num_args, req->kern_args);
3381                         ctl_free_args(req->num_args, req->kern_args);
3382                 }
3383                 break;
3384         }
3385         case CTL_PORT_LIST: {
3386                 struct sbuf *sb;
3387                 struct ctl_port *port;
3388                 struct ctl_lun_list *list;
3389                 struct ctl_option *opt;
3390                 int j;
3391                 uint32_t plun;
3392
3393                 list = (struct ctl_lun_list *)addr;
3394
3395                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3396                 if (sb == NULL) {
3397                         list->status = CTL_LUN_LIST_ERROR;
3398                         snprintf(list->error_str, sizeof(list->error_str),
3399                                  "Unable to allocate %d bytes for LUN list",
3400                                  list->alloc_len);
3401                         break;
3402                 }
3403
3404                 sbuf_printf(sb, "<ctlportlist>\n");
3405
3406                 mtx_lock(&softc->ctl_lock);
3407                 STAILQ_FOREACH(port, &softc->port_list, links) {
3408                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3409                                              (uintmax_t)port->targ_port);
3410
3411                         /*
3412                          * Bail out as soon as we see that we've overfilled
3413                          * the buffer.
3414                          */
3415                         if (retval != 0)
3416                                 break;
3417
3418                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3419                             "</frontend_type>\n", port->frontend->name);
3420                         if (retval != 0)
3421                                 break;
3422
3423                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3424                                              port->port_type);
3425                         if (retval != 0)
3426                                 break;
3427
3428                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3429                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3430                         if (retval != 0)
3431                                 break;
3432
3433                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3434                             port->port_name);
3435                         if (retval != 0)
3436                                 break;
3437
3438                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3439                             port->physical_port);
3440                         if (retval != 0)
3441                                 break;
3442
3443                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3444                             port->virtual_port);
3445                         if (retval != 0)
3446                                 break;
3447
3448                         if (port->target_devid != NULL) {
3449                                 sbuf_printf(sb, "\t<target>");
3450                                 ctl_id_sbuf(port->target_devid, sb);
3451                                 sbuf_printf(sb, "</target>\n");
3452                         }
3453
3454                         if (port->port_devid != NULL) {
3455                                 sbuf_printf(sb, "\t<port>");
3456                                 ctl_id_sbuf(port->port_devid, sb);
3457                                 sbuf_printf(sb, "</port>\n");
3458                         }
3459
3460                         if (port->port_info != NULL) {
3461                                 retval = port->port_info(port->onoff_arg, sb);
3462                                 if (retval != 0)
3463                                         break;
3464                         }
3465                         STAILQ_FOREACH(opt, &port->options, links) {
3466                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3467                                     opt->name, opt->value, opt->name);
3468                                 if (retval != 0)
3469                                         break;
3470                         }
3471
3472                         if (port->lun_map != NULL) {
3473                                 sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3474                                 for (j = 0; j < CTL_MAX_LUNS; j++) {
3475                                         plun = ctl_lun_map_from_port(port, j);
3476                                         if (plun >= CTL_MAX_LUNS)
3477                                                 continue;
3478                                         sbuf_printf(sb,
3479                                             "\t<lun id=\"%u\">%u</lun>\n",
3480                                             j, plun);
3481                                 }
3482                         }
3483
3484                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3485                                 if (port->wwpn_iid[j].in_use == 0 ||
3486                                     (port->wwpn_iid[j].wwpn == 0 &&
3487                                      port->wwpn_iid[j].name == NULL))
3488                                         continue;
3489
3490                                 if (port->wwpn_iid[j].name != NULL)
3491                                         retval = sbuf_printf(sb,
3492                                             "\t<initiator id=\"%u\">%s</initiator>\n",
3493                                             j, port->wwpn_iid[j].name);
3494                                 else
3495                                         retval = sbuf_printf(sb,
3496                                             "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3497                                             j, port->wwpn_iid[j].wwpn);
3498                                 if (retval != 0)
3499                                         break;
3500                         }
3501                         if (retval != 0)
3502                                 break;
3503
3504                         retval = sbuf_printf(sb, "</targ_port>\n");
3505                         if (retval != 0)
3506                                 break;
3507                 }
3508                 mtx_unlock(&softc->ctl_lock);
3509
3510                 if ((retval != 0)
3511                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3512                         retval = 0;
3513                         sbuf_delete(sb);
3514                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3515                         snprintf(list->error_str, sizeof(list->error_str),
3516                                  "Out of space, %d bytes is too small",
3517                                  list->alloc_len);
3518                         break;
3519                 }
3520
3521                 sbuf_finish(sb);
3522
3523                 retval = copyout(sbuf_data(sb), list->lun_xml,
3524                                  sbuf_len(sb) + 1);
3525
3526                 list->fill_len = sbuf_len(sb) + 1;
3527                 list->status = CTL_LUN_LIST_OK;
3528                 sbuf_delete(sb);
3529                 break;
3530         }
3531         case CTL_LUN_MAP: {
3532                 struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3533                 struct ctl_port *port;
3534
3535                 mtx_lock(&softc->ctl_lock);
3536                 if (lm->port >= CTL_MAX_PORTS ||
3537                     (port = softc->ctl_ports[lm->port]) == NULL) {
3538                         mtx_unlock(&softc->ctl_lock);
3539                         return (ENXIO);
3540                 }
3541                 mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3542                 if (lm->plun < CTL_MAX_LUNS) {
3543                         if (lm->lun == UINT32_MAX)
3544                                 retval = ctl_lun_map_unset(port, lm->plun);
3545                         else if (lm->lun < CTL_MAX_LUNS &&
3546                             softc->ctl_luns[lm->lun] != NULL)
3547                                 retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3548                         else
3549                                 return (ENXIO);
3550                 } else if (lm->plun == UINT32_MAX) {
3551                         if (lm->lun == UINT32_MAX)
3552                                 retval = ctl_lun_map_deinit(port);
3553                         else
3554                                 retval = ctl_lun_map_init(port);
3555                 } else
3556                         return (ENXIO);
3557                 break;
3558         }
3559         default: {
3560                 /* XXX KDM should we fix this? */
3561 #if 0
3562                 struct ctl_backend_driver *backend;
3563                 unsigned int type;
3564                 int found;
3565
3566                 found = 0;
3567
3568                 /*
3569                  * We encode the backend type as the ioctl type for backend
3570                  * ioctls.  So parse it out here, and then search for a
3571                  * backend of this type.
3572                  */
3573                 type = _IOC_TYPE(cmd);
3574
3575                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3576                         if (backend->type == type) {
3577                                 found = 1;
3578                                 break;
3579                         }
3580                 }
3581                 if (found == 0) {
3582                         printf("ctl: unknown ioctl command %#lx or backend "
3583                                "%d\n", cmd, type);
3584                         retval = EINVAL;
3585                         break;
3586                 }
3587                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3588 #endif
3589                 retval = ENOTTY;
3590                 break;
3591         }
3592         }
3593         return (retval);
3594 }
3595
3596 uint32_t
3597 ctl_get_initindex(struct ctl_nexus *nexus)
3598 {
3599         if (nexus->targ_port < CTL_MAX_PORTS)
3600                 return (nexus->initid.id +
3601                         (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3602         else
3603                 return (nexus->initid.id +
3604                        ((nexus->targ_port - CTL_MAX_PORTS) *
3605                         CTL_MAX_INIT_PER_PORT));
3606 }
3607
3608 uint32_t
3609 ctl_get_resindex(struct ctl_nexus *nexus)
3610 {
3611         return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3612 }
3613
3614 uint32_t
3615 ctl_port_idx(int port_num)
3616 {
3617         if (port_num < CTL_MAX_PORTS)
3618                 return(port_num);
3619         else
3620                 return(port_num - CTL_MAX_PORTS);
3621 }
3622
3623 int
3624 ctl_lun_map_init(struct ctl_port *port)
3625 {
3626         struct ctl_softc *softc = control_softc;
3627         struct ctl_lun *lun;
3628         uint32_t i;
3629
3630         if (port->lun_map == NULL)
3631                 port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3632                     M_CTL, M_NOWAIT);
3633         if (port->lun_map == NULL)
3634                 return (ENOMEM);
3635         for (i = 0; i < CTL_MAX_LUNS; i++)
3636                 port->lun_map[i] = UINT32_MAX;
3637         if (port->status & CTL_PORT_STATUS_ONLINE) {
3638                 STAILQ_FOREACH(lun, &softc->lun_list, links)
3639                         port->lun_disable(port->targ_lun_arg, lun->lun);
3640         }
3641         return (0);
3642 }
3643
3644 int
3645 ctl_lun_map_deinit(struct ctl_port *port)
3646 {
3647         struct ctl_softc *softc = control_softc;
3648         struct ctl_lun *lun;
3649
3650         if (port->lun_map == NULL)
3651                 return (0);
3652         free(port->lun_map, M_CTL);
3653         port->lun_map = NULL;
3654         if (port->status & CTL_PORT_STATUS_ONLINE) {
3655                 STAILQ_FOREACH(lun, &softc->lun_list, links)
3656                         port->lun_enable(port->targ_lun_arg, lun->lun);
3657         }
3658         return (0);
3659 }
3660
3661 int
3662 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3663 {
3664         int status;
3665         uint32_t old;
3666
3667         if (port->lun_map == NULL) {
3668                 status = ctl_lun_map_init(port);
3669                 if (status != 0)
3670                         return (status);
3671         }
3672         old = port->lun_map[plun];
3673         port->lun_map[plun] = glun;
3674         if ((port->status & CTL_PORT_STATUS_ONLINE) && old >= CTL_MAX_LUNS)
3675                 port->lun_enable(port->targ_lun_arg, plun);
3676         return (0);
3677 }
3678
3679 int
3680 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3681 {
3682         uint32_t old;
3683
3684         if (port->lun_map == NULL)
3685                 return (0);
3686         old = port->lun_map[plun];
3687         port->lun_map[plun] = UINT32_MAX;
3688         if ((port->status & CTL_PORT_STATUS_ONLINE) && old < CTL_MAX_LUNS)
3689                 port->lun_disable(port->targ_lun_arg, plun);
3690         return (0);
3691 }
3692
3693 uint32_t
3694 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3695 {
3696
3697         if (port == NULL)
3698                 return (UINT32_MAX);
3699         if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3700                 return (lun_id);
3701         return (port->lun_map[lun_id]);
3702 }
3703
3704 uint32_t
3705 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3706 {
3707         uint32_t i;
3708
3709         if (port == NULL)
3710                 return (UINT32_MAX);
3711         if (port->lun_map == NULL)
3712                 return (lun_id);
3713         for (i = 0; i < CTL_MAX_LUNS; i++) {
3714                 if (port->lun_map[i] == lun_id)
3715                         return (i);
3716         }
3717         return (UINT32_MAX);
3718 }
3719
3720 static struct ctl_port *
3721 ctl_io_port(struct ctl_io_hdr *io_hdr)
3722 {
3723         int port_num;
3724
3725         port_num = io_hdr->nexus.targ_port;
3726         return (control_softc->ctl_ports[ctl_port_idx(port_num)]);
3727 }
3728
3729 /*
3730  * Note:  This only works for bitmask sizes that are at least 32 bits, and
3731  * that are a power of 2.
3732  */
3733 int
3734 ctl_ffz(uint32_t *mask, uint32_t size)
3735 {
3736         uint32_t num_chunks, num_pieces;
3737         int i, j;
3738
3739         num_chunks = (size >> 5);
3740         if (num_chunks == 0)
3741                 num_chunks++;
3742         num_pieces = MIN((sizeof(uint32_t) * 8), size);
3743
3744         for (i = 0; i < num_chunks; i++) {
3745                 for (j = 0; j < num_pieces; j++) {
3746                         if ((mask[i] & (1 << j)) == 0)
3747                                 return ((i << 5) + j);
3748                 }
3749         }
3750
3751         return (-1);
3752 }
3753
3754 int
3755 ctl_set_mask(uint32_t *mask, uint32_t bit)
3756 {
3757         uint32_t chunk, piece;
3758
3759         chunk = bit >> 5;
3760         piece = bit % (sizeof(uint32_t) * 8);
3761
3762         if ((mask[chunk] & (1 << piece)) != 0)
3763                 return (-1);
3764         else
3765                 mask[chunk] |= (1 << piece);
3766
3767         return (0);
3768 }
3769
3770 int
3771 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3772 {
3773         uint32_t chunk, piece;
3774
3775         chunk = bit >> 5;
3776         piece = bit % (sizeof(uint32_t) * 8);
3777
3778         if ((mask[chunk] & (1 << piece)) == 0)
3779                 return (-1);
3780         else
3781                 mask[chunk] &= ~(1 << piece);
3782
3783         return (0);
3784 }
3785
3786 int
3787 ctl_is_set(uint32_t *mask, uint32_t bit)
3788 {
3789         uint32_t chunk, piece;
3790
3791         chunk = bit >> 5;
3792         piece = bit % (sizeof(uint32_t) * 8);
3793
3794         if ((mask[chunk] & (1 << piece)) == 0)
3795                 return (0);
3796         else
3797                 return (1);
3798 }
3799
3800 static uint64_t
3801 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3802 {
3803         uint64_t *t;
3804
3805         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3806         if (t == NULL)
3807                 return (0);
3808         return (t[residx % CTL_MAX_INIT_PER_PORT]);
3809 }
3810
3811 static void
3812 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3813 {
3814         uint64_t *t;
3815
3816         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3817         if (t == NULL)
3818                 return;
3819         t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3820 }
3821
3822 static void
3823 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3824 {
3825         uint64_t *p;
3826         u_int i;
3827
3828         i = residx/CTL_MAX_INIT_PER_PORT;
3829         if (lun->pr_keys[i] != NULL)
3830                 return;
3831         mtx_unlock(&lun->lun_lock);
3832         p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3833             M_WAITOK | M_ZERO);
3834         mtx_lock(&lun->lun_lock);
3835         if (lun->pr_keys[i] == NULL)
3836                 lun->pr_keys[i] = p;
3837         else
3838                 free(p, M_CTL);
3839 }
3840
3841 static void
3842 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3843 {
3844         uint64_t *t;
3845
3846         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3847         KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3848         t[residx % CTL_MAX_INIT_PER_PORT] = key;
3849 }
3850
3851 /*
3852  * ctl_softc, pool_name, total_ctl_io are passed in.
3853  * npool is passed out.
3854  */
3855 int
3856 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3857                 uint32_t total_ctl_io, void **npool)
3858 {
3859 #ifdef IO_POOLS
3860         struct ctl_io_pool *pool;
3861
3862         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3863                                             M_NOWAIT | M_ZERO);
3864         if (pool == NULL)
3865                 return (ENOMEM);
3866
3867         snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3868         pool->ctl_softc = ctl_softc;
3869         pool->zone = uma_zsecond_create(pool->name, NULL,
3870             NULL, NULL, NULL, ctl_softc->io_zone);
3871         /* uma_prealloc(pool->zone, total_ctl_io); */
3872
3873         *npool = pool;
3874 #else
3875         *npool = ctl_softc->io_zone;
3876 #endif
3877         return (0);
3878 }
3879
3880 void
3881 ctl_pool_free(struct ctl_io_pool *pool)
3882 {
3883
3884         if (pool == NULL)
3885                 return;
3886
3887 #ifdef IO_POOLS
3888         uma_zdestroy(pool->zone);
3889         free(pool, M_CTL);
3890 #endif
3891 }
3892
3893 union ctl_io *
3894 ctl_alloc_io(void *pool_ref)
3895 {
3896         union ctl_io *io;
3897 #ifdef IO_POOLS
3898         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3899
3900         io = uma_zalloc(pool->zone, M_WAITOK);
3901 #else
3902         io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3903 #endif
3904         if (io != NULL)
3905                 io->io_hdr.pool = pool_ref;
3906         return (io);
3907 }
3908
3909 union ctl_io *
3910 ctl_alloc_io_nowait(void *pool_ref)
3911 {
3912         union ctl_io *io;
3913 #ifdef IO_POOLS
3914         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3915
3916         io = uma_zalloc(pool->zone, M_NOWAIT);
3917 #else
3918         io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3919 #endif
3920         if (io != NULL)
3921                 io->io_hdr.pool = pool_ref;
3922         return (io);
3923 }
3924
3925 void
3926 ctl_free_io(union ctl_io *io)
3927 {
3928 #ifdef IO_POOLS
3929         struct ctl_io_pool *pool;
3930 #endif
3931
3932         if (io == NULL)
3933                 return;
3934
3935 #ifdef IO_POOLS
3936         pool = (struct ctl_io_pool *)io->io_hdr.pool;
3937         uma_zfree(pool->zone, io);
3938 #else
3939         uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3940 #endif
3941 }
3942
3943 void
3944 ctl_zero_io(union ctl_io *io)
3945 {
3946         void *pool_ref;
3947
3948         if (io == NULL)
3949                 return;
3950
3951         /*
3952          * May need to preserve linked list pointers at some point too.
3953          */
3954         pool_ref = io->io_hdr.pool;
3955         memset(io, 0, sizeof(*io));
3956         io->io_hdr.pool = pool_ref;
3957 }
3958
3959 /*
3960  * This routine is currently used for internal copies of ctl_ios that need
3961  * to persist for some reason after we've already returned status to the
3962  * FETD.  (Thus the flag set.)
3963  *
3964  * XXX XXX
3965  * Note that this makes a blind copy of all fields in the ctl_io, except
3966  * for the pool reference.  This includes any memory that has been
3967  * allocated!  That memory will no longer be valid after done has been
3968  * called, so this would be VERY DANGEROUS for command that actually does
3969  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3970  * start and stop commands, which don't transfer any data, so this is not a
3971  * problem.  If it is used for anything else, the caller would also need to
3972  * allocate data buffer space and this routine would need to be modified to
3973  * copy the data buffer(s) as well.
3974  */
3975 void
3976 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3977 {
3978         void *pool_ref;
3979
3980         if ((src == NULL)
3981          || (dest == NULL))
3982                 return;
3983
3984         /*
3985          * May need to preserve linked list pointers at some point too.
3986          */
3987         pool_ref = dest->io_hdr.pool;
3988
3989         memcpy(dest, src, MIN(sizeof(*src), sizeof(*dest)));
3990
3991         dest->io_hdr.pool = pool_ref;
3992         /*
3993          * We need to know that this is an internal copy, and doesn't need
3994          * to get passed back to the FETD that allocated it.
3995          */
3996         dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3997 }
3998
3999 int
4000 ctl_expand_number(const char *buf, uint64_t *num)
4001 {
4002         char *endptr;
4003         uint64_t number;
4004         unsigned shift;
4005
4006         number = strtoq(buf, &endptr, 0);
4007
4008         switch (tolower((unsigned char)*endptr)) {
4009         case 'e':
4010                 shift = 60;
4011                 break;
4012         case 'p':
4013                 shift = 50;
4014                 break;
4015         case 't':
4016                 shift = 40;
4017                 break;
4018         case 'g':
4019                 shift = 30;
4020                 break;
4021         case 'm':
4022                 shift = 20;
4023                 break;
4024         case 'k':
4025                 shift = 10;
4026                 break;
4027         case 'b':
4028         case '\0': /* No unit. */
4029                 *num = number;
4030                 return (0);
4031         default:
4032                 /* Unrecognized unit. */
4033                 return (-1);
4034         }
4035
4036         if ((number << shift) >> shift != number) {
4037                 /* Overflow */
4038                 return (-1);
4039         }
4040         *num = number << shift;
4041         return (0);
4042 }
4043
4044
4045 /*
4046  * This routine could be used in the future to load default and/or saved
4047  * mode page parameters for a particuar lun.
4048  */
4049 static int
4050 ctl_init_page_index(struct ctl_lun *lun)
4051 {
4052         int i;
4053         struct ctl_page_index *page_index;
4054         const char *value;
4055         uint64_t ival;
4056
4057         memcpy(&lun->mode_pages.index, page_index_template,
4058                sizeof(page_index_template));
4059
4060         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4061
4062                 page_index = &lun->mode_pages.index[i];
4063                 /*
4064                  * If this is a disk-only mode page, there's no point in
4065                  * setting it up.  For some pages, we have to have some
4066                  * basic information about the disk in order to calculate the
4067                  * mode page data.
4068                  */
4069                 if ((lun->be_lun->lun_type != T_DIRECT)
4070                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4071                         continue;
4072
4073                 switch (page_index->page_code & SMPH_PC_MASK) {
4074                 case SMS_RW_ERROR_RECOVERY_PAGE: {
4075                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4076                                 panic("subpage is incorrect!");
4077                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4078                                &rw_er_page_default,
4079                                sizeof(rw_er_page_default));
4080                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4081                                &rw_er_page_changeable,
4082                                sizeof(rw_er_page_changeable));
4083                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4084                                &rw_er_page_default,
4085                                sizeof(rw_er_page_default));
4086                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4087                                &rw_er_page_default,
4088                                sizeof(rw_er_page_default));
4089                         page_index->page_data =
4090                                 (uint8_t *)lun->mode_pages.rw_er_page;
4091                         break;
4092                 }
4093                 case SMS_FORMAT_DEVICE_PAGE: {
4094                         struct scsi_format_page *format_page;
4095
4096                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4097                                 panic("subpage is incorrect!");
4098
4099                         /*
4100                          * Sectors per track are set above.  Bytes per
4101                          * sector need to be set here on a per-LUN basis.
4102                          */
4103                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4104                                &format_page_default,
4105                                sizeof(format_page_default));
4106                         memcpy(&lun->mode_pages.format_page[
4107                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
4108                                sizeof(format_page_changeable));
4109                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4110                                &format_page_default,
4111                                sizeof(format_page_default));
4112                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4113                                &format_page_default,
4114                                sizeof(format_page_default));
4115
4116                         format_page = &lun->mode_pages.format_page[
4117                                 CTL_PAGE_CURRENT];
4118                         scsi_ulto2b(lun->be_lun->blocksize,
4119                                     format_page->bytes_per_sector);
4120
4121                         format_page = &lun->mode_pages.format_page[
4122                                 CTL_PAGE_DEFAULT];
4123                         scsi_ulto2b(lun->be_lun->blocksize,
4124                                     format_page->bytes_per_sector);
4125
4126                         format_page = &lun->mode_pages.format_page[
4127                                 CTL_PAGE_SAVED];
4128                         scsi_ulto2b(lun->be_lun->blocksize,
4129                                     format_page->bytes_per_sector);
4130
4131                         page_index->page_data =
4132                                 (uint8_t *)lun->mode_pages.format_page;
4133                         break;
4134                 }
4135                 case SMS_RIGID_DISK_PAGE: {
4136                         struct scsi_rigid_disk_page *rigid_disk_page;
4137                         uint32_t sectors_per_cylinder;
4138                         uint64_t cylinders;
4139 #ifndef __XSCALE__
4140                         int shift;
4141 #endif /* !__XSCALE__ */
4142
4143                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4144                                 panic("invalid subpage value %d",
4145                                       page_index->subpage);
4146
4147                         /*
4148                          * Rotation rate and sectors per track are set
4149                          * above.  We calculate the cylinders here based on
4150                          * capacity.  Due to the number of heads and
4151                          * sectors per track we're using, smaller arrays
4152                          * may turn out to have 0 cylinders.  Linux and
4153                          * FreeBSD don't pay attention to these mode pages
4154                          * to figure out capacity, but Solaris does.  It
4155                          * seems to deal with 0 cylinders just fine, and
4156                          * works out a fake geometry based on the capacity.
4157                          */
4158                         memcpy(&lun->mode_pages.rigid_disk_page[
4159                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4160                                sizeof(rigid_disk_page_default));
4161                         memcpy(&lun->mode_pages.rigid_disk_page[
4162                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4163                                sizeof(rigid_disk_page_changeable));
4164
4165                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4166                                 CTL_DEFAULT_HEADS;
4167
4168                         /*
4169                          * The divide method here will be more accurate,
4170                          * probably, but results in floating point being
4171                          * used in the kernel on i386 (__udivdi3()).  On the
4172                          * XScale, though, __udivdi3() is implemented in
4173                          * software.
4174                          *
4175                          * The shift method for cylinder calculation is
4176                          * accurate if sectors_per_cylinder is a power of
4177                          * 2.  Otherwise it might be slightly off -- you
4178                          * might have a bit of a truncation problem.
4179                          */
4180 #ifdef  __XSCALE__
4181                         cylinders = (lun->be_lun->maxlba + 1) /
4182                                 sectors_per_cylinder;
4183 #else
4184                         for (shift = 31; shift > 0; shift--) {
4185                                 if (sectors_per_cylinder & (1 << shift))
4186                                         break;
4187                         }
4188                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
4189 #endif
4190
4191                         /*
4192                          * We've basically got 3 bytes, or 24 bits for the
4193                          * cylinder size in the mode page.  If we're over,
4194                          * just round down to 2^24.
4195                          */
4196                         if (cylinders > 0xffffff)
4197                                 cylinders = 0xffffff;
4198
4199                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4200                                 CTL_PAGE_DEFAULT];
4201                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4202
4203                         if ((value = ctl_get_opt(&lun->be_lun->options,
4204                             "rpm")) != NULL) {
4205                                 scsi_ulto2b(strtol(value, NULL, 0),
4206                                      rigid_disk_page->rotation_rate);
4207                         }
4208
4209                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4210                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4211                                sizeof(rigid_disk_page_default));
4212                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4213                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4214                                sizeof(rigid_disk_page_default));
4215
4216                         page_index->page_data =
4217                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
4218                         break;
4219                 }
4220                 case SMS_CACHING_PAGE: {
4221                         struct scsi_caching_page *caching_page;
4222
4223                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4224                                 panic("invalid subpage value %d",
4225                                       page_index->subpage);
4226                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4227                                &caching_page_default,
4228                                sizeof(caching_page_default));
4229                         memcpy(&lun->mode_pages.caching_page[
4230                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4231                                sizeof(caching_page_changeable));
4232                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4233                                &caching_page_default,
4234                                sizeof(caching_page_default));
4235                         caching_page = &lun->mode_pages.caching_page[
4236                             CTL_PAGE_SAVED];
4237                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
4238                         if (value != NULL && strcmp(value, "off") == 0)
4239                                 caching_page->flags1 &= ~SCP_WCE;
4240                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
4241                         if (value != NULL && strcmp(value, "off") == 0)
4242                                 caching_page->flags1 |= SCP_RCD;
4243                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4244                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4245                                sizeof(caching_page_default));
4246                         page_index->page_data =
4247                                 (uint8_t *)lun->mode_pages.caching_page;
4248                         break;
4249                 }
4250                 case SMS_CONTROL_MODE_PAGE: {
4251                         struct scsi_control_page *control_page;
4252
4253                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4254                                 panic("invalid subpage value %d",
4255                                       page_index->subpage);
4256
4257                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4258                                &control_page_default,
4259                                sizeof(control_page_default));
4260                         memcpy(&lun->mode_pages.control_page[
4261                                CTL_PAGE_CHANGEABLE], &control_page_changeable,
4262                                sizeof(control_page_changeable));
4263                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4264                                &control_page_default,
4265                                sizeof(control_page_default));
4266                         control_page = &lun->mode_pages.control_page[
4267                             CTL_PAGE_SAVED];
4268                         value = ctl_get_opt(&lun->be_lun->options, "reordering");
4269                         if (value != NULL && strcmp(value, "unrestricted") == 0) {
4270                                 control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4271                                 control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4272                         }
4273                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4274                                &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4275                                sizeof(control_page_default));
4276                         page_index->page_data =
4277                                 (uint8_t *)lun->mode_pages.control_page;
4278                         break;
4279
4280                 }
4281                 case SMS_INFO_EXCEPTIONS_PAGE: {
4282                         switch (page_index->subpage) {
4283                         case SMS_SUBPAGE_PAGE_0:
4284                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4285                                        &ie_page_default,
4286                                        sizeof(ie_page_default));
4287                                 memcpy(&lun->mode_pages.ie_page[
4288                                        CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4289                                        sizeof(ie_page_changeable));
4290                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4291                                        &ie_page_default,
4292                                        sizeof(ie_page_default));
4293                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4294                                        &ie_page_default,
4295                                        sizeof(ie_page_default));
4296                                 page_index->page_data =
4297                                         (uint8_t *)lun->mode_pages.ie_page;
4298                                 break;
4299                         case 0x02: {
4300                                 struct ctl_logical_block_provisioning_page *page;
4301
4302                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4303                                        &lbp_page_default,
4304                                        sizeof(lbp_page_default));
4305                                 memcpy(&lun->mode_pages.lbp_page[
4306                                        CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4307                                        sizeof(lbp_page_changeable));
4308                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4309                                        &lbp_page_default,
4310                                        sizeof(lbp_page_default));
4311                                 page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4312                                 value = ctl_get_opt(&lun->be_lun->options,
4313                                     "avail-threshold");
4314                                 if (value != NULL &&
4315                                     ctl_expand_number(value, &ival) == 0) {
4316                                         page->descr[0].flags |= SLBPPD_ENABLED |
4317                                             SLBPPD_ARMING_DEC;
4318                                         if (lun->be_lun->blocksize)
4319                                                 ival /= lun->be_lun->blocksize;
4320                                         else
4321                                                 ival /= 512;
4322                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4323                                             page->descr[0].count);
4324                                 }
4325                                 value = ctl_get_opt(&lun->be_lun->options,
4326                                     "used-threshold");
4327                                 if (value != NULL &&
4328                                     ctl_expand_number(value, &ival) == 0) {
4329                                         page->descr[1].flags |= SLBPPD_ENABLED |
4330                                             SLBPPD_ARMING_INC;
4331                                         if (lun->be_lun->blocksize)
4332                                                 ival /= lun->be_lun->blocksize;
4333                                         else
4334                                                 ival /= 512;
4335                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4336                                             page->descr[1].count);
4337                                 }
4338                                 value = ctl_get_opt(&lun->be_lun->options,
4339                                     "pool-avail-threshold");
4340                                 if (value != NULL &&
4341                                     ctl_expand_number(value, &ival) == 0) {
4342                                         page->descr[2].flags |= SLBPPD_ENABLED |
4343                                             SLBPPD_ARMING_DEC;
4344                                         if (lun->be_lun->blocksize)
4345                                                 ival /= lun->be_lun->blocksize;
4346                                         else
4347                                                 ival /= 512;
4348                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4349                                             page->descr[2].count);
4350                                 }
4351                                 value = ctl_get_opt(&lun->be_lun->options,
4352                                     "pool-used-threshold");
4353                                 if (value != NULL &&
4354                                     ctl_expand_number(value, &ival) == 0) {
4355                                         page->descr[3].flags |= SLBPPD_ENABLED |
4356                                             SLBPPD_ARMING_INC;
4357                                         if (lun->be_lun->blocksize)
4358                                                 ival /= lun->be_lun->blocksize;
4359                                         else
4360                                                 ival /= 512;
4361                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4362                                             page->descr[3].count);
4363                                 }
4364                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4365                                        &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4366                                        sizeof(lbp_page_default));
4367                                 page_index->page_data =
4368                                         (uint8_t *)lun->mode_pages.lbp_page;
4369                         }}
4370                         break;
4371                 }
4372                 case SMS_VENDOR_SPECIFIC_PAGE:{
4373                         switch (page_index->subpage) {
4374                         case DBGCNF_SUBPAGE_CODE: {
4375                                 struct copan_debugconf_subpage *current_page,
4376                                                                *saved_page;
4377
4378                                 memcpy(&lun->mode_pages.debugconf_subpage[
4379                                        CTL_PAGE_CURRENT],
4380                                        &debugconf_page_default,
4381                                        sizeof(debugconf_page_default));
4382                                 memcpy(&lun->mode_pages.debugconf_subpage[
4383                                        CTL_PAGE_CHANGEABLE],
4384                                        &debugconf_page_changeable,
4385                                        sizeof(debugconf_page_changeable));
4386                                 memcpy(&lun->mode_pages.debugconf_subpage[
4387                                        CTL_PAGE_DEFAULT],
4388                                        &debugconf_page_default,
4389                                        sizeof(debugconf_page_default));
4390                                 memcpy(&lun->mode_pages.debugconf_subpage[
4391                                        CTL_PAGE_SAVED],
4392                                        &debugconf_page_default,
4393                                        sizeof(debugconf_page_default));
4394                                 page_index->page_data =
4395                                         (uint8_t *)lun->mode_pages.debugconf_subpage;
4396
4397                                 current_page = (struct copan_debugconf_subpage *)
4398                                         (page_index->page_data +
4399                                          (page_index->page_len *
4400                                           CTL_PAGE_CURRENT));
4401                                 saved_page = (struct copan_debugconf_subpage *)
4402                                         (page_index->page_data +
4403                                          (page_index->page_len *
4404                                           CTL_PAGE_SAVED));
4405                                 break;
4406                         }
4407                         default:
4408                                 panic("invalid subpage value %d",
4409                                       page_index->subpage);
4410                                 break;
4411                         }
4412                         break;
4413                 }
4414                 default:
4415                         panic("invalid page value %d",
4416                               page_index->page_code & SMPH_PC_MASK);
4417                         break;
4418         }
4419         }
4420
4421         return (CTL_RETVAL_COMPLETE);
4422 }
4423
4424 static int
4425 ctl_init_log_page_index(struct ctl_lun *lun)
4426 {
4427         struct ctl_page_index *page_index;
4428         int i, j, k, prev;
4429
4430         memcpy(&lun->log_pages.index, log_page_index_template,
4431                sizeof(log_page_index_template));
4432
4433         prev = -1;
4434         for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4435
4436                 page_index = &lun->log_pages.index[i];
4437                 /*
4438                  * If this is a disk-only mode page, there's no point in
4439                  * setting it up.  For some pages, we have to have some
4440                  * basic information about the disk in order to calculate the
4441                  * mode page data.
4442                  */
4443                 if ((lun->be_lun->lun_type != T_DIRECT)
4444                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4445                         continue;
4446
4447                 if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4448                      lun->backend->lun_attr == NULL)
4449                         continue;
4450
4451                 if (page_index->page_code != prev) {
4452                         lun->log_pages.pages_page[j] = page_index->page_code;
4453                         prev = page_index->page_code;
4454                         j++;
4455                 }
4456                 lun->log_pages.subpages_page[k*2] = page_index->page_code;
4457                 lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4458                 k++;
4459         }
4460         lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4461         lun->log_pages.index[0].page_len = j;
4462         lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4463         lun->log_pages.index[1].page_len = k * 2;
4464         lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4465         lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4466         lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4467         lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4468
4469         return (CTL_RETVAL_COMPLETE);
4470 }
4471
4472 static int
4473 hex2bin(const char *str, uint8_t *buf, int buf_size)
4474 {
4475         int i;
4476         u_char c;
4477
4478         memset(buf, 0, buf_size);
4479         while (isspace(str[0]))
4480                 str++;
4481         if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4482                 str += 2;
4483         buf_size *= 2;
4484         for (i = 0; str[i] != 0 && i < buf_size; i++) {
4485                 c = str[i];
4486                 if (isdigit(c))
4487                         c -= '0';
4488                 else if (isalpha(c))
4489                         c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4490                 else
4491                         break;
4492                 if (c >= 16)
4493                         break;
4494                 if ((i & 1) == 0)
4495                         buf[i / 2] |= (c << 4);
4496                 else
4497                         buf[i / 2] |= c;
4498         }
4499         return ((i + 1) / 2);
4500 }
4501
4502 /*
4503  * LUN allocation.
4504  *
4505  * Requirements:
4506  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4507  *   wants us to allocate the LUN and he can block.
4508  * - ctl_softc is always set
4509  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4510  *
4511  * Returns 0 for success, non-zero (errno) for failure.
4512  */
4513 static int
4514 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4515               struct ctl_be_lun *const be_lun)
4516 {
4517         struct ctl_lun *nlun, *lun;
4518         struct scsi_vpd_id_descriptor *desc;
4519         struct scsi_vpd_id_t10 *t10id;
4520         const char *eui, *naa, *scsiname, *vendor, *value;
4521         int lun_number, i, lun_malloced;
4522         int devidlen, idlen1, idlen2 = 0, len;
4523
4524         if (be_lun == NULL)
4525                 return (EINVAL);
4526
4527         /*
4528          * We currently only support Direct Access or Processor LUN types.
4529          */
4530         switch (be_lun->lun_type) {
4531         case T_DIRECT:
4532                 break;
4533         case T_PROCESSOR:
4534                 break;
4535         case T_SEQUENTIAL:
4536         case T_CHANGER:
4537         default:
4538                 be_lun->lun_config_status(be_lun->be_lun,
4539                                           CTL_LUN_CONFIG_FAILURE);
4540                 break;
4541         }
4542         if (ctl_lun == NULL) {
4543                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4544                 lun_malloced = 1;
4545         } else {
4546                 lun_malloced = 0;
4547                 lun = ctl_lun;
4548         }
4549
4550         memset(lun, 0, sizeof(*lun));
4551         if (lun_malloced)
4552                 lun->flags = CTL_LUN_MALLOCED;
4553
4554         /* Generate LUN ID. */
4555         devidlen = max(CTL_DEVID_MIN_LEN,
4556             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4557         idlen1 = sizeof(*t10id) + devidlen;
4558         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4559         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4560         if (scsiname != NULL) {
4561                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4562                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4563         }
4564         eui = ctl_get_opt(&be_lun->options, "eui");
4565         if (eui != NULL) {
4566                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4567         }
4568         naa = ctl_get_opt(&be_lun->options, "naa");
4569         if (naa != NULL) {
4570                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4571         }
4572         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4573             M_CTL, M_WAITOK | M_ZERO);
4574         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4575         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4576         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4577         desc->length = idlen1;
4578         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4579         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4580         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4581                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4582         } else {
4583                 strncpy(t10id->vendor, vendor,
4584                     min(sizeof(t10id->vendor), strlen(vendor)));
4585         }
4586         strncpy((char *)t10id->vendor_spec_id,
4587             (char *)be_lun->device_id, devidlen);
4588         if (scsiname != NULL) {
4589                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4590                     desc->length);
4591                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4592                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4593                     SVPD_ID_TYPE_SCSI_NAME;
4594                 desc->length = idlen2;
4595                 strlcpy(desc->identifier, scsiname, idlen2);
4596         }
4597         if (eui != NULL) {
4598                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4599                     desc->length);
4600                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4601                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4602                     SVPD_ID_TYPE_EUI64;
4603                 desc->length = hex2bin(eui, desc->identifier, 16);
4604                 desc->length = desc->length > 12 ? 16 :
4605                     (desc->length > 8 ? 12 : 8);
4606                 len -= 16 - desc->length;
4607         }
4608         if (naa != NULL) {
4609                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4610                     desc->length);
4611                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4612                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4613                     SVPD_ID_TYPE_NAA;
4614                 desc->length = hex2bin(naa, desc->identifier, 16);
4615                 desc->length = desc->length > 8 ? 16 : 8;
4616                 len -= 16 - desc->length;
4617         }
4618         lun->lun_devid->len = len;
4619
4620         mtx_lock(&ctl_softc->ctl_lock);
4621         /*
4622          * See if the caller requested a particular LUN number.  If so, see
4623          * if it is available.  Otherwise, allocate the first available LUN.
4624          */
4625         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4626                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4627                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4628                         mtx_unlock(&ctl_softc->ctl_lock);
4629                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4630                                 printf("ctl: requested LUN ID %d is higher "
4631                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4632                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4633                         } else {
4634                                 /*
4635                                  * XXX KDM return an error, or just assign
4636                                  * another LUN ID in this case??
4637                                  */
4638                                 printf("ctl: requested LUN ID %d is already "
4639                                        "in use\n", be_lun->req_lun_id);
4640                         }
4641                         if (lun->flags & CTL_LUN_MALLOCED)
4642                                 free(lun, M_CTL);
4643                         be_lun->lun_config_status(be_lun->be_lun,
4644                                                   CTL_LUN_CONFIG_FAILURE);
4645                         return (ENOSPC);
4646                 }
4647                 lun_number = be_lun->req_lun_id;
4648         } else {
4649                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4650                 if (lun_number == -1) {
4651                         mtx_unlock(&ctl_softc->ctl_lock);
4652                         printf("ctl: can't allocate LUN, out of LUNs\n");
4653                         if (lun->flags & CTL_LUN_MALLOCED)
4654                                 free(lun, M_CTL);
4655                         be_lun->lun_config_status(be_lun->be_lun,
4656                                                   CTL_LUN_CONFIG_FAILURE);
4657                         return (ENOSPC);
4658                 }
4659         }
4660         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4661
4662         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4663         lun->lun = lun_number;
4664         lun->be_lun = be_lun;
4665         /*
4666          * The processor LUN is always enabled.  Disk LUNs come on line
4667          * disabled, and must be enabled by the backend.
4668          */
4669         lun->flags |= CTL_LUN_DISABLED;
4670         lun->backend = be_lun->be;
4671         be_lun->ctl_lun = lun;
4672         be_lun->lun_id = lun_number;
4673         atomic_add_int(&be_lun->be->num_luns, 1);
4674         if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4675                 lun->flags |= CTL_LUN_OFFLINE;
4676
4677         if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4678                 lun->flags |= CTL_LUN_STOPPED;
4679
4680         if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4681                 lun->flags |= CTL_LUN_INOPERABLE;
4682
4683         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4684                 lun->flags |= CTL_LUN_PRIMARY_SC;
4685
4686         value = ctl_get_opt(&be_lun->options, "readonly");
4687         if (value != NULL && strcmp(value, "on") == 0)
4688                 lun->flags |= CTL_LUN_READONLY;
4689
4690         lun->serseq = CTL_LUN_SERSEQ_OFF;
4691         if (be_lun->flags & CTL_LUN_FLAG_SERSEQ_READ)
4692                 lun->serseq = CTL_LUN_SERSEQ_READ;
4693         value = ctl_get_opt(&be_lun->options, "serseq");
4694         if (value != NULL && strcmp(value, "on") == 0)
4695                 lun->serseq = CTL_LUN_SERSEQ_ON;
4696         else if (value != NULL && strcmp(value, "read") == 0)
4697                 lun->serseq = CTL_LUN_SERSEQ_READ;
4698         else if (value != NULL && strcmp(value, "off") == 0)
4699                 lun->serseq = CTL_LUN_SERSEQ_OFF;
4700
4701         lun->ctl_softc = ctl_softc;
4702 #ifdef CTL_TIME_IO
4703         lun->last_busy = getsbinuptime();
4704 #endif
4705         TAILQ_INIT(&lun->ooa_queue);
4706         TAILQ_INIT(&lun->blocked_queue);
4707         STAILQ_INIT(&lun->error_list);
4708         ctl_tpc_lun_init(lun);
4709
4710         /*
4711          * Initialize the mode and log page index.
4712          */
4713         ctl_init_page_index(lun);
4714         ctl_init_log_page_index(lun);
4715
4716         /*
4717          * Now, before we insert this lun on the lun list, set the lun
4718          * inventory changed UA for all other luns.
4719          */
4720         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4721                 mtx_lock(&nlun->lun_lock);
4722                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4723                 mtx_unlock(&nlun->lun_lock);
4724         }
4725
4726         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4727
4728         ctl_softc->ctl_luns[lun_number] = lun;
4729
4730         ctl_softc->num_luns++;
4731
4732         /* Setup statistics gathering */
4733         lun->stats.device_type = be_lun->lun_type;
4734         lun->stats.lun_number = lun_number;
4735         if (lun->stats.device_type == T_DIRECT)
4736                 lun->stats.blocksize = be_lun->blocksize;
4737         else
4738                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4739         for (i = 0;i < CTL_MAX_PORTS;i++)
4740                 lun->stats.ports[i].targ_port = i;
4741
4742         mtx_unlock(&ctl_softc->ctl_lock);
4743
4744         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4745         return (0);
4746 }
4747
4748 /*
4749  * Delete a LUN.
4750  * Assumptions:
4751  * - LUN has already been marked invalid and any pending I/O has been taken
4752  *   care of.
4753  */
4754 static int
4755 ctl_free_lun(struct ctl_lun *lun)
4756 {
4757         struct ctl_softc *softc;
4758         struct ctl_lun *nlun;
4759         int i;
4760
4761         softc = lun->ctl_softc;
4762
4763         mtx_assert(&softc->ctl_lock, MA_OWNED);
4764
4765         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4766
4767         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4768
4769         softc->ctl_luns[lun->lun] = NULL;
4770
4771         if (!TAILQ_EMPTY(&lun->ooa_queue))
4772                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4773
4774         softc->num_luns--;
4775
4776         /*
4777          * Tell the backend to free resources, if this LUN has a backend.
4778          */
4779         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4780         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4781
4782         ctl_tpc_lun_shutdown(lun);
4783         mtx_destroy(&lun->lun_lock);
4784         free(lun->lun_devid, M_CTL);
4785         for (i = 0; i < CTL_MAX_PORTS; i++)
4786                 free(lun->pending_ua[i], M_CTL);
4787         for (i = 0; i < 2 * CTL_MAX_PORTS; i++)
4788                 free(lun->pr_keys[i], M_CTL);
4789         free(lun->write_buffer, M_CTL);
4790         if (lun->flags & CTL_LUN_MALLOCED)
4791                 free(lun, M_CTL);
4792
4793         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4794                 mtx_lock(&nlun->lun_lock);
4795                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4796                 mtx_unlock(&nlun->lun_lock);
4797         }
4798
4799         return (0);
4800 }
4801
4802 static void
4803 ctl_create_lun(struct ctl_be_lun *be_lun)
4804 {
4805         struct ctl_softc *softc;
4806
4807         softc = control_softc;
4808
4809         /*
4810          * ctl_alloc_lun() should handle all potential failure cases.
4811          */
4812         ctl_alloc_lun(softc, NULL, be_lun);
4813 }
4814
4815 int
4816 ctl_add_lun(struct ctl_be_lun *be_lun)
4817 {
4818         struct ctl_softc *softc = control_softc;
4819
4820         mtx_lock(&softc->ctl_lock);
4821         STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4822         mtx_unlock(&softc->ctl_lock);
4823         wakeup(&softc->pending_lun_queue);
4824
4825         return (0);
4826 }
4827
4828 int
4829 ctl_enable_lun(struct ctl_be_lun *be_lun)
4830 {
4831         struct ctl_softc *softc;
4832         struct ctl_port *port, *nport;
4833         struct ctl_lun *lun;
4834         int retval;
4835
4836         lun = (struct ctl_lun *)be_lun->ctl_lun;
4837         softc = lun->ctl_softc;
4838
4839         mtx_lock(&softc->ctl_lock);
4840         mtx_lock(&lun->lun_lock);
4841         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4842                 /*
4843                  * eh?  Why did we get called if the LUN is already
4844                  * enabled?
4845                  */
4846                 mtx_unlock(&lun->lun_lock);
4847                 mtx_unlock(&softc->ctl_lock);
4848                 return (0);
4849         }
4850         lun->flags &= ~CTL_LUN_DISABLED;
4851         mtx_unlock(&lun->lun_lock);
4852
4853         for (port = STAILQ_FIRST(&softc->port_list); port != NULL; port = nport) {
4854                 nport = STAILQ_NEXT(port, links);
4855                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4856                     port->lun_map != NULL)
4857                         continue;
4858
4859                 /*
4860                  * Drop the lock while we call the FETD's enable routine.
4861                  * This can lead to a callback into CTL (at least in the
4862                  * case of the internal initiator frontend.
4863                  */
4864                 mtx_unlock(&softc->ctl_lock);
4865                 retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4866                 mtx_lock(&softc->ctl_lock);
4867                 if (retval != 0) {
4868                         printf("%s: FETD %s port %d returned error "
4869                                "%d for lun_enable on lun %jd\n",
4870                                __func__, port->port_name, port->targ_port,
4871                                retval, (intmax_t)lun->lun);
4872                 }
4873         }
4874
4875         mtx_unlock(&softc->ctl_lock);
4876
4877         return (0);
4878 }
4879
4880 int
4881 ctl_disable_lun(struct ctl_be_lun *be_lun)
4882 {
4883         struct ctl_softc *softc;
4884         struct ctl_port *port;
4885         struct ctl_lun *lun;
4886         int retval;
4887
4888         lun = (struct ctl_lun *)be_lun->ctl_lun;
4889         softc = lun->ctl_softc;
4890
4891         mtx_lock(&softc->ctl_lock);
4892         mtx_lock(&lun->lun_lock);
4893         if (lun->flags & CTL_LUN_DISABLED) {
4894                 mtx_unlock(&lun->lun_lock);
4895                 mtx_unlock(&softc->ctl_lock);
4896                 return (0);
4897         }
4898         lun->flags |= CTL_LUN_DISABLED;
4899         mtx_unlock(&lun->lun_lock);
4900
4901         STAILQ_FOREACH(port, &softc->port_list, links) {
4902                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4903                     port->lun_map != NULL)
4904                         continue;
4905                 mtx_unlock(&softc->ctl_lock);
4906                 /*
4907                  * Drop the lock before we call the frontend's disable
4908                  * routine, to avoid lock order reversals.
4909                  *
4910                  * XXX KDM what happens if the frontend list changes while
4911                  * we're traversing it?  It's unlikely, but should be handled.
4912                  */
4913                 retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4914                 mtx_lock(&softc->ctl_lock);
4915                 if (retval != 0) {
4916                         printf("%s: FETD %s port %d returned error "
4917                                "%d for lun_disable on lun %jd\n",
4918                                __func__, port->port_name, port->targ_port,
4919                                retval, (intmax_t)lun->lun);
4920                 }
4921         }
4922
4923         mtx_unlock(&softc->ctl_lock);
4924
4925         return (0);
4926 }
4927
4928 int
4929 ctl_start_lun(struct ctl_be_lun *be_lun)
4930 {
4931         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4932
4933         mtx_lock(&lun->lun_lock);
4934         lun->flags &= ~CTL_LUN_STOPPED;
4935         mtx_unlock(&lun->lun_lock);
4936         return (0);
4937 }
4938
4939 int
4940 ctl_stop_lun(struct ctl_be_lun *be_lun)
4941 {
4942         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4943
4944         mtx_lock(&lun->lun_lock);
4945         lun->flags |= CTL_LUN_STOPPED;
4946         mtx_unlock(&lun->lun_lock);
4947         return (0);
4948 }
4949
4950 int
4951 ctl_lun_offline(struct ctl_be_lun *be_lun)
4952 {
4953         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4954
4955         mtx_lock(&lun->lun_lock);
4956         lun->flags |= CTL_LUN_OFFLINE;
4957         mtx_unlock(&lun->lun_lock);
4958         return (0);
4959 }
4960
4961 int
4962 ctl_lun_online(struct ctl_be_lun *be_lun)
4963 {
4964         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4965
4966         mtx_lock(&lun->lun_lock);
4967         lun->flags &= ~CTL_LUN_OFFLINE;
4968         mtx_unlock(&lun->lun_lock);
4969         return (0);
4970 }
4971
4972 int
4973 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4974 {
4975         struct ctl_softc *softc;
4976         struct ctl_lun *lun;
4977
4978         lun = (struct ctl_lun *)be_lun->ctl_lun;
4979         softc = lun->ctl_softc;
4980
4981         mtx_lock(&lun->lun_lock);
4982
4983         /*
4984          * The LUN needs to be disabled before it can be marked invalid.
4985          */
4986         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4987                 mtx_unlock(&lun->lun_lock);
4988                 return (-1);
4989         }
4990         /*
4991          * Mark the LUN invalid.
4992          */
4993         lun->flags |= CTL_LUN_INVALID;
4994
4995         /*
4996          * If there is nothing in the OOA queue, go ahead and free the LUN.
4997          * If we have something in the OOA queue, we'll free it when the
4998          * last I/O completes.
4999          */
5000         if (TAILQ_EMPTY(&lun->ooa_queue)) {
5001                 mtx_unlock(&lun->lun_lock);
5002                 mtx_lock(&softc->ctl_lock);
5003                 ctl_free_lun(lun);
5004                 mtx_unlock(&softc->ctl_lock);
5005         } else
5006                 mtx_unlock(&lun->lun_lock);
5007
5008         return (0);
5009 }
5010
5011 int
5012 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5013 {
5014         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5015
5016         mtx_lock(&lun->lun_lock);
5017         lun->flags |= CTL_LUN_INOPERABLE;
5018         mtx_unlock(&lun->lun_lock);
5019         return (0);
5020 }
5021
5022 int
5023 ctl_lun_operable(struct ctl_be_lun *be_lun)
5024 {
5025         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5026
5027         mtx_lock(&lun->lun_lock);
5028         lun->flags &= ~CTL_LUN_INOPERABLE;
5029         mtx_unlock(&lun->lun_lock);
5030         return (0);
5031 }
5032
5033 void
5034 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5035 {
5036         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5037
5038         mtx_lock(&lun->lun_lock);
5039         ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGED);
5040         mtx_unlock(&lun->lun_lock);
5041 }
5042
5043 /*
5044  * Backend "memory move is complete" callback for requests that never
5045  * make it down to say RAIDCore's configuration code.
5046  */
5047 int
5048 ctl_config_move_done(union ctl_io *io)
5049 {
5050         int retval;
5051
5052         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5053         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5054             ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5055
5056         if ((io->io_hdr.port_status != 0) &&
5057             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5058              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5059                 /*
5060                  * For hardware error sense keys, the sense key
5061                  * specific value is defined to be a retry count,
5062                  * but we use it to pass back an internal FETD
5063                  * error code.  XXX KDM  Hopefully the FETD is only
5064                  * using 16 bits for an error code, since that's
5065                  * all the space we have in the sks field.
5066                  */
5067                 ctl_set_internal_failure(&io->scsiio,
5068                                          /*sks_valid*/ 1,
5069                                          /*retry_count*/
5070                                          io->io_hdr.port_status);
5071         }
5072
5073         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5074             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5075              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5076             ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5077                 /*
5078                  * XXX KDM just assuming a single pointer here, and not a
5079                  * S/G list.  If we start using S/G lists for config data,
5080                  * we'll need to know how to clean them up here as well.
5081                  */
5082                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5083                         free(io->scsiio.kern_data_ptr, M_CTL);
5084                 ctl_done(io);
5085                 retval = CTL_RETVAL_COMPLETE;
5086         } else {
5087                 /*
5088                  * XXX KDM now we need to continue data movement.  Some
5089                  * options:
5090                  * - call ctl_scsiio() again?  We don't do this for data
5091                  *   writes, because for those at least we know ahead of
5092                  *   time where the write will go and how long it is.  For
5093                  *   config writes, though, that information is largely
5094                  *   contained within the write itself, thus we need to
5095                  *   parse out the data again.
5096                  *
5097                  * - Call some other function once the data is in?
5098                  */
5099                 if (ctl_debug & CTL_DEBUG_CDB_DATA)
5100                         ctl_data_print(io);
5101
5102                 /*
5103                  * XXX KDM call ctl_scsiio() again for now, and check flag
5104                  * bits to see whether we're allocated or not.
5105                  */
5106                 retval = ctl_scsiio(&io->scsiio);
5107         }
5108         return (retval);
5109 }
5110
5111 /*
5112  * This gets called by a backend driver when it is done with a
5113  * data_submit method.
5114  */
5115 void
5116 ctl_data_submit_done(union ctl_io *io)
5117 {
5118         /*
5119          * If the IO_CONT flag is set, we need to call the supplied
5120          * function to continue processing the I/O, instead of completing
5121          * the I/O just yet.
5122          *
5123          * If there is an error, though, we don't want to keep processing.
5124          * Instead, just send status back to the initiator.
5125          */
5126         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5127             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5128             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5129              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5130                 io->scsiio.io_cont(io);
5131                 return;
5132         }
5133         ctl_done(io);
5134 }
5135
5136 /*
5137  * This gets called by a backend driver when it is done with a
5138  * configuration write.
5139  */
5140 void
5141 ctl_config_write_done(union ctl_io *io)
5142 {
5143         uint8_t *buf;
5144
5145         /*
5146          * If the IO_CONT flag is set, we need to call the supplied
5147          * function to continue processing the I/O, instead of completing
5148          * the I/O just yet.
5149          *
5150          * If there is an error, though, we don't want to keep processing.
5151          * Instead, just send status back to the initiator.
5152          */
5153         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5154             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5155             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5156              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5157                 io->scsiio.io_cont(io);
5158                 return;
5159         }
5160         /*
5161          * Since a configuration write can be done for commands that actually
5162          * have data allocated, like write buffer, and commands that have
5163          * no data, like start/stop unit, we need to check here.
5164          */
5165         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5166                 buf = io->scsiio.kern_data_ptr;
5167         else
5168                 buf = NULL;
5169         ctl_done(io);
5170         if (buf)
5171                 free(buf, M_CTL);
5172 }
5173
5174 void
5175 ctl_config_read_done(union ctl_io *io)
5176 {
5177         uint8_t *buf;
5178
5179         /*
5180          * If there is some error -- we are done, skip data transfer.
5181          */
5182         if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5183             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5184              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5185                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5186                         buf = io->scsiio.kern_data_ptr;
5187                 else
5188                         buf = NULL;
5189                 ctl_done(io);
5190                 if (buf)
5191                         free(buf, M_CTL);
5192                 return;
5193         }
5194
5195         /*
5196          * If the IO_CONT flag is set, we need to call the supplied
5197          * function to continue processing the I/O, instead of completing
5198          * the I/O just yet.
5199          */
5200         if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5201                 io->scsiio.io_cont(io);
5202                 return;
5203         }
5204
5205         ctl_datamove(io);
5206 }
5207
5208 /*
5209  * SCSI release command.
5210  */
5211 int
5212 ctl_scsi_release(struct ctl_scsiio *ctsio)
5213 {
5214         int length, longid, thirdparty_id, resv_id;
5215         struct ctl_lun *lun;
5216         uint32_t residx;
5217
5218         length = 0;
5219         resv_id = 0;
5220
5221         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5222
5223         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5224         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5225
5226         switch (ctsio->cdb[0]) {
5227         case RELEASE_10: {
5228                 struct scsi_release_10 *cdb;
5229
5230                 cdb = (struct scsi_release_10 *)ctsio->cdb;
5231
5232                 if (cdb->byte2 & SR10_LONGID)
5233                         longid = 1;
5234                 else
5235                         thirdparty_id = cdb->thirdparty_id;
5236
5237                 resv_id = cdb->resv_id;
5238                 length = scsi_2btoul(cdb->length);
5239                 break;
5240         }
5241         }
5242
5243
5244         /*
5245          * XXX KDM right now, we only support LUN reservation.  We don't
5246          * support 3rd party reservations, or extent reservations, which
5247          * might actually need the parameter list.  If we've gotten this
5248          * far, we've got a LUN reservation.  Anything else got kicked out
5249          * above.  So, according to SPC, ignore the length.
5250          */
5251         length = 0;
5252
5253         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5254          && (length > 0)) {
5255                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5256                 ctsio->kern_data_len = length;
5257                 ctsio->kern_total_len = length;
5258                 ctsio->kern_data_resid = 0;
5259                 ctsio->kern_rel_offset = 0;
5260                 ctsio->kern_sg_entries = 0;
5261                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5262                 ctsio->be_move_done = ctl_config_move_done;
5263                 ctl_datamove((union ctl_io *)ctsio);
5264
5265                 return (CTL_RETVAL_COMPLETE);
5266         }
5267
5268         if (length > 0)
5269                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5270
5271         mtx_lock(&lun->lun_lock);
5272
5273         /*
5274          * According to SPC, it is not an error for an intiator to attempt
5275          * to release a reservation on a LUN that isn't reserved, or that
5276          * is reserved by another initiator.  The reservation can only be
5277          * released, though, by the initiator who made it or by one of
5278          * several reset type events.
5279          */
5280         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5281                         lun->flags &= ~CTL_LUN_RESERVED;
5282
5283         mtx_unlock(&lun->lun_lock);
5284
5285         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5286                 free(ctsio->kern_data_ptr, M_CTL);
5287                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5288         }
5289
5290         ctl_set_success(ctsio);
5291         ctl_done((union ctl_io *)ctsio);
5292         return (CTL_RETVAL_COMPLETE);
5293 }
5294
5295 int
5296 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5297 {
5298         int extent, thirdparty, longid;
5299         int resv_id, length;
5300         uint64_t thirdparty_id;
5301         struct ctl_lun *lun;
5302         uint32_t residx;
5303
5304         extent = 0;
5305         thirdparty = 0;
5306         longid = 0;
5307         resv_id = 0;
5308         length = 0;
5309         thirdparty_id = 0;
5310
5311         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5312
5313         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5314         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5315
5316         switch (ctsio->cdb[0]) {
5317         case RESERVE_10: {
5318                 struct scsi_reserve_10 *cdb;
5319
5320                 cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5321
5322                 if (cdb->byte2 & SR10_LONGID)
5323                         longid = 1;
5324                 else
5325                         thirdparty_id = cdb->thirdparty_id;
5326
5327                 resv_id = cdb->resv_id;
5328                 length = scsi_2btoul(cdb->length);
5329                 break;
5330         }
5331         }
5332
5333         /*
5334          * XXX KDM right now, we only support LUN reservation.  We don't
5335          * support 3rd party reservations, or extent reservations, which
5336          * might actually need the parameter list.  If we've gotten this
5337          * far, we've got a LUN reservation.  Anything else got kicked out
5338          * above.  So, according to SPC, ignore the length.
5339          */
5340         length = 0;
5341
5342         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5343          && (length > 0)) {
5344                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5345                 ctsio->kern_data_len = length;
5346                 ctsio->kern_total_len = length;
5347                 ctsio->kern_data_resid = 0;
5348                 ctsio->kern_rel_offset = 0;
5349                 ctsio->kern_sg_entries = 0;
5350                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5351                 ctsio->be_move_done = ctl_config_move_done;
5352                 ctl_datamove((union ctl_io *)ctsio);
5353
5354                 return (CTL_RETVAL_COMPLETE);
5355         }
5356
5357         if (length > 0)
5358                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5359
5360         mtx_lock(&lun->lun_lock);
5361         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5362                 ctl_set_reservation_conflict(ctsio);
5363                 goto bailout;
5364         }
5365
5366         lun->flags |= CTL_LUN_RESERVED;
5367         lun->res_idx = residx;
5368
5369         ctl_set_success(ctsio);
5370
5371 bailout:
5372         mtx_unlock(&lun->lun_lock);
5373
5374         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5375                 free(ctsio->kern_data_ptr, M_CTL);
5376                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5377         }
5378
5379         ctl_done((union ctl_io *)ctsio);
5380         return (CTL_RETVAL_COMPLETE);
5381 }
5382
5383 int
5384 ctl_start_stop(struct ctl_scsiio *ctsio)
5385 {
5386         struct scsi_start_stop_unit *cdb;
5387         struct ctl_lun *lun;
5388         int retval;
5389
5390         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5391
5392         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5393         retval = 0;
5394
5395         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5396
5397         /*
5398          * XXX KDM
5399          * We don't support the immediate bit on a stop unit.  In order to
5400          * do that, we would need to code up a way to know that a stop is
5401          * pending, and hold off any new commands until it completes, one
5402          * way or another.  Then we could accept or reject those commands
5403          * depending on its status.  We would almost need to do the reverse
5404          * of what we do below for an immediate start -- return the copy of
5405          * the ctl_io to the FETD with status to send to the host (and to
5406          * free the copy!) and then free the original I/O once the stop
5407          * actually completes.  That way, the OOA queue mechanism can work
5408          * to block commands that shouldn't proceed.  Another alternative
5409          * would be to put the copy in the queue in place of the original,
5410          * and return the original back to the caller.  That could be
5411          * slightly safer..
5412          */
5413         if ((cdb->byte2 & SSS_IMMED)
5414          && ((cdb->how & SSS_START) == 0)) {
5415                 ctl_set_invalid_field(ctsio,
5416                                       /*sks_valid*/ 1,
5417                                       /*command*/ 1,
5418                                       /*field*/ 1,
5419                                       /*bit_valid*/ 1,
5420                                       /*bit*/ 0);
5421                 ctl_done((union ctl_io *)ctsio);
5422                 return (CTL_RETVAL_COMPLETE);
5423         }
5424
5425         if ((lun->flags & CTL_LUN_PR_RESERVED)
5426          && ((cdb->how & SSS_START)==0)) {
5427                 uint32_t residx;
5428
5429                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5430                 if (ctl_get_prkey(lun, residx) == 0
5431                  || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5432
5433                         ctl_set_reservation_conflict(ctsio);
5434                         ctl_done((union ctl_io *)ctsio);
5435                         return (CTL_RETVAL_COMPLETE);
5436                 }
5437         }
5438
5439         /*
5440          * If there is no backend on this device, we can't start or stop
5441          * it.  In theory we shouldn't get any start/stop commands in the
5442          * first place at this level if the LUN doesn't have a backend.
5443          * That should get stopped by the command decode code.
5444          */
5445         if (lun->backend == NULL) {
5446                 ctl_set_invalid_opcode(ctsio);
5447                 ctl_done((union ctl_io *)ctsio);
5448                 return (CTL_RETVAL_COMPLETE);
5449         }
5450
5451         /*
5452          * XXX KDM Copan-specific offline behavior.
5453          * Figure out a reasonable way to port this?
5454          */
5455 #ifdef NEEDTOPORT
5456         mtx_lock(&lun->lun_lock);
5457
5458         if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5459          && (lun->flags & CTL_LUN_OFFLINE)) {
5460                 /*
5461                  * If the LUN is offline, and the on/offline bit isn't set,
5462                  * reject the start or stop.  Otherwise, let it through.
5463                  */
5464                 mtx_unlock(&lun->lun_lock);
5465                 ctl_set_lun_not_ready(ctsio);
5466                 ctl_done((union ctl_io *)ctsio);
5467         } else {
5468                 mtx_unlock(&lun->lun_lock);
5469 #endif /* NEEDTOPORT */
5470                 /*
5471                  * This could be a start or a stop when we're online,
5472                  * or a stop/offline or start/online.  A start or stop when
5473                  * we're offline is covered in the case above.
5474                  */
5475                 /*
5476                  * In the non-immediate case, we send the request to
5477                  * the backend and return status to the user when
5478                  * it is done.
5479                  *
5480                  * In the immediate case, we allocate a new ctl_io
5481                  * to hold a copy of the request, and send that to
5482                  * the backend.  We then set good status on the
5483                  * user's request and return it immediately.
5484                  */
5485                 if (cdb->byte2 & SSS_IMMED) {
5486                         union ctl_io *new_io;
5487
5488                         new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5489                         ctl_copy_io((union ctl_io *)ctsio, new_io);
5490                         retval = lun->backend->config_write(new_io);
5491                         ctl_set_success(ctsio);
5492                         ctl_done((union ctl_io *)ctsio);
5493                 } else {
5494                         retval = lun->backend->config_write(
5495                                 (union ctl_io *)ctsio);
5496                 }
5497 #ifdef NEEDTOPORT
5498         }
5499 #endif
5500         return (retval);
5501 }
5502
5503 /*
5504  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5505  * we don't really do anything with the LBA and length fields if the user
5506  * passes them in.  Instead we'll just flush out the cache for the entire
5507  * LUN.
5508  */
5509 int
5510 ctl_sync_cache(struct ctl_scsiio *ctsio)
5511 {
5512         struct ctl_lun *lun;
5513         struct ctl_softc *softc;
5514         struct ctl_lba_len_flags *lbalen;
5515         uint64_t starting_lba;
5516         uint32_t block_count;
5517         int retval;
5518         uint8_t byte2;
5519
5520         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5521
5522         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5523         softc = lun->ctl_softc;
5524         retval = 0;
5525
5526         switch (ctsio->cdb[0]) {
5527         case SYNCHRONIZE_CACHE: {
5528                 struct scsi_sync_cache *cdb;
5529                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5530
5531                 starting_lba = scsi_4btoul(cdb->begin_lba);
5532                 block_count = scsi_2btoul(cdb->lb_count);
5533                 byte2 = cdb->byte2;
5534                 break;
5535         }
5536         case SYNCHRONIZE_CACHE_16: {
5537                 struct scsi_sync_cache_16 *cdb;
5538                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5539
5540                 starting_lba = scsi_8btou64(cdb->begin_lba);
5541                 block_count = scsi_4btoul(cdb->lb_count);
5542                 byte2 = cdb->byte2;
5543                 break;
5544         }
5545         default:
5546                 ctl_set_invalid_opcode(ctsio);
5547                 ctl_done((union ctl_io *)ctsio);
5548                 goto bailout;
5549                 break; /* NOTREACHED */
5550         }
5551
5552         /*
5553          * We check the LBA and length, but don't do anything with them.
5554          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5555          * get flushed.  This check will just help satisfy anyone who wants
5556          * to see an error for an out of range LBA.
5557          */
5558         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5559                 ctl_set_lba_out_of_range(ctsio);
5560                 ctl_done((union ctl_io *)ctsio);
5561                 goto bailout;
5562         }
5563
5564         /*
5565          * If this LUN has no backend, we can't flush the cache anyway.
5566          */
5567         if (lun->backend == NULL) {
5568                 ctl_set_invalid_opcode(ctsio);
5569                 ctl_done((union ctl_io *)ctsio);
5570                 goto bailout;
5571         }
5572
5573         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5574         lbalen->lba = starting_lba;
5575         lbalen->len = block_count;
5576         lbalen->flags = byte2;
5577
5578         /*
5579          * Check to see whether we're configured to send the SYNCHRONIZE
5580          * CACHE command directly to the back end.
5581          */
5582         mtx_lock(&lun->lun_lock);
5583         if ((softc->flags & CTL_FLAG_REAL_SYNC)
5584          && (++(lun->sync_count) >= lun->sync_interval)) {
5585                 lun->sync_count = 0;
5586                 mtx_unlock(&lun->lun_lock);
5587                 retval = lun->backend->config_write((union ctl_io *)ctsio);
5588         } else {
5589                 mtx_unlock(&lun->lun_lock);
5590                 ctl_set_success(ctsio);
5591                 ctl_done((union ctl_io *)ctsio);
5592         }
5593
5594 bailout:
5595
5596         return (retval);
5597 }
5598
5599 int
5600 ctl_format(struct ctl_scsiio *ctsio)
5601 {
5602         struct scsi_format *cdb;
5603         struct ctl_lun *lun;
5604         int length, defect_list_len;
5605
5606         CTL_DEBUG_PRINT(("ctl_format\n"));
5607
5608         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5609
5610         cdb = (struct scsi_format *)ctsio->cdb;
5611
5612         length = 0;
5613         if (cdb->byte2 & SF_FMTDATA) {
5614                 if (cdb->byte2 & SF_LONGLIST)
5615                         length = sizeof(struct scsi_format_header_long);
5616                 else
5617                         length = sizeof(struct scsi_format_header_short);
5618         }
5619
5620         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5621          && (length > 0)) {
5622                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5623                 ctsio->kern_data_len = length;
5624                 ctsio->kern_total_len = length;
5625                 ctsio->kern_data_resid = 0;
5626                 ctsio->kern_rel_offset = 0;
5627                 ctsio->kern_sg_entries = 0;
5628                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5629                 ctsio->be_move_done = ctl_config_move_done;
5630                 ctl_datamove((union ctl_io *)ctsio);
5631
5632                 return (CTL_RETVAL_COMPLETE);
5633         }
5634
5635         defect_list_len = 0;
5636
5637         if (cdb->byte2 & SF_FMTDATA) {
5638                 if (cdb->byte2 & SF_LONGLIST) {
5639                         struct scsi_format_header_long *header;
5640
5641                         header = (struct scsi_format_header_long *)
5642                                 ctsio->kern_data_ptr;
5643
5644                         defect_list_len = scsi_4btoul(header->defect_list_len);
5645                         if (defect_list_len != 0) {
5646                                 ctl_set_invalid_field(ctsio,
5647                                                       /*sks_valid*/ 1,
5648                                                       /*command*/ 0,
5649                                                       /*field*/ 2,
5650                                                       /*bit_valid*/ 0,
5651                                                       /*bit*/ 0);
5652                                 goto bailout;
5653                         }
5654                 } else {
5655                         struct scsi_format_header_short *header;
5656
5657                         header = (struct scsi_format_header_short *)
5658                                 ctsio->kern_data_ptr;
5659
5660                         defect_list_len = scsi_2btoul(header->defect_list_len);
5661                         if (defect_list_len != 0) {
5662                                 ctl_set_invalid_field(ctsio,
5663                                                       /*sks_valid*/ 1,
5664                                                       /*command*/ 0,
5665                                                       /*field*/ 2,
5666                                                       /*bit_valid*/ 0,
5667                                                       /*bit*/ 0);
5668                                 goto bailout;
5669                         }
5670                 }
5671         }
5672
5673         /*
5674          * The format command will clear out the "Medium format corrupted"
5675          * status if set by the configuration code.  That status is really
5676          * just a way to notify the host that we have lost the media, and
5677          * get them to issue a command that will basically make them think
5678          * they're blowing away the media.
5679          */
5680         mtx_lock(&lun->lun_lock);
5681         lun->flags &= ~CTL_LUN_INOPERABLE;
5682         mtx_unlock(&lun->lun_lock);
5683
5684         ctl_set_success(ctsio);
5685 bailout:
5686
5687         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5688                 free(ctsio->kern_data_ptr, M_CTL);
5689                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5690         }
5691
5692         ctl_done((union ctl_io *)ctsio);
5693         return (CTL_RETVAL_COMPLETE);
5694 }
5695
5696 int
5697 ctl_read_buffer(struct ctl_scsiio *ctsio)
5698 {
5699         struct scsi_read_buffer *cdb;
5700         struct ctl_lun *lun;
5701         int buffer_offset, len;
5702         static uint8_t descr[4];
5703         static uint8_t echo_descr[4] = { 0 };
5704
5705         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5706
5707         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5708         cdb = (struct scsi_read_buffer *)ctsio->cdb;
5709
5710         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5711             (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5712             (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5713                 ctl_set_invalid_field(ctsio,
5714                                       /*sks_valid*/ 1,
5715                                       /*command*/ 1,
5716                                       /*field*/ 1,
5717                                       /*bit_valid*/ 1,
5718                                       /*bit*/ 4);
5719                 ctl_done((union ctl_io *)ctsio);
5720                 return (CTL_RETVAL_COMPLETE);
5721         }
5722
5723         len = scsi_3btoul(cdb->length);
5724         buffer_offset = scsi_3btoul(cdb->offset);
5725
5726         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5727                 ctl_set_invalid_field(ctsio,
5728                                       /*sks_valid*/ 1,
5729                                       /*command*/ 1,
5730                                       /*field*/ 6,
5731                                       /*bit_valid*/ 0,
5732                                       /*bit*/ 0);
5733                 ctl_done((union ctl_io *)ctsio);
5734                 return (CTL_RETVAL_COMPLETE);
5735         }
5736
5737         if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5738                 descr[0] = 0;
5739                 scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5740                 ctsio->kern_data_ptr = descr;
5741                 len = min(len, sizeof(descr));
5742         } else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5743                 ctsio->kern_data_ptr = echo_descr;
5744                 len = min(len, sizeof(echo_descr));
5745         } else {
5746                 if (lun->write_buffer == NULL) {
5747                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5748                             M_CTL, M_WAITOK);
5749                 }
5750                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5751         }
5752         ctsio->kern_data_len = len;
5753         ctsio->kern_total_len = len;
5754         ctsio->kern_data_resid = 0;
5755         ctsio->kern_rel_offset = 0;
5756         ctsio->kern_sg_entries = 0;
5757         ctl_set_success(ctsio);
5758         ctsio->be_move_done = ctl_config_move_done;
5759         ctl_datamove((union ctl_io *)ctsio);
5760         return (CTL_RETVAL_COMPLETE);
5761 }
5762
5763 int
5764 ctl_write_buffer(struct ctl_scsiio *ctsio)
5765 {
5766         struct scsi_write_buffer *cdb;
5767         struct ctl_lun *lun;
5768         int buffer_offset, len;
5769
5770         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5771
5772         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5773         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5774
5775         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5776                 ctl_set_invalid_field(ctsio,
5777                                       /*sks_valid*/ 1,
5778                                       /*command*/ 1,
5779                                       /*field*/ 1,
5780                                       /*bit_valid*/ 1,
5781                                       /*bit*/ 4);
5782                 ctl_done((union ctl_io *)ctsio);
5783                 return (CTL_RETVAL_COMPLETE);
5784         }
5785
5786         len = scsi_3btoul(cdb->length);
5787         buffer_offset = scsi_3btoul(cdb->offset);
5788
5789         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5790                 ctl_set_invalid_field(ctsio,
5791                                       /*sks_valid*/ 1,
5792                                       /*command*/ 1,
5793                                       /*field*/ 6,
5794                                       /*bit_valid*/ 0,
5795                                       /*bit*/ 0);
5796                 ctl_done((union ctl_io *)ctsio);
5797                 return (CTL_RETVAL_COMPLETE);
5798         }
5799
5800         /*
5801          * If we've got a kernel request that hasn't been malloced yet,
5802          * malloc it and tell the caller the data buffer is here.
5803          */
5804         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5805                 if (lun->write_buffer == NULL) {
5806                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5807                             M_CTL, M_WAITOK);
5808                 }
5809                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5810                 ctsio->kern_data_len = len;
5811                 ctsio->kern_total_len = len;
5812                 ctsio->kern_data_resid = 0;
5813                 ctsio->kern_rel_offset = 0;
5814                 ctsio->kern_sg_entries = 0;
5815                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5816                 ctsio->be_move_done = ctl_config_move_done;
5817                 ctl_datamove((union ctl_io *)ctsio);
5818
5819                 return (CTL_RETVAL_COMPLETE);
5820         }
5821
5822         ctl_set_success(ctsio);
5823         ctl_done((union ctl_io *)ctsio);
5824         return (CTL_RETVAL_COMPLETE);
5825 }
5826
5827 int
5828 ctl_write_same(struct ctl_scsiio *ctsio)
5829 {
5830         struct ctl_lun *lun;
5831         struct ctl_lba_len_flags *lbalen;
5832         uint64_t lba;
5833         uint32_t num_blocks;
5834         int len, retval;
5835         uint8_t byte2;
5836
5837         retval = CTL_RETVAL_COMPLETE;
5838
5839         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5840
5841         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5842
5843         switch (ctsio->cdb[0]) {
5844         case WRITE_SAME_10: {
5845                 struct scsi_write_same_10 *cdb;
5846
5847                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5848
5849                 lba = scsi_4btoul(cdb->addr);
5850                 num_blocks = scsi_2btoul(cdb->length);
5851                 byte2 = cdb->byte2;
5852                 break;
5853         }
5854         case WRITE_SAME_16: {
5855                 struct scsi_write_same_16 *cdb;
5856
5857                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5858
5859                 lba = scsi_8btou64(cdb->addr);
5860                 num_blocks = scsi_4btoul(cdb->length);
5861                 byte2 = cdb->byte2;
5862                 break;
5863         }
5864         default:
5865                 /*
5866                  * We got a command we don't support.  This shouldn't
5867                  * happen, commands should be filtered out above us.
5868                  */
5869                 ctl_set_invalid_opcode(ctsio);
5870                 ctl_done((union ctl_io *)ctsio);
5871
5872                 return (CTL_RETVAL_COMPLETE);
5873                 break; /* NOTREACHED */
5874         }
5875
5876         /* NDOB and ANCHOR flags can be used only together with UNMAP */
5877         if ((byte2 & SWS_UNMAP) == 0 &&
5878             (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5879                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5880                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5881                 ctl_done((union ctl_io *)ctsio);
5882                 return (CTL_RETVAL_COMPLETE);
5883         }
5884
5885         /*
5886          * The first check is to make sure we're in bounds, the second
5887          * check is to catch wrap-around problems.  If the lba + num blocks
5888          * is less than the lba, then we've wrapped around and the block
5889          * range is invalid anyway.
5890          */
5891         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5892          || ((lba + num_blocks) < lba)) {
5893                 ctl_set_lba_out_of_range(ctsio);
5894                 ctl_done((union ctl_io *)ctsio);
5895                 return (CTL_RETVAL_COMPLETE);
5896         }
5897
5898         /* Zero number of blocks means "to the last logical block" */
5899         if (num_blocks == 0) {
5900                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5901                         ctl_set_invalid_field(ctsio,
5902                                               /*sks_valid*/ 0,
5903                                               /*command*/ 1,
5904                                               /*field*/ 0,
5905                                               /*bit_valid*/ 0,
5906                                               /*bit*/ 0);
5907                         ctl_done((union ctl_io *)ctsio);
5908                         return (CTL_RETVAL_COMPLETE);
5909                 }
5910                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
5911         }
5912
5913         len = lun->be_lun->blocksize;
5914
5915         /*
5916          * If we've got a kernel request that hasn't been malloced yet,
5917          * malloc it and tell the caller the data buffer is here.
5918          */
5919         if ((byte2 & SWS_NDOB) == 0 &&
5920             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5921                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5922                 ctsio->kern_data_len = len;
5923                 ctsio->kern_total_len = len;
5924                 ctsio->kern_data_resid = 0;
5925                 ctsio->kern_rel_offset = 0;
5926                 ctsio->kern_sg_entries = 0;
5927                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5928                 ctsio->be_move_done = ctl_config_move_done;
5929                 ctl_datamove((union ctl_io *)ctsio);
5930
5931                 return (CTL_RETVAL_COMPLETE);
5932         }
5933
5934         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5935         lbalen->lba = lba;
5936         lbalen->len = num_blocks;
5937         lbalen->flags = byte2;
5938         retval = lun->backend->config_write((union ctl_io *)ctsio);
5939
5940         return (retval);
5941 }
5942
5943 int
5944 ctl_unmap(struct ctl_scsiio *ctsio)
5945 {
5946         struct ctl_lun *lun;
5947         struct scsi_unmap *cdb;
5948         struct ctl_ptr_len_flags *ptrlen;
5949         struct scsi_unmap_header *hdr;
5950         struct scsi_unmap_desc *buf, *end, *endnz, *range;
5951         uint64_t lba;
5952         uint32_t num_blocks;
5953         int len, retval;
5954         uint8_t byte2;
5955
5956         retval = CTL_RETVAL_COMPLETE;
5957
5958         CTL_DEBUG_PRINT(("ctl_unmap\n"));
5959
5960         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5961         cdb = (struct scsi_unmap *)ctsio->cdb;
5962
5963         len = scsi_2btoul(cdb->length);
5964         byte2 = cdb->byte2;
5965
5966         /*
5967          * If we've got a kernel request that hasn't been malloced yet,
5968          * malloc it and tell the caller the data buffer is here.
5969          */
5970         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5971                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5972                 ctsio->kern_data_len = len;
5973                 ctsio->kern_total_len = len;
5974                 ctsio->kern_data_resid = 0;
5975                 ctsio->kern_rel_offset = 0;
5976                 ctsio->kern_sg_entries = 0;
5977                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5978                 ctsio->be_move_done = ctl_config_move_done;
5979                 ctl_datamove((union ctl_io *)ctsio);
5980
5981                 return (CTL_RETVAL_COMPLETE);
5982         }
5983
5984         len = ctsio->kern_total_len - ctsio->kern_data_resid;
5985         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5986         if (len < sizeof (*hdr) ||
5987             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5988             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5989             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5990                 ctl_set_invalid_field(ctsio,
5991                                       /*sks_valid*/ 0,
5992                                       /*command*/ 0,
5993                                       /*field*/ 0,
5994                                       /*bit_valid*/ 0,
5995                                       /*bit*/ 0);
5996                 goto done;
5997         }
5998         len = scsi_2btoul(hdr->desc_length);
5999         buf = (struct scsi_unmap_desc *)(hdr + 1);
6000         end = buf + len / sizeof(*buf);
6001
6002         endnz = buf;
6003         for (range = buf; range < end; range++) {
6004                 lba = scsi_8btou64(range->lba);
6005                 num_blocks = scsi_4btoul(range->length);
6006                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6007                  || ((lba + num_blocks) < lba)) {
6008                         ctl_set_lba_out_of_range(ctsio);
6009                         ctl_done((union ctl_io *)ctsio);
6010                         return (CTL_RETVAL_COMPLETE);
6011                 }
6012                 if (num_blocks != 0)
6013                         endnz = range + 1;
6014         }
6015
6016         /*
6017          * Block backend can not handle zero last range.
6018          * Filter it out and return if there is nothing left.
6019          */
6020         len = (uint8_t *)endnz - (uint8_t *)buf;
6021         if (len == 0) {
6022                 ctl_set_success(ctsio);
6023                 goto done;
6024         }
6025
6026         mtx_lock(&lun->lun_lock);
6027         ptrlen = (struct ctl_ptr_len_flags *)
6028             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6029         ptrlen->ptr = (void *)buf;
6030         ptrlen->len = len;
6031         ptrlen->flags = byte2;
6032         ctl_check_blocked(lun);
6033         mtx_unlock(&lun->lun_lock);
6034
6035         retval = lun->backend->config_write((union ctl_io *)ctsio);
6036         return (retval);
6037
6038 done:
6039         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
6040                 free(ctsio->kern_data_ptr, M_CTL);
6041                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
6042         }
6043         ctl_done((union ctl_io *)ctsio);
6044         return (CTL_RETVAL_COMPLETE);
6045 }
6046
6047 /*
6048  * Note that this function currently doesn't actually do anything inside
6049  * CTL to enforce things if the DQue bit is turned on.
6050  *
6051  * Also note that this function can't be used in the default case, because
6052  * the DQue bit isn't set in the changeable mask for the control mode page
6053  * anyway.  This is just here as an example for how to implement a page
6054  * handler, and a placeholder in case we want to allow the user to turn
6055  * tagged queueing on and off.
6056  *
6057  * The D_SENSE bit handling is functional, however, and will turn
6058  * descriptor sense on and off for a given LUN.
6059  */
6060 int
6061 ctl_control_page_handler(struct ctl_scsiio *ctsio,
6062                          struct ctl_page_index *page_index, uint8_t *page_ptr)
6063 {
6064         struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6065         struct ctl_lun *lun;
6066         int set_ua;
6067         uint32_t initidx;
6068
6069         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6070         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6071         set_ua = 0;
6072
6073         user_cp = (struct scsi_control_page *)page_ptr;
6074         current_cp = (struct scsi_control_page *)
6075                 (page_index->page_data + (page_index->page_len *
6076                 CTL_PAGE_CURRENT));
6077         saved_cp = (struct scsi_control_page *)
6078                 (page_index->page_data + (page_index->page_len *
6079                 CTL_PAGE_SAVED));
6080
6081         mtx_lock(&lun->lun_lock);
6082         if (((current_cp->rlec & SCP_DSENSE) == 0)
6083          && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6084                 /*
6085                  * Descriptor sense is currently turned off and the user
6086                  * wants to turn it on.
6087                  */
6088                 current_cp->rlec |= SCP_DSENSE;
6089                 saved_cp->rlec |= SCP_DSENSE;
6090                 lun->flags |= CTL_LUN_SENSE_DESC;
6091                 set_ua = 1;
6092         } else if (((current_cp->rlec & SCP_DSENSE) != 0)
6093                 && ((user_cp->rlec & SCP_DSENSE) == 0)) {
6094                 /*
6095                  * Descriptor sense is currently turned on, and the user
6096                  * wants to turn it off.
6097                  */
6098                 current_cp->rlec &= ~SCP_DSENSE;
6099                 saved_cp->rlec &= ~SCP_DSENSE;
6100                 lun->flags &= ~CTL_LUN_SENSE_DESC;
6101                 set_ua = 1;
6102         }
6103         if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6104             (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6105                 current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6106                 current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6107                 saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6108                 saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6109                 set_ua = 1;
6110         }
6111         if ((current_cp->eca_and_aen & SCP_SWP) !=
6112             (user_cp->eca_and_aen & SCP_SWP)) {
6113                 current_cp->eca_and_aen &= ~SCP_SWP;
6114                 current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6115                 saved_cp->eca_and_aen &= ~SCP_SWP;
6116                 saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6117                 set_ua = 1;
6118         }
6119         if (set_ua != 0)
6120                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6121         mtx_unlock(&lun->lun_lock);
6122
6123         return (0);
6124 }
6125
6126 int
6127 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6128                      struct ctl_page_index *page_index, uint8_t *page_ptr)
6129 {
6130         struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6131         struct ctl_lun *lun;
6132         int set_ua;
6133         uint32_t initidx;
6134
6135         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6136         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6137         set_ua = 0;
6138
6139         user_cp = (struct scsi_caching_page *)page_ptr;
6140         current_cp = (struct scsi_caching_page *)
6141                 (page_index->page_data + (page_index->page_len *
6142                 CTL_PAGE_CURRENT));
6143         saved_cp = (struct scsi_caching_page *)
6144                 (page_index->page_data + (page_index->page_len *
6145                 CTL_PAGE_SAVED));
6146
6147         mtx_lock(&lun->lun_lock);
6148         if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6149             (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6150                 current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6151                 current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6152                 saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6153                 saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6154                 set_ua = 1;
6155         }
6156         if (set_ua != 0)
6157                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6158         mtx_unlock(&lun->lun_lock);
6159
6160         return (0);
6161 }
6162
6163 int
6164 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6165                                 struct ctl_page_index *page_index,
6166                                 uint8_t *page_ptr)
6167 {
6168         uint8_t *c;
6169         int i;
6170
6171         c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6172         ctl_time_io_secs =
6173                 (c[0] << 8) |
6174                 (c[1] << 0) |
6175                 0;
6176         CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6177         printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6178         printf("page data:");
6179         for (i=0; i<8; i++)
6180                 printf(" %.2x",page_ptr[i]);
6181         printf("\n");
6182         return (0);
6183 }
6184
6185 int
6186 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6187                                struct ctl_page_index *page_index,
6188                                int pc)
6189 {
6190         struct copan_debugconf_subpage *page;
6191
6192         page = (struct copan_debugconf_subpage *)page_index->page_data +
6193                 (page_index->page_len * pc);
6194
6195         switch (pc) {
6196         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6197         case SMS_PAGE_CTRL_DEFAULT >> 6:
6198         case SMS_PAGE_CTRL_SAVED >> 6:
6199                 /*
6200                  * We don't update the changable or default bits for this page.
6201                  */
6202                 break;
6203         case SMS_PAGE_CTRL_CURRENT >> 6:
6204                 page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6205                 page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6206                 break;
6207         default:
6208 #ifdef NEEDTOPORT
6209                 EPRINT(0, "Invalid PC %d!!", pc);
6210 #endif /* NEEDTOPORT */
6211                 break;
6212         }
6213         return (0);
6214 }
6215
6216
6217 static int
6218 ctl_do_mode_select(union ctl_io *io)
6219 {
6220         struct scsi_mode_page_header *page_header;
6221         struct ctl_page_index *page_index;
6222         struct ctl_scsiio *ctsio;
6223         int control_dev, page_len;
6224         int page_len_offset, page_len_size;
6225         union ctl_modepage_info *modepage_info;
6226         struct ctl_lun *lun;
6227         int *len_left, *len_used;
6228         int retval, i;
6229
6230         ctsio = &io->scsiio;
6231         page_index = NULL;
6232         page_len = 0;
6233         retval = CTL_RETVAL_COMPLETE;
6234
6235         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6236
6237         if (lun->be_lun->lun_type != T_DIRECT)
6238                 control_dev = 1;
6239         else
6240                 control_dev = 0;
6241
6242         modepage_info = (union ctl_modepage_info *)
6243                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6244         len_left = &modepage_info->header.len_left;
6245         len_used = &modepage_info->header.len_used;
6246
6247 do_next_page:
6248
6249         page_header = (struct scsi_mode_page_header *)
6250                 (ctsio->kern_data_ptr + *len_used);
6251
6252         if (*len_left == 0) {
6253                 free(ctsio->kern_data_ptr, M_CTL);
6254                 ctl_set_success(ctsio);
6255                 ctl_done((union ctl_io *)ctsio);
6256                 return (CTL_RETVAL_COMPLETE);
6257         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6258
6259                 free(ctsio->kern_data_ptr, M_CTL);
6260                 ctl_set_param_len_error(ctsio);
6261                 ctl_done((union ctl_io *)ctsio);
6262                 return (CTL_RETVAL_COMPLETE);
6263
6264         } else if ((page_header->page_code & SMPH_SPF)
6265                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6266
6267                 free(ctsio->kern_data_ptr, M_CTL);
6268                 ctl_set_param_len_error(ctsio);
6269                 ctl_done((union ctl_io *)ctsio);
6270                 return (CTL_RETVAL_COMPLETE);
6271         }
6272
6273
6274         /*
6275          * XXX KDM should we do something with the block descriptor?
6276          */
6277         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6278
6279                 if ((control_dev != 0)
6280                  && (lun->mode_pages.index[i].page_flags &
6281                      CTL_PAGE_FLAG_DISK_ONLY))
6282                         continue;
6283
6284                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6285                     (page_header->page_code & SMPH_PC_MASK))
6286                         continue;
6287
6288                 /*
6289                  * If neither page has a subpage code, then we've got a
6290                  * match.
6291                  */
6292                 if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6293                  && ((page_header->page_code & SMPH_SPF) == 0)) {
6294                         page_index = &lun->mode_pages.index[i];
6295                         page_len = page_header->page_length;
6296                         break;
6297                 }
6298
6299                 /*
6300                  * If both pages have subpages, then the subpage numbers
6301                  * have to match.
6302                  */
6303                 if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6304                   && (page_header->page_code & SMPH_SPF)) {
6305                         struct scsi_mode_page_header_sp *sph;
6306
6307                         sph = (struct scsi_mode_page_header_sp *)page_header;
6308
6309                         if (lun->mode_pages.index[i].subpage ==
6310                             sph->subpage) {
6311                                 page_index = &lun->mode_pages.index[i];
6312                                 page_len = scsi_2btoul(sph->page_length);
6313                                 break;
6314                         }
6315                 }
6316         }
6317
6318         /*
6319          * If we couldn't find the page, or if we don't have a mode select
6320          * handler for it, send back an error to the user.
6321          */
6322         if ((page_index == NULL)
6323          || (page_index->select_handler == NULL)) {
6324                 ctl_set_invalid_field(ctsio,
6325                                       /*sks_valid*/ 1,
6326                                       /*command*/ 0,
6327                                       /*field*/ *len_used,
6328                                       /*bit_valid*/ 0,
6329                                       /*bit*/ 0);
6330                 free(ctsio->kern_data_ptr, M_CTL);
6331                 ctl_done((union ctl_io *)ctsio);
6332                 return (CTL_RETVAL_COMPLETE);
6333         }
6334
6335         if (page_index->page_code & SMPH_SPF) {
6336                 page_len_offset = 2;
6337                 page_len_size = 2;
6338         } else {
6339                 page_len_size = 1;
6340                 page_len_offset = 1;
6341         }
6342
6343         /*
6344          * If the length the initiator gives us isn't the one we specify in
6345          * the mode page header, or if they didn't specify enough data in
6346          * the CDB to avoid truncating this page, kick out the request.
6347          */
6348         if ((page_len != (page_index->page_len - page_len_offset -
6349                           page_len_size))
6350          || (*len_left < page_index->page_len)) {
6351
6352
6353                 ctl_set_invalid_field(ctsio,
6354                                       /*sks_valid*/ 1,
6355                                       /*command*/ 0,
6356                                       /*field*/ *len_used + page_len_offset,
6357                                       /*bit_valid*/ 0,
6358                                       /*bit*/ 0);
6359                 free(ctsio->kern_data_ptr, M_CTL);
6360                 ctl_done((union ctl_io *)ctsio);
6361                 return (CTL_RETVAL_COMPLETE);
6362         }
6363
6364         /*
6365          * Run through the mode page, checking to make sure that the bits
6366          * the user changed are actually legal for him to change.
6367          */
6368         for (i = 0; i < page_index->page_len; i++) {
6369                 uint8_t *user_byte, *change_mask, *current_byte;
6370                 int bad_bit;
6371                 int j;
6372
6373                 user_byte = (uint8_t *)page_header + i;
6374                 change_mask = page_index->page_data +
6375                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6376                 current_byte = page_index->page_data +
6377                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6378
6379                 /*
6380                  * Check to see whether the user set any bits in this byte
6381                  * that he is not allowed to set.
6382                  */
6383                 if ((*user_byte & ~(*change_mask)) ==
6384                     (*current_byte & ~(*change_mask)))
6385                         continue;
6386
6387                 /*
6388                  * Go through bit by bit to determine which one is illegal.
6389                  */
6390                 bad_bit = 0;
6391                 for (j = 7; j >= 0; j--) {
6392                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6393                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6394                                 bad_bit = i;
6395                                 break;
6396                         }
6397                 }
6398                 ctl_set_invalid_field(ctsio,
6399                                       /*sks_valid*/ 1,
6400                                       /*command*/ 0,
6401                                       /*field*/ *len_used + i,
6402                                       /*bit_valid*/ 1,
6403                                       /*bit*/ bad_bit);
6404                 free(ctsio->kern_data_ptr, M_CTL);
6405                 ctl_done((union ctl_io *)ctsio);
6406                 return (CTL_RETVAL_COMPLETE);
6407         }
6408
6409         /*
6410          * Decrement these before we call the page handler, since we may
6411          * end up getting called back one way or another before the handler
6412          * returns to this context.
6413          */
6414         *len_left -= page_index->page_len;
6415         *len_used += page_index->page_len;
6416
6417         retval = page_index->select_handler(ctsio, page_index,
6418                                             (uint8_t *)page_header);
6419
6420         /*
6421          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6422          * wait until this queued command completes to finish processing
6423          * the mode page.  If it returns anything other than
6424          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6425          * already set the sense information, freed the data pointer, and
6426          * completed the io for us.
6427          */
6428         if (retval != CTL_RETVAL_COMPLETE)
6429                 goto bailout_no_done;
6430
6431         /*
6432          * If the initiator sent us more than one page, parse the next one.
6433          */
6434         if (*len_left > 0)
6435                 goto do_next_page;
6436
6437         ctl_set_success(ctsio);
6438         free(ctsio->kern_data_ptr, M_CTL);
6439         ctl_done((union ctl_io *)ctsio);
6440
6441 bailout_no_done:
6442
6443         return (CTL_RETVAL_COMPLETE);
6444
6445 }
6446
6447 int
6448 ctl_mode_select(struct ctl_scsiio *ctsio)
6449 {
6450         int param_len, pf, sp;
6451         int header_size, bd_len;
6452         int len_left, len_used;
6453         struct ctl_page_index *page_index;
6454         struct ctl_lun *lun;
6455         int control_dev, page_len;
6456         union ctl_modepage_info *modepage_info;
6457         int retval;
6458
6459         pf = 0;
6460         sp = 0;
6461         page_len = 0;
6462         len_used = 0;
6463         len_left = 0;
6464         retval = 0;
6465         bd_len = 0;
6466         page_index = NULL;
6467
6468         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6469
6470         if (lun->be_lun->lun_type != T_DIRECT)
6471                 control_dev = 1;
6472         else
6473                 control_dev = 0;
6474
6475         switch (ctsio->cdb[0]) {
6476         case MODE_SELECT_6: {
6477                 struct scsi_mode_select_6 *cdb;
6478
6479                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6480
6481                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6482                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6483
6484                 param_len = cdb->length;
6485                 header_size = sizeof(struct scsi_mode_header_6);
6486                 break;
6487         }
6488         case MODE_SELECT_10: {
6489                 struct scsi_mode_select_10 *cdb;
6490
6491                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6492
6493                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6494                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6495
6496                 param_len = scsi_2btoul(cdb->length);
6497                 header_size = sizeof(struct scsi_mode_header_10);
6498                 break;
6499         }
6500         default:
6501                 ctl_set_invalid_opcode(ctsio);
6502                 ctl_done((union ctl_io *)ctsio);
6503                 return (CTL_RETVAL_COMPLETE);
6504                 break; /* NOTREACHED */
6505         }
6506
6507         /*
6508          * From SPC-3:
6509          * "A parameter list length of zero indicates that the Data-Out Buffer
6510          * shall be empty. This condition shall not be considered as an error."
6511          */
6512         if (param_len == 0) {
6513                 ctl_set_success(ctsio);
6514                 ctl_done((union ctl_io *)ctsio);
6515                 return (CTL_RETVAL_COMPLETE);
6516         }
6517
6518         /*
6519          * Since we'll hit this the first time through, prior to
6520          * allocation, we don't need to free a data buffer here.
6521          */
6522         if (param_len < header_size) {
6523                 ctl_set_param_len_error(ctsio);
6524                 ctl_done((union ctl_io *)ctsio);
6525                 return (CTL_RETVAL_COMPLETE);
6526         }
6527
6528         /*
6529          * Allocate the data buffer and grab the user's data.  In theory,
6530          * we shouldn't have to sanity check the parameter list length here
6531          * because the maximum size is 64K.  We should be able to malloc
6532          * that much without too many problems.
6533          */
6534         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6535                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6536                 ctsio->kern_data_len = param_len;
6537                 ctsio->kern_total_len = param_len;
6538                 ctsio->kern_data_resid = 0;
6539                 ctsio->kern_rel_offset = 0;
6540                 ctsio->kern_sg_entries = 0;
6541                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6542                 ctsio->be_move_done = ctl_config_move_done;
6543                 ctl_datamove((union ctl_io *)ctsio);
6544
6545                 return (CTL_RETVAL_COMPLETE);
6546         }
6547
6548         switch (ctsio->cdb[0]) {
6549         case MODE_SELECT_6: {
6550                 struct scsi_mode_header_6 *mh6;
6551
6552                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6553                 bd_len = mh6->blk_desc_len;
6554                 break;
6555         }
6556         case MODE_SELECT_10: {
6557                 struct scsi_mode_header_10 *mh10;
6558
6559                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6560                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6561                 break;
6562         }
6563         default:
6564                 panic("Invalid CDB type %#x", ctsio->cdb[0]);
6565                 break;
6566         }
6567
6568         if (param_len < (header_size + bd_len)) {
6569                 free(ctsio->kern_data_ptr, M_CTL);
6570                 ctl_set_param_len_error(ctsio);
6571                 ctl_done((union ctl_io *)ctsio);
6572                 return (CTL_RETVAL_COMPLETE);
6573         }
6574
6575         /*
6576          * Set the IO_CONT flag, so that if this I/O gets passed to
6577          * ctl_config_write_done(), it'll get passed back to
6578          * ctl_do_mode_select() for further processing, or completion if
6579          * we're all done.
6580          */
6581         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6582         ctsio->io_cont = ctl_do_mode_select;
6583
6584         modepage_info = (union ctl_modepage_info *)
6585                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6586
6587         memset(modepage_info, 0, sizeof(*modepage_info));
6588
6589         len_left = param_len - header_size - bd_len;
6590         len_used = header_size + bd_len;
6591
6592         modepage_info->header.len_left = len_left;
6593         modepage_info->header.len_used = len_used;
6594
6595         return (ctl_do_mode_select((union ctl_io *)ctsio));
6596 }
6597
6598 int
6599 ctl_mode_sense(struct ctl_scsiio *ctsio)
6600 {
6601         struct ctl_lun *lun;
6602         int pc, page_code, dbd, llba, subpage;
6603         int alloc_len, page_len, header_len, total_len;
6604         struct scsi_mode_block_descr *block_desc;
6605         struct ctl_page_index *page_index;
6606         int control_dev;
6607
6608         dbd = 0;
6609         llba = 0;
6610         block_desc = NULL;
6611         page_index = NULL;
6612
6613         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6614
6615         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6616
6617         if (lun->be_lun->lun_type != T_DIRECT)
6618                 control_dev = 1;
6619         else
6620                 control_dev = 0;
6621
6622         switch (ctsio->cdb[0]) {
6623         case MODE_SENSE_6: {
6624                 struct scsi_mode_sense_6 *cdb;
6625
6626                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6627
6628                 header_len = sizeof(struct scsi_mode_hdr_6);
6629                 if (cdb->byte2 & SMS_DBD)
6630                         dbd = 1;
6631                 else
6632                         header_len += sizeof(struct scsi_mode_block_descr);
6633
6634                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6635                 page_code = cdb->page & SMS_PAGE_CODE;
6636                 subpage = cdb->subpage;
6637                 alloc_len = cdb->length;
6638                 break;
6639         }
6640         case MODE_SENSE_10: {
6641                 struct scsi_mode_sense_10 *cdb;
6642
6643                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6644
6645                 header_len = sizeof(struct scsi_mode_hdr_10);
6646
6647                 if (cdb->byte2 & SMS_DBD)
6648                         dbd = 1;
6649                 else
6650                         header_len += sizeof(struct scsi_mode_block_descr);
6651                 if (cdb->byte2 & SMS10_LLBAA)
6652                         llba = 1;
6653                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6654                 page_code = cdb->page & SMS_PAGE_CODE;
6655                 subpage = cdb->subpage;
6656                 alloc_len = scsi_2btoul(cdb->length);
6657                 break;
6658         }
6659         default:
6660                 ctl_set_invalid_opcode(ctsio);
6661                 ctl_done((union ctl_io *)ctsio);
6662                 return (CTL_RETVAL_COMPLETE);
6663                 break; /* NOTREACHED */
6664         }
6665
6666         /*
6667          * We have to make a first pass through to calculate the size of
6668          * the pages that match the user's query.  Then we allocate enough
6669          * memory to hold it, and actually copy the data into the buffer.
6670          */
6671         switch (page_code) {
6672         case SMS_ALL_PAGES_PAGE: {
6673                 int i;
6674
6675                 page_len = 0;
6676
6677                 /*
6678                  * At the moment, values other than 0 and 0xff here are
6679                  * reserved according to SPC-3.
6680                  */
6681                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6682                  && (subpage != SMS_SUBPAGE_ALL)) {
6683                         ctl_set_invalid_field(ctsio,
6684                                               /*sks_valid*/ 1,
6685                                               /*command*/ 1,
6686                                               /*field*/ 3,
6687                                               /*bit_valid*/ 0,
6688                                               /*bit*/ 0);
6689                         ctl_done((union ctl_io *)ctsio);
6690                         return (CTL_RETVAL_COMPLETE);
6691                 }
6692
6693                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6694                         if ((control_dev != 0)
6695                          && (lun->mode_pages.index[i].page_flags &
6696                              CTL_PAGE_FLAG_DISK_ONLY))
6697                                 continue;
6698
6699                         /*
6700                          * We don't use this subpage if the user didn't
6701                          * request all subpages.
6702                          */
6703                         if ((lun->mode_pages.index[i].subpage != 0)
6704                          && (subpage == SMS_SUBPAGE_PAGE_0))
6705                                 continue;
6706
6707 #if 0
6708                         printf("found page %#x len %d\n",
6709                                lun->mode_pages.index[i].page_code &
6710                                SMPH_PC_MASK,
6711                                lun->mode_pages.index[i].page_len);
6712 #endif
6713                         page_len += lun->mode_pages.index[i].page_len;
6714                 }
6715                 break;
6716         }
6717         default: {
6718                 int i;
6719
6720                 page_len = 0;
6721
6722                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6723                         /* Look for the right page code */
6724                         if ((lun->mode_pages.index[i].page_code &
6725                              SMPH_PC_MASK) != page_code)
6726                                 continue;
6727
6728                         /* Look for the right subpage or the subpage wildcard*/
6729                         if ((lun->mode_pages.index[i].subpage != subpage)
6730                          && (subpage != SMS_SUBPAGE_ALL))
6731                                 continue;
6732
6733                         /* Make sure the page is supported for this dev type */
6734                         if ((control_dev != 0)
6735                          && (lun->mode_pages.index[i].page_flags &
6736                              CTL_PAGE_FLAG_DISK_ONLY))
6737                                 continue;
6738
6739 #if 0
6740                         printf("found page %#x len %d\n",
6741                                lun->mode_pages.index[i].page_code &
6742                                SMPH_PC_MASK,
6743                                lun->mode_pages.index[i].page_len);
6744 #endif
6745
6746                         page_len += lun->mode_pages.index[i].page_len;
6747                 }
6748
6749                 if (page_len == 0) {
6750                         ctl_set_invalid_field(ctsio,
6751                                               /*sks_valid*/ 1,
6752                                               /*command*/ 1,
6753                                               /*field*/ 2,
6754                                               /*bit_valid*/ 1,
6755                                               /*bit*/ 5);
6756                         ctl_done((union ctl_io *)ctsio);
6757                         return (CTL_RETVAL_COMPLETE);
6758                 }
6759                 break;
6760         }
6761         }
6762
6763         total_len = header_len + page_len;
6764 #if 0
6765         printf("header_len = %d, page_len = %d, total_len = %d\n",
6766                header_len, page_len, total_len);
6767 #endif
6768
6769         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6770         ctsio->kern_sg_entries = 0;
6771         ctsio->kern_data_resid = 0;
6772         ctsio->kern_rel_offset = 0;
6773         if (total_len < alloc_len) {
6774                 ctsio->residual = alloc_len - total_len;
6775                 ctsio->kern_data_len = total_len;
6776                 ctsio->kern_total_len = total_len;
6777         } else {
6778                 ctsio->residual = 0;
6779                 ctsio->kern_data_len = alloc_len;
6780                 ctsio->kern_total_len = alloc_len;
6781         }
6782
6783         switch (ctsio->cdb[0]) {
6784         case MODE_SENSE_6: {
6785                 struct scsi_mode_hdr_6 *header;
6786
6787                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6788
6789                 header->datalen = MIN(total_len - 1, 254);
6790                 if (control_dev == 0) {
6791                         header->dev_specific = 0x10; /* DPOFUA */
6792                         if ((lun->flags & CTL_LUN_READONLY) ||
6793                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6794                             .eca_and_aen & SCP_SWP) != 0)
6795                                     header->dev_specific |= 0x80; /* WP */
6796                 }
6797                 if (dbd)
6798                         header->block_descr_len = 0;
6799                 else
6800                         header->block_descr_len =
6801                                 sizeof(struct scsi_mode_block_descr);
6802                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6803                 break;
6804         }
6805         case MODE_SENSE_10: {
6806                 struct scsi_mode_hdr_10 *header;
6807                 int datalen;
6808
6809                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6810
6811                 datalen = MIN(total_len - 2, 65533);
6812                 scsi_ulto2b(datalen, header->datalen);
6813                 if (control_dev == 0) {
6814                         header->dev_specific = 0x10; /* DPOFUA */
6815                         if ((lun->flags & CTL_LUN_READONLY) ||
6816                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6817                             .eca_and_aen & SCP_SWP) != 0)
6818                                     header->dev_specific |= 0x80; /* WP */
6819                 }
6820                 if (dbd)
6821                         scsi_ulto2b(0, header->block_descr_len);
6822                 else
6823                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6824                                     header->block_descr_len);
6825                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6826                 break;
6827         }
6828         default:
6829                 panic("invalid CDB type %#x", ctsio->cdb[0]);
6830                 break; /* NOTREACHED */
6831         }
6832
6833         /*
6834          * If we've got a disk, use its blocksize in the block
6835          * descriptor.  Otherwise, just set it to 0.
6836          */
6837         if (dbd == 0) {
6838                 if (control_dev == 0)
6839                         scsi_ulto3b(lun->be_lun->blocksize,
6840                                     block_desc->block_len);
6841                 else
6842                         scsi_ulto3b(0, block_desc->block_len);
6843         }
6844
6845         switch (page_code) {
6846         case SMS_ALL_PAGES_PAGE: {
6847                 int i, data_used;
6848
6849                 data_used = header_len;
6850                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6851                         struct ctl_page_index *page_index;
6852
6853                         page_index = &lun->mode_pages.index[i];
6854
6855                         if ((control_dev != 0)
6856                          && (page_index->page_flags &
6857                             CTL_PAGE_FLAG_DISK_ONLY))
6858                                 continue;
6859
6860                         /*
6861                          * We don't use this subpage if the user didn't
6862                          * request all subpages.  We already checked (above)
6863                          * to make sure the user only specified a subpage
6864                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6865                          */
6866                         if ((page_index->subpage != 0)
6867                          && (subpage == SMS_SUBPAGE_PAGE_0))
6868                                 continue;
6869
6870                         /*
6871                          * Call the handler, if it exists, to update the
6872                          * page to the latest values.
6873                          */
6874                         if (page_index->sense_handler != NULL)
6875                                 page_index->sense_handler(ctsio, page_index,pc);
6876
6877                         memcpy(ctsio->kern_data_ptr + data_used,
6878                                page_index->page_data +
6879                                (page_index->page_len * pc),
6880                                page_index->page_len);
6881                         data_used += page_index->page_len;
6882                 }
6883                 break;
6884         }
6885         default: {
6886                 int i, data_used;
6887
6888                 data_used = header_len;
6889
6890                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6891                         struct ctl_page_index *page_index;
6892
6893                         page_index = &lun->mode_pages.index[i];
6894
6895                         /* Look for the right page code */
6896                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6897                                 continue;
6898
6899                         /* Look for the right subpage or the subpage wildcard*/
6900                         if ((page_index->subpage != subpage)
6901                          && (subpage != SMS_SUBPAGE_ALL))
6902                                 continue;
6903
6904                         /* Make sure the page is supported for this dev type */
6905                         if ((control_dev != 0)
6906                          && (page_index->page_flags &
6907                              CTL_PAGE_FLAG_DISK_ONLY))
6908                                 continue;
6909
6910                         /*
6911                          * Call the handler, if it exists, to update the
6912                          * page to the latest values.
6913                          */
6914                         if (page_index->sense_handler != NULL)
6915                                 page_index->sense_handler(ctsio, page_index,pc);
6916
6917                         memcpy(ctsio->kern_data_ptr + data_used,
6918                                page_index->page_data +
6919                                (page_index->page_len * pc),
6920                                page_index->page_len);
6921                         data_used += page_index->page_len;
6922                 }
6923                 break;
6924         }
6925         }
6926
6927         ctl_set_success(ctsio);
6928         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6929         ctsio->be_move_done = ctl_config_move_done;
6930         ctl_datamove((union ctl_io *)ctsio);
6931         return (CTL_RETVAL_COMPLETE);
6932 }
6933
6934 int
6935 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6936                                struct ctl_page_index *page_index,
6937                                int pc)
6938 {
6939         struct ctl_lun *lun;
6940         struct scsi_log_param_header *phdr;
6941         uint8_t *data;
6942         uint64_t val;
6943
6944         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6945         data = page_index->page_data;
6946
6947         if (lun->backend->lun_attr != NULL &&
6948             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6949              != UINT64_MAX) {
6950                 phdr = (struct scsi_log_param_header *)data;
6951                 scsi_ulto2b(0x0001, phdr->param_code);
6952                 phdr->param_control = SLP_LBIN | SLP_LP;
6953                 phdr->param_len = 8;
6954                 data = (uint8_t *)(phdr + 1);
6955                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6956                 data[4] = 0x02; /* per-pool */
6957                 data += phdr->param_len;
6958         }
6959
6960         if (lun->backend->lun_attr != NULL &&
6961             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6962              != UINT64_MAX) {
6963                 phdr = (struct scsi_log_param_header *)data;
6964                 scsi_ulto2b(0x0002, phdr->param_code);
6965                 phdr->param_control = SLP_LBIN | SLP_LP;
6966                 phdr->param_len = 8;
6967                 data = (uint8_t *)(phdr + 1);
6968                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6969                 data[4] = 0x01; /* per-LUN */
6970                 data += phdr->param_len;
6971         }
6972
6973         if (lun->backend->lun_attr != NULL &&
6974             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6975              != UINT64_MAX) {
6976                 phdr = (struct scsi_log_param_header *)data;
6977                 scsi_ulto2b(0x00f1, phdr->param_code);
6978                 phdr->param_control = SLP_LBIN | SLP_LP;
6979                 phdr->param_len = 8;
6980                 data = (uint8_t *)(phdr + 1);
6981                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6982                 data[4] = 0x02; /* per-pool */
6983                 data += phdr->param_len;
6984         }
6985
6986         if (lun->backend->lun_attr != NULL &&
6987             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6988              != UINT64_MAX) {
6989                 phdr = (struct scsi_log_param_header *)data;
6990                 scsi_ulto2b(0x00f2, phdr->param_code);
6991                 phdr->param_control = SLP_LBIN | SLP_LP;
6992                 phdr->param_len = 8;
6993                 data = (uint8_t *)(phdr + 1);
6994                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6995                 data[4] = 0x02; /* per-pool */
6996                 data += phdr->param_len;
6997         }
6998
6999         page_index->page_len = data - page_index->page_data;
7000         return (0);
7001 }
7002
7003 int
7004 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
7005                                struct ctl_page_index *page_index,
7006                                int pc)
7007 {
7008         struct ctl_lun *lun;
7009         struct stat_page *data;
7010         uint64_t rn, wn, rb, wb;
7011         struct bintime rt, wt;
7012         int i;
7013
7014         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7015         data = (struct stat_page *)page_index->page_data;
7016
7017         scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
7018         data->sap.hdr.param_control = SLP_LBIN;
7019         data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
7020             sizeof(struct scsi_log_param_header);
7021         rn = wn = rb = wb = 0;
7022         bintime_clear(&rt);
7023         bintime_clear(&wt);
7024         for (i = 0; i < CTL_MAX_PORTS; i++) {
7025                 rn += lun->stats.ports[i].operations[CTL_STATS_READ];
7026                 wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
7027                 rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
7028                 wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
7029                 bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
7030                 bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
7031         }
7032         scsi_u64to8b(rn, data->sap.read_num);
7033         scsi_u64to8b(wn, data->sap.write_num);
7034         if (lun->stats.blocksize > 0) {
7035                 scsi_u64to8b(wb / lun->stats.blocksize,
7036                     data->sap.recvieved_lba);
7037                 scsi_u64to8b(rb / lun->stats.blocksize,
7038                     data->sap.transmitted_lba);
7039         }
7040         scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
7041             data->sap.read_int);
7042         scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
7043             data->sap.write_int);
7044         scsi_u64to8b(0, data->sap.weighted_num);
7045         scsi_u64to8b(0, data->sap.weighted_int);
7046         scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
7047         data->it.hdr.param_control = SLP_LBIN;
7048         data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
7049             sizeof(struct scsi_log_param_header);
7050 #ifdef CTL_TIME_IO
7051         scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
7052 #endif
7053         scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
7054         data->it.hdr.param_control = SLP_LBIN;
7055         data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
7056             sizeof(struct scsi_log_param_header);
7057         scsi_ulto4b(3, data->ti.exponent);
7058         scsi_ulto4b(1, data->ti.integer);
7059
7060         page_index->page_len = sizeof(*data);
7061         return (0);
7062 }
7063
7064 int
7065 ctl_log_sense(struct ctl_scsiio *ctsio)
7066 {
7067         struct ctl_lun *lun;
7068         int i, pc, page_code, subpage;
7069         int alloc_len, total_len;
7070         struct ctl_page_index *page_index;
7071         struct scsi_log_sense *cdb;
7072         struct scsi_log_header *header;
7073
7074         CTL_DEBUG_PRINT(("ctl_log_sense\n"));
7075
7076         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7077         cdb = (struct scsi_log_sense *)ctsio->cdb;
7078         pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
7079         page_code = cdb->page & SLS_PAGE_CODE;
7080         subpage = cdb->subpage;
7081         alloc_len = scsi_2btoul(cdb->length);
7082
7083         page_index = NULL;
7084         for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
7085                 page_index = &lun->log_pages.index[i];
7086
7087                 /* Look for the right page code */
7088                 if ((page_index->page_code & SL_PAGE_CODE) != page_code)
7089                         continue;
7090
7091                 /* Look for the right subpage or the subpage wildcard*/
7092                 if (page_index->subpage != subpage)
7093                         continue;
7094
7095                 break;
7096         }
7097         if (i >= CTL_NUM_LOG_PAGES) {
7098                 ctl_set_invalid_field(ctsio,
7099                                       /*sks_valid*/ 1,
7100                                       /*command*/ 1,
7101                                       /*field*/ 2,
7102                                       /*bit_valid*/ 0,
7103                                       /*bit*/ 0);
7104                 ctl_done((union ctl_io *)ctsio);
7105                 return (CTL_RETVAL_COMPLETE);
7106         }
7107
7108         total_len = sizeof(struct scsi_log_header) + page_index->page_len;
7109
7110         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7111         ctsio->kern_sg_entries = 0;
7112         ctsio->kern_data_resid = 0;
7113         ctsio->kern_rel_offset = 0;
7114         if (total_len < alloc_len) {
7115                 ctsio->residual = alloc_len - total_len;
7116                 ctsio->kern_data_len = total_len;
7117                 ctsio->kern_total_len = total_len;
7118         } else {
7119                 ctsio->residual = 0;
7120                 ctsio->kern_data_len = alloc_len;
7121                 ctsio->kern_total_len = alloc_len;
7122         }
7123
7124         header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7125         header->page = page_index->page_code;
7126         if (page_index->subpage) {
7127                 header->page |= SL_SPF;
7128                 header->subpage = page_index->subpage;
7129         }
7130         scsi_ulto2b(page_index->page_len, header->datalen);
7131
7132         /*
7133          * Call the handler, if it exists, to update the
7134          * page to the latest values.
7135          */
7136         if (page_index->sense_handler != NULL)
7137                 page_index->sense_handler(ctsio, page_index, pc);
7138
7139         memcpy(header + 1, page_index->page_data, page_index->page_len);
7140
7141         ctl_set_success(ctsio);
7142         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7143         ctsio->be_move_done = ctl_config_move_done;
7144         ctl_datamove((union ctl_io *)ctsio);
7145         return (CTL_RETVAL_COMPLETE);
7146 }
7147
7148 int
7149 ctl_read_capacity(struct ctl_scsiio *ctsio)
7150 {
7151         struct scsi_read_capacity *cdb;
7152         struct scsi_read_capacity_data *data;
7153         struct ctl_lun *lun;
7154         uint32_t lba;
7155
7156         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7157
7158         cdb = (struct scsi_read_capacity *)ctsio->cdb;
7159
7160         lba = scsi_4btoul(cdb->addr);
7161         if (((cdb->pmi & SRC_PMI) == 0)
7162          && (lba != 0)) {
7163                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7164                                       /*sks_valid*/ 1,
7165                                       /*command*/ 1,
7166                                       /*field*/ 2,
7167                                       /*bit_valid*/ 0,
7168                                       /*bit*/ 0);
7169                 ctl_done((union ctl_io *)ctsio);
7170                 return (CTL_RETVAL_COMPLETE);
7171         }
7172
7173         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7174
7175         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7176         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7177         ctsio->residual = 0;
7178         ctsio->kern_data_len = sizeof(*data);
7179         ctsio->kern_total_len = sizeof(*data);
7180         ctsio->kern_data_resid = 0;
7181         ctsio->kern_rel_offset = 0;
7182         ctsio->kern_sg_entries = 0;
7183
7184         /*
7185          * If the maximum LBA is greater than 0xfffffffe, the user must
7186          * issue a SERVICE ACTION IN (16) command, with the read capacity
7187          * serivce action set.
7188          */
7189         if (lun->be_lun->maxlba > 0xfffffffe)
7190                 scsi_ulto4b(0xffffffff, data->addr);
7191         else
7192                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7193
7194         /*
7195          * XXX KDM this may not be 512 bytes...
7196          */
7197         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7198
7199         ctl_set_success(ctsio);
7200         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7201         ctsio->be_move_done = ctl_config_move_done;
7202         ctl_datamove((union ctl_io *)ctsio);
7203         return (CTL_RETVAL_COMPLETE);
7204 }
7205
7206 int
7207 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7208 {
7209         struct scsi_read_capacity_16 *cdb;
7210         struct scsi_read_capacity_data_long *data;
7211         struct ctl_lun *lun;
7212         uint64_t lba;
7213         uint32_t alloc_len;
7214
7215         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7216
7217         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7218
7219         alloc_len = scsi_4btoul(cdb->alloc_len);
7220         lba = scsi_8btou64(cdb->addr);
7221
7222         if ((cdb->reladr & SRC16_PMI)
7223          && (lba != 0)) {
7224                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7225                                       /*sks_valid*/ 1,
7226                                       /*command*/ 1,
7227                                       /*field*/ 2,
7228                                       /*bit_valid*/ 0,
7229                                       /*bit*/ 0);
7230                 ctl_done((union ctl_io *)ctsio);
7231                 return (CTL_RETVAL_COMPLETE);
7232         }
7233
7234         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7235
7236         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7237         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7238
7239         if (sizeof(*data) < alloc_len) {
7240                 ctsio->residual = alloc_len - sizeof(*data);
7241                 ctsio->kern_data_len = sizeof(*data);
7242                 ctsio->kern_total_len = sizeof(*data);
7243         } else {
7244                 ctsio->residual = 0;
7245                 ctsio->kern_data_len = alloc_len;
7246                 ctsio->kern_total_len = alloc_len;
7247         }
7248         ctsio->kern_data_resid = 0;
7249         ctsio->kern_rel_offset = 0;
7250         ctsio->kern_sg_entries = 0;
7251
7252         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7253         /* XXX KDM this may not be 512 bytes... */
7254         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7255         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7256         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7257         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7258                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7259
7260         ctl_set_success(ctsio);
7261         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7262         ctsio->be_move_done = ctl_config_move_done;
7263         ctl_datamove((union ctl_io *)ctsio);
7264         return (CTL_RETVAL_COMPLETE);
7265 }
7266
7267 int
7268 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7269 {
7270         struct scsi_get_lba_status *cdb;
7271         struct scsi_get_lba_status_data *data;
7272         struct ctl_lun *lun;
7273         struct ctl_lba_len_flags *lbalen;
7274         uint64_t lba;
7275         uint32_t alloc_len, total_len;
7276         int retval;
7277
7278         CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7279
7280         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7281         cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7282         lba = scsi_8btou64(cdb->addr);
7283         alloc_len = scsi_4btoul(cdb->alloc_len);
7284
7285         if (lba > lun->be_lun->maxlba) {
7286                 ctl_set_lba_out_of_range(ctsio);
7287                 ctl_done((union ctl_io *)ctsio);
7288                 return (CTL_RETVAL_COMPLETE);
7289         }
7290
7291         total_len = sizeof(*data) + sizeof(data->descr[0]);
7292         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7293         data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7294
7295         if (total_len < alloc_len) {
7296                 ctsio->residual = alloc_len - total_len;
7297                 ctsio->kern_data_len = total_len;
7298                 ctsio->kern_total_len = total_len;
7299         } else {
7300                 ctsio->residual = 0;
7301                 ctsio->kern_data_len = alloc_len;
7302                 ctsio->kern_total_len = alloc_len;
7303         }
7304         ctsio->kern_data_resid = 0;
7305         ctsio->kern_rel_offset = 0;
7306         ctsio->kern_sg_entries = 0;
7307
7308         /* Fill dummy data in case backend can't tell anything. */
7309         scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7310         scsi_u64to8b(lba, data->descr[0].addr);
7311         scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7312             data->descr[0].length);
7313         data->descr[0].status = 0; /* Mapped or unknown. */
7314
7315         ctl_set_success(ctsio);
7316         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7317         ctsio->be_move_done = ctl_config_move_done;
7318
7319         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7320         lbalen->lba = lba;
7321         lbalen->len = total_len;
7322         lbalen->flags = 0;
7323         retval = lun->backend->config_read((union ctl_io *)ctsio);
7324         return (CTL_RETVAL_COMPLETE);
7325 }
7326
7327 int
7328 ctl_read_defect(struct ctl_scsiio *ctsio)
7329 {
7330         struct scsi_read_defect_data_10 *ccb10;
7331         struct scsi_read_defect_data_12 *ccb12;
7332         struct scsi_read_defect_data_hdr_10 *data10;
7333         struct scsi_read_defect_data_hdr_12 *data12;
7334         uint32_t alloc_len, data_len;
7335         uint8_t format;
7336
7337         CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7338
7339         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7340                 ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7341                 format = ccb10->format;
7342                 alloc_len = scsi_2btoul(ccb10->alloc_length);
7343                 data_len = sizeof(*data10);
7344         } else {
7345                 ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7346                 format = ccb12->format;
7347                 alloc_len = scsi_4btoul(ccb12->alloc_length);
7348                 data_len = sizeof(*data12);
7349         }
7350         if (alloc_len == 0) {
7351                 ctl_set_success(ctsio);
7352                 ctl_done((union ctl_io *)ctsio);
7353                 return (CTL_RETVAL_COMPLETE);
7354         }
7355
7356         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7357         if (data_len < alloc_len) {
7358                 ctsio->residual = alloc_len - data_len;
7359                 ctsio->kern_data_len = data_len;
7360                 ctsio->kern_total_len = data_len;
7361         } else {
7362                 ctsio->residual = 0;
7363                 ctsio->kern_data_len = alloc_len;
7364                 ctsio->kern_total_len = alloc_len;
7365         }
7366         ctsio->kern_data_resid = 0;
7367         ctsio->kern_rel_offset = 0;
7368         ctsio->kern_sg_entries = 0;
7369
7370         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7371                 data10 = (struct scsi_read_defect_data_hdr_10 *)
7372                     ctsio->kern_data_ptr;
7373                 data10->format = format;
7374                 scsi_ulto2b(0, data10->length);
7375         } else {
7376                 data12 = (struct scsi_read_defect_data_hdr_12 *)
7377                     ctsio->kern_data_ptr;
7378                 data12->format = format;
7379                 scsi_ulto2b(0, data12->generation);
7380                 scsi_ulto4b(0, data12->length);
7381         }
7382
7383         ctl_set_success(ctsio);
7384         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7385         ctsio->be_move_done = ctl_config_move_done;
7386         ctl_datamove((union ctl_io *)ctsio);
7387         return (CTL_RETVAL_COMPLETE);
7388 }
7389
7390 int
7391 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7392 {
7393         struct scsi_maintenance_in *cdb;
7394         int retval;
7395         int alloc_len, ext, total_len = 0, g, p, pc, pg, gs, os;
7396         int num_target_port_groups, num_target_ports;
7397         struct ctl_lun *lun;
7398         struct ctl_softc *softc;
7399         struct ctl_port *port;
7400         struct scsi_target_group_data *rtg_ptr;
7401         struct scsi_target_group_data_extended *rtg_ext_ptr;
7402         struct scsi_target_port_group_descriptor *tpg_desc;
7403
7404         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7405
7406         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7407         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7408         softc = lun->ctl_softc;
7409
7410         retval = CTL_RETVAL_COMPLETE;
7411
7412         switch (cdb->byte2 & STG_PDF_MASK) {
7413         case STG_PDF_LENGTH:
7414                 ext = 0;
7415                 break;
7416         case STG_PDF_EXTENDED:
7417                 ext = 1;
7418                 break;
7419         default:
7420                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7421                                       /*sks_valid*/ 1,
7422                                       /*command*/ 1,
7423                                       /*field*/ 2,
7424                                       /*bit_valid*/ 1,
7425                                       /*bit*/ 5);
7426                 ctl_done((union ctl_io *)ctsio);
7427                 return(retval);
7428         }
7429
7430         if (softc->is_single)
7431                 num_target_port_groups = 1;
7432         else
7433                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7434         num_target_ports = 0;
7435         mtx_lock(&softc->ctl_lock);
7436         STAILQ_FOREACH(port, &softc->port_list, links) {
7437                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7438                         continue;
7439                 if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7440                         continue;
7441                 num_target_ports++;
7442         }
7443         mtx_unlock(&softc->ctl_lock);
7444
7445         if (ext)
7446                 total_len = sizeof(struct scsi_target_group_data_extended);
7447         else
7448                 total_len = sizeof(struct scsi_target_group_data);
7449         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7450                 num_target_port_groups +
7451             sizeof(struct scsi_target_port_descriptor) *
7452                 num_target_ports * num_target_port_groups;
7453
7454         alloc_len = scsi_4btoul(cdb->length);
7455
7456         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7457
7458         ctsio->kern_sg_entries = 0;
7459
7460         if (total_len < alloc_len) {
7461                 ctsio->residual = alloc_len - total_len;
7462                 ctsio->kern_data_len = total_len;
7463                 ctsio->kern_total_len = total_len;
7464         } else {
7465                 ctsio->residual = 0;
7466                 ctsio->kern_data_len = alloc_len;
7467                 ctsio->kern_total_len = alloc_len;
7468         }
7469         ctsio->kern_data_resid = 0;
7470         ctsio->kern_rel_offset = 0;
7471
7472         if (ext) {
7473                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7474                     ctsio->kern_data_ptr;
7475                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7476                 rtg_ext_ptr->format_type = 0x10;
7477                 rtg_ext_ptr->implicit_transition_time = 0;
7478                 tpg_desc = &rtg_ext_ptr->groups[0];
7479         } else {
7480                 rtg_ptr = (struct scsi_target_group_data *)
7481                     ctsio->kern_data_ptr;
7482                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7483                 tpg_desc = &rtg_ptr->groups[0];
7484         }
7485
7486         mtx_lock(&softc->ctl_lock);
7487         pg = softc->port_offset / CTL_MAX_PORTS;
7488         if (softc->flags & CTL_FLAG_ACTIVE_SHELF) {
7489                 if (softc->ha_mode == CTL_HA_MODE_ACT_STBY) {
7490                         gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7491                         os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7492                 } else if (lun->flags & CTL_LUN_PRIMARY_SC) {
7493                         gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7494                         os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7495                 } else {
7496                         gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7497                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7498                 }
7499         } else {
7500                 gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7501                 os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7502         }
7503         for (g = 0; g < num_target_port_groups; g++) {
7504                 tpg_desc->pref_state = (g == pg) ? gs : os;
7505                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP;
7506                 scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7507                 tpg_desc->status = TPG_IMPLICIT;
7508                 pc = 0;
7509                 STAILQ_FOREACH(port, &softc->port_list, links) {
7510                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7511                                 continue;
7512                         if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7513                                 continue;
7514                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7515                         scsi_ulto2b(p, tpg_desc->descriptors[pc].
7516                             relative_target_port_identifier);
7517                         pc++;
7518                 }
7519                 tpg_desc->target_port_count = pc;
7520                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7521                     &tpg_desc->descriptors[pc];
7522         }
7523         mtx_unlock(&softc->ctl_lock);
7524
7525         ctl_set_success(ctsio);
7526         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7527         ctsio->be_move_done = ctl_config_move_done;
7528         ctl_datamove((union ctl_io *)ctsio);
7529         return(retval);
7530 }
7531
7532 int
7533 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7534 {
7535         struct ctl_lun *lun;
7536         struct scsi_report_supported_opcodes *cdb;
7537         const struct ctl_cmd_entry *entry, *sentry;
7538         struct scsi_report_supported_opcodes_all *all;
7539         struct scsi_report_supported_opcodes_descr *descr;
7540         struct scsi_report_supported_opcodes_one *one;
7541         int retval;
7542         int alloc_len, total_len;
7543         int opcode, service_action, i, j, num;
7544
7545         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7546
7547         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7548         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7549
7550         retval = CTL_RETVAL_COMPLETE;
7551
7552         opcode = cdb->requested_opcode;
7553         service_action = scsi_2btoul(cdb->requested_service_action);
7554         switch (cdb->options & RSO_OPTIONS_MASK) {
7555         case RSO_OPTIONS_ALL:
7556                 num = 0;
7557                 for (i = 0; i < 256; i++) {
7558                         entry = &ctl_cmd_table[i];
7559                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7560                                 for (j = 0; j < 32; j++) {
7561                                         sentry = &((const struct ctl_cmd_entry *)
7562                                             entry->execute)[j];
7563                                         if (ctl_cmd_applicable(
7564                                             lun->be_lun->lun_type, sentry))
7565                                                 num++;
7566                                 }
7567                         } else {
7568                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7569                                     entry))
7570                                         num++;
7571                         }
7572                 }
7573                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7574                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7575                 break;
7576         case RSO_OPTIONS_OC:
7577                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7578                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7579                                               /*sks_valid*/ 1,
7580                                               /*command*/ 1,
7581                                               /*field*/ 2,
7582                                               /*bit_valid*/ 1,
7583                                               /*bit*/ 2);
7584                         ctl_done((union ctl_io *)ctsio);
7585                         return (CTL_RETVAL_COMPLETE);
7586                 }
7587                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7588                 break;
7589         case RSO_OPTIONS_OC_SA:
7590                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7591                     service_action >= 32) {
7592                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7593                                               /*sks_valid*/ 1,
7594                                               /*command*/ 1,
7595                                               /*field*/ 2,
7596                                               /*bit_valid*/ 1,
7597                                               /*bit*/ 2);
7598                         ctl_done((union ctl_io *)ctsio);
7599                         return (CTL_RETVAL_COMPLETE);
7600                 }
7601                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7602                 break;
7603         default:
7604                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7605                                       /*sks_valid*/ 1,
7606                                       /*command*/ 1,
7607                                       /*field*/ 2,
7608                                       /*bit_valid*/ 1,
7609                                       /*bit*/ 2);
7610                 ctl_done((union ctl_io *)ctsio);
7611                 return (CTL_RETVAL_COMPLETE);
7612         }
7613
7614         alloc_len = scsi_4btoul(cdb->length);
7615
7616         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7617
7618         ctsio->kern_sg_entries = 0;
7619
7620         if (total_len < alloc_len) {
7621                 ctsio->residual = alloc_len - total_len;
7622                 ctsio->kern_data_len = total_len;
7623                 ctsio->kern_total_len = total_len;
7624         } else {
7625                 ctsio->residual = 0;
7626                 ctsio->kern_data_len = alloc_len;
7627                 ctsio->kern_total_len = alloc_len;
7628         }
7629         ctsio->kern_data_resid = 0;
7630         ctsio->kern_rel_offset = 0;
7631
7632         switch (cdb->options & RSO_OPTIONS_MASK) {
7633         case RSO_OPTIONS_ALL:
7634                 all = (struct scsi_report_supported_opcodes_all *)
7635                     ctsio->kern_data_ptr;
7636                 num = 0;
7637                 for (i = 0; i < 256; i++) {
7638                         entry = &ctl_cmd_table[i];
7639                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7640                                 for (j = 0; j < 32; j++) {
7641                                         sentry = &((const struct ctl_cmd_entry *)
7642                                             entry->execute)[j];
7643                                         if (!ctl_cmd_applicable(
7644                                             lun->be_lun->lun_type, sentry))
7645                                                 continue;
7646                                         descr = &all->descr[num++];
7647                                         descr->opcode = i;
7648                                         scsi_ulto2b(j, descr->service_action);
7649                                         descr->flags = RSO_SERVACTV;
7650                                         scsi_ulto2b(sentry->length,
7651                                             descr->cdb_length);
7652                                 }
7653                         } else {
7654                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7655                                     entry))
7656                                         continue;
7657                                 descr = &all->descr[num++];
7658                                 descr->opcode = i;
7659                                 scsi_ulto2b(0, descr->service_action);
7660                                 descr->flags = 0;
7661                                 scsi_ulto2b(entry->length, descr->cdb_length);
7662                         }
7663                 }
7664                 scsi_ulto4b(
7665                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7666                     all->length);
7667                 break;
7668         case RSO_OPTIONS_OC:
7669                 one = (struct scsi_report_supported_opcodes_one *)
7670                     ctsio->kern_data_ptr;
7671                 entry = &ctl_cmd_table[opcode];
7672                 goto fill_one;
7673         case RSO_OPTIONS_OC_SA:
7674                 one = (struct scsi_report_supported_opcodes_one *)
7675                     ctsio->kern_data_ptr;
7676                 entry = &ctl_cmd_table[opcode];
7677                 entry = &((const struct ctl_cmd_entry *)
7678                     entry->execute)[service_action];
7679 fill_one:
7680                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7681                         one->support = 3;
7682                         scsi_ulto2b(entry->length, one->cdb_length);
7683                         one->cdb_usage[0] = opcode;
7684                         memcpy(&one->cdb_usage[1], entry->usage,
7685                             entry->length - 1);
7686                 } else
7687                         one->support = 1;
7688                 break;
7689         }
7690
7691         ctl_set_success(ctsio);
7692         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7693         ctsio->be_move_done = ctl_config_move_done;
7694         ctl_datamove((union ctl_io *)ctsio);
7695         return(retval);
7696 }
7697
7698 int
7699 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7700 {
7701         struct scsi_report_supported_tmf *cdb;
7702         struct scsi_report_supported_tmf_data *data;
7703         int retval;
7704         int alloc_len, total_len;
7705
7706         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7707
7708         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7709
7710         retval = CTL_RETVAL_COMPLETE;
7711
7712         total_len = sizeof(struct scsi_report_supported_tmf_data);
7713         alloc_len = scsi_4btoul(cdb->length);
7714
7715         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7716
7717         ctsio->kern_sg_entries = 0;
7718
7719         if (total_len < alloc_len) {
7720                 ctsio->residual = alloc_len - total_len;
7721                 ctsio->kern_data_len = total_len;
7722                 ctsio->kern_total_len = total_len;
7723         } else {
7724                 ctsio->residual = 0;
7725                 ctsio->kern_data_len = alloc_len;
7726                 ctsio->kern_total_len = alloc_len;
7727         }
7728         ctsio->kern_data_resid = 0;
7729         ctsio->kern_rel_offset = 0;
7730
7731         data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7732         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7733         data->byte2 |= RST_ITNRS;
7734
7735         ctl_set_success(ctsio);
7736         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7737         ctsio->be_move_done = ctl_config_move_done;
7738         ctl_datamove((union ctl_io *)ctsio);
7739         return (retval);
7740 }
7741
7742 int
7743 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7744 {
7745         struct scsi_report_timestamp *cdb;
7746         struct scsi_report_timestamp_data *data;
7747         struct timeval tv;
7748         int64_t timestamp;
7749         int retval;
7750         int alloc_len, total_len;
7751
7752         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7753
7754         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7755
7756         retval = CTL_RETVAL_COMPLETE;
7757
7758         total_len = sizeof(struct scsi_report_timestamp_data);
7759         alloc_len = scsi_4btoul(cdb->length);
7760
7761         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7762
7763         ctsio->kern_sg_entries = 0;
7764
7765         if (total_len < alloc_len) {
7766                 ctsio->residual = alloc_len - total_len;
7767                 ctsio->kern_data_len = total_len;
7768                 ctsio->kern_total_len = total_len;
7769         } else {
7770                 ctsio->residual = 0;
7771                 ctsio->kern_data_len = alloc_len;
7772                 ctsio->kern_total_len = alloc_len;
7773         }
7774         ctsio->kern_data_resid = 0;
7775         ctsio->kern_rel_offset = 0;
7776
7777         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7778         scsi_ulto2b(sizeof(*data) - 2, data->length);
7779         data->origin = RTS_ORIG_OUTSIDE;
7780         getmicrotime(&tv);
7781         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7782         scsi_ulto4b(timestamp >> 16, data->timestamp);
7783         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7784
7785         ctl_set_success(ctsio);
7786         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7787         ctsio->be_move_done = ctl_config_move_done;
7788         ctl_datamove((union ctl_io *)ctsio);
7789         return (retval);
7790 }
7791
7792 int
7793 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7794 {
7795         struct scsi_per_res_in *cdb;
7796         int alloc_len, total_len = 0;
7797         /* struct scsi_per_res_in_rsrv in_data; */
7798         struct ctl_lun *lun;
7799         struct ctl_softc *softc;
7800         uint64_t key;
7801
7802         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7803
7804         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7805
7806         alloc_len = scsi_2btoul(cdb->length);
7807
7808         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7809         softc = lun->ctl_softc;
7810
7811 retry:
7812         mtx_lock(&lun->lun_lock);
7813         switch (cdb->action) {
7814         case SPRI_RK: /* read keys */
7815                 total_len = sizeof(struct scsi_per_res_in_keys) +
7816                         lun->pr_key_count *
7817                         sizeof(struct scsi_per_res_key);
7818                 break;
7819         case SPRI_RR: /* read reservation */
7820                 if (lun->flags & CTL_LUN_PR_RESERVED)
7821                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7822                 else
7823                         total_len = sizeof(struct scsi_per_res_in_header);
7824                 break;
7825         case SPRI_RC: /* report capabilities */
7826                 total_len = sizeof(struct scsi_per_res_cap);
7827                 break;
7828         case SPRI_RS: /* read full status */
7829                 total_len = sizeof(struct scsi_per_res_in_header) +
7830                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7831                     lun->pr_key_count;
7832                 break;
7833         default:
7834                 panic("Invalid PR type %x", cdb->action);
7835         }
7836         mtx_unlock(&lun->lun_lock);
7837
7838         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7839
7840         if (total_len < alloc_len) {
7841                 ctsio->residual = alloc_len - total_len;
7842                 ctsio->kern_data_len = total_len;
7843                 ctsio->kern_total_len = total_len;
7844         } else {
7845                 ctsio->residual = 0;
7846                 ctsio->kern_data_len = alloc_len;
7847                 ctsio->kern_total_len = alloc_len;
7848         }
7849
7850         ctsio->kern_data_resid = 0;
7851         ctsio->kern_rel_offset = 0;
7852         ctsio->kern_sg_entries = 0;
7853
7854         mtx_lock(&lun->lun_lock);
7855         switch (cdb->action) {
7856         case SPRI_RK: { // read keys
7857         struct scsi_per_res_in_keys *res_keys;
7858                 int i, key_count;
7859
7860                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7861
7862                 /*
7863                  * We had to drop the lock to allocate our buffer, which
7864                  * leaves time for someone to come in with another
7865                  * persistent reservation.  (That is unlikely, though,
7866                  * since this should be the only persistent reservation
7867                  * command active right now.)
7868                  */
7869                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7870                     (lun->pr_key_count *
7871                      sizeof(struct scsi_per_res_key)))){
7872                         mtx_unlock(&lun->lun_lock);
7873                         free(ctsio->kern_data_ptr, M_CTL);
7874                         printf("%s: reservation length changed, retrying\n",
7875                                __func__);
7876                         goto retry;
7877                 }
7878
7879                 scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7880
7881                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7882                              lun->pr_key_count, res_keys->header.length);
7883
7884                 for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7885                         if ((key = ctl_get_prkey(lun, i)) == 0)
7886                                 continue;
7887
7888                         /*
7889                          * We used lun->pr_key_count to calculate the
7890                          * size to allocate.  If it turns out the number of
7891                          * initiators with the registered flag set is
7892                          * larger than that (i.e. they haven't been kept in
7893                          * sync), we've got a problem.
7894                          */
7895                         if (key_count >= lun->pr_key_count) {
7896 #ifdef NEEDTOPORT
7897                                 csevent_log(CSC_CTL | CSC_SHELF_SW |
7898                                             CTL_PR_ERROR,
7899                                             csevent_LogType_Fault,
7900                                             csevent_AlertLevel_Yellow,
7901                                             csevent_FRU_ShelfController,
7902                                             csevent_FRU_Firmware,
7903                                         csevent_FRU_Unknown,
7904                                             "registered keys %d >= key "
7905                                             "count %d", key_count,
7906                                             lun->pr_key_count);
7907 #endif
7908                                 key_count++;
7909                                 continue;
7910                         }
7911                         scsi_u64to8b(key, res_keys->keys[key_count].key);
7912                         key_count++;
7913                 }
7914                 break;
7915         }
7916         case SPRI_RR: { // read reservation
7917                 struct scsi_per_res_in_rsrv *res;
7918                 int tmp_len, header_only;
7919
7920                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7921
7922                 scsi_ulto4b(lun->PRGeneration, res->header.generation);
7923
7924                 if (lun->flags & CTL_LUN_PR_RESERVED)
7925                 {
7926                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7927                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7928                                     res->header.length);
7929                         header_only = 0;
7930                 } else {
7931                         tmp_len = sizeof(struct scsi_per_res_in_header);
7932                         scsi_ulto4b(0, res->header.length);
7933                         header_only = 1;
7934                 }
7935
7936                 /*
7937                  * We had to drop the lock to allocate our buffer, which
7938                  * leaves time for someone to come in with another
7939                  * persistent reservation.  (That is unlikely, though,
7940                  * since this should be the only persistent reservation
7941                  * command active right now.)
7942                  */
7943                 if (tmp_len != total_len) {
7944                         mtx_unlock(&lun->lun_lock);
7945                         free(ctsio->kern_data_ptr, M_CTL);
7946                         printf("%s: reservation status changed, retrying\n",
7947                                __func__);
7948                         goto retry;
7949                 }
7950
7951                 /*
7952                  * No reservation held, so we're done.
7953                  */
7954                 if (header_only != 0)
7955                         break;
7956
7957                 /*
7958                  * If the registration is an All Registrants type, the key
7959                  * is 0, since it doesn't really matter.
7960                  */
7961                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7962                         scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7963                             res->data.reservation);
7964                 }
7965                 res->data.scopetype = lun->res_type;
7966                 break;
7967         }
7968         case SPRI_RC:     //report capabilities
7969         {
7970                 struct scsi_per_res_cap *res_cap;
7971                 uint16_t type_mask;
7972
7973                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7974                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7975                 res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7976                 type_mask = SPRI_TM_WR_EX_AR |
7977                             SPRI_TM_EX_AC_RO |
7978                             SPRI_TM_WR_EX_RO |
7979                             SPRI_TM_EX_AC |
7980                             SPRI_TM_WR_EX |
7981                             SPRI_TM_EX_AC_AR;
7982                 scsi_ulto2b(type_mask, res_cap->type_mask);
7983                 break;
7984         }
7985         case SPRI_RS: { // read full status
7986                 struct scsi_per_res_in_full *res_status;
7987                 struct scsi_per_res_in_full_desc *res_desc;
7988                 struct ctl_port *port;
7989                 int i, len;
7990
7991                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7992
7993                 /*
7994                  * We had to drop the lock to allocate our buffer, which
7995                  * leaves time for someone to come in with another
7996                  * persistent reservation.  (That is unlikely, though,
7997                  * since this should be the only persistent reservation
7998                  * command active right now.)
7999                  */
8000                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
8001                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
8002                      lun->pr_key_count)){
8003                         mtx_unlock(&lun->lun_lock);
8004                         free(ctsio->kern_data_ptr, M_CTL);
8005                         printf("%s: reservation length changed, retrying\n",
8006                                __func__);
8007                         goto retry;
8008                 }
8009
8010                 scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
8011
8012                 res_desc = &res_status->desc[0];
8013                 for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
8014                         if ((key = ctl_get_prkey(lun, i)) == 0)
8015                                 continue;
8016
8017                         scsi_u64to8b(key, res_desc->res_key.key);
8018                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
8019                             (lun->pr_res_idx == i ||
8020                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
8021                                 res_desc->flags = SPRI_FULL_R_HOLDER;
8022                                 res_desc->scopetype = lun->res_type;
8023                         }
8024                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
8025                             res_desc->rel_trgt_port_id);
8026                         len = 0;
8027                         port = softc->ctl_ports[
8028                             ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
8029                         if (port != NULL)
8030                                 len = ctl_create_iid(port,
8031                                     i % CTL_MAX_INIT_PER_PORT,
8032                                     res_desc->transport_id);
8033                         scsi_ulto4b(len, res_desc->additional_length);
8034                         res_desc = (struct scsi_per_res_in_full_desc *)
8035                             &res_desc->transport_id[len];
8036                 }
8037                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
8038                     res_status->header.length);
8039                 break;
8040         }
8041         default:
8042                 /*
8043                  * This is a bug, because we just checked for this above,
8044                  * and should have returned an error.
8045                  */
8046                 panic("Invalid PR type %x", cdb->action);
8047                 break; /* NOTREACHED */
8048         }
8049         mtx_unlock(&lun->lun_lock);
8050
8051         ctl_set_success(ctsio);
8052         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8053         ctsio->be_move_done = ctl_config_move_done;
8054         ctl_datamove((union ctl_io *)ctsio);
8055         return (CTL_RETVAL_COMPLETE);
8056 }
8057
8058 static void
8059 ctl_est_res_ua(struct ctl_lun *lun, uint32_t residx, ctl_ua_type ua)
8060 {
8061         int off = lun->ctl_softc->persis_offset;
8062
8063         if (residx >= off && residx < off + CTL_MAX_INITIATORS)
8064                 ctl_est_ua(lun, residx - off, ua);
8065 }
8066
8067 /*
8068  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
8069  * it should return.
8070  */
8071 static int
8072 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
8073                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
8074                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
8075                 struct scsi_per_res_out_parms* param)
8076 {
8077         union ctl_ha_msg persis_io;
8078         int retval, i;
8079         int isc_retval;
8080
8081         retval = 0;
8082
8083         mtx_lock(&lun->lun_lock);
8084         if (sa_res_key == 0) {
8085                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8086                         /* validate scope and type */
8087                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8088                              SPR_LU_SCOPE) {
8089                                 mtx_unlock(&lun->lun_lock);
8090                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8091                                                       /*sks_valid*/ 1,
8092                                                       /*command*/ 1,
8093                                                       /*field*/ 2,
8094                                                       /*bit_valid*/ 1,
8095                                                       /*bit*/ 4);
8096                                 ctl_done((union ctl_io *)ctsio);
8097                                 return (1);
8098                         }
8099
8100                         if (type>8 || type==2 || type==4 || type==0) {
8101                                 mtx_unlock(&lun->lun_lock);
8102                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8103                                                       /*sks_valid*/ 1,
8104                                                       /*command*/ 1,
8105                                                       /*field*/ 2,
8106                                                       /*bit_valid*/ 1,
8107                                                       /*bit*/ 0);
8108                                 ctl_done((union ctl_io *)ctsio);
8109                                 return (1);
8110                         }
8111
8112                         /*
8113                          * Unregister everybody else and build UA for
8114                          * them
8115                          */
8116                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8117                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8118                                         continue;
8119
8120                                 ctl_clr_prkey(lun, i);
8121                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8122                         }
8123                         lun->pr_key_count = 1;
8124                         lun->res_type = type;
8125                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8126                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8127                                 lun->pr_res_idx = residx;
8128
8129                         /* send msg to other side */
8130                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8131                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8132                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8133                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8134                         persis_io.pr.pr_info.res_type = type;
8135                         memcpy(persis_io.pr.pr_info.sa_res_key,
8136                                param->serv_act_res_key,
8137                                sizeof(param->serv_act_res_key));
8138                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8139                              &persis_io, sizeof(persis_io), 0)) >
8140                              CTL_HA_STATUS_SUCCESS) {
8141                                 printf("CTL:Persis Out error returned "
8142                                        "from ctl_ha_msg_send %d\n",
8143                                        isc_retval);
8144                         }
8145                 } else {
8146                         /* not all registrants */
8147                         mtx_unlock(&lun->lun_lock);
8148                         free(ctsio->kern_data_ptr, M_CTL);
8149                         ctl_set_invalid_field(ctsio,
8150                                               /*sks_valid*/ 1,
8151                                               /*command*/ 0,
8152                                               /*field*/ 8,
8153                                               /*bit_valid*/ 0,
8154                                               /*bit*/ 0);
8155                         ctl_done((union ctl_io *)ctsio);
8156                         return (1);
8157                 }
8158         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8159                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
8160                 int found = 0;
8161
8162                 if (res_key == sa_res_key) {
8163                         /* special case */
8164                         /*
8165                          * The spec implies this is not good but doesn't
8166                          * say what to do. There are two choices either
8167                          * generate a res conflict or check condition
8168                          * with illegal field in parameter data. Since
8169                          * that is what is done when the sa_res_key is
8170                          * zero I'll take that approach since this has
8171                          * to do with the sa_res_key.
8172                          */
8173                         mtx_unlock(&lun->lun_lock);
8174                         free(ctsio->kern_data_ptr, M_CTL);
8175                         ctl_set_invalid_field(ctsio,
8176                                               /*sks_valid*/ 1,
8177                                               /*command*/ 0,
8178                                               /*field*/ 8,
8179                                               /*bit_valid*/ 0,
8180                                               /*bit*/ 0);
8181                         ctl_done((union ctl_io *)ctsio);
8182                         return (1);
8183                 }
8184
8185                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8186                         if (ctl_get_prkey(lun, i) != sa_res_key)
8187                                 continue;
8188
8189                         found = 1;
8190                         ctl_clr_prkey(lun, i);
8191                         lun->pr_key_count--;
8192                         ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8193                 }
8194                 if (!found) {
8195                         mtx_unlock(&lun->lun_lock);
8196                         free(ctsio->kern_data_ptr, M_CTL);
8197                         ctl_set_reservation_conflict(ctsio);
8198                         ctl_done((union ctl_io *)ctsio);
8199                         return (CTL_RETVAL_COMPLETE);
8200                 }
8201                 /* send msg to other side */
8202                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8203                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8204                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8205                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
8206                 persis_io.pr.pr_info.res_type = type;
8207                 memcpy(persis_io.pr.pr_info.sa_res_key,
8208                        param->serv_act_res_key,
8209                        sizeof(param->serv_act_res_key));
8210                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8211                      &persis_io, sizeof(persis_io), 0)) >
8212                      CTL_HA_STATUS_SUCCESS) {
8213                         printf("CTL:Persis Out error returned from "
8214                                "ctl_ha_msg_send %d\n", isc_retval);
8215                 }
8216         } else {
8217                 /* Reserved but not all registrants */
8218                 /* sa_res_key is res holder */
8219                 if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8220                         /* validate scope and type */
8221                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8222                              SPR_LU_SCOPE) {
8223                                 mtx_unlock(&lun->lun_lock);
8224                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8225                                                       /*sks_valid*/ 1,
8226                                                       /*command*/ 1,
8227                                                       /*field*/ 2,
8228                                                       /*bit_valid*/ 1,
8229                                                       /*bit*/ 4);
8230                                 ctl_done((union ctl_io *)ctsio);
8231                                 return (1);
8232                         }
8233
8234                         if (type>8 || type==2 || type==4 || type==0) {
8235                                 mtx_unlock(&lun->lun_lock);
8236                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8237                                                       /*sks_valid*/ 1,
8238                                                       /*command*/ 1,
8239                                                       /*field*/ 2,
8240                                                       /*bit_valid*/ 1,
8241                                                       /*bit*/ 0);
8242                                 ctl_done((union ctl_io *)ctsio);
8243                                 return (1);
8244                         }
8245
8246                         /*
8247                          * Do the following:
8248                          * if sa_res_key != res_key remove all
8249                          * registrants w/sa_res_key and generate UA
8250                          * for these registrants(Registrations
8251                          * Preempted) if it wasn't an exclusive
8252                          * reservation generate UA(Reservations
8253                          * Preempted) for all other registered nexuses
8254                          * if the type has changed. Establish the new
8255                          * reservation and holder. If res_key and
8256                          * sa_res_key are the same do the above
8257                          * except don't unregister the res holder.
8258                          */
8259
8260                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8261                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8262                                         continue;
8263
8264                                 if (sa_res_key == ctl_get_prkey(lun, i)) {
8265                                         ctl_clr_prkey(lun, i);
8266                                         lun->pr_key_count--;
8267                                         ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8268                                 } else if (type != lun->res_type
8269                                         && (lun->res_type == SPR_TYPE_WR_EX_RO
8270                                          || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8271                                         ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
8272                                 }
8273                         }
8274                         lun->res_type = type;
8275                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8276                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8277                                 lun->pr_res_idx = residx;
8278                         else
8279                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8280
8281                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8282                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8283                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8284                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8285                         persis_io.pr.pr_info.res_type = type;
8286                         memcpy(persis_io.pr.pr_info.sa_res_key,
8287                                param->serv_act_res_key,
8288                                sizeof(param->serv_act_res_key));
8289                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8290                              &persis_io, sizeof(persis_io), 0)) >
8291                              CTL_HA_STATUS_SUCCESS) {
8292                                 printf("CTL:Persis Out error returned "
8293                                        "from ctl_ha_msg_send %d\n",
8294                                        isc_retval);
8295                         }
8296                 } else {
8297                         /*
8298                          * sa_res_key is not the res holder just
8299                          * remove registrants
8300                          */
8301                         int found=0;
8302
8303                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8304                                 if (sa_res_key != ctl_get_prkey(lun, i))
8305                                         continue;
8306
8307                                 found = 1;
8308                                 ctl_clr_prkey(lun, i);
8309                                 lun->pr_key_count--;
8310                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8311                         }
8312
8313                         if (!found) {
8314                                 mtx_unlock(&lun->lun_lock);
8315                                 free(ctsio->kern_data_ptr, M_CTL);
8316                                 ctl_set_reservation_conflict(ctsio);
8317                                 ctl_done((union ctl_io *)ctsio);
8318                                 return (1);
8319                         }
8320                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8321                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8322                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8323                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8324                         persis_io.pr.pr_info.res_type = type;
8325                         memcpy(persis_io.pr.pr_info.sa_res_key,
8326                                param->serv_act_res_key,
8327                                sizeof(param->serv_act_res_key));
8328                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8329                              &persis_io, sizeof(persis_io), 0)) >
8330                              CTL_HA_STATUS_SUCCESS) {
8331                                 printf("CTL:Persis Out error returned "
8332                                        "from ctl_ha_msg_send %d\n",
8333                                 isc_retval);
8334                         }
8335                 }
8336         }
8337
8338         lun->PRGeneration++;
8339         mtx_unlock(&lun->lun_lock);
8340
8341         return (retval);
8342 }
8343
8344 static void
8345 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8346 {
8347         uint64_t sa_res_key;
8348         int i;
8349
8350         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8351
8352         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8353          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8354          || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8355                 if (sa_res_key == 0) {
8356                         /*
8357                          * Unregister everybody else and build UA for
8358                          * them
8359                          */
8360                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8361                                 if (i == msg->pr.pr_info.residx ||
8362                                     ctl_get_prkey(lun, i) == 0)
8363                                         continue;
8364
8365                                 ctl_clr_prkey(lun, i);
8366                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8367                         }
8368
8369                         lun->pr_key_count = 1;
8370                         lun->res_type = msg->pr.pr_info.res_type;
8371                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8372                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8373                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8374                 } else {
8375                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8376                                 if (sa_res_key == ctl_get_prkey(lun, i))
8377                                         continue;
8378
8379                                 ctl_clr_prkey(lun, i);
8380                                 lun->pr_key_count--;
8381                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8382                         }
8383                 }
8384         } else {
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                         if (sa_res_key == ctl_get_prkey(lun, i)) {
8391                                 ctl_clr_prkey(lun, i);
8392                                 lun->pr_key_count--;
8393                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8394                         } else if (msg->pr.pr_info.res_type != lun->res_type
8395                                 && (lun->res_type == SPR_TYPE_WR_EX_RO
8396                                  || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8397                                 ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
8398                         }
8399                 }
8400                 lun->res_type = msg->pr.pr_info.res_type;
8401                 if (lun->res_type != SPR_TYPE_WR_EX_AR
8402                  && lun->res_type != SPR_TYPE_EX_AC_AR)
8403                         lun->pr_res_idx = msg->pr.pr_info.residx;
8404                 else
8405                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8406         }
8407         lun->PRGeneration++;
8408
8409 }
8410
8411
8412 int
8413 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8414 {
8415         int retval;
8416         int isc_retval;
8417         u_int32_t param_len;
8418         struct scsi_per_res_out *cdb;
8419         struct ctl_lun *lun;
8420         struct scsi_per_res_out_parms* param;
8421         struct ctl_softc *softc;
8422         uint32_t residx;
8423         uint64_t res_key, sa_res_key, key;
8424         uint8_t type;
8425         union ctl_ha_msg persis_io;
8426         int    i;
8427
8428         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8429
8430         retval = CTL_RETVAL_COMPLETE;
8431
8432         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8433         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8434         softc = lun->ctl_softc;
8435
8436         /*
8437          * We only support whole-LUN scope.  The scope & type are ignored for
8438          * register, register and ignore existing key and clear.
8439          * We sometimes ignore scope and type on preempts too!!
8440          * Verify reservation type here as well.
8441          */
8442         type = cdb->scope_type & SPR_TYPE_MASK;
8443         if ((cdb->action == SPRO_RESERVE)
8444          || (cdb->action == SPRO_RELEASE)) {
8445                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8446                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8447                                               /*sks_valid*/ 1,
8448                                               /*command*/ 1,
8449                                               /*field*/ 2,
8450                                               /*bit_valid*/ 1,
8451                                               /*bit*/ 4);
8452                         ctl_done((union ctl_io *)ctsio);
8453                         return (CTL_RETVAL_COMPLETE);
8454                 }
8455
8456                 if (type>8 || type==2 || type==4 || type==0) {
8457                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8458                                               /*sks_valid*/ 1,
8459                                               /*command*/ 1,
8460                                               /*field*/ 2,
8461                                               /*bit_valid*/ 1,
8462                                               /*bit*/ 0);
8463                         ctl_done((union ctl_io *)ctsio);
8464                         return (CTL_RETVAL_COMPLETE);
8465                 }
8466         }
8467
8468         param_len = scsi_4btoul(cdb->length);
8469
8470         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8471                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8472                 ctsio->kern_data_len = param_len;
8473                 ctsio->kern_total_len = param_len;
8474                 ctsio->kern_data_resid = 0;
8475                 ctsio->kern_rel_offset = 0;
8476                 ctsio->kern_sg_entries = 0;
8477                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8478                 ctsio->be_move_done = ctl_config_move_done;
8479                 ctl_datamove((union ctl_io *)ctsio);
8480
8481                 return (CTL_RETVAL_COMPLETE);
8482         }
8483
8484         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8485
8486         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8487         res_key = scsi_8btou64(param->res_key.key);
8488         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8489
8490         /*
8491          * Validate the reservation key here except for SPRO_REG_IGNO
8492          * This must be done for all other service actions
8493          */
8494         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8495                 mtx_lock(&lun->lun_lock);
8496                 if ((key = ctl_get_prkey(lun, residx)) != 0) {
8497                         if (res_key != key) {
8498                                 /*
8499                                  * The current key passed in doesn't match
8500                                  * the one the initiator previously
8501                                  * registered.
8502                                  */
8503                                 mtx_unlock(&lun->lun_lock);
8504                                 free(ctsio->kern_data_ptr, M_CTL);
8505                                 ctl_set_reservation_conflict(ctsio);
8506                                 ctl_done((union ctl_io *)ctsio);
8507                                 return (CTL_RETVAL_COMPLETE);
8508                         }
8509                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8510                         /*
8511                          * We are not registered
8512                          */
8513                         mtx_unlock(&lun->lun_lock);
8514                         free(ctsio->kern_data_ptr, M_CTL);
8515                         ctl_set_reservation_conflict(ctsio);
8516                         ctl_done((union ctl_io *)ctsio);
8517                         return (CTL_RETVAL_COMPLETE);
8518                 } else if (res_key != 0) {
8519                         /*
8520                          * We are not registered and trying to register but
8521                          * the register key isn't zero.
8522                          */
8523                         mtx_unlock(&lun->lun_lock);
8524                         free(ctsio->kern_data_ptr, M_CTL);
8525                         ctl_set_reservation_conflict(ctsio);
8526                         ctl_done((union ctl_io *)ctsio);
8527                         return (CTL_RETVAL_COMPLETE);
8528                 }
8529                 mtx_unlock(&lun->lun_lock);
8530         }
8531
8532         switch (cdb->action & SPRO_ACTION_MASK) {
8533         case SPRO_REGISTER:
8534         case SPRO_REG_IGNO: {
8535
8536 #if 0
8537                 printf("Registration received\n");
8538 #endif
8539
8540                 /*
8541                  * We don't support any of these options, as we report in
8542                  * the read capabilities request (see
8543                  * ctl_persistent_reserve_in(), above).
8544                  */
8545                 if ((param->flags & SPR_SPEC_I_PT)
8546                  || (param->flags & SPR_ALL_TG_PT)
8547                  || (param->flags & SPR_APTPL)) {
8548                         int bit_ptr;
8549
8550                         if (param->flags & SPR_APTPL)
8551                                 bit_ptr = 0;
8552                         else if (param->flags & SPR_ALL_TG_PT)
8553                                 bit_ptr = 2;
8554                         else /* SPR_SPEC_I_PT */
8555                                 bit_ptr = 3;
8556
8557                         free(ctsio->kern_data_ptr, M_CTL);
8558                         ctl_set_invalid_field(ctsio,
8559                                               /*sks_valid*/ 1,
8560                                               /*command*/ 0,
8561                                               /*field*/ 20,
8562                                               /*bit_valid*/ 1,
8563                                               /*bit*/ bit_ptr);
8564                         ctl_done((union ctl_io *)ctsio);
8565                         return (CTL_RETVAL_COMPLETE);
8566                 }
8567
8568                 mtx_lock(&lun->lun_lock);
8569
8570                 /*
8571                  * The initiator wants to clear the
8572                  * key/unregister.
8573                  */
8574                 if (sa_res_key == 0) {
8575                         if ((res_key == 0
8576                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8577                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8578                           && ctl_get_prkey(lun, residx) == 0)) {
8579                                 mtx_unlock(&lun->lun_lock);
8580                                 goto done;
8581                         }
8582
8583                         ctl_clr_prkey(lun, residx);
8584                         lun->pr_key_count--;
8585
8586                         if (residx == lun->pr_res_idx) {
8587                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8588                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8589
8590                                 if ((lun->res_type == SPR_TYPE_WR_EX_RO
8591                                   || lun->res_type == SPR_TYPE_EX_AC_RO)
8592                                  && lun->pr_key_count) {
8593                                         /*
8594                                          * If the reservation is a registrants
8595                                          * only type we need to generate a UA
8596                                          * for other registered inits.  The
8597                                          * sense code should be RESERVATIONS
8598                                          * RELEASED
8599                                          */
8600
8601                                         for (i = 0; i < CTL_MAX_INITIATORS;i++){
8602                                                 if (ctl_get_prkey(lun, i +
8603                                                     softc->persis_offset) == 0)
8604                                                         continue;
8605                                                 ctl_est_ua(lun, i,
8606                                                     CTL_UA_RES_RELEASE);
8607                                         }
8608                                 }
8609                                 lun->res_type = 0;
8610                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8611                                 if (lun->pr_key_count==0) {
8612                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8613                                         lun->res_type = 0;
8614                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8615                                 }
8616                         }
8617                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8618                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8619                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8620                         persis_io.pr.pr_info.residx = residx;
8621                         if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8622                              &persis_io, sizeof(persis_io), 0 )) >
8623                              CTL_HA_STATUS_SUCCESS) {
8624                                 printf("CTL:Persis Out error returned from "
8625                                        "ctl_ha_msg_send %d\n", isc_retval);
8626                         }
8627                 } else /* sa_res_key != 0 */ {
8628
8629                         /*
8630                          * If we aren't registered currently then increment
8631                          * the key count and set the registered flag.
8632                          */
8633                         ctl_alloc_prkey(lun, residx);
8634                         if (ctl_get_prkey(lun, residx) == 0)
8635                                 lun->pr_key_count++;
8636                         ctl_set_prkey(lun, residx, sa_res_key);
8637
8638                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8639                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8640                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8641                         persis_io.pr.pr_info.residx = residx;
8642                         memcpy(persis_io.pr.pr_info.sa_res_key,
8643                                param->serv_act_res_key,
8644                                sizeof(param->serv_act_res_key));
8645                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8646                              &persis_io, sizeof(persis_io), 0)) >
8647                              CTL_HA_STATUS_SUCCESS) {
8648                                 printf("CTL:Persis Out error returned from "
8649                                        "ctl_ha_msg_send %d\n", isc_retval);
8650                         }
8651                 }
8652                 lun->PRGeneration++;
8653                 mtx_unlock(&lun->lun_lock);
8654
8655                 break;
8656         }
8657         case SPRO_RESERVE:
8658 #if 0
8659                 printf("Reserve executed type %d\n", type);
8660 #endif
8661                 mtx_lock(&lun->lun_lock);
8662                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8663                         /*
8664                          * if this isn't the reservation holder and it's
8665                          * not a "all registrants" type or if the type is
8666                          * different then we have a conflict
8667                          */
8668                         if ((lun->pr_res_idx != residx
8669                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8670                          || lun->res_type != type) {
8671                                 mtx_unlock(&lun->lun_lock);
8672                                 free(ctsio->kern_data_ptr, M_CTL);
8673                                 ctl_set_reservation_conflict(ctsio);
8674                                 ctl_done((union ctl_io *)ctsio);
8675                                 return (CTL_RETVAL_COMPLETE);
8676                         }
8677                         mtx_unlock(&lun->lun_lock);
8678                 } else /* create a reservation */ {
8679                         /*
8680                          * If it's not an "all registrants" type record
8681                          * reservation holder
8682                          */
8683                         if (type != SPR_TYPE_WR_EX_AR
8684                          && type != SPR_TYPE_EX_AC_AR)
8685                                 lun->pr_res_idx = residx; /* Res holder */
8686                         else
8687                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8688
8689                         lun->flags |= CTL_LUN_PR_RESERVED;
8690                         lun->res_type = type;
8691
8692                         mtx_unlock(&lun->lun_lock);
8693
8694                         /* send msg to other side */
8695                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8696                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8697                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8698                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8699                         persis_io.pr.pr_info.res_type = type;
8700                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8701                              &persis_io, sizeof(persis_io), 0)) >
8702                              CTL_HA_STATUS_SUCCESS) {
8703                                 printf("CTL:Persis Out error returned from "
8704                                        "ctl_ha_msg_send %d\n", isc_retval);
8705                         }
8706                 }
8707                 break;
8708
8709         case SPRO_RELEASE:
8710                 mtx_lock(&lun->lun_lock);
8711                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8712                         /* No reservation exists return good status */
8713                         mtx_unlock(&lun->lun_lock);
8714                         goto done;
8715                 }
8716                 /*
8717                  * Is this nexus a reservation holder?
8718                  */
8719                 if (lun->pr_res_idx != residx
8720                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8721                         /*
8722                          * not a res holder return good status but
8723                          * do nothing
8724                          */
8725                         mtx_unlock(&lun->lun_lock);
8726                         goto done;
8727                 }
8728
8729                 if (lun->res_type != type) {
8730                         mtx_unlock(&lun->lun_lock);
8731                         free(ctsio->kern_data_ptr, M_CTL);
8732                         ctl_set_illegal_pr_release(ctsio);
8733                         ctl_done((union ctl_io *)ctsio);
8734                         return (CTL_RETVAL_COMPLETE);
8735                 }
8736
8737                 /* okay to release */
8738                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8739                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8740                 lun->res_type = 0;
8741
8742                 /*
8743                  * if this isn't an exclusive access
8744                  * res generate UA for all other
8745                  * registrants.
8746                  */
8747                 if (type != SPR_TYPE_EX_AC
8748                  && type != SPR_TYPE_WR_EX) {
8749                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8750                                 if (i == residx ||
8751                                     ctl_get_prkey(lun,
8752                                      i + softc->persis_offset) == 0)
8753                                         continue;
8754                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8755                         }
8756                 }
8757                 mtx_unlock(&lun->lun_lock);
8758                 /* Send msg to other side */
8759                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8760                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8761                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8762                 if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8763                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8764                         printf("CTL:Persis Out error returned from "
8765                                "ctl_ha_msg_send %d\n", isc_retval);
8766                 }
8767                 break;
8768
8769         case SPRO_CLEAR:
8770                 /* send msg to other side */
8771
8772                 mtx_lock(&lun->lun_lock);
8773                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8774                 lun->res_type = 0;
8775                 lun->pr_key_count = 0;
8776                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8777
8778                 ctl_clr_prkey(lun, residx);
8779                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8780                         if (ctl_get_prkey(lun, i) != 0) {
8781                                 ctl_clr_prkey(lun, i);
8782                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8783                         }
8784                 lun->PRGeneration++;
8785                 mtx_unlock(&lun->lun_lock);
8786                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8787                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8788                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8789                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8790                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8791                         printf("CTL:Persis Out error returned from "
8792                                "ctl_ha_msg_send %d\n", isc_retval);
8793                 }
8794                 break;
8795
8796         case SPRO_PREEMPT:
8797         case SPRO_PRE_ABO: {
8798                 int nretval;
8799
8800                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8801                                           residx, ctsio, cdb, param);
8802                 if (nretval != 0)
8803                         return (CTL_RETVAL_COMPLETE);
8804                 break;
8805         }
8806         default:
8807                 panic("Invalid PR type %x", cdb->action);
8808         }
8809
8810 done:
8811         free(ctsio->kern_data_ptr, M_CTL);
8812         ctl_set_success(ctsio);
8813         ctl_done((union ctl_io *)ctsio);
8814
8815         return (retval);
8816 }
8817
8818 /*
8819  * This routine is for handling a message from the other SC pertaining to
8820  * persistent reserve out. All the error checking will have been done
8821  * so only perorming the action need be done here to keep the two
8822  * in sync.
8823  */
8824 static void
8825 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8826 {
8827         struct ctl_lun *lun;
8828         struct ctl_softc *softc;
8829         int i;
8830         uint32_t targ_lun;
8831
8832         softc = control_softc;
8833
8834         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8835         lun = softc->ctl_luns[targ_lun];
8836         mtx_lock(&lun->lun_lock);
8837         switch(msg->pr.pr_info.action) {
8838         case CTL_PR_REG_KEY:
8839                 ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8840                 if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8841                         lun->pr_key_count++;
8842                 ctl_set_prkey(lun, msg->pr.pr_info.residx,
8843                     scsi_8btou64(msg->pr.pr_info.sa_res_key));
8844                 lun->PRGeneration++;
8845                 break;
8846
8847         case CTL_PR_UNREG_KEY:
8848                 ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8849                 lun->pr_key_count--;
8850
8851                 /* XXX Need to see if the reservation has been released */
8852                 /* if so do we need to generate UA? */
8853                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8854                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8855                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8856
8857                         if ((lun->res_type == SPR_TYPE_WR_EX_RO
8858                           || lun->res_type == SPR_TYPE_EX_AC_RO)
8859                          && lun->pr_key_count) {
8860                                 /*
8861                                  * If the reservation is a registrants
8862                                  * only type we need to generate a UA
8863                                  * for other registered inits.  The
8864                                  * sense code should be RESERVATIONS
8865                                  * RELEASED
8866                                  */
8867
8868                                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8869                                         if (ctl_get_prkey(lun, i +
8870                                             softc->persis_offset) == 0)
8871                                                 continue;
8872
8873                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8874                                 }
8875                         }
8876                         lun->res_type = 0;
8877                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8878                         if (lun->pr_key_count==0) {
8879                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8880                                 lun->res_type = 0;
8881                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8882                         }
8883                 }
8884                 lun->PRGeneration++;
8885                 break;
8886
8887         case CTL_PR_RESERVE:
8888                 lun->flags |= CTL_LUN_PR_RESERVED;
8889                 lun->res_type = msg->pr.pr_info.res_type;
8890                 lun->pr_res_idx = msg->pr.pr_info.residx;
8891
8892                 break;
8893
8894         case CTL_PR_RELEASE:
8895                 /*
8896                  * if this isn't an exclusive access res generate UA for all
8897                  * other registrants.
8898                  */
8899                 if (lun->res_type != SPR_TYPE_EX_AC
8900                  && lun->res_type != SPR_TYPE_WR_EX) {
8901                         for (i = 0; i < CTL_MAX_INITIATORS; i++)
8902                                 if (ctl_get_prkey(lun, i + softc->persis_offset) != 0)
8903                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8904                 }
8905
8906                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8907                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8908                 lun->res_type = 0;
8909                 break;
8910
8911         case CTL_PR_PREEMPT:
8912                 ctl_pro_preempt_other(lun, msg);
8913                 break;
8914         case CTL_PR_CLEAR:
8915                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8916                 lun->res_type = 0;
8917                 lun->pr_key_count = 0;
8918                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8919
8920                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8921                         if (ctl_get_prkey(lun, i) == 0)
8922                                 continue;
8923                         ctl_clr_prkey(lun, i);
8924                         ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8925                 }
8926                 lun->PRGeneration++;
8927                 break;
8928         }
8929
8930         mtx_unlock(&lun->lun_lock);
8931 }
8932
8933 int
8934 ctl_read_write(struct ctl_scsiio *ctsio)
8935 {
8936         struct ctl_lun *lun;
8937         struct ctl_lba_len_flags *lbalen;
8938         uint64_t lba;
8939         uint32_t num_blocks;
8940         int flags, retval;
8941         int isread;
8942
8943         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8944
8945         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8946
8947         flags = 0;
8948         retval = CTL_RETVAL_COMPLETE;
8949
8950         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8951               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8952         switch (ctsio->cdb[0]) {
8953         case READ_6:
8954         case WRITE_6: {
8955                 struct scsi_rw_6 *cdb;
8956
8957                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
8958
8959                 lba = scsi_3btoul(cdb->addr);
8960                 /* only 5 bits are valid in the most significant address byte */
8961                 lba &= 0x1fffff;
8962                 num_blocks = cdb->length;
8963                 /*
8964                  * This is correct according to SBC-2.
8965                  */
8966                 if (num_blocks == 0)
8967                         num_blocks = 256;
8968                 break;
8969         }
8970         case READ_10:
8971         case WRITE_10: {
8972                 struct scsi_rw_10 *cdb;
8973
8974                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
8975                 if (cdb->byte2 & SRW10_FUA)
8976                         flags |= CTL_LLF_FUA;
8977                 if (cdb->byte2 & SRW10_DPO)
8978                         flags |= CTL_LLF_DPO;
8979                 lba = scsi_4btoul(cdb->addr);
8980                 num_blocks = scsi_2btoul(cdb->length);
8981                 break;
8982         }
8983         case WRITE_VERIFY_10: {
8984                 struct scsi_write_verify_10 *cdb;
8985
8986                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8987                 flags |= CTL_LLF_FUA;
8988                 if (cdb->byte2 & SWV_DPO)
8989                         flags |= CTL_LLF_DPO;
8990                 lba = scsi_4btoul(cdb->addr);
8991                 num_blocks = scsi_2btoul(cdb->length);
8992                 break;
8993         }
8994         case READ_12:
8995         case WRITE_12: {
8996                 struct scsi_rw_12 *cdb;
8997
8998                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
8999                 if (cdb->byte2 & SRW12_FUA)
9000                         flags |= CTL_LLF_FUA;
9001                 if (cdb->byte2 & SRW12_DPO)
9002                         flags |= CTL_LLF_DPO;
9003                 lba = scsi_4btoul(cdb->addr);
9004                 num_blocks = scsi_4btoul(cdb->length);
9005                 break;
9006         }
9007         case WRITE_VERIFY_12: {
9008                 struct scsi_write_verify_12 *cdb;
9009
9010                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
9011                 flags |= CTL_LLF_FUA;
9012                 if (cdb->byte2 & SWV_DPO)
9013                         flags |= CTL_LLF_DPO;
9014                 lba = scsi_4btoul(cdb->addr);
9015                 num_blocks = scsi_4btoul(cdb->length);
9016                 break;
9017         }
9018         case READ_16:
9019         case WRITE_16: {
9020                 struct scsi_rw_16 *cdb;
9021
9022                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9023                 if (cdb->byte2 & SRW12_FUA)
9024                         flags |= CTL_LLF_FUA;
9025                 if (cdb->byte2 & SRW12_DPO)
9026                         flags |= CTL_LLF_DPO;
9027                 lba = scsi_8btou64(cdb->addr);
9028                 num_blocks = scsi_4btoul(cdb->length);
9029                 break;
9030         }
9031         case WRITE_ATOMIC_16: {
9032                 struct scsi_rw_16 *cdb;
9033
9034                 if (lun->be_lun->atomicblock == 0) {
9035                         ctl_set_invalid_opcode(ctsio);
9036                         ctl_done((union ctl_io *)ctsio);
9037                         return (CTL_RETVAL_COMPLETE);
9038                 }
9039
9040                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9041                 if (cdb->byte2 & SRW12_FUA)
9042                         flags |= CTL_LLF_FUA;
9043                 if (cdb->byte2 & SRW12_DPO)
9044                         flags |= CTL_LLF_DPO;
9045                 lba = scsi_8btou64(cdb->addr);
9046                 num_blocks = scsi_4btoul(cdb->length);
9047                 if (num_blocks > lun->be_lun->atomicblock) {
9048                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
9049                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
9050                             /*bit*/ 0);
9051                         ctl_done((union ctl_io *)ctsio);
9052                         return (CTL_RETVAL_COMPLETE);
9053                 }
9054                 break;
9055         }
9056         case WRITE_VERIFY_16: {
9057                 struct scsi_write_verify_16 *cdb;
9058
9059                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9060                 flags |= CTL_LLF_FUA;
9061                 if (cdb->byte2 & SWV_DPO)
9062                         flags |= CTL_LLF_DPO;
9063                 lba = scsi_8btou64(cdb->addr);
9064                 num_blocks = scsi_4btoul(cdb->length);
9065                 break;
9066         }
9067         default:
9068                 /*
9069                  * We got a command we don't support.  This shouldn't
9070                  * happen, commands should be filtered out above us.
9071                  */
9072                 ctl_set_invalid_opcode(ctsio);
9073                 ctl_done((union ctl_io *)ctsio);
9074
9075                 return (CTL_RETVAL_COMPLETE);
9076                 break; /* NOTREACHED */
9077         }
9078
9079         /*
9080          * The first check is to make sure we're in bounds, the second
9081          * check is to catch wrap-around problems.  If the lba + num blocks
9082          * is less than the lba, then we've wrapped around and the block
9083          * range is invalid anyway.
9084          */
9085         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9086          || ((lba + num_blocks) < lba)) {
9087                 ctl_set_lba_out_of_range(ctsio);
9088                 ctl_done((union ctl_io *)ctsio);
9089                 return (CTL_RETVAL_COMPLETE);
9090         }
9091
9092         /*
9093          * According to SBC-3, a transfer length of 0 is not an error.
9094          * Note that this cannot happen with WRITE(6) or READ(6), since 0
9095          * translates to 256 blocks for those commands.
9096          */
9097         if (num_blocks == 0) {
9098                 ctl_set_success(ctsio);
9099                 ctl_done((union ctl_io *)ctsio);
9100                 return (CTL_RETVAL_COMPLETE);
9101         }
9102
9103         /* Set FUA and/or DPO if caches are disabled. */
9104         if (isread) {
9105                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9106                     SCP_RCD) != 0)
9107                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9108         } else {
9109                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9110                     SCP_WCE) == 0)
9111                         flags |= CTL_LLF_FUA;
9112         }
9113
9114         lbalen = (struct ctl_lba_len_flags *)
9115             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9116         lbalen->lba = lba;
9117         lbalen->len = num_blocks;
9118         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9119
9120         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9121         ctsio->kern_rel_offset = 0;
9122
9123         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9124
9125         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9126
9127         return (retval);
9128 }
9129
9130 static int
9131 ctl_cnw_cont(union ctl_io *io)
9132 {
9133         struct ctl_scsiio *ctsio;
9134         struct ctl_lun *lun;
9135         struct ctl_lba_len_flags *lbalen;
9136         int retval;
9137
9138         ctsio = &io->scsiio;
9139         ctsio->io_hdr.status = CTL_STATUS_NONE;
9140         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9141         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9142         lbalen = (struct ctl_lba_len_flags *)
9143             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9144         lbalen->flags &= ~CTL_LLF_COMPARE;
9145         lbalen->flags |= CTL_LLF_WRITE;
9146
9147         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9148         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9149         return (retval);
9150 }
9151
9152 int
9153 ctl_cnw(struct ctl_scsiio *ctsio)
9154 {
9155         struct ctl_lun *lun;
9156         struct ctl_lba_len_flags *lbalen;
9157         uint64_t lba;
9158         uint32_t num_blocks;
9159         int flags, retval;
9160
9161         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9162
9163         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9164
9165         flags = 0;
9166         retval = CTL_RETVAL_COMPLETE;
9167
9168         switch (ctsio->cdb[0]) {
9169         case COMPARE_AND_WRITE: {
9170                 struct scsi_compare_and_write *cdb;
9171
9172                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9173                 if (cdb->byte2 & SRW10_FUA)
9174                         flags |= CTL_LLF_FUA;
9175                 if (cdb->byte2 & SRW10_DPO)
9176                         flags |= CTL_LLF_DPO;
9177                 lba = scsi_8btou64(cdb->addr);
9178                 num_blocks = cdb->length;
9179                 break;
9180         }
9181         default:
9182                 /*
9183                  * We got a command we don't support.  This shouldn't
9184                  * happen, commands should be filtered out above us.
9185                  */
9186                 ctl_set_invalid_opcode(ctsio);
9187                 ctl_done((union ctl_io *)ctsio);
9188
9189                 return (CTL_RETVAL_COMPLETE);
9190                 break; /* NOTREACHED */
9191         }
9192
9193         /*
9194          * The first check is to make sure we're in bounds, the second
9195          * check is to catch wrap-around problems.  If the lba + num blocks
9196          * is less than the lba, then we've wrapped around and the block
9197          * range is invalid anyway.
9198          */
9199         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9200          || ((lba + num_blocks) < lba)) {
9201                 ctl_set_lba_out_of_range(ctsio);
9202                 ctl_done((union ctl_io *)ctsio);
9203                 return (CTL_RETVAL_COMPLETE);
9204         }
9205
9206         /*
9207          * According to SBC-3, a transfer length of 0 is not an error.
9208          */
9209         if (num_blocks == 0) {
9210                 ctl_set_success(ctsio);
9211                 ctl_done((union ctl_io *)ctsio);
9212                 return (CTL_RETVAL_COMPLETE);
9213         }
9214
9215         /* Set FUA if write cache is disabled. */
9216         if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9217             SCP_WCE) == 0)
9218                 flags |= CTL_LLF_FUA;
9219
9220         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9221         ctsio->kern_rel_offset = 0;
9222
9223         /*
9224          * Set the IO_CONT flag, so that if this I/O gets passed to
9225          * ctl_data_submit_done(), it'll get passed back to
9226          * ctl_ctl_cnw_cont() for further processing.
9227          */
9228         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9229         ctsio->io_cont = ctl_cnw_cont;
9230
9231         lbalen = (struct ctl_lba_len_flags *)
9232             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9233         lbalen->lba = lba;
9234         lbalen->len = num_blocks;
9235         lbalen->flags = CTL_LLF_COMPARE | flags;
9236
9237         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9238         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9239         return (retval);
9240 }
9241
9242 int
9243 ctl_verify(struct ctl_scsiio *ctsio)
9244 {
9245         struct ctl_lun *lun;
9246         struct ctl_lba_len_flags *lbalen;
9247         uint64_t lba;
9248         uint32_t num_blocks;
9249         int bytchk, flags;
9250         int retval;
9251
9252         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9253
9254         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9255
9256         bytchk = 0;
9257         flags = CTL_LLF_FUA;
9258         retval = CTL_RETVAL_COMPLETE;
9259
9260         switch (ctsio->cdb[0]) {
9261         case VERIFY_10: {
9262                 struct scsi_verify_10 *cdb;
9263
9264                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
9265                 if (cdb->byte2 & SVFY_BYTCHK)
9266                         bytchk = 1;
9267                 if (cdb->byte2 & SVFY_DPO)
9268                         flags |= CTL_LLF_DPO;
9269                 lba = scsi_4btoul(cdb->addr);
9270                 num_blocks = scsi_2btoul(cdb->length);
9271                 break;
9272         }
9273         case VERIFY_12: {
9274                 struct scsi_verify_12 *cdb;
9275
9276                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
9277                 if (cdb->byte2 & SVFY_BYTCHK)
9278                         bytchk = 1;
9279                 if (cdb->byte2 & SVFY_DPO)
9280                         flags |= CTL_LLF_DPO;
9281                 lba = scsi_4btoul(cdb->addr);
9282                 num_blocks = scsi_4btoul(cdb->length);
9283                 break;
9284         }
9285         case VERIFY_16: {
9286                 struct scsi_rw_16 *cdb;
9287
9288                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9289                 if (cdb->byte2 & SVFY_BYTCHK)
9290                         bytchk = 1;
9291                 if (cdb->byte2 & SVFY_DPO)
9292                         flags |= CTL_LLF_DPO;
9293                 lba = scsi_8btou64(cdb->addr);
9294                 num_blocks = scsi_4btoul(cdb->length);
9295                 break;
9296         }
9297         default:
9298                 /*
9299                  * We got a command we don't support.  This shouldn't
9300                  * happen, commands should be filtered out above us.
9301                  */
9302                 ctl_set_invalid_opcode(ctsio);
9303                 ctl_done((union ctl_io *)ctsio);
9304                 return (CTL_RETVAL_COMPLETE);
9305         }
9306
9307         /*
9308          * The first check is to make sure we're in bounds, the second
9309          * check is to catch wrap-around problems.  If the lba + num blocks
9310          * is less than the lba, then we've wrapped around and the block
9311          * range is invalid anyway.
9312          */
9313         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9314          || ((lba + num_blocks) < lba)) {
9315                 ctl_set_lba_out_of_range(ctsio);
9316                 ctl_done((union ctl_io *)ctsio);
9317                 return (CTL_RETVAL_COMPLETE);
9318         }
9319
9320         /*
9321          * According to SBC-3, a transfer length of 0 is not an error.
9322          */
9323         if (num_blocks == 0) {
9324                 ctl_set_success(ctsio);
9325                 ctl_done((union ctl_io *)ctsio);
9326                 return (CTL_RETVAL_COMPLETE);
9327         }
9328
9329         lbalen = (struct ctl_lba_len_flags *)
9330             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9331         lbalen->lba = lba;
9332         lbalen->len = num_blocks;
9333         if (bytchk) {
9334                 lbalen->flags = CTL_LLF_COMPARE | flags;
9335                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9336         } else {
9337                 lbalen->flags = CTL_LLF_VERIFY | flags;
9338                 ctsio->kern_total_len = 0;
9339         }
9340         ctsio->kern_rel_offset = 0;
9341
9342         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9343         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9344         return (retval);
9345 }
9346
9347 int
9348 ctl_report_luns(struct ctl_scsiio *ctsio)
9349 {
9350         struct ctl_softc *softc = control_softc;
9351         struct scsi_report_luns *cdb;
9352         struct scsi_report_luns_data *lun_data;
9353         struct ctl_lun *lun, *request_lun;
9354         struct ctl_port *port;
9355         int num_luns, retval;
9356         uint32_t alloc_len, lun_datalen;
9357         int num_filled, well_known;
9358         uint32_t initidx, targ_lun_id, lun_id;
9359
9360         retval = CTL_RETVAL_COMPLETE;
9361         well_known = 0;
9362
9363         cdb = (struct scsi_report_luns *)ctsio->cdb;
9364         port = ctl_io_port(&ctsio->io_hdr);
9365
9366         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9367
9368         mtx_lock(&softc->ctl_lock);
9369         num_luns = 0;
9370         for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
9371                 if (ctl_lun_map_from_port(port, targ_lun_id) < CTL_MAX_LUNS)
9372                         num_luns++;
9373         }
9374         mtx_unlock(&softc->ctl_lock);
9375
9376         switch (cdb->select_report) {
9377         case RPL_REPORT_DEFAULT:
9378         case RPL_REPORT_ALL:
9379                 break;
9380         case RPL_REPORT_WELLKNOWN:
9381                 well_known = 1;
9382                 num_luns = 0;
9383                 break;
9384         default:
9385                 ctl_set_invalid_field(ctsio,
9386                                       /*sks_valid*/ 1,
9387                                       /*command*/ 1,
9388                                       /*field*/ 2,
9389                                       /*bit_valid*/ 0,
9390                                       /*bit*/ 0);
9391                 ctl_done((union ctl_io *)ctsio);
9392                 return (retval);
9393                 break; /* NOTREACHED */
9394         }
9395
9396         alloc_len = scsi_4btoul(cdb->length);
9397         /*
9398          * The initiator has to allocate at least 16 bytes for this request,
9399          * so he can at least get the header and the first LUN.  Otherwise
9400          * we reject the request (per SPC-3 rev 14, section 6.21).
9401          */
9402         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9403             sizeof(struct scsi_report_luns_lundata))) {
9404                 ctl_set_invalid_field(ctsio,
9405                                       /*sks_valid*/ 1,
9406                                       /*command*/ 1,
9407                                       /*field*/ 6,
9408                                       /*bit_valid*/ 0,
9409                                       /*bit*/ 0);
9410                 ctl_done((union ctl_io *)ctsio);
9411                 return (retval);
9412         }
9413
9414         request_lun = (struct ctl_lun *)
9415                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9416
9417         lun_datalen = sizeof(*lun_data) +
9418                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9419
9420         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9421         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9422         ctsio->kern_sg_entries = 0;
9423
9424         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9425
9426         mtx_lock(&softc->ctl_lock);
9427         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9428                 lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9429                 if (lun_id >= CTL_MAX_LUNS)
9430                         continue;
9431                 lun = softc->ctl_luns[lun_id];
9432                 if (lun == NULL)
9433                         continue;
9434
9435                 if (targ_lun_id <= 0xff) {
9436                         /*
9437                          * Peripheral addressing method, bus number 0.
9438                          */
9439                         lun_data->luns[num_filled].lundata[0] =
9440                                 RPL_LUNDATA_ATYP_PERIPH;
9441                         lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9442                         num_filled++;
9443                 } else if (targ_lun_id <= 0x3fff) {
9444                         /*
9445                          * Flat addressing method.
9446                          */
9447                         lun_data->luns[num_filled].lundata[0] =
9448                                 RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9449                         lun_data->luns[num_filled].lundata[1] =
9450                                 (targ_lun_id & 0xff);
9451                         num_filled++;
9452                 } else if (targ_lun_id <= 0xffffff) {
9453                         /*
9454                          * Extended flat addressing method.
9455                          */
9456                         lun_data->luns[num_filled].lundata[0] =
9457                             RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9458                         scsi_ulto3b(targ_lun_id,
9459                             &lun_data->luns[num_filled].lundata[1]);
9460                         num_filled++;
9461                 } else {
9462                         printf("ctl_report_luns: bogus LUN number %jd, "
9463                                "skipping\n", (intmax_t)targ_lun_id);
9464                 }
9465                 /*
9466                  * According to SPC-3, rev 14 section 6.21:
9467                  *
9468                  * "The execution of a REPORT LUNS command to any valid and
9469                  * installed logical unit shall clear the REPORTED LUNS DATA
9470                  * HAS CHANGED unit attention condition for all logical
9471                  * units of that target with respect to the requesting
9472                  * initiator. A valid and installed logical unit is one
9473                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9474                  * INQUIRY data (see 6.4.2)."
9475                  *
9476                  * If request_lun is NULL, the LUN this report luns command
9477                  * was issued to is either disabled or doesn't exist. In that
9478                  * case, we shouldn't clear any pending lun change unit
9479                  * attention.
9480                  */
9481                 if (request_lun != NULL) {
9482                         mtx_lock(&lun->lun_lock);
9483                         ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9484                         mtx_unlock(&lun->lun_lock);
9485                 }
9486         }
9487         mtx_unlock(&softc->ctl_lock);
9488
9489         /*
9490          * It's quite possible that we've returned fewer LUNs than we allocated
9491          * space for.  Trim it.
9492          */
9493         lun_datalen = sizeof(*lun_data) +
9494                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9495
9496         if (lun_datalen < alloc_len) {
9497                 ctsio->residual = alloc_len - lun_datalen;
9498                 ctsio->kern_data_len = lun_datalen;
9499                 ctsio->kern_total_len = lun_datalen;
9500         } else {
9501                 ctsio->residual = 0;
9502                 ctsio->kern_data_len = alloc_len;
9503                 ctsio->kern_total_len = alloc_len;
9504         }
9505         ctsio->kern_data_resid = 0;
9506         ctsio->kern_rel_offset = 0;
9507         ctsio->kern_sg_entries = 0;
9508
9509         /*
9510          * We set this to the actual data length, regardless of how much
9511          * space we actually have to return results.  If the user looks at
9512          * this value, he'll know whether or not he allocated enough space
9513          * and reissue the command if necessary.  We don't support well
9514          * known logical units, so if the user asks for that, return none.
9515          */
9516         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9517
9518         /*
9519          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9520          * this request.
9521          */
9522         ctl_set_success(ctsio);
9523         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9524         ctsio->be_move_done = ctl_config_move_done;
9525         ctl_datamove((union ctl_io *)ctsio);
9526         return (retval);
9527 }
9528
9529 int
9530 ctl_request_sense(struct ctl_scsiio *ctsio)
9531 {
9532         struct scsi_request_sense *cdb;
9533         struct scsi_sense_data *sense_ptr;
9534         struct ctl_softc *ctl_softc;
9535         struct ctl_lun *lun;
9536         uint32_t initidx;
9537         int have_error;
9538         scsi_sense_data_type sense_format;
9539         ctl_ua_type ua_type;
9540
9541         cdb = (struct scsi_request_sense *)ctsio->cdb;
9542
9543         ctl_softc = control_softc;
9544         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9545
9546         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9547
9548         /*
9549          * Determine which sense format the user wants.
9550          */
9551         if (cdb->byte2 & SRS_DESC)
9552                 sense_format = SSD_TYPE_DESC;
9553         else
9554                 sense_format = SSD_TYPE_FIXED;
9555
9556         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9557         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9558         ctsio->kern_sg_entries = 0;
9559
9560         /*
9561          * struct scsi_sense_data, which is currently set to 256 bytes, is
9562          * larger than the largest allowed value for the length field in the
9563          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9564          */
9565         ctsio->residual = 0;
9566         ctsio->kern_data_len = cdb->length;
9567         ctsio->kern_total_len = cdb->length;
9568
9569         ctsio->kern_data_resid = 0;
9570         ctsio->kern_rel_offset = 0;
9571         ctsio->kern_sg_entries = 0;
9572
9573         /*
9574          * If we don't have a LUN, we don't have any pending sense.
9575          */
9576         if (lun == NULL)
9577                 goto no_sense;
9578
9579         have_error = 0;
9580         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9581         /*
9582          * Check for pending sense, and then for pending unit attentions.
9583          * Pending sense gets returned first, then pending unit attentions.
9584          */
9585         mtx_lock(&lun->lun_lock);
9586 #ifdef CTL_WITH_CA
9587         if (ctl_is_set(lun->have_ca, initidx)) {
9588                 scsi_sense_data_type stored_format;
9589
9590                 /*
9591                  * Check to see which sense format was used for the stored
9592                  * sense data.
9593                  */
9594                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9595
9596                 /*
9597                  * If the user requested a different sense format than the
9598                  * one we stored, then we need to convert it to the other
9599                  * format.  If we're going from descriptor to fixed format
9600                  * sense data, we may lose things in translation, depending
9601                  * on what options were used.
9602                  *
9603                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9604                  * for some reason we'll just copy it out as-is.
9605                  */
9606                 if ((stored_format == SSD_TYPE_FIXED)
9607                  && (sense_format == SSD_TYPE_DESC))
9608                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9609                             &lun->pending_sense[initidx],
9610                             (struct scsi_sense_data_desc *)sense_ptr);
9611                 else if ((stored_format == SSD_TYPE_DESC)
9612                       && (sense_format == SSD_TYPE_FIXED))
9613                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9614                             &lun->pending_sense[initidx],
9615                             (struct scsi_sense_data_fixed *)sense_ptr);
9616                 else
9617                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9618                                MIN(sizeof(*sense_ptr),
9619                                sizeof(lun->pending_sense[initidx])));
9620
9621                 ctl_clear_mask(lun->have_ca, initidx);
9622                 have_error = 1;
9623         } else
9624 #endif
9625         {
9626                 ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9627                 if (ua_type != CTL_UA_NONE)
9628                         have_error = 1;
9629                 if (ua_type == CTL_UA_LUN_CHANGE) {
9630                         mtx_unlock(&lun->lun_lock);
9631                         mtx_lock(&ctl_softc->ctl_lock);
9632                         ctl_clear_ua(ctl_softc, initidx, ua_type);
9633                         mtx_unlock(&ctl_softc->ctl_lock);
9634                         mtx_lock(&lun->lun_lock);
9635                 }
9636
9637         }
9638         mtx_unlock(&lun->lun_lock);
9639
9640         /*
9641          * We already have a pending error, return it.
9642          */
9643         if (have_error != 0) {
9644                 /*
9645                  * We report the SCSI status as OK, since the status of the
9646                  * request sense command itself is OK.
9647                  * We report 0 for the sense length, because we aren't doing
9648                  * autosense in this case.  We're reporting sense as
9649                  * parameter data.
9650                  */
9651                 ctl_set_success(ctsio);
9652                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9653                 ctsio->be_move_done = ctl_config_move_done;
9654                 ctl_datamove((union ctl_io *)ctsio);
9655                 return (CTL_RETVAL_COMPLETE);
9656         }
9657
9658 no_sense:
9659
9660         /*
9661          * No sense information to report, so we report that everything is
9662          * okay.
9663          */
9664         ctl_set_sense_data(sense_ptr,
9665                            lun,
9666                            sense_format,
9667                            /*current_error*/ 1,
9668                            /*sense_key*/ SSD_KEY_NO_SENSE,
9669                            /*asc*/ 0x00,
9670                            /*ascq*/ 0x00,
9671                            SSD_ELEM_NONE);
9672
9673         /*
9674          * We report 0 for the sense length, because we aren't doing
9675          * autosense in this case.  We're reporting sense as parameter data.
9676          */
9677         ctl_set_success(ctsio);
9678         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9679         ctsio->be_move_done = ctl_config_move_done;
9680         ctl_datamove((union ctl_io *)ctsio);
9681         return (CTL_RETVAL_COMPLETE);
9682 }
9683
9684 int
9685 ctl_tur(struct ctl_scsiio *ctsio)
9686 {
9687
9688         CTL_DEBUG_PRINT(("ctl_tur\n"));
9689
9690         ctl_set_success(ctsio);
9691         ctl_done((union ctl_io *)ctsio);
9692
9693         return (CTL_RETVAL_COMPLETE);
9694 }
9695
9696 #ifdef notyet
9697 static int
9698 ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9699 {
9700
9701 }
9702 #endif
9703
9704 /*
9705  * SCSI VPD page 0x00, the Supported VPD Pages page.
9706  */
9707 static int
9708 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9709 {
9710         struct scsi_vpd_supported_pages *pages;
9711         int sup_page_size;
9712         struct ctl_lun *lun;
9713         int p;
9714
9715         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9716
9717         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9718             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9719         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9720         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9721         ctsio->kern_sg_entries = 0;
9722
9723         if (sup_page_size < alloc_len) {
9724                 ctsio->residual = alloc_len - sup_page_size;
9725                 ctsio->kern_data_len = sup_page_size;
9726                 ctsio->kern_total_len = sup_page_size;
9727         } else {
9728                 ctsio->residual = 0;
9729                 ctsio->kern_data_len = alloc_len;
9730                 ctsio->kern_total_len = alloc_len;
9731         }
9732         ctsio->kern_data_resid = 0;
9733         ctsio->kern_rel_offset = 0;
9734         ctsio->kern_sg_entries = 0;
9735
9736         /*
9737          * The control device is always connected.  The disk device, on the
9738          * other hand, may not be online all the time.  Need to change this
9739          * to figure out whether the disk device is actually online or not.
9740          */
9741         if (lun != NULL)
9742                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9743                                 lun->be_lun->lun_type;
9744         else
9745                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9746
9747         p = 0;
9748         /* Supported VPD pages */
9749         pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9750         /* Serial Number */
9751         pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9752         /* Device Identification */
9753         pages->page_list[p++] = SVPD_DEVICE_ID;
9754         /* Extended INQUIRY Data */
9755         pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9756         /* Mode Page Policy */
9757         pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9758         /* SCSI Ports */
9759         pages->page_list[p++] = SVPD_SCSI_PORTS;
9760         /* Third-party Copy */
9761         pages->page_list[p++] = SVPD_SCSI_TPC;
9762         if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9763                 /* Block limits */
9764                 pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9765                 /* Block Device Characteristics */
9766                 pages->page_list[p++] = SVPD_BDC;
9767                 /* Logical Block Provisioning */
9768                 pages->page_list[p++] = SVPD_LBP;
9769         }
9770         pages->length = p;
9771
9772         ctl_set_success(ctsio);
9773         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9774         ctsio->be_move_done = ctl_config_move_done;
9775         ctl_datamove((union ctl_io *)ctsio);
9776         return (CTL_RETVAL_COMPLETE);
9777 }
9778
9779 /*
9780  * SCSI VPD page 0x80, the Unit Serial Number page.
9781  */
9782 static int
9783 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9784 {
9785         struct scsi_vpd_unit_serial_number *sn_ptr;
9786         struct ctl_lun *lun;
9787         int data_len;
9788
9789         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9790
9791         data_len = 4 + CTL_SN_LEN;
9792         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9793         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9794         if (data_len < alloc_len) {
9795                 ctsio->residual = alloc_len - data_len;
9796                 ctsio->kern_data_len = data_len;
9797                 ctsio->kern_total_len = data_len;
9798         } else {
9799                 ctsio->residual = 0;
9800                 ctsio->kern_data_len = alloc_len;
9801                 ctsio->kern_total_len = alloc_len;
9802         }
9803         ctsio->kern_data_resid = 0;
9804         ctsio->kern_rel_offset = 0;
9805         ctsio->kern_sg_entries = 0;
9806
9807         /*
9808          * The control device is always connected.  The disk device, on the
9809          * other hand, may not be online all the time.  Need to change this
9810          * to figure out whether the disk device is actually online or not.
9811          */
9812         if (lun != NULL)
9813                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9814                                   lun->be_lun->lun_type;
9815         else
9816                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9817
9818         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9819         sn_ptr->length = CTL_SN_LEN;
9820         /*
9821          * If we don't have a LUN, we just leave the serial number as
9822          * all spaces.
9823          */
9824         if (lun != NULL) {
9825                 strncpy((char *)sn_ptr->serial_num,
9826                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9827         } else
9828                 memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9829
9830         ctl_set_success(ctsio);
9831         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9832         ctsio->be_move_done = ctl_config_move_done;
9833         ctl_datamove((union ctl_io *)ctsio);
9834         return (CTL_RETVAL_COMPLETE);
9835 }
9836
9837
9838 /*
9839  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9840  */
9841 static int
9842 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9843 {
9844         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9845         struct ctl_lun *lun;
9846         int data_len;
9847
9848         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9849
9850         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9851         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9852         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9853         ctsio->kern_sg_entries = 0;
9854
9855         if (data_len < alloc_len) {
9856                 ctsio->residual = alloc_len - data_len;
9857                 ctsio->kern_data_len = data_len;
9858                 ctsio->kern_total_len = data_len;
9859         } else {
9860                 ctsio->residual = 0;
9861                 ctsio->kern_data_len = alloc_len;
9862                 ctsio->kern_total_len = alloc_len;
9863         }
9864         ctsio->kern_data_resid = 0;
9865         ctsio->kern_rel_offset = 0;
9866         ctsio->kern_sg_entries = 0;
9867
9868         /*
9869          * The control device is always connected.  The disk device, on the
9870          * other hand, may not be online all the time.
9871          */
9872         if (lun != NULL)
9873                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9874                                      lun->be_lun->lun_type;
9875         else
9876                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9877         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9878         scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9879         /*
9880          * We support head of queue, ordered and simple tags.
9881          */
9882         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9883         /*
9884          * Volatile cache supported.
9885          */
9886         eid_ptr->flags3 = SVPD_EID_V_SUP;
9887
9888         /*
9889          * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9890          * attention for a particular IT nexus on all LUNs once we report
9891          * it to that nexus once.  This bit is required as of SPC-4.
9892          */
9893         eid_ptr->flags4 = SVPD_EID_LUICLT;
9894
9895         /*
9896          * XXX KDM in order to correctly answer this, we would need
9897          * information from the SIM to determine how much sense data it
9898          * can send.  So this would really be a path inquiry field, most
9899          * likely.  This can be set to a maximum of 252 according to SPC-4,
9900          * but the hardware may or may not be able to support that much.
9901          * 0 just means that the maximum sense data length is not reported.
9902          */
9903         eid_ptr->max_sense_length = 0;
9904
9905         ctl_set_success(ctsio);
9906         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9907         ctsio->be_move_done = ctl_config_move_done;
9908         ctl_datamove((union ctl_io *)ctsio);
9909         return (CTL_RETVAL_COMPLETE);
9910 }
9911
9912 static int
9913 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9914 {
9915         struct scsi_vpd_mode_page_policy *mpp_ptr;
9916         struct ctl_lun *lun;
9917         int data_len;
9918
9919         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9920
9921         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9922             sizeof(struct scsi_vpd_mode_page_policy_descr);
9923
9924         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9925         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9926         ctsio->kern_sg_entries = 0;
9927
9928         if (data_len < alloc_len) {
9929                 ctsio->residual = alloc_len - data_len;
9930                 ctsio->kern_data_len = data_len;
9931                 ctsio->kern_total_len = data_len;
9932         } else {
9933                 ctsio->residual = 0;
9934                 ctsio->kern_data_len = alloc_len;
9935                 ctsio->kern_total_len = alloc_len;
9936         }
9937         ctsio->kern_data_resid = 0;
9938         ctsio->kern_rel_offset = 0;
9939         ctsio->kern_sg_entries = 0;
9940
9941         /*
9942          * The control device is always connected.  The disk device, on the
9943          * other hand, may not be online all the time.
9944          */
9945         if (lun != NULL)
9946                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9947                                      lun->be_lun->lun_type;
9948         else
9949                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9950         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9951         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9952         mpp_ptr->descr[0].page_code = 0x3f;
9953         mpp_ptr->descr[0].subpage_code = 0xff;
9954         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9955
9956         ctl_set_success(ctsio);
9957         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9958         ctsio->be_move_done = ctl_config_move_done;
9959         ctl_datamove((union ctl_io *)ctsio);
9960         return (CTL_RETVAL_COMPLETE);
9961 }
9962
9963 /*
9964  * SCSI VPD page 0x83, the Device Identification page.
9965  */
9966 static int
9967 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9968 {
9969         struct scsi_vpd_device_id *devid_ptr;
9970         struct scsi_vpd_id_descriptor *desc;
9971         struct ctl_softc *softc;
9972         struct ctl_lun *lun;
9973         struct ctl_port *port;
9974         int data_len;
9975         uint8_t proto;
9976
9977         softc = control_softc;
9978
9979         port = softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9980         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9981
9982         data_len = sizeof(struct scsi_vpd_device_id) +
9983             sizeof(struct scsi_vpd_id_descriptor) +
9984                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9985             sizeof(struct scsi_vpd_id_descriptor) +
9986                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9987         if (lun && lun->lun_devid)
9988                 data_len += lun->lun_devid->len;
9989         if (port->port_devid)
9990                 data_len += port->port_devid->len;
9991         if (port->target_devid)
9992                 data_len += port->target_devid->len;
9993
9994         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9995         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9996         ctsio->kern_sg_entries = 0;
9997
9998         if (data_len < alloc_len) {
9999                 ctsio->residual = alloc_len - data_len;
10000                 ctsio->kern_data_len = data_len;
10001                 ctsio->kern_total_len = data_len;
10002         } else {
10003                 ctsio->residual = 0;
10004                 ctsio->kern_data_len = alloc_len;
10005                 ctsio->kern_total_len = alloc_len;
10006         }
10007         ctsio->kern_data_resid = 0;
10008         ctsio->kern_rel_offset = 0;
10009         ctsio->kern_sg_entries = 0;
10010
10011         /*
10012          * The control device is always connected.  The disk device, on the
10013          * other hand, may not be online all the time.
10014          */
10015         if (lun != NULL)
10016                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10017                                      lun->be_lun->lun_type;
10018         else
10019                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10020         devid_ptr->page_code = SVPD_DEVICE_ID;
10021         scsi_ulto2b(data_len - 4, devid_ptr->length);
10022
10023         if (port->port_type == CTL_PORT_FC)
10024                 proto = SCSI_PROTO_FC << 4;
10025         else if (port->port_type == CTL_PORT_ISCSI)
10026                 proto = SCSI_PROTO_ISCSI << 4;
10027         else
10028                 proto = SCSI_PROTO_SPI << 4;
10029         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
10030
10031         /*
10032          * We're using a LUN association here.  i.e., this device ID is a
10033          * per-LUN identifier.
10034          */
10035         if (lun && lun->lun_devid) {
10036                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
10037                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10038                     lun->lun_devid->len);
10039         }
10040
10041         /*
10042          * This is for the WWPN which is a port association.
10043          */
10044         if (port->port_devid) {
10045                 memcpy(desc, port->port_devid->data, port->port_devid->len);
10046                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10047                     port->port_devid->len);
10048         }
10049
10050         /*
10051          * This is for the Relative Target Port(type 4h) identifier
10052          */
10053         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10054         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10055             SVPD_ID_TYPE_RELTARG;
10056         desc->length = 4;
10057         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
10058         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10059             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
10060
10061         /*
10062          * This is for the Target Port Group(type 5h) identifier
10063          */
10064         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10065         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10066             SVPD_ID_TYPE_TPORTGRP;
10067         desc->length = 4;
10068         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
10069             &desc->identifier[2]);
10070         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10071             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
10072
10073         /*
10074          * This is for the Target identifier
10075          */
10076         if (port->target_devid) {
10077                 memcpy(desc, port->target_devid->data, port->target_devid->len);
10078         }
10079
10080         ctl_set_success(ctsio);
10081         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10082         ctsio->be_move_done = ctl_config_move_done;
10083         ctl_datamove((union ctl_io *)ctsio);
10084         return (CTL_RETVAL_COMPLETE);
10085 }
10086
10087 static int
10088 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
10089 {
10090         struct ctl_softc *softc = control_softc;
10091         struct scsi_vpd_scsi_ports *sp;
10092         struct scsi_vpd_port_designation *pd;
10093         struct scsi_vpd_port_designation_cont *pdc;
10094         struct ctl_lun *lun;
10095         struct ctl_port *port;
10096         int data_len, num_target_ports, iid_len, id_len, g, pg, p;
10097         int num_target_port_groups;
10098
10099         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10100
10101         if (softc->is_single)
10102                 num_target_port_groups = 1;
10103         else
10104                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10105         num_target_ports = 0;
10106         iid_len = 0;
10107         id_len = 0;
10108         mtx_lock(&softc->ctl_lock);
10109         STAILQ_FOREACH(port, &softc->port_list, links) {
10110                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10111                         continue;
10112                 if (lun != NULL &&
10113                     ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
10114                         continue;
10115                 num_target_ports++;
10116                 if (port->init_devid)
10117                         iid_len += port->init_devid->len;
10118                 if (port->port_devid)
10119                         id_len += port->port_devid->len;
10120         }
10121         mtx_unlock(&softc->ctl_lock);
10122
10123         data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10124             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10125              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10126         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10127         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10128         ctsio->kern_sg_entries = 0;
10129
10130         if (data_len < alloc_len) {
10131                 ctsio->residual = alloc_len - data_len;
10132                 ctsio->kern_data_len = data_len;
10133                 ctsio->kern_total_len = data_len;
10134         } else {
10135                 ctsio->residual = 0;
10136                 ctsio->kern_data_len = alloc_len;
10137                 ctsio->kern_total_len = alloc_len;
10138         }
10139         ctsio->kern_data_resid = 0;
10140         ctsio->kern_rel_offset = 0;
10141         ctsio->kern_sg_entries = 0;
10142
10143         /*
10144          * The control device is always connected.  The disk device, on the
10145          * other hand, may not be online all the time.  Need to change this
10146          * to figure out whether the disk device is actually online or not.
10147          */
10148         if (lun != NULL)
10149                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10150                                   lun->be_lun->lun_type;
10151         else
10152                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10153
10154         sp->page_code = SVPD_SCSI_PORTS;
10155         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10156             sp->page_length);
10157         pd = &sp->design[0];
10158
10159         mtx_lock(&softc->ctl_lock);
10160         pg = softc->port_offset / CTL_MAX_PORTS;
10161         for (g = 0; g < num_target_port_groups; g++) {
10162                 STAILQ_FOREACH(port, &softc->port_list, links) {
10163                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10164                                 continue;
10165                         if (lun != NULL &&
10166                             ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
10167                                 continue;
10168                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10169                         scsi_ulto2b(p, pd->relative_port_id);
10170                         if (port->init_devid && g == pg) {
10171                                 iid_len = port->init_devid->len;
10172                                 memcpy(pd->initiator_transportid,
10173                                     port->init_devid->data, port->init_devid->len);
10174                         } else
10175                                 iid_len = 0;
10176                         scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10177                         pdc = (struct scsi_vpd_port_designation_cont *)
10178                             (&pd->initiator_transportid[iid_len]);
10179                         if (port->port_devid && g == pg) {
10180                                 id_len = port->port_devid->len;
10181                                 memcpy(pdc->target_port_descriptors,
10182                                     port->port_devid->data, port->port_devid->len);
10183                         } else
10184                                 id_len = 0;
10185                         scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10186                         pd = (struct scsi_vpd_port_designation *)
10187                             ((uint8_t *)pdc->target_port_descriptors + id_len);
10188                 }
10189         }
10190         mtx_unlock(&softc->ctl_lock);
10191
10192         ctl_set_success(ctsio);
10193         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10194         ctsio->be_move_done = ctl_config_move_done;
10195         ctl_datamove((union ctl_io *)ctsio);
10196         return (CTL_RETVAL_COMPLETE);
10197 }
10198
10199 static int
10200 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10201 {
10202         struct scsi_vpd_block_limits *bl_ptr;
10203         struct ctl_lun *lun;
10204         int bs;
10205
10206         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10207
10208         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10209         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10210         ctsio->kern_sg_entries = 0;
10211
10212         if (sizeof(*bl_ptr) < alloc_len) {
10213                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
10214                 ctsio->kern_data_len = sizeof(*bl_ptr);
10215                 ctsio->kern_total_len = sizeof(*bl_ptr);
10216         } else {
10217                 ctsio->residual = 0;
10218                 ctsio->kern_data_len = alloc_len;
10219                 ctsio->kern_total_len = alloc_len;
10220         }
10221         ctsio->kern_data_resid = 0;
10222         ctsio->kern_rel_offset = 0;
10223         ctsio->kern_sg_entries = 0;
10224
10225         /*
10226          * The control device is always connected.  The disk device, on the
10227          * other hand, may not be online all the time.  Need to change this
10228          * to figure out whether the disk device is actually online or not.
10229          */
10230         if (lun != NULL)
10231                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10232                                   lun->be_lun->lun_type;
10233         else
10234                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10235
10236         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10237         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10238         bl_ptr->max_cmp_write_len = 0xff;
10239         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10240         if (lun != NULL) {
10241                 bs = lun->be_lun->blocksize;
10242                 scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
10243                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10244                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10245                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10246                         if (lun->be_lun->ublockexp != 0) {
10247                                 scsi_ulto4b((1 << lun->be_lun->ublockexp),
10248                                     bl_ptr->opt_unmap_grain);
10249                                 scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
10250                                     bl_ptr->unmap_grain_align);
10251                         }
10252                 }
10253                 scsi_ulto4b(lun->be_lun->atomicblock,
10254                     bl_ptr->max_atomic_transfer_length);
10255                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
10256                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10257         }
10258         scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10259
10260         ctl_set_success(ctsio);
10261         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10262         ctsio->be_move_done = ctl_config_move_done;
10263         ctl_datamove((union ctl_io *)ctsio);
10264         return (CTL_RETVAL_COMPLETE);
10265 }
10266
10267 static int
10268 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10269 {
10270         struct scsi_vpd_block_device_characteristics *bdc_ptr;
10271         struct ctl_lun *lun;
10272         const char *value;
10273         u_int i;
10274
10275         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10276
10277         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10278         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10279         ctsio->kern_sg_entries = 0;
10280
10281         if (sizeof(*bdc_ptr) < alloc_len) {
10282                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10283                 ctsio->kern_data_len = sizeof(*bdc_ptr);
10284                 ctsio->kern_total_len = sizeof(*bdc_ptr);
10285         } else {
10286                 ctsio->residual = 0;
10287                 ctsio->kern_data_len = alloc_len;
10288                 ctsio->kern_total_len = alloc_len;
10289         }
10290         ctsio->kern_data_resid = 0;
10291         ctsio->kern_rel_offset = 0;
10292         ctsio->kern_sg_entries = 0;
10293
10294         /*
10295          * The control device is always connected.  The disk device, on the
10296          * other hand, may not be online all the time.  Need to change this
10297          * to figure out whether the disk device is actually online or not.
10298          */
10299         if (lun != NULL)
10300                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10301                                   lun->be_lun->lun_type;
10302         else
10303                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10304         bdc_ptr->page_code = SVPD_BDC;
10305         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10306         if (lun != NULL &&
10307             (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10308                 i = strtol(value, NULL, 0);
10309         else
10310                 i = CTL_DEFAULT_ROTATION_RATE;
10311         scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10312         if (lun != NULL &&
10313             (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10314                 i = strtol(value, NULL, 0);
10315         else
10316                 i = 0;
10317         bdc_ptr->wab_wac_ff = (i & 0x0f);
10318         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10319
10320         ctl_set_success(ctsio);
10321         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10322         ctsio->be_move_done = ctl_config_move_done;
10323         ctl_datamove((union ctl_io *)ctsio);
10324         return (CTL_RETVAL_COMPLETE);
10325 }
10326
10327 static int
10328 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10329 {
10330         struct scsi_vpd_logical_block_prov *lbp_ptr;
10331         struct ctl_lun *lun;
10332
10333         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10334
10335         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10336         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10337         ctsio->kern_sg_entries = 0;
10338
10339         if (sizeof(*lbp_ptr) < alloc_len) {
10340                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10341                 ctsio->kern_data_len = sizeof(*lbp_ptr);
10342                 ctsio->kern_total_len = sizeof(*lbp_ptr);
10343         } else {
10344                 ctsio->residual = 0;
10345                 ctsio->kern_data_len = alloc_len;
10346                 ctsio->kern_total_len = alloc_len;
10347         }
10348         ctsio->kern_data_resid = 0;
10349         ctsio->kern_rel_offset = 0;
10350         ctsio->kern_sg_entries = 0;
10351
10352         /*
10353          * The control device is always connected.  The disk device, on the
10354          * other hand, may not be online all the time.  Need to change this
10355          * to figure out whether the disk device is actually online or not.
10356          */
10357         if (lun != NULL)
10358                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10359                                   lun->be_lun->lun_type;
10360         else
10361                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10362
10363         lbp_ptr->page_code = SVPD_LBP;
10364         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10365         lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10366         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10367                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10368                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10369                 lbp_ptr->prov_type = SVPD_LBP_THIN;
10370         }
10371
10372         ctl_set_success(ctsio);
10373         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10374         ctsio->be_move_done = ctl_config_move_done;
10375         ctl_datamove((union ctl_io *)ctsio);
10376         return (CTL_RETVAL_COMPLETE);
10377 }
10378
10379 /*
10380  * INQUIRY with the EVPD bit set.
10381  */
10382 static int
10383 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10384 {
10385         struct ctl_lun *lun;
10386         struct scsi_inquiry *cdb;
10387         int alloc_len, retval;
10388
10389         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10390         cdb = (struct scsi_inquiry *)ctsio->cdb;
10391         alloc_len = scsi_2btoul(cdb->length);
10392
10393         switch (cdb->page_code) {
10394         case SVPD_SUPPORTED_PAGES:
10395                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10396                 break;
10397         case SVPD_UNIT_SERIAL_NUMBER:
10398                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10399                 break;
10400         case SVPD_DEVICE_ID:
10401                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10402                 break;
10403         case SVPD_EXTENDED_INQUIRY_DATA:
10404                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10405                 break;
10406         case SVPD_MODE_PAGE_POLICY:
10407                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10408                 break;
10409         case SVPD_SCSI_PORTS:
10410                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10411                 break;
10412         case SVPD_SCSI_TPC:
10413                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10414                 break;
10415         case SVPD_BLOCK_LIMITS:
10416                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10417                         goto err;
10418                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10419                 break;
10420         case SVPD_BDC:
10421                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10422                         goto err;
10423                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10424                 break;
10425         case SVPD_LBP:
10426                 if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10427                         goto err;
10428                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10429                 break;
10430         default:
10431 err:
10432                 ctl_set_invalid_field(ctsio,
10433                                       /*sks_valid*/ 1,
10434                                       /*command*/ 1,
10435                                       /*field*/ 2,
10436                                       /*bit_valid*/ 0,
10437                                       /*bit*/ 0);
10438                 ctl_done((union ctl_io *)ctsio);
10439                 retval = CTL_RETVAL_COMPLETE;
10440                 break;
10441         }
10442
10443         return (retval);
10444 }
10445
10446 /*
10447  * Standard INQUIRY data.
10448  */
10449 static int
10450 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10451 {
10452         struct scsi_inquiry_data *inq_ptr;
10453         struct scsi_inquiry *cdb;
10454         struct ctl_softc *softc;
10455         struct ctl_lun *lun;
10456         char *val;
10457         uint32_t alloc_len, data_len;
10458         ctl_port_type port_type;
10459
10460         softc = control_softc;
10461
10462         /*
10463          * Figure out whether we're talking to a Fibre Channel port or not.
10464          * We treat the ioctl front end, and any SCSI adapters, as packetized
10465          * SCSI front ends.
10466          */
10467         port_type = softc->ctl_ports[
10468             ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10469         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10470                 port_type = CTL_PORT_SCSI;
10471
10472         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10473         cdb = (struct scsi_inquiry *)ctsio->cdb;
10474         alloc_len = scsi_2btoul(cdb->length);
10475
10476         /*
10477          * We malloc the full inquiry data size here and fill it
10478          * in.  If the user only asks for less, we'll give him
10479          * that much.
10480          */
10481         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10482         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10483         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10484         ctsio->kern_sg_entries = 0;
10485         ctsio->kern_data_resid = 0;
10486         ctsio->kern_rel_offset = 0;
10487
10488         if (data_len < alloc_len) {
10489                 ctsio->residual = alloc_len - data_len;
10490                 ctsio->kern_data_len = data_len;
10491                 ctsio->kern_total_len = data_len;
10492         } else {
10493                 ctsio->residual = 0;
10494                 ctsio->kern_data_len = alloc_len;
10495                 ctsio->kern_total_len = alloc_len;
10496         }
10497
10498         /*
10499          * If we have a LUN configured, report it as connected.  Otherwise,
10500          * report that it is offline or no device is supported, depending 
10501          * on the value of inquiry_pq_no_lun.
10502          *
10503          * According to the spec (SPC-4 r34), the peripheral qualifier
10504          * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10505          *
10506          * "A peripheral device having the specified peripheral device type 
10507          * is not connected to this logical unit. However, the device
10508          * server is capable of supporting the specified peripheral device
10509          * type on this logical unit."
10510          *
10511          * According to the same spec, the peripheral qualifier
10512          * SID_QUAL_BAD_LU (011b) is used in this scenario:
10513          *
10514          * "The device server is not capable of supporting a peripheral
10515          * device on this logical unit. For this peripheral qualifier the
10516          * peripheral device type shall be set to 1Fh. All other peripheral
10517          * device type values are reserved for this peripheral qualifier."
10518          *
10519          * Given the text, it would seem that we probably want to report that
10520          * the LUN is offline here.  There is no LUN connected, but we can
10521          * support a LUN at the given LUN number.
10522          *
10523          * In the real world, though, it sounds like things are a little
10524          * different:
10525          *
10526          * - Linux, when presented with a LUN with the offline peripheral
10527          *   qualifier, will create an sg driver instance for it.  So when
10528          *   you attach it to CTL, you wind up with a ton of sg driver
10529          *   instances.  (One for every LUN that Linux bothered to probe.)
10530          *   Linux does this despite the fact that it issues a REPORT LUNs
10531          *   to LUN 0 to get the inventory of supported LUNs.
10532          *
10533          * - There is other anecdotal evidence (from Emulex folks) about
10534          *   arrays that use the offline peripheral qualifier for LUNs that
10535          *   are on the "passive" path in an active/passive array.
10536          *
10537          * So the solution is provide a hopefully reasonable default
10538          * (return bad/no LUN) and allow the user to change the behavior
10539          * with a tunable/sysctl variable.
10540          */
10541         if (lun != NULL)
10542                 inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10543                                   lun->be_lun->lun_type;
10544         else if (softc->inquiry_pq_no_lun == 0)
10545                 inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10546         else
10547                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10548
10549         /* RMB in byte 2 is 0 */
10550         inq_ptr->version = SCSI_REV_SPC4;
10551
10552         /*
10553          * According to SAM-3, even if a device only supports a single
10554          * level of LUN addressing, it should still set the HISUP bit:
10555          *
10556          * 4.9.1 Logical unit numbers overview
10557          *
10558          * All logical unit number formats described in this standard are
10559          * hierarchical in structure even when only a single level in that
10560          * hierarchy is used. The HISUP bit shall be set to one in the
10561          * standard INQUIRY data (see SPC-2) when any logical unit number
10562          * format described in this standard is used.  Non-hierarchical
10563          * formats are outside the scope of this standard.
10564          *
10565          * Therefore we set the HiSup bit here.
10566          *
10567          * The reponse format is 2, per SPC-3.
10568          */
10569         inq_ptr->response_format = SID_HiSup | 2;
10570
10571         inq_ptr->additional_length = data_len -
10572             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10573         CTL_DEBUG_PRINT(("additional_length = %d\n",
10574                          inq_ptr->additional_length));
10575
10576         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10577         /* 16 bit addressing */
10578         if (port_type == CTL_PORT_SCSI)
10579                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10580         /* XXX set the SID_MultiP bit here if we're actually going to
10581            respond on multiple ports */
10582         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10583
10584         /* 16 bit data bus, synchronous transfers */
10585         if (port_type == CTL_PORT_SCSI)
10586                 inq_ptr->flags = SID_WBus16 | SID_Sync;
10587         /*
10588          * XXX KDM do we want to support tagged queueing on the control
10589          * device at all?
10590          */
10591         if ((lun == NULL)
10592          || (lun->be_lun->lun_type != T_PROCESSOR))
10593                 inq_ptr->flags |= SID_CmdQue;
10594         /*
10595          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10596          * We have 8 bytes for the vendor name, and 16 bytes for the device
10597          * name and 4 bytes for the revision.
10598          */
10599         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10600             "vendor")) == NULL) {
10601                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10602         } else {
10603                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10604                 strncpy(inq_ptr->vendor, val,
10605                     min(sizeof(inq_ptr->vendor), strlen(val)));
10606         }
10607         if (lun == NULL) {
10608                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10609                     sizeof(inq_ptr->product));
10610         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10611                 switch (lun->be_lun->lun_type) {
10612                 case T_DIRECT:
10613                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10614                             sizeof(inq_ptr->product));
10615                         break;
10616                 case T_PROCESSOR:
10617                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10618                             sizeof(inq_ptr->product));
10619                         break;
10620                 default:
10621                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10622                             sizeof(inq_ptr->product));
10623                         break;
10624                 }
10625         } else {
10626                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10627                 strncpy(inq_ptr->product, val,
10628                     min(sizeof(inq_ptr->product), strlen(val)));
10629         }
10630
10631         /*
10632          * XXX make this a macro somewhere so it automatically gets
10633          * incremented when we make changes.
10634          */
10635         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10636             "revision")) == NULL) {
10637                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10638         } else {
10639                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10640                 strncpy(inq_ptr->revision, val,
10641                     min(sizeof(inq_ptr->revision), strlen(val)));
10642         }
10643
10644         /*
10645          * For parallel SCSI, we support double transition and single
10646          * transition clocking.  We also support QAS (Quick Arbitration
10647          * and Selection) and Information Unit transfers on both the
10648          * control and array devices.
10649          */
10650         if (port_type == CTL_PORT_SCSI)
10651                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10652                                     SID_SPI_IUS;
10653
10654         /* SAM-5 (no version claimed) */
10655         scsi_ulto2b(0x00A0, inq_ptr->version1);
10656         /* SPC-4 (no version claimed) */
10657         scsi_ulto2b(0x0460, inq_ptr->version2);
10658         if (port_type == CTL_PORT_FC) {
10659                 /* FCP-2 ANSI INCITS.350:2003 */
10660                 scsi_ulto2b(0x0917, inq_ptr->version3);
10661         } else if (port_type == CTL_PORT_SCSI) {
10662                 /* SPI-4 ANSI INCITS.362:200x */
10663                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10664         } else if (port_type == CTL_PORT_ISCSI) {
10665                 /* iSCSI (no version claimed) */
10666                 scsi_ulto2b(0x0960, inq_ptr->version3);
10667         } else if (port_type == CTL_PORT_SAS) {
10668                 /* SAS (no version claimed) */
10669                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10670         }
10671
10672         if (lun == NULL) {
10673                 /* SBC-4 (no version claimed) */
10674                 scsi_ulto2b(0x0600, inq_ptr->version4);
10675         } else {
10676                 switch (lun->be_lun->lun_type) {
10677                 case T_DIRECT:
10678                         /* SBC-4 (no version claimed) */
10679                         scsi_ulto2b(0x0600, inq_ptr->version4);
10680                         break;
10681                 case T_PROCESSOR:
10682                 default:
10683                         break;
10684                 }
10685         }
10686
10687         ctl_set_success(ctsio);
10688         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10689         ctsio->be_move_done = ctl_config_move_done;
10690         ctl_datamove((union ctl_io *)ctsio);
10691         return (CTL_RETVAL_COMPLETE);
10692 }
10693
10694 int
10695 ctl_inquiry(struct ctl_scsiio *ctsio)
10696 {
10697         struct scsi_inquiry *cdb;
10698         int retval;
10699
10700         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10701
10702         cdb = (struct scsi_inquiry *)ctsio->cdb;
10703         if (cdb->byte2 & SI_EVPD)
10704                 retval = ctl_inquiry_evpd(ctsio);
10705         else if (cdb->page_code == 0)
10706                 retval = ctl_inquiry_std(ctsio);
10707         else {
10708                 ctl_set_invalid_field(ctsio,
10709                                       /*sks_valid*/ 1,
10710                                       /*command*/ 1,
10711                                       /*field*/ 2,
10712                                       /*bit_valid*/ 0,
10713                                       /*bit*/ 0);
10714                 ctl_done((union ctl_io *)ctsio);
10715                 return (CTL_RETVAL_COMPLETE);
10716         }
10717
10718         return (retval);
10719 }
10720
10721 /*
10722  * For known CDB types, parse the LBA and length.
10723  */
10724 static int
10725 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10726 {
10727         if (io->io_hdr.io_type != CTL_IO_SCSI)
10728                 return (1);
10729
10730         switch (io->scsiio.cdb[0]) {
10731         case COMPARE_AND_WRITE: {
10732                 struct scsi_compare_and_write *cdb;
10733
10734                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10735
10736                 *lba = scsi_8btou64(cdb->addr);
10737                 *len = cdb->length;
10738                 break;
10739         }
10740         case READ_6:
10741         case WRITE_6: {
10742                 struct scsi_rw_6 *cdb;
10743
10744                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10745
10746                 *lba = scsi_3btoul(cdb->addr);
10747                 /* only 5 bits are valid in the most significant address byte */
10748                 *lba &= 0x1fffff;
10749                 *len = cdb->length;
10750                 break;
10751         }
10752         case READ_10:
10753         case WRITE_10: {
10754                 struct scsi_rw_10 *cdb;
10755
10756                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10757
10758                 *lba = scsi_4btoul(cdb->addr);
10759                 *len = scsi_2btoul(cdb->length);
10760                 break;
10761         }
10762         case WRITE_VERIFY_10: {
10763                 struct scsi_write_verify_10 *cdb;
10764
10765                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10766
10767                 *lba = scsi_4btoul(cdb->addr);
10768                 *len = scsi_2btoul(cdb->length);
10769                 break;
10770         }
10771         case READ_12:
10772         case WRITE_12: {
10773                 struct scsi_rw_12 *cdb;
10774
10775                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10776
10777                 *lba = scsi_4btoul(cdb->addr);
10778                 *len = scsi_4btoul(cdb->length);
10779                 break;
10780         }
10781         case WRITE_VERIFY_12: {
10782                 struct scsi_write_verify_12 *cdb;
10783
10784                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10785
10786                 *lba = scsi_4btoul(cdb->addr);
10787                 *len = scsi_4btoul(cdb->length);
10788                 break;
10789         }
10790         case READ_16:
10791         case WRITE_16:
10792         case WRITE_ATOMIC_16: {
10793                 struct scsi_rw_16 *cdb;
10794
10795                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10796
10797                 *lba = scsi_8btou64(cdb->addr);
10798                 *len = scsi_4btoul(cdb->length);
10799                 break;
10800         }
10801         case WRITE_VERIFY_16: {
10802                 struct scsi_write_verify_16 *cdb;
10803
10804                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10805
10806                 *lba = scsi_8btou64(cdb->addr);
10807                 *len = scsi_4btoul(cdb->length);
10808                 break;
10809         }
10810         case WRITE_SAME_10: {
10811                 struct scsi_write_same_10 *cdb;
10812
10813                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10814
10815                 *lba = scsi_4btoul(cdb->addr);
10816                 *len = scsi_2btoul(cdb->length);
10817                 break;
10818         }
10819         case WRITE_SAME_16: {
10820                 struct scsi_write_same_16 *cdb;
10821
10822                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10823
10824                 *lba = scsi_8btou64(cdb->addr);
10825                 *len = scsi_4btoul(cdb->length);
10826                 break;
10827         }
10828         case VERIFY_10: {
10829                 struct scsi_verify_10 *cdb;
10830
10831                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10832
10833                 *lba = scsi_4btoul(cdb->addr);
10834                 *len = scsi_2btoul(cdb->length);
10835                 break;
10836         }
10837         case VERIFY_12: {
10838                 struct scsi_verify_12 *cdb;
10839
10840                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10841
10842                 *lba = scsi_4btoul(cdb->addr);
10843                 *len = scsi_4btoul(cdb->length);
10844                 break;
10845         }
10846         case VERIFY_16: {
10847                 struct scsi_verify_16 *cdb;
10848
10849                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10850
10851                 *lba = scsi_8btou64(cdb->addr);
10852                 *len = scsi_4btoul(cdb->length);
10853                 break;
10854         }
10855         case UNMAP: {
10856                 *lba = 0;
10857                 *len = UINT64_MAX;
10858                 break;
10859         }
10860         case SERVICE_ACTION_IN: {       /* GET LBA STATUS */
10861                 struct scsi_get_lba_status *cdb;
10862
10863                 cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10864                 *lba = scsi_8btou64(cdb->addr);
10865                 *len = UINT32_MAX;
10866                 break;
10867         }
10868         default:
10869                 return (1);
10870                 break; /* NOTREACHED */
10871         }
10872
10873         return (0);
10874 }
10875
10876 static ctl_action
10877 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10878     bool seq)
10879 {
10880         uint64_t endlba1, endlba2;
10881
10882         endlba1 = lba1 + len1 - (seq ? 0 : 1);
10883         endlba2 = lba2 + len2 - 1;
10884
10885         if ((endlba1 < lba2) || (endlba2 < lba1))
10886                 return (CTL_ACTION_PASS);
10887         else
10888                 return (CTL_ACTION_BLOCK);
10889 }
10890
10891 static int
10892 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10893 {
10894         struct ctl_ptr_len_flags *ptrlen;
10895         struct scsi_unmap_desc *buf, *end, *range;
10896         uint64_t lba;
10897         uint32_t len;
10898
10899         /* If not UNMAP -- go other way. */
10900         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10901             io->scsiio.cdb[0] != UNMAP)
10902                 return (CTL_ACTION_ERROR);
10903
10904         /* If UNMAP without data -- block and wait for data. */
10905         ptrlen = (struct ctl_ptr_len_flags *)
10906             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10907         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10908             ptrlen->ptr == NULL)
10909                 return (CTL_ACTION_BLOCK);
10910
10911         /* UNMAP with data -- check for collision. */
10912         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10913         end = buf + ptrlen->len / sizeof(*buf);
10914         for (range = buf; range < end; range++) {
10915                 lba = scsi_8btou64(range->lba);
10916                 len = scsi_4btoul(range->length);
10917                 if ((lba < lba2 + len2) && (lba + len > lba2))
10918                         return (CTL_ACTION_BLOCK);
10919         }
10920         return (CTL_ACTION_PASS);
10921 }
10922
10923 static ctl_action
10924 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10925 {
10926         uint64_t lba1, lba2;
10927         uint64_t len1, len2;
10928         int retval;
10929
10930         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10931                 return (CTL_ACTION_ERROR);
10932
10933         retval = ctl_extent_check_unmap(io1, lba2, len2);
10934         if (retval != CTL_ACTION_ERROR)
10935                 return (retval);
10936
10937         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10938                 return (CTL_ACTION_ERROR);
10939
10940         return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10941 }
10942
10943 static ctl_action
10944 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10945 {
10946         uint64_t lba1, lba2;
10947         uint64_t len1, len2;
10948
10949         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10950                 return (CTL_ACTION_ERROR);
10951         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10952                 return (CTL_ACTION_ERROR);
10953
10954         if (lba1 + len1 == lba2)
10955                 return (CTL_ACTION_BLOCK);
10956         return (CTL_ACTION_PASS);
10957 }
10958
10959 static ctl_action
10960 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10961     union ctl_io *ooa_io)
10962 {
10963         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10964         ctl_serialize_action *serialize_row;
10965
10966         /*
10967          * The initiator attempted multiple untagged commands at the same
10968          * time.  Can't do that.
10969          */
10970         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10971          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10972          && ((pending_io->io_hdr.nexus.targ_port ==
10973               ooa_io->io_hdr.nexus.targ_port)
10974           && (pending_io->io_hdr.nexus.initid.id ==
10975               ooa_io->io_hdr.nexus.initid.id))
10976          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10977               CTL_FLAG_STATUS_SENT)) == 0))
10978                 return (CTL_ACTION_OVERLAP);
10979
10980         /*
10981          * The initiator attempted to send multiple tagged commands with
10982          * the same ID.  (It's fine if different initiators have the same
10983          * tag ID.)
10984          *
10985          * Even if all of those conditions are true, we don't kill the I/O
10986          * if the command ahead of us has been aborted.  We won't end up
10987          * sending it to the FETD, and it's perfectly legal to resend a
10988          * command with the same tag number as long as the previous
10989          * instance of this tag number has been aborted somehow.
10990          */
10991         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10992          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10993          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10994          && ((pending_io->io_hdr.nexus.targ_port ==
10995               ooa_io->io_hdr.nexus.targ_port)
10996           && (pending_io->io_hdr.nexus.initid.id ==
10997               ooa_io->io_hdr.nexus.initid.id))
10998          && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10999               CTL_FLAG_STATUS_SENT)) == 0))
11000                 return (CTL_ACTION_OVERLAP_TAG);
11001
11002         /*
11003          * If we get a head of queue tag, SAM-3 says that we should
11004          * immediately execute it.
11005          *
11006          * What happens if this command would normally block for some other
11007          * reason?  e.g. a request sense with a head of queue tag
11008          * immediately after a write.  Normally that would block, but this
11009          * will result in its getting executed immediately...
11010          *
11011          * We currently return "pass" instead of "skip", so we'll end up
11012          * going through the rest of the queue to check for overlapped tags.
11013          *
11014          * XXX KDM check for other types of blockage first??
11015          */
11016         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11017                 return (CTL_ACTION_PASS);
11018
11019         /*
11020          * Ordered tags have to block until all items ahead of them
11021          * have completed.  If we get called with an ordered tag, we always
11022          * block, if something else is ahead of us in the queue.
11023          */
11024         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11025                 return (CTL_ACTION_BLOCK);
11026
11027         /*
11028          * Simple tags get blocked until all head of queue and ordered tags
11029          * ahead of them have completed.  I'm lumping untagged commands in
11030          * with simple tags here.  XXX KDM is that the right thing to do?
11031          */
11032         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11033           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11034          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11035           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11036                 return (CTL_ACTION_BLOCK);
11037
11038         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11039         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11040
11041         serialize_row = ctl_serialize_table[ooa_entry->seridx];
11042
11043         switch (serialize_row[pending_entry->seridx]) {
11044         case CTL_SER_BLOCK:
11045                 return (CTL_ACTION_BLOCK);
11046         case CTL_SER_EXTENT:
11047                 return (ctl_extent_check(ooa_io, pending_io,
11048                     (lun->serseq == CTL_LUN_SERSEQ_ON)));
11049         case CTL_SER_EXTENTOPT:
11050                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11051                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11052                         return (ctl_extent_check(ooa_io, pending_io,
11053                             (lun->serseq == CTL_LUN_SERSEQ_ON)));
11054                 return (CTL_ACTION_PASS);
11055         case CTL_SER_EXTENTSEQ:
11056                 if (lun->serseq != CTL_LUN_SERSEQ_OFF)
11057                         return (ctl_extent_check_seq(ooa_io, pending_io));
11058                 return (CTL_ACTION_PASS);
11059         case CTL_SER_PASS:
11060                 return (CTL_ACTION_PASS);
11061         case CTL_SER_BLOCKOPT:
11062                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11063                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11064                         return (CTL_ACTION_BLOCK);
11065                 return (CTL_ACTION_PASS);
11066         case CTL_SER_SKIP:
11067                 return (CTL_ACTION_SKIP);
11068         default:
11069                 panic("invalid serialization value %d",
11070                       serialize_row[pending_entry->seridx]);
11071         }
11072
11073         return (CTL_ACTION_ERROR);
11074 }
11075
11076 /*
11077  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11078  * Assumptions:
11079  * - pending_io is generally either incoming, or on the blocked queue
11080  * - starting I/O is the I/O we want to start the check with.
11081  */
11082 static ctl_action
11083 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11084               union ctl_io *starting_io)
11085 {
11086         union ctl_io *ooa_io;
11087         ctl_action action;
11088
11089         mtx_assert(&lun->lun_lock, MA_OWNED);
11090
11091         /*
11092          * Run back along the OOA queue, starting with the current
11093          * blocked I/O and going through every I/O before it on the
11094          * queue.  If starting_io is NULL, we'll just end up returning
11095          * CTL_ACTION_PASS.
11096          */
11097         for (ooa_io = starting_io; ooa_io != NULL;
11098              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11099              ooa_links)){
11100
11101                 /*
11102                  * This routine just checks to see whether
11103                  * cur_blocked is blocked by ooa_io, which is ahead
11104                  * of it in the queue.  It doesn't queue/dequeue
11105                  * cur_blocked.
11106                  */
11107                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11108                 switch (action) {
11109                 case CTL_ACTION_BLOCK:
11110                 case CTL_ACTION_OVERLAP:
11111                 case CTL_ACTION_OVERLAP_TAG:
11112                 case CTL_ACTION_SKIP:
11113                 case CTL_ACTION_ERROR:
11114                         return (action);
11115                         break; /* NOTREACHED */
11116                 case CTL_ACTION_PASS:
11117                         break;
11118                 default:
11119                         panic("invalid action %d", action);
11120                         break;  /* NOTREACHED */
11121                 }
11122         }
11123
11124         return (CTL_ACTION_PASS);
11125 }
11126
11127 /*
11128  * Assumptions:
11129  * - An I/O has just completed, and has been removed from the per-LUN OOA
11130  *   queue, so some items on the blocked queue may now be unblocked.
11131  */
11132 static int
11133 ctl_check_blocked(struct ctl_lun *lun)
11134 {
11135         union ctl_io *cur_blocked, *next_blocked;
11136
11137         mtx_assert(&lun->lun_lock, MA_OWNED);
11138
11139         /*
11140          * Run forward from the head of the blocked queue, checking each
11141          * entry against the I/Os prior to it on the OOA queue to see if
11142          * there is still any blockage.
11143          *
11144          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11145          * with our removing a variable on it while it is traversing the
11146          * list.
11147          */
11148         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11149              cur_blocked != NULL; cur_blocked = next_blocked) {
11150                 union ctl_io *prev_ooa;
11151                 ctl_action action;
11152
11153                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11154                                                           blocked_links);
11155
11156                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11157                                                       ctl_ooaq, ooa_links);
11158
11159                 /*
11160                  * If cur_blocked happens to be the first item in the OOA
11161                  * queue now, prev_ooa will be NULL, and the action
11162                  * returned will just be CTL_ACTION_PASS.
11163                  */
11164                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11165
11166                 switch (action) {
11167                 case CTL_ACTION_BLOCK:
11168                         /* Nothing to do here, still blocked */
11169                         break;
11170                 case CTL_ACTION_OVERLAP:
11171                 case CTL_ACTION_OVERLAP_TAG:
11172                         /*
11173                          * This shouldn't happen!  In theory we've already
11174                          * checked this command for overlap...
11175                          */
11176                         break;
11177                 case CTL_ACTION_PASS:
11178                 case CTL_ACTION_SKIP: {
11179                         const struct ctl_cmd_entry *entry;
11180                         int isc_retval;
11181
11182                         /*
11183                          * The skip case shouldn't happen, this transaction
11184                          * should have never made it onto the blocked queue.
11185                          */
11186                         /*
11187                          * This I/O is no longer blocked, we can remove it
11188                          * from the blocked queue.  Since this is a TAILQ
11189                          * (doubly linked list), we can do O(1) removals
11190                          * from any place on the list.
11191                          */
11192                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11193                                      blocked_links);
11194                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11195
11196                         if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11197                                 /*
11198                                  * Need to send IO back to original side to
11199                                  * run
11200                                  */
11201                                 union ctl_ha_msg msg_info;
11202
11203                                 msg_info.hdr.original_sc =
11204                                         cur_blocked->io_hdr.original_sc;
11205                                 msg_info.hdr.serializing_sc = cur_blocked;
11206                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
11207                                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11208                                      &msg_info, sizeof(msg_info), 0)) >
11209                                      CTL_HA_STATUS_SUCCESS) {
11210                                         printf("CTL:Check Blocked error from "
11211                                                "ctl_ha_msg_send %d\n",
11212                                                isc_retval);
11213                                 }
11214                                 break;
11215                         }
11216                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11217
11218                         /*
11219                          * Check this I/O for LUN state changes that may
11220                          * have happened while this command was blocked.
11221                          * The LUN state may have been changed by a command
11222                          * ahead of us in the queue, so we need to re-check
11223                          * for any states that can be caused by SCSI
11224                          * commands.
11225                          */
11226                         if (ctl_scsiio_lun_check(lun, entry,
11227                                                  &cur_blocked->scsiio) == 0) {
11228                                 cur_blocked->io_hdr.flags |=
11229                                                       CTL_FLAG_IS_WAS_ON_RTR;
11230                                 ctl_enqueue_rtr(cur_blocked);
11231                         } else
11232                                 ctl_done(cur_blocked);
11233                         break;
11234                 }
11235                 default:
11236                         /*
11237                          * This probably shouldn't happen -- we shouldn't
11238                          * get CTL_ACTION_ERROR, or anything else.
11239                          */
11240                         break;
11241                 }
11242         }
11243
11244         return (CTL_RETVAL_COMPLETE);
11245 }
11246
11247 /*
11248  * This routine (with one exception) checks LUN flags that can be set by
11249  * commands ahead of us in the OOA queue.  These flags have to be checked
11250  * when a command initially comes in, and when we pull a command off the
11251  * blocked queue and are preparing to execute it.  The reason we have to
11252  * check these flags for commands on the blocked queue is that the LUN
11253  * state may have been changed by a command ahead of us while we're on the
11254  * blocked queue.
11255  *
11256  * Ordering is somewhat important with these checks, so please pay
11257  * careful attention to the placement of any new checks.
11258  */
11259 static int
11260 ctl_scsiio_lun_check(struct ctl_lun *lun,
11261     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11262 {
11263         struct ctl_softc *softc = lun->ctl_softc;
11264         int retval;
11265         uint32_t residx;
11266
11267         retval = 0;
11268
11269         mtx_assert(&lun->lun_lock, MA_OWNED);
11270
11271         /*
11272          * If this shelf is a secondary shelf controller, we have to reject
11273          * any media access commands.
11274          */
11275         if ((softc->flags & CTL_FLAG_ACTIVE_SHELF) == 0 &&
11276             (entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0) {
11277                 ctl_set_lun_standby(ctsio);
11278                 retval = 1;
11279                 goto bailout;
11280         }
11281
11282         if (entry->pattern & CTL_LUN_PAT_WRITE) {
11283                 if (lun->flags & CTL_LUN_READONLY) {
11284                         ctl_set_sense(ctsio, /*current_error*/ 1,
11285                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11286                             /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11287                         retval = 1;
11288                         goto bailout;
11289                 }
11290                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11291                     .eca_and_aen & SCP_SWP) != 0) {
11292                         ctl_set_sense(ctsio, /*current_error*/ 1,
11293                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11294                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11295                         retval = 1;
11296                         goto bailout;
11297                 }
11298         }
11299
11300         /*
11301          * Check for a reservation conflict.  If this command isn't allowed
11302          * even on reserved LUNs, and if this initiator isn't the one who
11303          * reserved us, reject the command with a reservation conflict.
11304          */
11305         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11306         if ((lun->flags & CTL_LUN_RESERVED)
11307          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11308                 if (lun->res_idx != residx) {
11309                         ctl_set_reservation_conflict(ctsio);
11310                         retval = 1;
11311                         goto bailout;
11312                 }
11313         }
11314
11315         if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11316             (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11317                 /* No reservation or command is allowed. */;
11318         } else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11319             (lun->res_type == SPR_TYPE_WR_EX ||
11320              lun->res_type == SPR_TYPE_WR_EX_RO ||
11321              lun->res_type == SPR_TYPE_WR_EX_AR)) {
11322                 /* The command is allowed for Write Exclusive resv. */;
11323         } else {
11324                 /*
11325                  * if we aren't registered or it's a res holder type
11326                  * reservation and this isn't the res holder then set a
11327                  * conflict.
11328                  */
11329                 if (ctl_get_prkey(lun, residx) == 0
11330                  || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11331                         ctl_set_reservation_conflict(ctsio);
11332                         retval = 1;
11333                         goto bailout;
11334                 }
11335
11336         }
11337
11338         if ((lun->flags & CTL_LUN_OFFLINE)
11339          && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11340                 ctl_set_lun_not_ready(ctsio);
11341                 retval = 1;
11342                 goto bailout;
11343         }
11344
11345         /*
11346          * If the LUN is stopped, see if this particular command is allowed
11347          * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11348          */
11349         if ((lun->flags & CTL_LUN_STOPPED)
11350          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11351                 /* "Logical unit not ready, initializing cmd. required" */
11352                 ctl_set_lun_stopped(ctsio);
11353                 retval = 1;
11354                 goto bailout;
11355         }
11356
11357         if ((lun->flags & CTL_LUN_INOPERABLE)
11358          && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11359                 /* "Medium format corrupted" */
11360                 ctl_set_medium_format_corrupted(ctsio);
11361                 retval = 1;
11362                 goto bailout;
11363         }
11364
11365 bailout:
11366         return (retval);
11367
11368 }
11369
11370 static void
11371 ctl_failover_io(union ctl_io *io, int have_lock)
11372 {
11373         ctl_set_busy(&io->scsiio);
11374         ctl_done(io);
11375 }
11376
11377 #ifdef notyet
11378 static void
11379 ctl_failover(void)
11380 {
11381         struct ctl_lun *lun;
11382         struct ctl_softc *softc;
11383         union ctl_io *next_io, *pending_io;
11384         union ctl_io *io;
11385         int lun_idx;
11386
11387         softc = control_softc;
11388
11389         mtx_lock(&softc->ctl_lock);
11390         /*
11391          * Remove any cmds from the other SC from the rtr queue.  These
11392          * will obviously only be for LUNs for which we're the primary.
11393          * We can't send status or get/send data for these commands.
11394          * Since they haven't been executed yet, we can just remove them.
11395          * We'll either abort them or delete them below, depending on
11396          * which HA mode we're in.
11397          */
11398 #ifdef notyet
11399         mtx_lock(&softc->queue_lock);
11400         for (io = (union ctl_io *)STAILQ_FIRST(&softc->rtr_queue);
11401              io != NULL; io = next_io) {
11402                 next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11403                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11404                         STAILQ_REMOVE(&softc->rtr_queue, &io->io_hdr,
11405                                       ctl_io_hdr, links);
11406         }
11407         mtx_unlock(&softc->queue_lock);
11408 #endif
11409
11410         for (lun_idx=0; lun_idx < softc->num_luns; lun_idx++) {
11411                 lun = softc->ctl_luns[lun_idx];
11412                 if (lun==NULL)
11413                         continue;
11414
11415                 /*
11416                  * Processor LUNs are primary on both sides.
11417                  * XXX will this always be true?
11418                  */
11419                 if (lun->be_lun->lun_type == T_PROCESSOR)
11420                         continue;
11421
11422                 if ((lun->flags & CTL_LUN_PRIMARY_SC)
11423                  && (softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11424                         printf("FAILOVER: primary lun %d\n", lun_idx);
11425                         /*
11426                          * Remove all commands from the other SC. First from the
11427                          * blocked queue then from the ooa queue. Once we have
11428                          * removed them. Call ctl_check_blocked to see if there
11429                          * is anything that can run.
11430                          */
11431                         for (io = (union ctl_io *)TAILQ_FIRST(
11432                              &lun->blocked_queue); io != NULL; io = next_io) {
11433
11434                                 next_io = (union ctl_io *)TAILQ_NEXT(
11435                                     &io->io_hdr, blocked_links);
11436
11437                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11438                                         TAILQ_REMOVE(&lun->blocked_queue,
11439                                                      &io->io_hdr,blocked_links);
11440                                         io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11441                                         TAILQ_REMOVE(&lun->ooa_queue,
11442                                                      &io->io_hdr, ooa_links);
11443
11444                                         ctl_free_io(io);
11445                                 }
11446                         }
11447
11448                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11449                              io != NULL; io = next_io) {
11450
11451                                 next_io = (union ctl_io *)TAILQ_NEXT(
11452                                     &io->io_hdr, ooa_links);
11453
11454                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11455
11456                                         TAILQ_REMOVE(&lun->ooa_queue,
11457                                                 &io->io_hdr,
11458                                                 ooa_links);
11459
11460                                         ctl_free_io(io);
11461                                 }
11462                         }
11463                         ctl_check_blocked(lun);
11464                 } else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11465                         && (softc->ha_mode == CTL_HA_MODE_XFER)) {
11466
11467                         printf("FAILOVER: primary lun %d\n", lun_idx);
11468                         /*
11469                          * Abort all commands from the other SC.  We can't
11470                          * send status back for them now.  These should get
11471                          * cleaned up when they are completed or come out
11472                          * for a datamove operation.
11473                          */
11474                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11475                              io != NULL; io = next_io) {
11476                                 next_io = (union ctl_io *)TAILQ_NEXT(
11477                                         &io->io_hdr, ooa_links);
11478
11479                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11480                                         io->io_hdr.flags |= CTL_FLAG_ABORT;
11481                         }
11482                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11483                         && (softc->ha_mode == CTL_HA_MODE_XFER)) {
11484
11485                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11486
11487                         lun->flags |= CTL_LUN_PRIMARY_SC;
11488
11489                         /*
11490                          * We send all I/O that was sent to this controller
11491                          * and redirected to the other side back with
11492                          * busy status, and have the initiator retry it.
11493                          * Figuring out how much data has been transferred,
11494                          * etc. and picking up where we left off would be 
11495                          * very tricky.
11496                          *
11497                          * XXX KDM need to remove I/O from the blocked
11498                          * queue as well!
11499                          */
11500                         for (pending_io = (union ctl_io *)TAILQ_FIRST(
11501                              &lun->ooa_queue); pending_io != NULL;
11502                              pending_io = next_io) {
11503
11504                                 next_io =  (union ctl_io *)TAILQ_NEXT(
11505                                         &pending_io->io_hdr, ooa_links);
11506
11507                                 pending_io->io_hdr.flags &=
11508                                         ~CTL_FLAG_SENT_2OTHER_SC;
11509
11510                                 if (pending_io->io_hdr.flags &
11511                                     CTL_FLAG_IO_ACTIVE) {
11512                                         pending_io->io_hdr.flags |=
11513                                                 CTL_FLAG_FAILOVER;
11514                                 } else {
11515                                         ctl_set_busy(&pending_io->scsiio);
11516                                         ctl_done(pending_io);
11517                                 }
11518                         }
11519
11520                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11521                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11522                         && (softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11523                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11524                         /*
11525                          * if the first io on the OOA is not on the RtR queue
11526                          * add it.
11527                          */
11528                         lun->flags |= CTL_LUN_PRIMARY_SC;
11529
11530                         pending_io = (union ctl_io *)TAILQ_FIRST(
11531                             &lun->ooa_queue);
11532                         if (pending_io==NULL) {
11533                                 printf("Nothing on OOA queue\n");
11534                                 continue;
11535                         }
11536
11537                         pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11538                         if ((pending_io->io_hdr.flags &
11539                              CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11540                                 pending_io->io_hdr.flags |=
11541                                     CTL_FLAG_IS_WAS_ON_RTR;
11542                                 ctl_enqueue_rtr(pending_io);
11543                         }
11544 #if 0
11545                         else
11546                         {
11547                                 printf("Tag 0x%04x is running\n",
11548                                       pending_io->scsiio.tag_num);
11549                         }
11550 #endif
11551
11552                         next_io = (union ctl_io *)TAILQ_NEXT(
11553                             &pending_io->io_hdr, ooa_links);
11554                         for (pending_io=next_io; pending_io != NULL;
11555                              pending_io = next_io) {
11556                                 pending_io->io_hdr.flags &=
11557                                     ~CTL_FLAG_SENT_2OTHER_SC;
11558                                 next_io = (union ctl_io *)TAILQ_NEXT(
11559                                         &pending_io->io_hdr, ooa_links);
11560                                 if (pending_io->io_hdr.flags &
11561                                     CTL_FLAG_IS_WAS_ON_RTR) {
11562 #if 0
11563                                         printf("Tag 0x%04x is running\n",
11564                                                 pending_io->scsiio.tag_num);
11565 #endif
11566                                         continue;
11567                                 }
11568
11569                                 switch (ctl_check_ooa(lun, pending_io,
11570                                     (union ctl_io *)TAILQ_PREV(
11571                                     &pending_io->io_hdr, ctl_ooaq,
11572                                     ooa_links))) {
11573
11574                                 case CTL_ACTION_BLOCK:
11575                                         TAILQ_INSERT_TAIL(&lun->blocked_queue,
11576                                                           &pending_io->io_hdr,
11577                                                           blocked_links);
11578                                         pending_io->io_hdr.flags |=
11579                                             CTL_FLAG_BLOCKED;
11580                                         break;
11581                                 case CTL_ACTION_PASS:
11582                                 case CTL_ACTION_SKIP:
11583                                         pending_io->io_hdr.flags |=
11584                                             CTL_FLAG_IS_WAS_ON_RTR;
11585                                         ctl_enqueue_rtr(pending_io);
11586                                         break;
11587                                 case CTL_ACTION_OVERLAP:
11588                                         ctl_set_overlapped_cmd(
11589                                             (struct ctl_scsiio *)pending_io);
11590                                         ctl_done(pending_io);
11591                                         break;
11592                                 case CTL_ACTION_OVERLAP_TAG:
11593                                         ctl_set_overlapped_tag(
11594                                             (struct ctl_scsiio *)pending_io,
11595                                             pending_io->scsiio.tag_num & 0xff);
11596                                         ctl_done(pending_io);
11597                                         break;
11598                                 case CTL_ACTION_ERROR:
11599                                 default:
11600                                         ctl_set_internal_failure(
11601                                                 (struct ctl_scsiio *)pending_io,
11602                                                 0,  // sks_valid
11603                                                 0); //retry count
11604                                         ctl_done(pending_io);
11605                                         break;
11606                                 }
11607                         }
11608
11609                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11610                 } else {
11611                         panic("Unhandled HA mode failover, LUN flags = %#x, "
11612                               "ha_mode = #%x", lun->flags, softc->ha_mode);
11613                 }
11614         }
11615         ctl_pause_rtr = 0;
11616         mtx_unlock(&softc->ctl_lock);
11617 }
11618 #endif
11619
11620 static void
11621 ctl_clear_ua(struct ctl_softc *ctl_softc, uint32_t initidx,
11622              ctl_ua_type ua_type)
11623 {
11624         struct ctl_lun *lun;
11625         ctl_ua_type *pu;
11626
11627         mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
11628
11629         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
11630                 mtx_lock(&lun->lun_lock);
11631                 pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
11632                 if (pu != NULL)
11633                         pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua_type;
11634                 mtx_unlock(&lun->lun_lock);
11635         }
11636 }
11637
11638 static int
11639 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11640 {
11641         struct ctl_lun *lun;
11642         const struct ctl_cmd_entry *entry;
11643         uint32_t initidx, targ_lun;
11644         int retval;
11645
11646         retval = 0;
11647
11648         lun = NULL;
11649
11650         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11651         if ((targ_lun < CTL_MAX_LUNS)
11652          && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11653                 /*
11654                  * If the LUN is invalid, pretend that it doesn't exist.
11655                  * It will go away as soon as all pending I/O has been
11656                  * completed.
11657                  */
11658                 mtx_lock(&lun->lun_lock);
11659                 if (lun->flags & CTL_LUN_DISABLED) {
11660                         mtx_unlock(&lun->lun_lock);
11661                         lun = NULL;
11662                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11663                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11664                 } else {
11665                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11666                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11667                                 lun->be_lun;
11668                         if (lun->be_lun->lun_type == T_PROCESSOR) {
11669                                 ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11670                         }
11671
11672                         /*
11673                          * Every I/O goes into the OOA queue for a
11674                          * particular LUN, and stays there until completion.
11675                          */
11676 #ifdef CTL_TIME_IO
11677                         if (TAILQ_EMPTY(&lun->ooa_queue)) {
11678                                 lun->idle_time += getsbinuptime() -
11679                                     lun->last_busy;
11680                         }
11681 #endif
11682                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11683                             ooa_links);
11684                 }
11685         } else {
11686                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11687                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11688         }
11689
11690         /* Get command entry and return error if it is unsuppotyed. */
11691         entry = ctl_validate_command(ctsio);
11692         if (entry == NULL) {
11693                 if (lun)
11694                         mtx_unlock(&lun->lun_lock);
11695                 return (retval);
11696         }
11697
11698         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11699         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11700
11701         /*
11702          * Check to see whether we can send this command to LUNs that don't
11703          * exist.  This should pretty much only be the case for inquiry
11704          * and request sense.  Further checks, below, really require having
11705          * a LUN, so we can't really check the command anymore.  Just put
11706          * it on the rtr queue.
11707          */
11708         if (lun == NULL) {
11709                 if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11710                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11711                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11712                         return (retval);
11713                 }
11714
11715                 ctl_set_unsupported_lun(ctsio);
11716                 ctl_done((union ctl_io *)ctsio);
11717                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11718                 return (retval);
11719         } else {
11720                 /*
11721                  * Make sure we support this particular command on this LUN.
11722                  * e.g., we don't support writes to the control LUN.
11723                  */
11724                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11725                         mtx_unlock(&lun->lun_lock);
11726                         ctl_set_invalid_opcode(ctsio);
11727                         ctl_done((union ctl_io *)ctsio);
11728                         return (retval);
11729                 }
11730         }
11731
11732         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11733
11734 #ifdef CTL_WITH_CA
11735         /*
11736          * If we've got a request sense, it'll clear the contingent
11737          * allegiance condition.  Otherwise, if we have a CA condition for
11738          * this initiator, clear it, because it sent down a command other
11739          * than request sense.
11740          */
11741         if ((ctsio->cdb[0] != REQUEST_SENSE)
11742          && (ctl_is_set(lun->have_ca, initidx)))
11743                 ctl_clear_mask(lun->have_ca, initidx);
11744 #endif
11745
11746         /*
11747          * If the command has this flag set, it handles its own unit
11748          * attention reporting, we shouldn't do anything.  Otherwise we
11749          * check for any pending unit attentions, and send them back to the
11750          * initiator.  We only do this when a command initially comes in,
11751          * not when we pull it off the blocked queue.
11752          *
11753          * According to SAM-3, section 5.3.2, the order that things get
11754          * presented back to the host is basically unit attentions caused
11755          * by some sort of reset event, busy status, reservation conflicts
11756          * or task set full, and finally any other status.
11757          *
11758          * One issue here is that some of the unit attentions we report
11759          * don't fall into the "reset" category (e.g. "reported luns data
11760          * has changed").  So reporting it here, before the reservation
11761          * check, may be technically wrong.  I guess the only thing to do
11762          * would be to check for and report the reset events here, and then
11763          * check for the other unit attention types after we check for a
11764          * reservation conflict.
11765          *
11766          * XXX KDM need to fix this
11767          */
11768         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11769                 ctl_ua_type ua_type;
11770                 scsi_sense_data_type sense_format;
11771
11772                 if (lun->flags & CTL_LUN_SENSE_DESC)
11773                         sense_format = SSD_TYPE_DESC;
11774                 else
11775                         sense_format = SSD_TYPE_FIXED;
11776
11777                 ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11778                     sense_format);
11779                 if (ua_type != CTL_UA_NONE) {
11780                         mtx_unlock(&lun->lun_lock);
11781                         ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11782                         ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11783                         ctsio->sense_len = SSD_FULL_SIZE;
11784                         ctl_done((union ctl_io *)ctsio);
11785                         return (retval);
11786                 }
11787         }
11788
11789
11790         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11791                 mtx_unlock(&lun->lun_lock);
11792                 ctl_done((union ctl_io *)ctsio);
11793                 return (retval);
11794         }
11795
11796         /*
11797          * XXX CHD this is where we want to send IO to other side if
11798          * this LUN is secondary on this SC. We will need to make a copy
11799          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11800          * the copy we send as FROM_OTHER.
11801          * We also need to stuff the address of the original IO so we can
11802          * find it easily. Something similar will need be done on the other
11803          * side so when we are done we can find the copy.
11804          */
11805         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11806                 union ctl_ha_msg msg_info;
11807                 int isc_retval;
11808
11809                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11810
11811                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11812                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11813 #if 0
11814                 printf("1. ctsio %p\n", ctsio);
11815 #endif
11816                 msg_info.hdr.serializing_sc = NULL;
11817                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11818                 msg_info.scsi.tag_num = ctsio->tag_num;
11819                 msg_info.scsi.tag_type = ctsio->tag_type;
11820                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11821
11822                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11823
11824                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11825                     (void *)&msg_info, sizeof(msg_info), 0)) >
11826                     CTL_HA_STATUS_SUCCESS) {
11827                         printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11828                                isc_retval);
11829                         printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11830                 } else {
11831 #if 0
11832                         printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11833 #endif
11834                 }
11835
11836                 /*
11837                  * XXX KDM this I/O is off the incoming queue, but hasn't
11838                  * been inserted on any other queue.  We may need to come
11839                  * up with a holding queue while we wait for serialization
11840                  * so that we have an idea of what we're waiting for from
11841                  * the other side.
11842                  */
11843                 mtx_unlock(&lun->lun_lock);
11844                 return (retval);
11845         }
11846
11847         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11848                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11849                               ctl_ooaq, ooa_links))) {
11850         case CTL_ACTION_BLOCK:
11851                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11852                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11853                                   blocked_links);
11854                 mtx_unlock(&lun->lun_lock);
11855                 return (retval);
11856         case CTL_ACTION_PASS:
11857         case CTL_ACTION_SKIP:
11858                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11859                 mtx_unlock(&lun->lun_lock);
11860                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11861                 break;
11862         case CTL_ACTION_OVERLAP:
11863                 mtx_unlock(&lun->lun_lock);
11864                 ctl_set_overlapped_cmd(ctsio);
11865                 ctl_done((union ctl_io *)ctsio);
11866                 break;
11867         case CTL_ACTION_OVERLAP_TAG:
11868                 mtx_unlock(&lun->lun_lock);
11869                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11870                 ctl_done((union ctl_io *)ctsio);
11871                 break;
11872         case CTL_ACTION_ERROR:
11873         default:
11874                 mtx_unlock(&lun->lun_lock);
11875                 ctl_set_internal_failure(ctsio,
11876                                          /*sks_valid*/ 0,
11877                                          /*retry_count*/ 0);
11878                 ctl_done((union ctl_io *)ctsio);
11879                 break;
11880         }
11881         return (retval);
11882 }
11883
11884 const struct ctl_cmd_entry *
11885 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11886 {
11887         const struct ctl_cmd_entry *entry;
11888         int service_action;
11889
11890         entry = &ctl_cmd_table[ctsio->cdb[0]];
11891         if (sa)
11892                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11893         if (entry->flags & CTL_CMD_FLAG_SA5) {
11894                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11895                 entry = &((const struct ctl_cmd_entry *)
11896                     entry->execute)[service_action];
11897         }
11898         return (entry);
11899 }
11900
11901 const struct ctl_cmd_entry *
11902 ctl_validate_command(struct ctl_scsiio *ctsio)
11903 {
11904         const struct ctl_cmd_entry *entry;
11905         int i, sa;
11906         uint8_t diff;
11907
11908         entry = ctl_get_cmd_entry(ctsio, &sa);
11909         if (entry->execute == NULL) {
11910                 if (sa)
11911                         ctl_set_invalid_field(ctsio,
11912                                               /*sks_valid*/ 1,
11913                                               /*command*/ 1,
11914                                               /*field*/ 1,
11915                                               /*bit_valid*/ 1,
11916                                               /*bit*/ 4);
11917                 else
11918                         ctl_set_invalid_opcode(ctsio);
11919                 ctl_done((union ctl_io *)ctsio);
11920                 return (NULL);
11921         }
11922         KASSERT(entry->length > 0,
11923             ("Not defined length for command 0x%02x/0x%02x",
11924              ctsio->cdb[0], ctsio->cdb[1]));
11925         for (i = 1; i < entry->length; i++) {
11926                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11927                 if (diff == 0)
11928                         continue;
11929                 ctl_set_invalid_field(ctsio,
11930                                       /*sks_valid*/ 1,
11931                                       /*command*/ 1,
11932                                       /*field*/ i,
11933                                       /*bit_valid*/ 1,
11934                                       /*bit*/ fls(diff) - 1);
11935                 ctl_done((union ctl_io *)ctsio);
11936                 return (NULL);
11937         }
11938         return (entry);
11939 }
11940
11941 static int
11942 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11943 {
11944
11945         switch (lun_type) {
11946         case T_PROCESSOR:
11947                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11948                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11949                         return (0);
11950                 break;
11951         case T_DIRECT:
11952                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11953                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11954                         return (0);
11955                 break;
11956         default:
11957                 return (0);
11958         }
11959         return (1);
11960 }
11961
11962 static int
11963 ctl_scsiio(struct ctl_scsiio *ctsio)
11964 {
11965         int retval;
11966         const struct ctl_cmd_entry *entry;
11967
11968         retval = CTL_RETVAL_COMPLETE;
11969
11970         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11971
11972         entry = ctl_get_cmd_entry(ctsio, NULL);
11973
11974         /*
11975          * If this I/O has been aborted, just send it straight to
11976          * ctl_done() without executing it.
11977          */
11978         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11979                 ctl_done((union ctl_io *)ctsio);
11980                 goto bailout;
11981         }
11982
11983         /*
11984          * All the checks should have been handled by ctl_scsiio_precheck().
11985          * We should be clear now to just execute the I/O.
11986          */
11987         retval = entry->execute(ctsio);
11988
11989 bailout:
11990         return (retval);
11991 }
11992
11993 /*
11994  * Since we only implement one target right now, a bus reset simply resets
11995  * our single target.
11996  */
11997 static int
11998 ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11999 {
12000         return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
12001 }
12002
12003 static int
12004 ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
12005                  ctl_ua_type ua_type)
12006 {
12007         struct ctl_lun *lun;
12008         int retval;
12009
12010         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12011                 union ctl_ha_msg msg_info;
12012
12013                 io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
12014                 msg_info.hdr.nexus = io->io_hdr.nexus;
12015                 if (ua_type==CTL_UA_TARG_RESET)
12016                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
12017                 else
12018                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
12019                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12020                 msg_info.hdr.original_sc = NULL;
12021                 msg_info.hdr.serializing_sc = NULL;
12022                 if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12023                     (void *)&msg_info, sizeof(msg_info), 0)) {
12024                 }
12025         }
12026         retval = 0;
12027
12028         mtx_lock(&softc->ctl_lock);
12029         STAILQ_FOREACH(lun, &softc->lun_list, links)
12030                 retval += ctl_lun_reset(lun, io, ua_type);
12031         mtx_unlock(&softc->ctl_lock);
12032
12033         return (retval);
12034 }
12035
12036 /*
12037  * The LUN should always be set.  The I/O is optional, and is used to
12038  * distinguish between I/Os sent by this initiator, and by other
12039  * initiators.  We set unit attention for initiators other than this one.
12040  * SAM-3 is vague on this point.  It does say that a unit attention should
12041  * be established for other initiators when a LUN is reset (see section
12042  * 5.7.3), but it doesn't specifically say that the unit attention should
12043  * be established for this particular initiator when a LUN is reset.  Here
12044  * is the relevant text, from SAM-3 rev 8:
12045  *
12046  * 5.7.2 When a SCSI initiator port aborts its own tasks
12047  *
12048  * When a SCSI initiator port causes its own task(s) to be aborted, no
12049  * notification that the task(s) have been aborted shall be returned to
12050  * the SCSI initiator port other than the completion response for the
12051  * command or task management function action that caused the task(s) to
12052  * be aborted and notification(s) associated with related effects of the
12053  * action (e.g., a reset unit attention condition).
12054  *
12055  * XXX KDM for now, we're setting unit attention for all initiators.
12056  */
12057 static int
12058 ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
12059 {
12060         union ctl_io *xio;
12061 #if 0
12062         uint32_t initidx;
12063 #endif
12064 #ifdef CTL_WITH_CA
12065         int i;
12066 #endif
12067
12068         mtx_lock(&lun->lun_lock);
12069         /*
12070          * Run through the OOA queue and abort each I/O.
12071          */
12072         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12073              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12074                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
12075         }
12076
12077         /*
12078          * This version sets unit attention for every
12079          */
12080 #if 0
12081         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12082         ctl_est_ua_all(lun, initidx, ua_type);
12083 #else
12084         ctl_est_ua_all(lun, -1, ua_type);
12085 #endif
12086
12087         /*
12088          * A reset (any kind, really) clears reservations established with
12089          * RESERVE/RELEASE.  It does not clear reservations established
12090          * with PERSISTENT RESERVE OUT, but we don't support that at the
12091          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
12092          * reservations made with the RESERVE/RELEASE commands, because
12093          * those commands are obsolete in SPC-3.
12094          */
12095         lun->flags &= ~CTL_LUN_RESERVED;
12096
12097 #ifdef CTL_WITH_CA
12098         for (i = 0; i < CTL_MAX_INITIATORS; i++)
12099                 ctl_clear_mask(lun->have_ca, i);
12100 #endif
12101         mtx_unlock(&lun->lun_lock);
12102
12103         return (0);
12104 }
12105
12106 static void
12107 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
12108     int other_sc)
12109 {
12110         union ctl_io *xio;
12111
12112         mtx_assert(&lun->lun_lock, MA_OWNED);
12113
12114         /*
12115          * Run through the OOA queue and attempt to find the given I/O.
12116          * The target port, initiator ID, tag type and tag number have to
12117          * match the values that we got from the initiator.  If we have an
12118          * untagged command to abort, simply abort the first untagged command
12119          * we come to.  We only allow one untagged command at a time of course.
12120          */
12121         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12122              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12123
12124                 if ((targ_port == UINT32_MAX ||
12125                      targ_port == xio->io_hdr.nexus.targ_port) &&
12126                     (init_id == UINT32_MAX ||
12127                      init_id == xio->io_hdr.nexus.initid.id)) {
12128                         if (targ_port != xio->io_hdr.nexus.targ_port ||
12129                             init_id != xio->io_hdr.nexus.initid.id)
12130                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12131                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12132                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12133                                 union ctl_ha_msg msg_info;
12134
12135                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
12136                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12137                                 msg_info.task.tag_num = xio->scsiio.tag_num;
12138                                 msg_info.task.tag_type = xio->scsiio.tag_type;
12139                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12140                                 msg_info.hdr.original_sc = NULL;
12141                                 msg_info.hdr.serializing_sc = NULL;
12142                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12143                                     (void *)&msg_info, sizeof(msg_info), 0);
12144                         }
12145                 }
12146         }
12147 }
12148
12149 static int
12150 ctl_abort_task_set(union ctl_io *io)
12151 {
12152         struct ctl_softc *softc = control_softc;
12153         struct ctl_lun *lun;
12154         uint32_t targ_lun;
12155
12156         /*
12157          * Look up the LUN.
12158          */
12159         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12160         mtx_lock(&softc->ctl_lock);
12161         if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
12162                 lun = softc->ctl_luns[targ_lun];
12163         else {
12164                 mtx_unlock(&softc->ctl_lock);
12165                 return (1);
12166         }
12167
12168         mtx_lock(&lun->lun_lock);
12169         mtx_unlock(&softc->ctl_lock);
12170         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12171                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12172                     io->io_hdr.nexus.initid.id,
12173                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12174         } else { /* CTL_TASK_CLEAR_TASK_SET */
12175                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12176                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12177         }
12178         mtx_unlock(&lun->lun_lock);
12179         return (0);
12180 }
12181
12182 static int
12183 ctl_i_t_nexus_reset(union ctl_io *io)
12184 {
12185         struct ctl_softc *softc = control_softc;
12186         struct ctl_lun *lun;
12187         uint32_t initidx, residx;
12188
12189         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12190         residx = ctl_get_resindex(&io->io_hdr.nexus);
12191         mtx_lock(&softc->ctl_lock);
12192         STAILQ_FOREACH(lun, &softc->lun_list, links) {
12193                 mtx_lock(&lun->lun_lock);
12194                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12195                     io->io_hdr.nexus.initid.id,
12196                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12197 #ifdef CTL_WITH_CA
12198                 ctl_clear_mask(lun->have_ca, initidx);
12199 #endif
12200                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
12201                         lun->flags &= ~CTL_LUN_RESERVED;
12202                 ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12203                 mtx_unlock(&lun->lun_lock);
12204         }
12205         mtx_unlock(&softc->ctl_lock);
12206         return (0);
12207 }
12208
12209 static int
12210 ctl_abort_task(union ctl_io *io)
12211 {
12212         union ctl_io *xio;
12213         struct ctl_lun *lun;
12214         struct ctl_softc *softc;
12215 #if 0
12216         struct sbuf sb;
12217         char printbuf[128];
12218 #endif
12219         int found;
12220         uint32_t targ_lun;
12221
12222         softc = control_softc;
12223         found = 0;
12224
12225         /*
12226          * Look up the LUN.
12227          */
12228         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12229         mtx_lock(&softc->ctl_lock);
12230         if ((targ_lun < CTL_MAX_LUNS)
12231          && (softc->ctl_luns[targ_lun] != NULL))
12232                 lun = softc->ctl_luns[targ_lun];
12233         else {
12234                 mtx_unlock(&softc->ctl_lock);
12235                 return (1);
12236         }
12237
12238 #if 0
12239         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12240                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12241 #endif
12242
12243         mtx_lock(&lun->lun_lock);
12244         mtx_unlock(&softc->ctl_lock);
12245         /*
12246          * Run through the OOA queue and attempt to find the given I/O.
12247          * The target port, initiator ID, tag type and tag number have to
12248          * match the values that we got from the initiator.  If we have an
12249          * untagged command to abort, simply abort the first untagged command
12250          * we come to.  We only allow one untagged command at a time of course.
12251          */
12252         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12253              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12254 #if 0
12255                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12256
12257                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12258                             lun->lun, xio->scsiio.tag_num,
12259                             xio->scsiio.tag_type,
12260                             (xio->io_hdr.blocked_links.tqe_prev
12261                             == NULL) ? "" : " BLOCKED",
12262                             (xio->io_hdr.flags &
12263                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12264                             (xio->io_hdr.flags &
12265                             CTL_FLAG_ABORT) ? " ABORT" : "",
12266                             (xio->io_hdr.flags &
12267                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12268                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12269                 sbuf_finish(&sb);
12270                 printf("%s\n", sbuf_data(&sb));
12271 #endif
12272
12273                 if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12274                  || (xio->io_hdr.nexus.initid.id != io->io_hdr.nexus.initid.id)
12275                  || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12276                         continue;
12277
12278                 /*
12279                  * If the abort says that the task is untagged, the
12280                  * task in the queue must be untagged.  Otherwise,
12281                  * we just check to see whether the tag numbers
12282                  * match.  This is because the QLogic firmware
12283                  * doesn't pass back the tag type in an abort
12284                  * request.
12285                  */
12286 #if 0
12287                 if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12288                   && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12289                  || (xio->scsiio.tag_num == io->taskio.tag_num))
12290 #endif
12291                 /*
12292                  * XXX KDM we've got problems with FC, because it
12293                  * doesn't send down a tag type with aborts.  So we
12294                  * can only really go by the tag number...
12295                  * This may cause problems with parallel SCSI.
12296                  * Need to figure that out!!
12297                  */
12298                 if (xio->scsiio.tag_num == io->taskio.tag_num) {
12299                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
12300                         found = 1;
12301                         if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12302                             !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12303                                 union ctl_ha_msg msg_info;
12304
12305                                 io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
12306                                 msg_info.hdr.nexus = io->io_hdr.nexus;
12307                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12308                                 msg_info.task.tag_num = io->taskio.tag_num;
12309                                 msg_info.task.tag_type = io->taskio.tag_type;
12310                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12311                                 msg_info.hdr.original_sc = NULL;
12312                                 msg_info.hdr.serializing_sc = NULL;
12313 #if 0
12314                                 printf("Sent Abort to other side\n");
12315 #endif
12316                                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12317                                     (void *)&msg_info, sizeof(msg_info), 0) !=
12318                                     CTL_HA_STATUS_SUCCESS) {
12319                                 }
12320                         }
12321 #if 0
12322                         printf("ctl_abort_task: found I/O to abort\n");
12323 #endif
12324                 }
12325         }
12326         mtx_unlock(&lun->lun_lock);
12327
12328         if (found == 0) {
12329                 /*
12330                  * This isn't really an error.  It's entirely possible for
12331                  * the abort and command completion to cross on the wire.
12332                  * This is more of an informative/diagnostic error.
12333                  */
12334 #if 0
12335                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12336                        "%d:%d:%d:%d tag %d type %d\n",
12337                        io->io_hdr.nexus.initid.id,
12338                        io->io_hdr.nexus.targ_port,
12339                        io->io_hdr.nexus.targ_target.id,
12340                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12341                        io->taskio.tag_type);
12342 #endif
12343         }
12344         return (0);
12345 }
12346
12347 static void
12348 ctl_run_task(union ctl_io *io)
12349 {
12350         struct ctl_softc *softc = control_softc;
12351         int retval = 1;
12352         const char *task_desc;
12353
12354         CTL_DEBUG_PRINT(("ctl_run_task\n"));
12355
12356         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12357             ("ctl_run_task: Unextected io_type %d\n",
12358              io->io_hdr.io_type));
12359
12360         task_desc = ctl_scsi_task_string(&io->taskio);
12361         if (task_desc != NULL) {
12362 #ifdef NEEDTOPORT
12363                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12364                             CTL_TASK_REPORT,
12365                             csevent_LogType_Trace,
12366                             csevent_Severity_Information,
12367                             csevent_AlertLevel_Green,
12368                             csevent_FRU_Firmware,
12369                             csevent_FRU_Unknown,
12370                             "CTL: received task: %s",task_desc);
12371 #endif
12372         } else {
12373 #ifdef NEEDTOPORT
12374                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12375                             CTL_TASK_REPORT,
12376                             csevent_LogType_Trace,
12377                             csevent_Severity_Information,
12378                             csevent_AlertLevel_Green,
12379                             csevent_FRU_Firmware,
12380                             csevent_FRU_Unknown,
12381                             "CTL: received unknown task "
12382                             "type: %d (%#x)",
12383                             io->taskio.task_action,
12384                             io->taskio.task_action);
12385 #endif
12386         }
12387         switch (io->taskio.task_action) {
12388         case CTL_TASK_ABORT_TASK:
12389                 retval = ctl_abort_task(io);
12390                 break;
12391         case CTL_TASK_ABORT_TASK_SET:
12392         case CTL_TASK_CLEAR_TASK_SET:
12393                 retval = ctl_abort_task_set(io);
12394                 break;
12395         case CTL_TASK_CLEAR_ACA:
12396                 break;
12397         case CTL_TASK_I_T_NEXUS_RESET:
12398                 retval = ctl_i_t_nexus_reset(io);
12399                 break;
12400         case CTL_TASK_LUN_RESET: {
12401                 struct ctl_lun *lun;
12402                 uint32_t targ_lun;
12403
12404                 targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12405                 mtx_lock(&softc->ctl_lock);
12406                 if ((targ_lun < CTL_MAX_LUNS)
12407                  && (softc->ctl_luns[targ_lun] != NULL))
12408                         lun = softc->ctl_luns[targ_lun];
12409                 else {
12410                         mtx_unlock(&softc->ctl_lock);
12411                         retval = 1;
12412                         break;
12413                 }
12414
12415                 if (!(io->io_hdr.flags &
12416                     CTL_FLAG_FROM_OTHER_SC)) {
12417                         union ctl_ha_msg msg_info;
12418
12419                         io->io_hdr.flags |=
12420                                 CTL_FLAG_SENT_2OTHER_SC;
12421                         msg_info.hdr.msg_type =
12422                                 CTL_MSG_MANAGE_TASKS;
12423                         msg_info.hdr.nexus = io->io_hdr.nexus;
12424                         msg_info.task.task_action =
12425                                 CTL_TASK_LUN_RESET;
12426                         msg_info.hdr.original_sc = NULL;
12427                         msg_info.hdr.serializing_sc = NULL;
12428                         if (CTL_HA_STATUS_SUCCESS !=
12429                             ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12430                             (void *)&msg_info,
12431                             sizeof(msg_info), 0)) {
12432                         }
12433                 }
12434
12435                 retval = ctl_lun_reset(lun, io,
12436                                        CTL_UA_LUN_RESET);
12437                 mtx_unlock(&softc->ctl_lock);
12438                 break;
12439         }
12440         case CTL_TASK_TARGET_RESET:
12441                 retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12442                 break;
12443         case CTL_TASK_BUS_RESET:
12444                 retval = ctl_bus_reset(softc, io);
12445                 break;
12446         case CTL_TASK_PORT_LOGIN:
12447                 break;
12448         case CTL_TASK_PORT_LOGOUT:
12449                 break;
12450         default:
12451                 printf("ctl_run_task: got unknown task management event %d\n",
12452                        io->taskio.task_action);
12453                 break;
12454         }
12455         if (retval == 0)
12456                 io->io_hdr.status = CTL_SUCCESS;
12457         else
12458                 io->io_hdr.status = CTL_ERROR;
12459         ctl_done(io);
12460 }
12461
12462 /*
12463  * For HA operation.  Handle commands that come in from the other
12464  * controller.
12465  */
12466 static void
12467 ctl_handle_isc(union ctl_io *io)
12468 {
12469         int free_io;
12470         struct ctl_lun *lun;
12471         struct ctl_softc *softc;
12472         uint32_t targ_lun;
12473
12474         softc = control_softc;
12475
12476         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12477         lun = softc->ctl_luns[targ_lun];
12478
12479         switch (io->io_hdr.msg_type) {
12480         case CTL_MSG_SERIALIZE:
12481                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12482                 break;
12483         case CTL_MSG_R2R: {
12484                 const struct ctl_cmd_entry *entry;
12485
12486                 /*
12487                  * This is only used in SER_ONLY mode.
12488                  */
12489                 free_io = 0;
12490                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12491                 mtx_lock(&lun->lun_lock);
12492                 if (ctl_scsiio_lun_check(lun,
12493                     entry, (struct ctl_scsiio *)io) != 0) {
12494                         mtx_unlock(&lun->lun_lock);
12495                         ctl_done(io);
12496                         break;
12497                 }
12498                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12499                 mtx_unlock(&lun->lun_lock);
12500                 ctl_enqueue_rtr(io);
12501                 break;
12502         }
12503         case CTL_MSG_FINISH_IO:
12504                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
12505                         free_io = 0;
12506                         ctl_done(io);
12507                 } else {
12508                         free_io = 1;
12509                         mtx_lock(&lun->lun_lock);
12510                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12511                                      ooa_links);
12512                         ctl_check_blocked(lun);
12513                         mtx_unlock(&lun->lun_lock);
12514                 }
12515                 break;
12516         case CTL_MSG_PERS_ACTION:
12517                 ctl_hndl_per_res_out_on_other_sc(
12518                         (union ctl_ha_msg *)&io->presio.pr_msg);
12519                 free_io = 1;
12520                 break;
12521         case CTL_MSG_BAD_JUJU:
12522                 free_io = 0;
12523                 ctl_done(io);
12524                 break;
12525         case CTL_MSG_DATAMOVE:
12526                 /* Only used in XFER mode */
12527                 free_io = 0;
12528                 ctl_datamove_remote(io);
12529                 break;
12530         case CTL_MSG_DATAMOVE_DONE:
12531                 /* Only used in XFER mode */
12532                 free_io = 0;
12533                 io->scsiio.be_move_done(io);
12534                 break;
12535         default:
12536                 free_io = 1;
12537                 printf("%s: Invalid message type %d\n",
12538                        __func__, io->io_hdr.msg_type);
12539                 break;
12540         }
12541         if (free_io)
12542                 ctl_free_io(io);
12543
12544 }
12545
12546
12547 /*
12548  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12549  * there is no match.
12550  */
12551 static ctl_lun_error_pattern
12552 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12553 {
12554         const struct ctl_cmd_entry *entry;
12555         ctl_lun_error_pattern filtered_pattern, pattern;
12556
12557         pattern = desc->error_pattern;
12558
12559         /*
12560          * XXX KDM we need more data passed into this function to match a
12561          * custom pattern, and we actually need to implement custom pattern
12562          * matching.
12563          */
12564         if (pattern & CTL_LUN_PAT_CMD)
12565                 return (CTL_LUN_PAT_CMD);
12566
12567         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12568                 return (CTL_LUN_PAT_ANY);
12569
12570         entry = ctl_get_cmd_entry(ctsio, NULL);
12571
12572         filtered_pattern = entry->pattern & pattern;
12573
12574         /*
12575          * If the user requested specific flags in the pattern (e.g.
12576          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12577          * flags.
12578          *
12579          * If the user did not specify any flags, it doesn't matter whether
12580          * or not the command supports the flags.
12581          */
12582         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12583              (pattern & ~CTL_LUN_PAT_MASK))
12584                 return (CTL_LUN_PAT_NONE);
12585
12586         /*
12587          * If the user asked for a range check, see if the requested LBA
12588          * range overlaps with this command's LBA range.
12589          */
12590         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12591                 uint64_t lba1;
12592                 uint64_t len1;
12593                 ctl_action action;
12594                 int retval;
12595
12596                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12597                 if (retval != 0)
12598                         return (CTL_LUN_PAT_NONE);
12599
12600                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12601                                               desc->lba_range.len, FALSE);
12602                 /*
12603                  * A "pass" means that the LBA ranges don't overlap, so
12604                  * this doesn't match the user's range criteria.
12605                  */
12606                 if (action == CTL_ACTION_PASS)
12607                         return (CTL_LUN_PAT_NONE);
12608         }
12609
12610         return (filtered_pattern);
12611 }
12612
12613 static void
12614 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12615 {
12616         struct ctl_error_desc *desc, *desc2;
12617
12618         mtx_assert(&lun->lun_lock, MA_OWNED);
12619
12620         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12621                 ctl_lun_error_pattern pattern;
12622                 /*
12623                  * Check to see whether this particular command matches
12624                  * the pattern in the descriptor.
12625                  */
12626                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12627                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12628                         continue;
12629
12630                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12631                 case CTL_LUN_INJ_ABORTED:
12632                         ctl_set_aborted(&io->scsiio);
12633                         break;
12634                 case CTL_LUN_INJ_MEDIUM_ERR:
12635                         ctl_set_medium_error(&io->scsiio);
12636                         break;
12637                 case CTL_LUN_INJ_UA:
12638                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12639                          * OCCURRED */
12640                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12641                         break;
12642                 case CTL_LUN_INJ_CUSTOM:
12643                         /*
12644                          * We're assuming the user knows what he is doing.
12645                          * Just copy the sense information without doing
12646                          * checks.
12647                          */
12648                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12649                               MIN(sizeof(desc->custom_sense),
12650                                   sizeof(io->scsiio.sense_data)));
12651                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12652                         io->scsiio.sense_len = SSD_FULL_SIZE;
12653                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12654                         break;
12655                 case CTL_LUN_INJ_NONE:
12656                 default:
12657                         /*
12658                          * If this is an error injection type we don't know
12659                          * about, clear the continuous flag (if it is set)
12660                          * so it will get deleted below.
12661                          */
12662                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12663                         break;
12664                 }
12665                 /*
12666                  * By default, each error injection action is a one-shot
12667                  */
12668                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12669                         continue;
12670
12671                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12672
12673                 free(desc, M_CTL);
12674         }
12675 }
12676
12677 #ifdef CTL_IO_DELAY
12678 static void
12679 ctl_datamove_timer_wakeup(void *arg)
12680 {
12681         union ctl_io *io;
12682
12683         io = (union ctl_io *)arg;
12684
12685         ctl_datamove(io);
12686 }
12687 #endif /* CTL_IO_DELAY */
12688
12689 void
12690 ctl_datamove(union ctl_io *io)
12691 {
12692         void (*fe_datamove)(union ctl_io *io);
12693
12694         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12695
12696         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12697
12698 #ifdef CTL_TIME_IO
12699         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12700                 char str[256];
12701                 char path_str[64];
12702                 struct sbuf sb;
12703
12704                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12705                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12706
12707                 sbuf_cat(&sb, path_str);
12708                 switch (io->io_hdr.io_type) {
12709                 case CTL_IO_SCSI:
12710                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12711                         sbuf_printf(&sb, "\n");
12712                         sbuf_cat(&sb, path_str);
12713                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12714                                     io->scsiio.tag_num, io->scsiio.tag_type);
12715                         break;
12716                 case CTL_IO_TASK:
12717                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12718                                     "Tag Type: %d\n", io->taskio.task_action,
12719                                     io->taskio.tag_num, io->taskio.tag_type);
12720                         break;
12721                 default:
12722                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12723                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12724                         break;
12725                 }
12726                 sbuf_cat(&sb, path_str);
12727                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12728                             (intmax_t)time_uptime - io->io_hdr.start_time);
12729                 sbuf_finish(&sb);
12730                 printf("%s", sbuf_data(&sb));
12731         }
12732 #endif /* CTL_TIME_IO */
12733
12734 #ifdef CTL_IO_DELAY
12735         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12736                 struct ctl_lun *lun;
12737
12738                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12739
12740                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12741         } else {
12742                 struct ctl_lun *lun;
12743
12744                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12745                 if ((lun != NULL)
12746                  && (lun->delay_info.datamove_delay > 0)) {
12747                         struct callout *callout;
12748
12749                         callout = (struct callout *)&io->io_hdr.timer_bytes;
12750                         callout_init(callout, /*mpsafe*/ 1);
12751                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12752                         callout_reset(callout,
12753                                       lun->delay_info.datamove_delay * hz,
12754                                       ctl_datamove_timer_wakeup, io);
12755                         if (lun->delay_info.datamove_type ==
12756                             CTL_DELAY_TYPE_ONESHOT)
12757                                 lun->delay_info.datamove_delay = 0;
12758                         return;
12759                 }
12760         }
12761 #endif
12762
12763         /*
12764          * This command has been aborted.  Set the port status, so we fail
12765          * the data move.
12766          */
12767         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12768                 printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12769                        io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12770                        io->io_hdr.nexus.targ_port,
12771                        (uintmax_t)io->io_hdr.nexus.targ_target.id,
12772                        io->io_hdr.nexus.targ_lun);
12773                 io->io_hdr.port_status = 31337;
12774                 /*
12775                  * Note that the backend, in this case, will get the
12776                  * callback in its context.  In other cases it may get
12777                  * called in the frontend's interrupt thread context.
12778                  */
12779                 io->scsiio.be_move_done(io);
12780                 return;
12781         }
12782
12783         /* Don't confuse frontend with zero length data move. */
12784         if (io->scsiio.kern_data_len == 0) {
12785                 io->scsiio.be_move_done(io);
12786                 return;
12787         }
12788
12789         /*
12790          * If we're in XFER mode and this I/O is from the other shelf
12791          * controller, we need to send the DMA to the other side to
12792          * actually transfer the data to/from the host.  In serialize only
12793          * mode the transfer happens below CTL and ctl_datamove() is only
12794          * called on the machine that originally received the I/O.
12795          */
12796         if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12797          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12798                 union ctl_ha_msg msg;
12799                 uint32_t sg_entries_sent;
12800                 int do_sg_copy;
12801                 int i;
12802
12803                 memset(&msg, 0, sizeof(msg));
12804                 msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12805                 msg.hdr.original_sc = io->io_hdr.original_sc;
12806                 msg.hdr.serializing_sc = io;
12807                 msg.hdr.nexus = io->io_hdr.nexus;
12808                 msg.dt.flags = io->io_hdr.flags;
12809                 /*
12810                  * We convert everything into a S/G list here.  We can't
12811                  * pass by reference, only by value between controllers.
12812                  * So we can't pass a pointer to the S/G list, only as many
12813                  * S/G entries as we can fit in here.  If it's possible for
12814                  * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12815                  * then we need to break this up into multiple transfers.
12816                  */
12817                 if (io->scsiio.kern_sg_entries == 0) {
12818                         msg.dt.kern_sg_entries = 1;
12819                         /*
12820                          * If this is in cached memory, flush the cache
12821                          * before we send the DMA request to the other
12822                          * controller.  We want to do this in either the
12823                          * read or the write case.  The read case is
12824                          * straightforward.  In the write case, we want to
12825                          * make sure nothing is in the local cache that
12826                          * could overwrite the DMAed data.
12827                          */
12828                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12829                                 /*
12830                                  * XXX KDM use bus_dmamap_sync() here.
12831                                  */
12832                         }
12833
12834                         /*
12835                          * Convert to a physical address if this is a
12836                          * virtual address.
12837                          */
12838                         if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12839                                 msg.dt.sg_list[0].addr =
12840                                         io->scsiio.kern_data_ptr;
12841                         } else {
12842                                 /*
12843                                  * XXX KDM use busdma here!
12844                                  */
12845 #if 0
12846                                 msg.dt.sg_list[0].addr = (void *)
12847                                         vtophys(io->scsiio.kern_data_ptr);
12848 #endif
12849                         }
12850
12851                         msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12852                         do_sg_copy = 0;
12853                 } else {
12854                         struct ctl_sg_entry *sgl;
12855
12856                         do_sg_copy = 1;
12857                         msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12858                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12859                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12860                                 /*
12861                                  * XXX KDM use bus_dmamap_sync() here.
12862                                  */
12863                         }
12864                 }
12865
12866                 msg.dt.kern_data_len = io->scsiio.kern_data_len;
12867                 msg.dt.kern_total_len = io->scsiio.kern_total_len;
12868                 msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12869                 msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12870                 msg.dt.sg_sequence = 0;
12871
12872                 /*
12873                  * Loop until we've sent all of the S/G entries.  On the
12874                  * other end, we'll recompose these S/G entries into one
12875                  * contiguous list before passing it to the
12876                  */
12877                 for (sg_entries_sent = 0; sg_entries_sent <
12878                      msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12879                         msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list)/
12880                                 sizeof(msg.dt.sg_list[0])),
12881                                 msg.dt.kern_sg_entries - sg_entries_sent);
12882
12883                         if (do_sg_copy != 0) {
12884                                 struct ctl_sg_entry *sgl;
12885                                 int j;
12886
12887                                 sgl = (struct ctl_sg_entry *)
12888                                         io->scsiio.kern_data_ptr;
12889                                 /*
12890                                  * If this is in cached memory, flush the cache
12891                                  * before we send the DMA request to the other
12892                                  * controller.  We want to do this in either
12893                                  * the * read or the write case.  The read
12894                                  * case is straightforward.  In the write
12895                                  * case, we want to make sure nothing is
12896                                  * in the local cache that could overwrite
12897                                  * the DMAed data.
12898                                  */
12899
12900                                 for (i = sg_entries_sent, j = 0;
12901                                      i < msg.dt.cur_sg_entries; i++, j++) {
12902                                         if ((io->io_hdr.flags &
12903                                              CTL_FLAG_NO_DATASYNC) == 0) {
12904                                                 /*
12905                                                  * XXX KDM use bus_dmamap_sync()
12906                                                  */
12907                                         }
12908                                         if ((io->io_hdr.flags &
12909                                              CTL_FLAG_BUS_ADDR) == 0) {
12910                                                 /*
12911                                                  * XXX KDM use busdma.
12912                                                  */
12913 #if 0
12914                                                 msg.dt.sg_list[j].addr =(void *)
12915                                                        vtophys(sgl[i].addr);
12916 #endif
12917                                         } else {
12918                                                 msg.dt.sg_list[j].addr =
12919                                                         sgl[i].addr;
12920                                         }
12921                                         msg.dt.sg_list[j].len = sgl[i].len;
12922                                 }
12923                         }
12924
12925                         sg_entries_sent += msg.dt.cur_sg_entries;
12926                         if (sg_entries_sent >= msg.dt.kern_sg_entries)
12927                                 msg.dt.sg_last = 1;
12928                         else
12929                                 msg.dt.sg_last = 0;
12930
12931                         /*
12932                          * XXX KDM drop and reacquire the lock here?
12933                          */
12934                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12935                             sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12936                                 /*
12937                                  * XXX do something here.
12938                                  */
12939                         }
12940
12941                         msg.dt.sent_sg_entries = sg_entries_sent;
12942                 }
12943                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12944                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12945                         ctl_failover_io(io, /*have_lock*/ 0);
12946
12947         } else {
12948
12949                 /*
12950                  * Lookup the fe_datamove() function for this particular
12951                  * front end.
12952                  */
12953                 fe_datamove =
12954                     control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12955
12956                 fe_datamove(io);
12957         }
12958 }
12959
12960 static void
12961 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12962 {
12963         union ctl_ha_msg msg;
12964         int isc_status;
12965
12966         memset(&msg, 0, sizeof(msg));
12967
12968         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12969         msg.hdr.original_sc = io;
12970         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12971         msg.hdr.nexus = io->io_hdr.nexus;
12972         msg.hdr.status = io->io_hdr.status;
12973         msg.scsi.tag_num = io->scsiio.tag_num;
12974         msg.scsi.tag_type = io->scsiio.tag_type;
12975         msg.scsi.scsi_status = io->scsiio.scsi_status;
12976         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12977                sizeof(io->scsiio.sense_data));
12978         msg.scsi.sense_len = io->scsiio.sense_len;
12979         msg.scsi.sense_residual = io->scsiio.sense_residual;
12980         msg.scsi.fetd_status = io->io_hdr.port_status;
12981         msg.scsi.residual = io->scsiio.residual;
12982         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12983
12984         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12985                 ctl_failover_io(io, /*have_lock*/ have_lock);
12986                 return;
12987         }
12988
12989         isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12990         if (isc_status > CTL_HA_STATUS_SUCCESS) {
12991                 /* XXX do something if this fails */
12992         }
12993
12994 }
12995
12996 /*
12997  * The DMA to the remote side is done, now we need to tell the other side
12998  * we're done so it can continue with its data movement.
12999  */
13000 static void
13001 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
13002 {
13003         union ctl_io *io;
13004
13005         io = rq->context;
13006
13007         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13008                 printf("%s: ISC DMA write failed with error %d", __func__,
13009                        rq->ret);
13010                 ctl_set_internal_failure(&io->scsiio,
13011                                          /*sks_valid*/ 1,
13012                                          /*retry_count*/ rq->ret);
13013         }
13014
13015         ctl_dt_req_free(rq);
13016
13017         /*
13018          * In this case, we had to malloc the memory locally.  Free it.
13019          */
13020         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13021                 int i;
13022                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13023                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13024         }
13025         /*
13026          * The data is in local and remote memory, so now we need to send
13027          * status (good or back) back to the other side.
13028          */
13029         ctl_send_datamove_done(io, /*have_lock*/ 0);
13030 }
13031
13032 /*
13033  * We've moved the data from the host/controller into local memory.  Now we
13034  * need to push it over to the remote controller's memory.
13035  */
13036 static int
13037 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
13038 {
13039         int retval;
13040
13041         retval = 0;
13042
13043         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
13044                                           ctl_datamove_remote_write_cb);
13045
13046         return (retval);
13047 }
13048
13049 static void
13050 ctl_datamove_remote_write(union ctl_io *io)
13051 {
13052         int retval;
13053         void (*fe_datamove)(union ctl_io *io);
13054
13055         /*
13056          * - Get the data from the host/HBA into local memory.
13057          * - DMA memory from the local controller to the remote controller.
13058          * - Send status back to the remote controller.
13059          */
13060
13061         retval = ctl_datamove_remote_sgl_setup(io);
13062         if (retval != 0)
13063                 return;
13064
13065         /* Switch the pointer over so the FETD knows what to do */
13066         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13067
13068         /*
13069          * Use a custom move done callback, since we need to send completion
13070          * back to the other controller, not to the backend on this side.
13071          */
13072         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
13073
13074         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13075
13076         fe_datamove(io);
13077
13078         return;
13079
13080 }
13081
13082 static int
13083 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
13084 {
13085 #if 0
13086         char str[256];
13087         char path_str[64];
13088         struct sbuf sb;
13089 #endif
13090
13091         /*
13092          * In this case, we had to malloc the memory locally.  Free it.
13093          */
13094         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13095                 int i;
13096                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13097                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13098         }
13099
13100 #if 0
13101         scsi_path_string(io, path_str, sizeof(path_str));
13102         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13103         sbuf_cat(&sb, path_str);
13104         scsi_command_string(&io->scsiio, NULL, &sb);
13105         sbuf_printf(&sb, "\n");
13106         sbuf_cat(&sb, path_str);
13107         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13108                     io->scsiio.tag_num, io->scsiio.tag_type);
13109         sbuf_cat(&sb, path_str);
13110         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
13111                     io->io_hdr.flags, io->io_hdr.status);
13112         sbuf_finish(&sb);
13113         printk("%s", sbuf_data(&sb));
13114 #endif
13115
13116
13117         /*
13118          * The read is done, now we need to send status (good or bad) back
13119          * to the other side.
13120          */
13121         ctl_send_datamove_done(io, /*have_lock*/ 0);
13122
13123         return (0);
13124 }
13125
13126 static void
13127 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
13128 {
13129         union ctl_io *io;
13130         void (*fe_datamove)(union ctl_io *io);
13131
13132         io = rq->context;
13133
13134         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13135                 printf("%s: ISC DMA read failed with error %d", __func__,
13136                        rq->ret);
13137                 ctl_set_internal_failure(&io->scsiio,
13138                                          /*sks_valid*/ 1,
13139                                          /*retry_count*/ rq->ret);
13140         }
13141
13142         ctl_dt_req_free(rq);
13143
13144         /* Switch the pointer over so the FETD knows what to do */
13145         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13146
13147         /*
13148          * Use a custom move done callback, since we need to send completion
13149          * back to the other controller, not to the backend on this side.
13150          */
13151         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13152
13153         /* XXX KDM add checks like the ones in ctl_datamove? */
13154
13155         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13156
13157         fe_datamove(io);
13158 }
13159
13160 static int
13161 ctl_datamove_remote_sgl_setup(union ctl_io *io)
13162 {
13163         struct ctl_sg_entry *local_sglist, *remote_sglist;
13164         struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13165         struct ctl_softc *softc;
13166         int retval;
13167         int i;
13168
13169         retval = 0;
13170         softc = control_softc;
13171
13172         local_sglist = io->io_hdr.local_sglist;
13173         local_dma_sglist = io->io_hdr.local_dma_sglist;
13174         remote_sglist = io->io_hdr.remote_sglist;
13175         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13176
13177         if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13178                 for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13179                         local_sglist[i].len = remote_sglist[i].len;
13180
13181                         /*
13182                          * XXX Detect the situation where the RS-level I/O
13183                          * redirector on the other side has already read the
13184                          * data off of the AOR RS on this side, and
13185                          * transferred it to remote (mirror) memory on the
13186                          * other side.  Since we already have the data in
13187                          * memory here, we just need to use it.
13188                          *
13189                          * XXX KDM this can probably be removed once we
13190                          * get the cache device code in and take the
13191                          * current AOR implementation out.
13192                          */
13193 #ifdef NEEDTOPORT
13194                         if ((remote_sglist[i].addr >=
13195                              (void *)vtophys(softc->mirr->addr))
13196                          && (remote_sglist[i].addr <
13197                              ((void *)vtophys(softc->mirr->addr) +
13198                              CacheMirrorOffset))) {
13199                                 local_sglist[i].addr = remote_sglist[i].addr -
13200                                         CacheMirrorOffset;
13201                                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13202                                      CTL_FLAG_DATA_IN)
13203                                         io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13204                         } else {
13205                                 local_sglist[i].addr = remote_sglist[i].addr +
13206                                         CacheMirrorOffset;
13207                         }
13208 #endif
13209 #if 0
13210                         printf("%s: local %p, remote %p, len %d\n",
13211                                __func__, local_sglist[i].addr,
13212                                remote_sglist[i].addr, local_sglist[i].len);
13213 #endif
13214                 }
13215         } else {
13216                 uint32_t len_to_go;
13217
13218                 /*
13219                  * In this case, we don't have automatically allocated
13220                  * memory for this I/O on this controller.  This typically
13221                  * happens with internal CTL I/O -- e.g. inquiry, mode
13222                  * sense, etc.  Anything coming from RAIDCore will have
13223                  * a mirror area available.
13224                  */
13225                 len_to_go = io->scsiio.kern_data_len;
13226
13227                 /*
13228                  * Clear the no datasync flag, we have to use malloced
13229                  * buffers.
13230                  */
13231                 io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13232
13233                 /*
13234                  * The difficult thing here is that the size of the various
13235                  * S/G segments may be different than the size from the
13236                  * remote controller.  That'll make it harder when DMAing
13237                  * the data back to the other side.
13238                  */
13239                 for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13240                      sizeof(io->io_hdr.remote_sglist[0])) &&
13241                      (len_to_go > 0); i++) {
13242                         local_sglist[i].len = MIN(len_to_go, 131072);
13243                         CTL_SIZE_8B(local_dma_sglist[i].len,
13244                                     local_sglist[i].len);
13245                         local_sglist[i].addr =
13246                                 malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13247
13248                         local_dma_sglist[i].addr = local_sglist[i].addr;
13249
13250                         if (local_sglist[i].addr == NULL) {
13251                                 int j;
13252
13253                                 printf("malloc failed for %zd bytes!",
13254                                        local_dma_sglist[i].len);
13255                                 for (j = 0; j < i; j++) {
13256                                         free(local_sglist[j].addr, M_CTL);
13257                                 }
13258                                 ctl_set_internal_failure(&io->scsiio,
13259                                                          /*sks_valid*/ 1,
13260                                                          /*retry_count*/ 4857);
13261                                 retval = 1;
13262                                 goto bailout_error;
13263                                 
13264                         }
13265                         /* XXX KDM do we need a sync here? */
13266
13267                         len_to_go -= local_sglist[i].len;
13268                 }
13269                 /*
13270                  * Reset the number of S/G entries accordingly.  The
13271                  * original number of S/G entries is available in
13272                  * rem_sg_entries.
13273                  */
13274                 io->scsiio.kern_sg_entries = i;
13275
13276 #if 0
13277                 printf("%s: kern_sg_entries = %d\n", __func__,
13278                        io->scsiio.kern_sg_entries);
13279                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13280                         printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13281                                local_sglist[i].addr, local_sglist[i].len,
13282                                local_dma_sglist[i].len);
13283 #endif
13284         }
13285
13286
13287         return (retval);
13288
13289 bailout_error:
13290
13291         ctl_send_datamove_done(io, /*have_lock*/ 0);
13292
13293         return (retval);
13294 }
13295
13296 static int
13297 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13298                          ctl_ha_dt_cb callback)
13299 {
13300         struct ctl_ha_dt_req *rq;
13301         struct ctl_sg_entry *remote_sglist, *local_sglist;
13302         struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13303         uint32_t local_used, remote_used, total_used;
13304         int retval;
13305         int i, j;
13306
13307         retval = 0;
13308
13309         rq = ctl_dt_req_alloc();
13310
13311         /*
13312          * If we failed to allocate the request, and if the DMA didn't fail
13313          * anyway, set busy status.  This is just a resource allocation
13314          * failure.
13315          */
13316         if ((rq == NULL)
13317          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13318                 ctl_set_busy(&io->scsiio);
13319
13320         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13321
13322                 if (rq != NULL)
13323                         ctl_dt_req_free(rq);
13324
13325                 /*
13326                  * The data move failed.  We need to return status back
13327                  * to the other controller.  No point in trying to DMA
13328                  * data to the remote controller.
13329                  */
13330
13331                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13332
13333                 retval = 1;
13334
13335                 goto bailout;
13336         }
13337
13338         local_sglist = io->io_hdr.local_sglist;
13339         local_dma_sglist = io->io_hdr.local_dma_sglist;
13340         remote_sglist = io->io_hdr.remote_sglist;
13341         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13342         local_used = 0;
13343         remote_used = 0;
13344         total_used = 0;
13345
13346         if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13347                 rq->ret = CTL_HA_STATUS_SUCCESS;
13348                 rq->context = io;
13349                 callback(rq);
13350                 goto bailout;
13351         }
13352
13353         /*
13354          * Pull/push the data over the wire from/to the other controller.
13355          * This takes into account the possibility that the local and
13356          * remote sglists may not be identical in terms of the size of
13357          * the elements and the number of elements.
13358          *
13359          * One fundamental assumption here is that the length allocated for
13360          * both the local and remote sglists is identical.  Otherwise, we've
13361          * essentially got a coding error of some sort.
13362          */
13363         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13364                 int isc_ret;
13365                 uint32_t cur_len, dma_length;
13366                 uint8_t *tmp_ptr;
13367
13368                 rq->id = CTL_HA_DATA_CTL;
13369                 rq->command = command;
13370                 rq->context = io;
13371
13372                 /*
13373                  * Both pointers should be aligned.  But it is possible
13374                  * that the allocation length is not.  They should both
13375                  * also have enough slack left over at the end, though,
13376                  * to round up to the next 8 byte boundary.
13377                  */
13378                 cur_len = MIN(local_sglist[i].len - local_used,
13379                               remote_sglist[j].len - remote_used);
13380
13381                 /*
13382                  * In this case, we have a size issue and need to decrease
13383                  * the size, except in the case where we actually have less
13384                  * than 8 bytes left.  In that case, we need to increase
13385                  * the DMA length to get the last bit.
13386                  */
13387                 if ((cur_len & 0x7) != 0) {
13388                         if (cur_len > 0x7) {
13389                                 cur_len = cur_len - (cur_len & 0x7);
13390                                 dma_length = cur_len;
13391                         } else {
13392                                 CTL_SIZE_8B(dma_length, cur_len);
13393                         }
13394
13395                 } else
13396                         dma_length = cur_len;
13397
13398                 /*
13399                  * If we had to allocate memory for this I/O, instead of using
13400                  * the non-cached mirror memory, we'll need to flush the cache
13401                  * before trying to DMA to the other controller.
13402                  *
13403                  * We could end up doing this multiple times for the same
13404                  * segment if we have a larger local segment than remote
13405                  * segment.  That shouldn't be an issue.
13406                  */
13407                 if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13408                         /*
13409                          * XXX KDM use bus_dmamap_sync() here.
13410                          */
13411                 }
13412
13413                 rq->size = dma_length;
13414
13415                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
13416                 tmp_ptr += local_used;
13417
13418                 /* Use physical addresses when talking to ISC hardware */
13419                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13420                         /* XXX KDM use busdma */
13421 #if 0
13422                         rq->local = vtophys(tmp_ptr);
13423 #endif
13424                 } else
13425                         rq->local = tmp_ptr;
13426
13427                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13428                 tmp_ptr += remote_used;
13429                 rq->remote = tmp_ptr;
13430
13431                 rq->callback = NULL;
13432
13433                 local_used += cur_len;
13434                 if (local_used >= local_sglist[i].len) {
13435                         i++;
13436                         local_used = 0;
13437                 }
13438
13439                 remote_used += cur_len;
13440                 if (remote_used >= remote_sglist[j].len) {
13441                         j++;
13442                         remote_used = 0;
13443                 }
13444                 total_used += cur_len;
13445
13446                 if (total_used >= io->scsiio.kern_data_len)
13447                         rq->callback = callback;
13448
13449                 if ((rq->size & 0x7) != 0) {
13450                         printf("%s: warning: size %d is not on 8b boundary\n",
13451                                __func__, rq->size);
13452                 }
13453                 if (((uintptr_t)rq->local & 0x7) != 0) {
13454                         printf("%s: warning: local %p not on 8b boundary\n",
13455                                __func__, rq->local);
13456                 }
13457                 if (((uintptr_t)rq->remote & 0x7) != 0) {
13458                         printf("%s: warning: remote %p not on 8b boundary\n",
13459                                __func__, rq->local);
13460                 }
13461 #if 0
13462                 printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13463                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13464                        rq->local, rq->remote, rq->size);
13465 #endif
13466
13467                 isc_ret = ctl_dt_single(rq);
13468                 if (isc_ret == CTL_HA_STATUS_WAIT)
13469                         continue;
13470
13471                 if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13472                         rq->ret = CTL_HA_STATUS_SUCCESS;
13473                 } else {
13474                         rq->ret = isc_ret;
13475                 }
13476                 callback(rq);
13477                 goto bailout;
13478         }
13479
13480 bailout:
13481         return (retval);
13482
13483 }
13484
13485 static void
13486 ctl_datamove_remote_read(union ctl_io *io)
13487 {
13488         int retval;
13489         int i;
13490
13491         /*
13492          * This will send an error to the other controller in the case of a
13493          * failure.
13494          */
13495         retval = ctl_datamove_remote_sgl_setup(io);
13496         if (retval != 0)
13497                 return;
13498
13499         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13500                                           ctl_datamove_remote_read_cb);
13501         if ((retval != 0)
13502          && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13503                 /*
13504                  * Make sure we free memory if there was an error..  The
13505                  * ctl_datamove_remote_xfer() function will send the
13506                  * datamove done message, or call the callback with an
13507                  * error if there is a problem.
13508                  */
13509                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13510                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13511         }
13512
13513         return;
13514 }
13515
13516 /*
13517  * Process a datamove request from the other controller.  This is used for
13518  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13519  * first.  Once that is complete, the data gets DMAed into the remote
13520  * controller's memory.  For reads, we DMA from the remote controller's
13521  * memory into our memory first, and then move it out to the FETD.
13522  */
13523 static void
13524 ctl_datamove_remote(union ctl_io *io)
13525 {
13526         struct ctl_softc *softc;
13527
13528         softc = control_softc;
13529
13530         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13531
13532         /*
13533          * Note that we look for an aborted I/O here, but don't do some of
13534          * the other checks that ctl_datamove() normally does.
13535          * We don't need to run the datamove delay code, since that should
13536          * have been done if need be on the other controller.
13537          */
13538         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13539                 printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13540                        io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13541                        io->io_hdr.nexus.targ_port,
13542                        io->io_hdr.nexus.targ_target.id,
13543                        io->io_hdr.nexus.targ_lun);
13544                 io->io_hdr.port_status = 31338;
13545                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13546                 return;
13547         }
13548
13549         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13550                 ctl_datamove_remote_write(io);
13551         } else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13552                 ctl_datamove_remote_read(io);
13553         } else {
13554                 union ctl_ha_msg msg;
13555                 struct scsi_sense_data *sense;
13556                 uint8_t sks[3];
13557                 int retry_count;
13558
13559                 memset(&msg, 0, sizeof(msg));
13560
13561                 msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13562                 msg.hdr.status = CTL_SCSI_ERROR;
13563                 msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13564
13565                 retry_count = 4243;
13566
13567                 sense = &msg.scsi.sense_data;
13568                 sks[0] = SSD_SCS_VALID;
13569                 sks[1] = (retry_count >> 8) & 0xff;
13570                 sks[2] = retry_count & 0xff;
13571
13572                 /* "Internal target failure" */
13573                 scsi_set_sense_data(sense,
13574                                     /*sense_format*/ SSD_TYPE_NONE,
13575                                     /*current_error*/ 1,
13576                                     /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13577                                     /*asc*/ 0x44,
13578                                     /*ascq*/ 0x00,
13579                                     /*type*/ SSD_ELEM_SKS,
13580                                     /*size*/ sizeof(sks),
13581                                     /*data*/ sks,
13582                                     SSD_ELEM_NONE);
13583
13584                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13585                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13586                         ctl_failover_io(io, /*have_lock*/ 1);
13587                         return;
13588                 }
13589
13590                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13591                     CTL_HA_STATUS_SUCCESS) {
13592                         /* XXX KDM what to do if this fails? */
13593                 }
13594                 return;
13595         }
13596         
13597 }
13598
13599 static int
13600 ctl_process_done(union ctl_io *io)
13601 {
13602         struct ctl_lun *lun;
13603         struct ctl_softc *softc = control_softc;
13604         void (*fe_done)(union ctl_io *io);
13605         uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13606
13607         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13608
13609         fe_done = softc->ctl_ports[targ_port]->fe_done;
13610
13611 #ifdef CTL_TIME_IO
13612         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13613                 char str[256];
13614                 char path_str[64];
13615                 struct sbuf sb;
13616
13617                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13618                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13619
13620                 sbuf_cat(&sb, path_str);
13621                 switch (io->io_hdr.io_type) {
13622                 case CTL_IO_SCSI:
13623                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13624                         sbuf_printf(&sb, "\n");
13625                         sbuf_cat(&sb, path_str);
13626                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13627                                     io->scsiio.tag_num, io->scsiio.tag_type);
13628                         break;
13629                 case CTL_IO_TASK:
13630                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13631                                     "Tag Type: %d\n", io->taskio.task_action,
13632                                     io->taskio.tag_num, io->taskio.tag_type);
13633                         break;
13634                 default:
13635                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13636                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13637                         break;
13638                 }
13639                 sbuf_cat(&sb, path_str);
13640                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13641                             (intmax_t)time_uptime - io->io_hdr.start_time);
13642                 sbuf_finish(&sb);
13643                 printf("%s", sbuf_data(&sb));
13644         }
13645 #endif /* CTL_TIME_IO */
13646
13647         switch (io->io_hdr.io_type) {
13648         case CTL_IO_SCSI:
13649                 break;
13650         case CTL_IO_TASK:
13651                 if (ctl_debug & CTL_DEBUG_INFO)
13652                         ctl_io_error_print(io, NULL);
13653                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13654                         ctl_free_io(io);
13655                 else
13656                         fe_done(io);
13657                 return (CTL_RETVAL_COMPLETE);
13658         default:
13659                 panic("ctl_process_done: invalid io type %d\n",
13660                       io->io_hdr.io_type);
13661                 break; /* NOTREACHED */
13662         }
13663
13664         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13665         if (lun == NULL) {
13666                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13667                                  io->io_hdr.nexus.targ_mapped_lun));
13668                 goto bailout;
13669         }
13670
13671         mtx_lock(&lun->lun_lock);
13672
13673         /*
13674          * Check to see if we have any errors to inject here.  We only
13675          * inject errors for commands that don't already have errors set.
13676          */
13677         if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13678             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13679             ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13680                 ctl_inject_error(lun, io);
13681
13682         /*
13683          * XXX KDM how do we treat commands that aren't completed
13684          * successfully?
13685          *
13686          * XXX KDM should we also track I/O latency?
13687          */
13688         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13689             io->io_hdr.io_type == CTL_IO_SCSI) {
13690 #ifdef CTL_TIME_IO
13691                 struct bintime cur_bt;
13692 #endif
13693                 int type;
13694
13695                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13696                     CTL_FLAG_DATA_IN)
13697                         type = CTL_STATS_READ;
13698                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13699                     CTL_FLAG_DATA_OUT)
13700                         type = CTL_STATS_WRITE;
13701                 else
13702                         type = CTL_STATS_NO_IO;
13703
13704                 lun->stats.ports[targ_port].bytes[type] +=
13705                     io->scsiio.kern_total_len;
13706                 lun->stats.ports[targ_port].operations[type]++;
13707 #ifdef CTL_TIME_IO
13708                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13709                    &io->io_hdr.dma_bt);
13710                 lun->stats.ports[targ_port].num_dmas[type] +=
13711                     io->io_hdr.num_dmas;
13712                 getbintime(&cur_bt);
13713                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13714                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13715 #endif
13716         }
13717
13718         /*
13719          * Remove this from the OOA queue.
13720          */
13721         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13722 #ifdef CTL_TIME_IO
13723         if (TAILQ_EMPTY(&lun->ooa_queue))
13724                 lun->last_busy = getsbinuptime();
13725 #endif
13726
13727         /*
13728          * Run through the blocked queue on this LUN and see if anything
13729          * has become unblocked, now that this transaction is done.
13730          */
13731         ctl_check_blocked(lun);
13732
13733         /*
13734          * If the LUN has been invalidated, free it if there is nothing
13735          * left on its OOA queue.
13736          */
13737         if ((lun->flags & CTL_LUN_INVALID)
13738          && TAILQ_EMPTY(&lun->ooa_queue)) {
13739                 mtx_unlock(&lun->lun_lock);
13740                 mtx_lock(&softc->ctl_lock);
13741                 ctl_free_lun(lun);
13742                 mtx_unlock(&softc->ctl_lock);
13743         } else
13744                 mtx_unlock(&lun->lun_lock);
13745
13746 bailout:
13747
13748         /*
13749          * If this command has been aborted, make sure we set the status
13750          * properly.  The FETD is responsible for freeing the I/O and doing
13751          * whatever it needs to do to clean up its state.
13752          */
13753         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13754                 ctl_set_task_aborted(&io->scsiio);
13755
13756         /*
13757          * If enabled, print command error status.
13758          */
13759         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13760             (ctl_debug & CTL_DEBUG_INFO) != 0)
13761                 ctl_io_error_print(io, NULL);
13762
13763         /*
13764          * Tell the FETD or the other shelf controller we're done with this
13765          * command.  Note that only SCSI commands get to this point.  Task
13766          * management commands are completed above.
13767          *
13768          * We only send status to the other controller if we're in XFER
13769          * mode.  In SER_ONLY mode, the I/O is done on the controller that
13770          * received the I/O (from CTL's perspective), and so the status is
13771          * generated there.
13772          * 
13773          * XXX KDM if we hold the lock here, we could cause a deadlock
13774          * if the frontend comes back in in this context to queue
13775          * something.
13776          */
13777         if ((softc->ha_mode == CTL_HA_MODE_XFER)
13778          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13779                 union ctl_ha_msg msg;
13780
13781                 memset(&msg, 0, sizeof(msg));
13782                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13783                 msg.hdr.original_sc = io->io_hdr.original_sc;
13784                 msg.hdr.nexus = io->io_hdr.nexus;
13785                 msg.hdr.status = io->io_hdr.status;
13786                 msg.scsi.scsi_status = io->scsiio.scsi_status;
13787                 msg.scsi.tag_num = io->scsiio.tag_num;
13788                 msg.scsi.tag_type = io->scsiio.tag_type;
13789                 msg.scsi.sense_len = io->scsiio.sense_len;
13790                 msg.scsi.sense_residual = io->scsiio.sense_residual;
13791                 msg.scsi.residual = io->scsiio.residual;
13792                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13793                        sizeof(io->scsiio.sense_data));
13794                 /*
13795                  * We copy this whether or not this is an I/O-related
13796                  * command.  Otherwise, we'd have to go and check to see
13797                  * whether it's a read/write command, and it really isn't
13798                  * worth it.
13799                  */
13800                 memcpy(&msg.scsi.lbalen,
13801                        &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13802                        sizeof(msg.scsi.lbalen));
13803
13804                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13805                                 sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13806                         /* XXX do something here */
13807                 }
13808
13809                 ctl_free_io(io);
13810         } else 
13811                 fe_done(io);
13812
13813         return (CTL_RETVAL_COMPLETE);
13814 }
13815
13816 #ifdef CTL_WITH_CA
13817 /*
13818  * Front end should call this if it doesn't do autosense.  When the request
13819  * sense comes back in from the initiator, we'll dequeue this and send it.
13820  */
13821 int
13822 ctl_queue_sense(union ctl_io *io)
13823 {
13824         struct ctl_lun *lun;
13825         struct ctl_port *port;
13826         struct ctl_softc *softc;
13827         uint32_t initidx, targ_lun;
13828
13829         softc = control_softc;
13830
13831         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13832
13833         /*
13834          * LUN lookup will likely move to the ctl_work_thread() once we
13835          * have our new queueing infrastructure (that doesn't put things on
13836          * a per-LUN queue initially).  That is so that we can handle
13837          * things like an INQUIRY to a LUN that we don't have enabled.  We
13838          * can't deal with that right now.
13839          */
13840         mtx_lock(&softc->ctl_lock);
13841
13842         /*
13843          * If we don't have a LUN for this, just toss the sense
13844          * information.
13845          */
13846         port = ctl_io_port(&ctsio->io_hdr);
13847         targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13848         if ((targ_lun < CTL_MAX_LUNS)
13849          && (softc->ctl_luns[targ_lun] != NULL))
13850                 lun = softc->ctl_luns[targ_lun];
13851         else
13852                 goto bailout;
13853
13854         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13855
13856         mtx_lock(&lun->lun_lock);
13857         /*
13858          * Already have CA set for this LUN...toss the sense information.
13859          */
13860         if (ctl_is_set(lun->have_ca, initidx)) {
13861                 mtx_unlock(&lun->lun_lock);
13862                 goto bailout;
13863         }
13864
13865         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13866                MIN(sizeof(lun->pending_sense[initidx]),
13867                sizeof(io->scsiio.sense_data)));
13868         ctl_set_mask(lun->have_ca, initidx);
13869         mtx_unlock(&lun->lun_lock);
13870
13871 bailout:
13872         mtx_unlock(&softc->ctl_lock);
13873
13874         ctl_free_io(io);
13875
13876         return (CTL_RETVAL_COMPLETE);
13877 }
13878 #endif
13879
13880 /*
13881  * Primary command inlet from frontend ports.  All SCSI and task I/O
13882  * requests must go through this function.
13883  */
13884 int
13885 ctl_queue(union ctl_io *io)
13886 {
13887         struct ctl_port *port;
13888
13889         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13890
13891 #ifdef CTL_TIME_IO
13892         io->io_hdr.start_time = time_uptime;
13893         getbintime(&io->io_hdr.start_bt);
13894 #endif /* CTL_TIME_IO */
13895
13896         /* Map FE-specific LUN ID into global one. */
13897         port = ctl_io_port(&io->io_hdr);
13898         io->io_hdr.nexus.targ_mapped_lun =
13899             ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13900
13901         switch (io->io_hdr.io_type) {
13902         case CTL_IO_SCSI:
13903         case CTL_IO_TASK:
13904                 if (ctl_debug & CTL_DEBUG_CDB)
13905                         ctl_io_print(io);
13906                 ctl_enqueue_incoming(io);
13907                 break;
13908         default:
13909                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13910                 return (EINVAL);
13911         }
13912
13913         return (CTL_RETVAL_COMPLETE);
13914 }
13915
13916 #ifdef CTL_IO_DELAY
13917 static void
13918 ctl_done_timer_wakeup(void *arg)
13919 {
13920         union ctl_io *io;
13921
13922         io = (union ctl_io *)arg;
13923         ctl_done(io);
13924 }
13925 #endif /* CTL_IO_DELAY */
13926
13927 void
13928 ctl_done(union ctl_io *io)
13929 {
13930
13931         /*
13932          * Enable this to catch duplicate completion issues.
13933          */
13934 #if 0
13935         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13936                 printf("%s: type %d msg %d cdb %x iptl: "
13937                        "%d:%d:%d:%d tag 0x%04x "
13938                        "flag %#x status %x\n",
13939                         __func__,
13940                         io->io_hdr.io_type,
13941                         io->io_hdr.msg_type,
13942                         io->scsiio.cdb[0],
13943                         io->io_hdr.nexus.initid.id,
13944                         io->io_hdr.nexus.targ_port,
13945                         io->io_hdr.nexus.targ_target.id,
13946                         io->io_hdr.nexus.targ_lun,
13947                         (io->io_hdr.io_type ==
13948                         CTL_IO_TASK) ?
13949                         io->taskio.tag_num :
13950                         io->scsiio.tag_num,
13951                         io->io_hdr.flags,
13952                         io->io_hdr.status);
13953         } else
13954                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13955 #endif
13956
13957         /*
13958          * This is an internal copy of an I/O, and should not go through
13959          * the normal done processing logic.
13960          */
13961         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13962                 return;
13963
13964         /*
13965          * We need to send a msg to the serializing shelf to finish the IO
13966          * as well.  We don't send a finish message to the other shelf if
13967          * this is a task management command.  Task management commands
13968          * aren't serialized in the OOA queue, but rather just executed on
13969          * both shelf controllers for commands that originated on that
13970          * controller.
13971          */
13972         if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13973          && (io->io_hdr.io_type != CTL_IO_TASK)) {
13974                 union ctl_ha_msg msg_io;
13975
13976                 msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13977                 msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13978                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13979                     sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13980                 }
13981                 /* continue on to finish IO */
13982         }
13983 #ifdef CTL_IO_DELAY
13984         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13985                 struct ctl_lun *lun;
13986
13987                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13988
13989                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13990         } else {
13991                 struct ctl_lun *lun;
13992
13993                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13994
13995                 if ((lun != NULL)
13996                  && (lun->delay_info.done_delay > 0)) {
13997                         struct callout *callout;
13998
13999                         callout = (struct callout *)&io->io_hdr.timer_bytes;
14000                         callout_init(callout, /*mpsafe*/ 1);
14001                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
14002                         callout_reset(callout,
14003                                       lun->delay_info.done_delay * hz,
14004                                       ctl_done_timer_wakeup, io);
14005                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
14006                                 lun->delay_info.done_delay = 0;
14007                         return;
14008                 }
14009         }
14010 #endif /* CTL_IO_DELAY */
14011
14012         ctl_enqueue_done(io);
14013 }
14014
14015 int
14016 ctl_isc(struct ctl_scsiio *ctsio)
14017 {
14018         struct ctl_lun *lun;
14019         int retval;
14020
14021         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14022
14023         CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
14024
14025         CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
14026
14027         retval = lun->backend->data_submit((union ctl_io *)ctsio);
14028
14029         return (retval);
14030 }
14031
14032
14033 static void
14034 ctl_work_thread(void *arg)
14035 {
14036         struct ctl_thread *thr = (struct ctl_thread *)arg;
14037         struct ctl_softc *softc = thr->ctl_softc;
14038         union ctl_io *io;
14039         int retval;
14040
14041         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
14042
14043         for (;;) {
14044                 retval = 0;
14045
14046                 /*
14047                  * We handle the queues in this order:
14048                  * - ISC
14049                  * - done queue (to free up resources, unblock other commands)
14050                  * - RtR queue
14051                  * - incoming queue
14052                  *
14053                  * If those queues are empty, we break out of the loop and
14054                  * go to sleep.
14055                  */
14056                 mtx_lock(&thr->queue_lock);
14057                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
14058                 if (io != NULL) {
14059                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
14060                         mtx_unlock(&thr->queue_lock);
14061                         ctl_handle_isc(io);
14062                         continue;
14063                 }
14064                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
14065                 if (io != NULL) {
14066                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
14067                         /* clear any blocked commands, call fe_done */
14068                         mtx_unlock(&thr->queue_lock);
14069                         retval = ctl_process_done(io);
14070                         continue;
14071                 }
14072                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
14073                 if (io != NULL) {
14074                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
14075                         mtx_unlock(&thr->queue_lock);
14076                         if (io->io_hdr.io_type == CTL_IO_TASK)
14077                                 ctl_run_task(io);
14078                         else
14079                                 ctl_scsiio_precheck(softc, &io->scsiio);
14080                         continue;
14081                 }
14082                 if (!ctl_pause_rtr) {
14083                         io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
14084                         if (io != NULL) {
14085                                 STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
14086                                 mtx_unlock(&thr->queue_lock);
14087                                 retval = ctl_scsiio(&io->scsiio);
14088                                 if (retval != CTL_RETVAL_COMPLETE)
14089                                         CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
14090                                 continue;
14091                         }
14092                 }
14093
14094                 /* Sleep until we have something to do. */
14095                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
14096         }
14097 }
14098
14099 static void
14100 ctl_lun_thread(void *arg)
14101 {
14102         struct ctl_softc *softc = (struct ctl_softc *)arg;
14103         struct ctl_be_lun *be_lun;
14104         int retval;
14105
14106         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
14107
14108         for (;;) {
14109                 retval = 0;
14110                 mtx_lock(&softc->ctl_lock);
14111                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
14112                 if (be_lun != NULL) {
14113                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
14114                         mtx_unlock(&softc->ctl_lock);
14115                         ctl_create_lun(be_lun);
14116                         continue;
14117                 }
14118
14119                 /* Sleep until we have something to do. */
14120                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
14121                     PDROP | PRIBIO, "-", 0);
14122         }
14123 }
14124
14125 static void
14126 ctl_thresh_thread(void *arg)
14127 {
14128         struct ctl_softc *softc = (struct ctl_softc *)arg;
14129         struct ctl_lun *lun;
14130         struct ctl_be_lun *be_lun;
14131         struct scsi_da_rw_recovery_page *rwpage;
14132         struct ctl_logical_block_provisioning_page *page;
14133         const char *attr;
14134         uint64_t thres, val;
14135         int i, e;
14136
14137         CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
14138
14139         for (;;) {
14140                 mtx_lock(&softc->ctl_lock);
14141                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
14142                         be_lun = lun->be_lun;
14143                         if ((lun->flags & CTL_LUN_DISABLED) ||
14144                             (lun->flags & CTL_LUN_OFFLINE) ||
14145                             lun->backend->lun_attr == NULL)
14146                                 continue;
14147                         rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
14148                         if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
14149                                 continue;
14150                         e = 0;
14151                         page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
14152                         for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
14153                                 if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
14154                                         continue;
14155                                 thres = scsi_4btoul(page->descr[i].count);
14156                                 thres <<= CTL_LBP_EXPONENT;
14157                                 switch (page->descr[i].resource) {
14158                                 case 0x01:
14159                                         attr = "blocksavail";
14160                                         break;
14161                                 case 0x02:
14162                                         attr = "blocksused";
14163                                         break;
14164                                 case 0xf1:
14165                                         attr = "poolblocksavail";
14166                                         break;
14167                                 case 0xf2:
14168                                         attr = "poolblocksused";
14169                                         break;
14170                                 default:
14171                                         continue;
14172                                 }
14173                                 mtx_unlock(&softc->ctl_lock); // XXX
14174                                 val = lun->backend->lun_attr(
14175                                     lun->be_lun->be_lun, attr);
14176                                 mtx_lock(&softc->ctl_lock);
14177                                 if (val == UINT64_MAX)
14178                                         continue;
14179                                 if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
14180                                     == SLBPPD_ARMING_INC)
14181                                         e |= (val >= thres);
14182                                 else
14183                                         e |= (val <= thres);
14184                         }
14185                         mtx_lock(&lun->lun_lock);
14186                         if (e) {
14187                                 if (lun->lasttpt == 0 ||
14188                                     time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
14189                                         lun->lasttpt = time_uptime;
14190                                         ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14191                                 }
14192                         } else {
14193                                 lun->lasttpt = 0;
14194                                 ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14195                         }
14196                         mtx_unlock(&lun->lun_lock);
14197                 }
14198                 mtx_unlock(&softc->ctl_lock);
14199                 pause("-", CTL_LBP_PERIOD * hz);
14200         }
14201 }
14202
14203 static void
14204 ctl_enqueue_incoming(union ctl_io *io)
14205 {
14206         struct ctl_softc *softc = control_softc;
14207         struct ctl_thread *thr;
14208         u_int idx;
14209
14210         idx = (io->io_hdr.nexus.targ_port * 127 +
14211                io->io_hdr.nexus.initid.id) % worker_threads;
14212         thr = &softc->threads[idx];
14213         mtx_lock(&thr->queue_lock);
14214         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14215         mtx_unlock(&thr->queue_lock);
14216         wakeup(thr);
14217 }
14218
14219 static void
14220 ctl_enqueue_rtr(union ctl_io *io)
14221 {
14222         struct ctl_softc *softc = control_softc;
14223         struct ctl_thread *thr;
14224
14225         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14226         mtx_lock(&thr->queue_lock);
14227         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14228         mtx_unlock(&thr->queue_lock);
14229         wakeup(thr);
14230 }
14231
14232 static void
14233 ctl_enqueue_done(union ctl_io *io)
14234 {
14235         struct ctl_softc *softc = control_softc;
14236         struct ctl_thread *thr;
14237
14238         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14239         mtx_lock(&thr->queue_lock);
14240         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14241         mtx_unlock(&thr->queue_lock);
14242         wakeup(thr);
14243 }
14244
14245 #ifdef notyet
14246 static void
14247 ctl_enqueue_isc(union ctl_io *io)
14248 {
14249         struct ctl_softc *softc = control_softc;
14250         struct ctl_thread *thr;
14251
14252         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14253         mtx_lock(&thr->queue_lock);
14254         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14255         mtx_unlock(&thr->queue_lock);
14256         wakeup(thr);
14257 }
14258
14259 /* Initialization and failover */
14260
14261 void
14262 ctl_init_isc_msg(void)
14263 {
14264         printf("CTL: Still calling this thing\n");
14265 }
14266
14267 /*
14268  * Init component
14269  *      Initializes component into configuration defined by bootMode
14270  *      (see hasc-sv.c)
14271  *      returns hasc_Status:
14272  *              OK
14273  *              ERROR - fatal error
14274  */
14275 static ctl_ha_comp_status
14276 ctl_isc_init(struct ctl_ha_component *c)
14277 {
14278         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14279
14280         c->status = ret;
14281         return ret;
14282 }
14283
14284 /* Start component
14285  *      Starts component in state requested. If component starts successfully,
14286  *      it must set its own state to the requestrd state
14287  *      When requested state is HASC_STATE_HA, the component may refine it
14288  *      by adding _SLAVE or _MASTER flags.
14289  *      Currently allowed state transitions are:
14290  *      UNKNOWN->HA             - initial startup
14291  *      UNKNOWN->SINGLE - initial startup when no parter detected
14292  *      HA->SINGLE              - failover
14293  * returns ctl_ha_comp_status:
14294  *              OK      - component successfully started in requested state
14295  *              FAILED  - could not start the requested state, failover may
14296  *                        be possible
14297  *              ERROR   - fatal error detected, no future startup possible
14298  */
14299 static ctl_ha_comp_status
14300 ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14301 {
14302         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14303
14304         printf("%s: go\n", __func__);
14305
14306         // UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14307         if (c->state == CTL_HA_STATE_UNKNOWN ) {
14308                 control_softc->is_single = 0;
14309                 if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14310                     != CTL_HA_STATUS_SUCCESS) {
14311                         printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14312                         ret = CTL_HA_COMP_STATUS_ERROR;
14313                 }
14314         } else if (CTL_HA_STATE_IS_HA(c->state)
14315                 && CTL_HA_STATE_IS_SINGLE(state)){
14316                 // HA->SINGLE transition
14317                 ctl_failover();
14318                 control_softc->is_single = 1;
14319         } else {
14320                 printf("ctl_isc_start:Invalid state transition %X->%X\n",
14321                        c->state, state);
14322                 ret = CTL_HA_COMP_STATUS_ERROR;
14323         }
14324         if (CTL_HA_STATE_IS_SINGLE(state))
14325                 control_softc->is_single = 1;
14326
14327         c->state = state;
14328         c->status = ret;
14329         return ret;
14330 }
14331
14332 /*
14333  * Quiesce component
14334  * The component must clear any error conditions (set status to OK) and
14335  * prepare itself to another Start call
14336  * returns ctl_ha_comp_status:
14337  *      OK
14338  *      ERROR
14339  */
14340 static ctl_ha_comp_status
14341 ctl_isc_quiesce(struct ctl_ha_component *c)
14342 {
14343         int ret = CTL_HA_COMP_STATUS_OK;
14344
14345         ctl_pause_rtr = 1;
14346         c->status = ret;
14347         return ret;
14348 }
14349
14350 struct ctl_ha_component ctl_ha_component_ctlisc =
14351 {
14352         .name = "CTL ISC",
14353         .state = CTL_HA_STATE_UNKNOWN,
14354         .init = ctl_isc_init,
14355         .start = ctl_isc_start,
14356         .quiesce = ctl_isc_quiesce
14357 };
14358 #endif
14359
14360 /*
14361  *  vim: ts=8
14362  */