]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/ctl.c
MFC r275942: Reduce number of places where global control_softc is used.
[FreeBSD/stable/10.git] / sys / cam / ctl / ctl.c
1 /*-
2  * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3  * Copyright (c) 2012 The FreeBSD Foundation
4  * All rights reserved.
5  *
6  * Portions of this software were developed by Edward Tomasz Napierala
7  * under sponsorship from the FreeBSD Foundation.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions, and the following disclaimer,
14  *    without modification.
15  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
16  *    substantially similar to the "NO WARRANTY" disclaimer below
17  *    ("Disclaimer") and any redistribution must be conditioned upon
18  *    including a substantially similar Disclaimer requirement for further
19  *    binary redistribution.
20  *
21  * NO WARRANTY
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
25  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
31  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGES.
33  *
34  * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/ctl.c#8 $
35  */
36 /*
37  * CAM Target Layer, a SCSI device emulation subsystem.
38  *
39  * Author: Ken Merry <ken@FreeBSD.org>
40  */
41
42 #define _CTL_C
43
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/ctype.h>
50 #include <sys/kernel.h>
51 #include <sys/types.h>
52 #include <sys/kthread.h>
53 #include <sys/bio.h>
54 #include <sys/fcntl.h>
55 #include <sys/lock.h>
56 #include <sys/module.h>
57 #include <sys/mutex.h>
58 #include <sys/condvar.h>
59 #include <sys/malloc.h>
60 #include <sys/conf.h>
61 #include <sys/ioccom.h>
62 #include <sys/queue.h>
63 #include <sys/sbuf.h>
64 #include <sys/smp.h>
65 #include <sys/endian.h>
66 #include <sys/sysctl.h>
67 #include <vm/uma.h>
68
69 #include <cam/cam.h>
70 #include <cam/scsi/scsi_all.h>
71 #include <cam/scsi/scsi_da.h>
72 #include <cam/ctl/ctl_io.h>
73 #include <cam/ctl/ctl.h>
74 #include <cam/ctl/ctl_frontend.h>
75 #include <cam/ctl/ctl_frontend_internal.h>
76 #include <cam/ctl/ctl_util.h>
77 #include <cam/ctl/ctl_backend.h>
78 #include <cam/ctl/ctl_ioctl.h>
79 #include <cam/ctl/ctl_ha.h>
80 #include <cam/ctl/ctl_private.h>
81 #include <cam/ctl/ctl_debug.h>
82 #include <cam/ctl/ctl_scsi_all.h>
83 #include <cam/ctl/ctl_error.h>
84
85 struct ctl_softc *control_softc = NULL;
86
87 /*
88  * Size and alignment macros needed for Copan-specific HA hardware.  These
89  * can go away when the HA code is re-written, and uses busdma for any
90  * hardware.
91  */
92 #define CTL_ALIGN_8B(target, source, type)                              \
93         if (((uint32_t)source & 0x7) != 0)                              \
94                 target = (type)(source + (0x8 - ((uint32_t)source & 0x7)));\
95         else                                                            \
96                 target = (type)source;
97
98 #define CTL_SIZE_8B(target, size)                                       \
99         if ((size & 0x7) != 0)                                          \
100                 target = size + (0x8 - (size & 0x7));                   \
101         else                                                            \
102                 target = size;
103
104 #define CTL_ALIGN_8B_MARGIN     16
105
106 /*
107  * Template mode pages.
108  */
109
110 /*
111  * Note that these are default values only.  The actual values will be
112  * filled in when the user does a mode sense.
113  */
114 static struct copan_debugconf_subpage debugconf_page_default = {
115         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
116         DBGCNF_SUBPAGE_CODE,            /* subpage */
117         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
118          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
119         DBGCNF_VERSION,                 /* page_version */
120         {CTL_TIME_IO_DEFAULT_SECS>>8,
121          CTL_TIME_IO_DEFAULT_SECS>>0},  /* ctl_time_io_secs */
122 };
123
124 static struct copan_debugconf_subpage debugconf_page_changeable = {
125         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
126         DBGCNF_SUBPAGE_CODE,            /* subpage */
127         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
128          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
129         0,                              /* page_version */
130         {0xff,0xff},                    /* ctl_time_io_secs */
131 };
132
133 static struct scsi_da_rw_recovery_page rw_er_page_default = {
134         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
135         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
136         /*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
137         /*read_retry_count*/0,
138         /*correction_span*/0,
139         /*head_offset_count*/0,
140         /*data_strobe_offset_cnt*/0,
141         /*byte8*/SMS_RWER_LBPERE,
142         /*write_retry_count*/0,
143         /*reserved2*/0,
144         /*recovery_time_limit*/{0, 0},
145 };
146
147 static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
148         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
149         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
150         /*byte3*/0,
151         /*read_retry_count*/0,
152         /*correction_span*/0,
153         /*head_offset_count*/0,
154         /*data_strobe_offset_cnt*/0,
155         /*byte8*/0,
156         /*write_retry_count*/0,
157         /*reserved2*/0,
158         /*recovery_time_limit*/{0, 0},
159 };
160
161 static struct scsi_format_page format_page_default = {
162         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
163         /*page_length*/sizeof(struct scsi_format_page) - 2,
164         /*tracks_per_zone*/ {0, 0},
165         /*alt_sectors_per_zone*/ {0, 0},
166         /*alt_tracks_per_zone*/ {0, 0},
167         /*alt_tracks_per_lun*/ {0, 0},
168         /*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
169                                 CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
170         /*bytes_per_sector*/ {0, 0},
171         /*interleave*/ {0, 0},
172         /*track_skew*/ {0, 0},
173         /*cylinder_skew*/ {0, 0},
174         /*flags*/ SFP_HSEC,
175         /*reserved*/ {0, 0, 0}
176 };
177
178 static struct scsi_format_page format_page_changeable = {
179         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
180         /*page_length*/sizeof(struct scsi_format_page) - 2,
181         /*tracks_per_zone*/ {0, 0},
182         /*alt_sectors_per_zone*/ {0, 0},
183         /*alt_tracks_per_zone*/ {0, 0},
184         /*alt_tracks_per_lun*/ {0, 0},
185         /*sectors_per_track*/ {0, 0},
186         /*bytes_per_sector*/ {0, 0},
187         /*interleave*/ {0, 0},
188         /*track_skew*/ {0, 0},
189         /*cylinder_skew*/ {0, 0},
190         /*flags*/ 0,
191         /*reserved*/ {0, 0, 0}
192 };
193
194 static struct scsi_rigid_disk_page rigid_disk_page_default = {
195         /*page_code*/SMS_RIGID_DISK_PAGE,
196         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
197         /*cylinders*/ {0, 0, 0},
198         /*heads*/ CTL_DEFAULT_HEADS,
199         /*start_write_precomp*/ {0, 0, 0},
200         /*start_reduced_current*/ {0, 0, 0},
201         /*step_rate*/ {0, 0},
202         /*landing_zone_cylinder*/ {0, 0, 0},
203         /*rpl*/ SRDP_RPL_DISABLED,
204         /*rotational_offset*/ 0,
205         /*reserved1*/ 0,
206         /*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
207                            CTL_DEFAULT_ROTATION_RATE & 0xff},
208         /*reserved2*/ {0, 0}
209 };
210
211 static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
212         /*page_code*/SMS_RIGID_DISK_PAGE,
213         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
214         /*cylinders*/ {0, 0, 0},
215         /*heads*/ 0,
216         /*start_write_precomp*/ {0, 0, 0},
217         /*start_reduced_current*/ {0, 0, 0},
218         /*step_rate*/ {0, 0},
219         /*landing_zone_cylinder*/ {0, 0, 0},
220         /*rpl*/ 0,
221         /*rotational_offset*/ 0,
222         /*reserved1*/ 0,
223         /*rotation_rate*/ {0, 0},
224         /*reserved2*/ {0, 0}
225 };
226
227 static struct scsi_caching_page caching_page_default = {
228         /*page_code*/SMS_CACHING_PAGE,
229         /*page_length*/sizeof(struct scsi_caching_page) - 2,
230         /*flags1*/ SCP_DISC | SCP_WCE,
231         /*ret_priority*/ 0,
232         /*disable_pf_transfer_len*/ {0xff, 0xff},
233         /*min_prefetch*/ {0, 0},
234         /*max_prefetch*/ {0xff, 0xff},
235         /*max_pf_ceiling*/ {0xff, 0xff},
236         /*flags2*/ 0,
237         /*cache_segments*/ 0,
238         /*cache_seg_size*/ {0, 0},
239         /*reserved*/ 0,
240         /*non_cache_seg_size*/ {0, 0, 0}
241 };
242
243 static struct scsi_caching_page caching_page_changeable = {
244         /*page_code*/SMS_CACHING_PAGE,
245         /*page_length*/sizeof(struct scsi_caching_page) - 2,
246         /*flags1*/ SCP_WCE | SCP_RCD,
247         /*ret_priority*/ 0,
248         /*disable_pf_transfer_len*/ {0, 0},
249         /*min_prefetch*/ {0, 0},
250         /*max_prefetch*/ {0, 0},
251         /*max_pf_ceiling*/ {0, 0},
252         /*flags2*/ 0,
253         /*cache_segments*/ 0,
254         /*cache_seg_size*/ {0, 0},
255         /*reserved*/ 0,
256         /*non_cache_seg_size*/ {0, 0, 0}
257 };
258
259 static struct scsi_control_page control_page_default = {
260         /*page_code*/SMS_CONTROL_MODE_PAGE,
261         /*page_length*/sizeof(struct scsi_control_page) - 2,
262         /*rlec*/0,
263         /*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
264         /*eca_and_aen*/0,
265         /*flags4*/SCP_TAS,
266         /*aen_holdoff_period*/{0, 0},
267         /*busy_timeout_period*/{0, 0},
268         /*extended_selftest_completion_time*/{0, 0}
269 };
270
271 static struct scsi_control_page control_page_changeable = {
272         /*page_code*/SMS_CONTROL_MODE_PAGE,
273         /*page_length*/sizeof(struct scsi_control_page) - 2,
274         /*rlec*/SCP_DSENSE,
275         /*queue_flags*/SCP_QUEUE_ALG_MASK,
276         /*eca_and_aen*/SCP_SWP,
277         /*flags4*/0,
278         /*aen_holdoff_period*/{0, 0},
279         /*busy_timeout_period*/{0, 0},
280         /*extended_selftest_completion_time*/{0, 0}
281 };
282
283 static struct scsi_info_exceptions_page ie_page_default = {
284         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
285         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
286         /*info_flags*/SIEP_FLAGS_DEXCPT,
287         /*mrie*/0,
288         /*interval_timer*/{0, 0, 0, 0},
289         /*report_count*/{0, 0, 0, 0}
290 };
291
292 static struct scsi_info_exceptions_page ie_page_changeable = {
293         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
294         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
295         /*info_flags*/0,
296         /*mrie*/0,
297         /*interval_timer*/{0, 0, 0, 0},
298         /*report_count*/{0, 0, 0, 0}
299 };
300
301 #define CTL_LBPM_LEN    (sizeof(struct ctl_logical_block_provisioning_page) - 4)
302
303 static struct ctl_logical_block_provisioning_page lbp_page_default = {{
304         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
305         /*subpage_code*/0x02,
306         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
307         /*flags*/0,
308         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
309         /*descr*/{}},
310         {{/*flags*/0,
311           /*resource*/0x01,
312           /*reserved*/{0, 0},
313           /*count*/{0, 0, 0, 0}},
314          {/*flags*/0,
315           /*resource*/0x02,
316           /*reserved*/{0, 0},
317           /*count*/{0, 0, 0, 0}},
318          {/*flags*/0,
319           /*resource*/0xf1,
320           /*reserved*/{0, 0},
321           /*count*/{0, 0, 0, 0}},
322          {/*flags*/0,
323           /*resource*/0xf2,
324           /*reserved*/{0, 0},
325           /*count*/{0, 0, 0, 0}}
326         }
327 };
328
329 static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
330         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
331         /*subpage_code*/0x02,
332         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
333         /*flags*/0,
334         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
335         /*descr*/{}},
336         {{/*flags*/0,
337           /*resource*/0,
338           /*reserved*/{0, 0},
339           /*count*/{0, 0, 0, 0}},
340          {/*flags*/0,
341           /*resource*/0,
342           /*reserved*/{0, 0},
343           /*count*/{0, 0, 0, 0}},
344          {/*flags*/0,
345           /*resource*/0,
346           /*reserved*/{0, 0},
347           /*count*/{0, 0, 0, 0}},
348          {/*flags*/0,
349           /*resource*/0,
350           /*reserved*/{0, 0},
351           /*count*/{0, 0, 0, 0}}
352         }
353 };
354
355 /*
356  * XXX KDM move these into the softc.
357  */
358 static int rcv_sync_msg;
359 static uint8_t ctl_pause_rtr;
360
361 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
362 static int worker_threads = -1;
363 TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
364 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
365     &worker_threads, 1, "Number of worker threads");
366 static int ctl_debug = CTL_DEBUG_NONE;
367 TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
368 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
369     &ctl_debug, 0, "Enabled debug flags");
370
371 /*
372  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
373  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
374  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
375  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
376  */
377 #define SCSI_EVPD_NUM_SUPPORTED_PAGES   10
378
379 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
380                                   int param);
381 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
382 static int ctl_init(void);
383 void ctl_shutdown(void);
384 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
385 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
386 static void ctl_ioctl_online(void *arg);
387 static void ctl_ioctl_offline(void *arg);
388 static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
389 static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
390 static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
391 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
392 static int ctl_ioctl_submit_wait(union ctl_io *io);
393 static void ctl_ioctl_datamove(union ctl_io *io);
394 static void ctl_ioctl_done(union ctl_io *io);
395 static void ctl_ioctl_hard_startstop_callback(void *arg,
396                                               struct cfi_metatask *metatask);
397 static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
398 static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
399                               struct ctl_ooa *ooa_hdr,
400                               struct ctl_ooa_entry *kern_entries);
401 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
402                      struct thread *td);
403 static uint32_t ctl_map_lun(struct ctl_softc *softc, int port_num, uint32_t lun);
404 static uint32_t ctl_map_lun_back(struct ctl_softc *softc, int port_num, uint32_t lun);
405 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
406                          struct ctl_be_lun *be_lun, struct ctl_id target_id);
407 static int ctl_free_lun(struct ctl_lun *lun);
408 static void ctl_create_lun(struct ctl_be_lun *be_lun);
409 /**
410 static void ctl_failover_change_pages(struct ctl_softc *softc,
411                                       struct ctl_scsiio *ctsio, int master);
412 **/
413
414 static int ctl_do_mode_select(union ctl_io *io);
415 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
416                            uint64_t res_key, uint64_t sa_res_key,
417                            uint8_t type, uint32_t residx,
418                            struct ctl_scsiio *ctsio,
419                            struct scsi_per_res_out *cdb,
420                            struct scsi_per_res_out_parms* param);
421 static void ctl_pro_preempt_other(struct ctl_lun *lun,
422                                   union ctl_ha_msg *msg);
423 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
424 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
425 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
426 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
427 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
428 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
429 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
430                                          int alloc_len);
431 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
432                                          int alloc_len);
433 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
434 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
435 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
436 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
437 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
438 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
439     bool seq);
440 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
441 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
442     union ctl_io *pending_io, union ctl_io *ooa_io);
443 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
444                                 union ctl_io *starting_io);
445 static int ctl_check_blocked(struct ctl_lun *lun);
446 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
447                                 const struct ctl_cmd_entry *entry,
448                                 struct ctl_scsiio *ctsio);
449 //static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
450 static void ctl_failover(void);
451 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
452                                struct ctl_scsiio *ctsio);
453 static int ctl_scsiio(struct ctl_scsiio *ctsio);
454
455 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
456 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
457                             ctl_ua_type ua_type);
458 static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
459                          ctl_ua_type ua_type);
460 static int ctl_abort_task(union ctl_io *io);
461 static int ctl_abort_task_set(union ctl_io *io);
462 static int ctl_i_t_nexus_reset(union ctl_io *io);
463 static void ctl_run_task(union ctl_io *io);
464 #ifdef CTL_IO_DELAY
465 static void ctl_datamove_timer_wakeup(void *arg);
466 static void ctl_done_timer_wakeup(void *arg);
467 #endif /* CTL_IO_DELAY */
468
469 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
470 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
471 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
472 static void ctl_datamove_remote_write(union ctl_io *io);
473 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
474 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
475 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
476 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
477                                     ctl_ha_dt_cb callback);
478 static void ctl_datamove_remote_read(union ctl_io *io);
479 static void ctl_datamove_remote(union ctl_io *io);
480 static int ctl_process_done(union ctl_io *io);
481 static void ctl_lun_thread(void *arg);
482 static void ctl_thresh_thread(void *arg);
483 static void ctl_work_thread(void *arg);
484 static void ctl_enqueue_incoming(union ctl_io *io);
485 static void ctl_enqueue_rtr(union ctl_io *io);
486 static void ctl_enqueue_done(union ctl_io *io);
487 static void ctl_enqueue_isc(union ctl_io *io);
488 static const struct ctl_cmd_entry *
489     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
490 static const struct ctl_cmd_entry *
491     ctl_validate_command(struct ctl_scsiio *ctsio);
492 static int ctl_cmd_applicable(uint8_t lun_type,
493     const struct ctl_cmd_entry *entry);
494
495 /*
496  * Load the serialization table.  This isn't very pretty, but is probably
497  * the easiest way to do it.
498  */
499 #include "ctl_ser_table.c"
500
501 /*
502  * We only need to define open, close and ioctl routines for this driver.
503  */
504 static struct cdevsw ctl_cdevsw = {
505         .d_version =    D_VERSION,
506         .d_flags =      0,
507         .d_open =       ctl_open,
508         .d_close =      ctl_close,
509         .d_ioctl =      ctl_ioctl,
510         .d_name =       "ctl",
511 };
512
513
514 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
515 MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
516
517 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
518
519 static moduledata_t ctl_moduledata = {
520         "ctl",
521         ctl_module_event_handler,
522         NULL
523 };
524
525 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
526 MODULE_VERSION(ctl, 1);
527
528 static struct ctl_frontend ioctl_frontend =
529 {
530         .name = "ioctl",
531 };
532
533 static void
534 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
535                             union ctl_ha_msg *msg_info)
536 {
537         struct ctl_scsiio *ctsio;
538
539         if (msg_info->hdr.original_sc == NULL) {
540                 printf("%s: original_sc == NULL!\n", __func__);
541                 /* XXX KDM now what? */
542                 return;
543         }
544
545         ctsio = &msg_info->hdr.original_sc->scsiio;
546         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
547         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
548         ctsio->io_hdr.status = msg_info->hdr.status;
549         ctsio->scsi_status = msg_info->scsi.scsi_status;
550         ctsio->sense_len = msg_info->scsi.sense_len;
551         ctsio->sense_residual = msg_info->scsi.sense_residual;
552         ctsio->residual = msg_info->scsi.residual;
553         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
554                sizeof(ctsio->sense_data));
555         memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
556                &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
557         ctl_enqueue_isc((union ctl_io *)ctsio);
558 }
559
560 static void
561 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
562                                 union ctl_ha_msg *msg_info)
563 {
564         struct ctl_scsiio *ctsio;
565
566         if (msg_info->hdr.serializing_sc == NULL) {
567                 printf("%s: serializing_sc == NULL!\n", __func__);
568                 /* XXX KDM now what? */
569                 return;
570         }
571
572         ctsio = &msg_info->hdr.serializing_sc->scsiio;
573 #if 0
574         /*
575          * Attempt to catch the situation where an I/O has
576          * been freed, and we're using it again.
577          */
578         if (ctsio->io_hdr.io_type == 0xff) {
579                 union ctl_io *tmp_io;
580                 tmp_io = (union ctl_io *)ctsio;
581                 printf("%s: %p use after free!\n", __func__,
582                        ctsio);
583                 printf("%s: type %d msg %d cdb %x iptl: "
584                        "%d:%d:%d:%d tag 0x%04x "
585                        "flag %#x status %x\n",
586                         __func__,
587                         tmp_io->io_hdr.io_type,
588                         tmp_io->io_hdr.msg_type,
589                         tmp_io->scsiio.cdb[0],
590                         tmp_io->io_hdr.nexus.initid.id,
591                         tmp_io->io_hdr.nexus.targ_port,
592                         tmp_io->io_hdr.nexus.targ_target.id,
593                         tmp_io->io_hdr.nexus.targ_lun,
594                         (tmp_io->io_hdr.io_type ==
595                         CTL_IO_TASK) ?
596                         tmp_io->taskio.tag_num :
597                         tmp_io->scsiio.tag_num,
598                         tmp_io->io_hdr.flags,
599                         tmp_io->io_hdr.status);
600         }
601 #endif
602         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
603         ctl_enqueue_isc((union ctl_io *)ctsio);
604 }
605
606 /*
607  * ISC (Inter Shelf Communication) event handler.  Events from the HA
608  * subsystem come in here.
609  */
610 static void
611 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
612 {
613         struct ctl_softc *softc;
614         union ctl_io *io;
615         struct ctl_prio *presio;
616         ctl_ha_status isc_status;
617
618         softc = control_softc;
619         io = NULL;
620
621
622 #if 0
623         printf("CTL: Isc Msg event %d\n", event);
624 #endif
625         if (event == CTL_HA_EVT_MSG_RECV) {
626                 union ctl_ha_msg msg_info;
627
628                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
629                                              sizeof(msg_info), /*wait*/ 0);
630 #if 0
631                 printf("CTL: msg_type %d\n", msg_info.msg_type);
632 #endif
633                 if (isc_status != 0) {
634                         printf("Error receiving message, status = %d\n",
635                                isc_status);
636                         return;
637                 }
638
639                 switch (msg_info.hdr.msg_type) {
640                 case CTL_MSG_SERIALIZE:
641 #if 0
642                         printf("Serialize\n");
643 #endif
644                         io = ctl_alloc_io_nowait(softc->othersc_pool);
645                         if (io == NULL) {
646                                 printf("ctl_isc_event_handler: can't allocate "
647                                        "ctl_io!\n");
648                                 /* Bad Juju */
649                                 /* Need to set busy and send msg back */
650                                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
651                                 msg_info.hdr.status = CTL_SCSI_ERROR;
652                                 msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
653                                 msg_info.scsi.sense_len = 0;
654                                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
655                                     sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
656                                 }
657                                 goto bailout;
658                         }
659                         ctl_zero_io(io);
660                         // populate ctsio from msg_info
661                         io->io_hdr.io_type = CTL_IO_SCSI;
662                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
663                         io->io_hdr.original_sc = msg_info.hdr.original_sc;
664 #if 0
665                         printf("pOrig %x\n", (int)msg_info.original_sc);
666 #endif
667                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
668                                             CTL_FLAG_IO_ACTIVE;
669                         /*
670                          * If we're in serialization-only mode, we don't
671                          * want to go through full done processing.  Thus
672                          * the COPY flag.
673                          *
674                          * XXX KDM add another flag that is more specific.
675                          */
676                         if (softc->ha_mode == CTL_HA_MODE_SER_ONLY)
677                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
678                         io->io_hdr.nexus = msg_info.hdr.nexus;
679 #if 0
680                         printf("targ %d, port %d, iid %d, lun %d\n",
681                                io->io_hdr.nexus.targ_target.id,
682                                io->io_hdr.nexus.targ_port,
683                                io->io_hdr.nexus.initid.id,
684                                io->io_hdr.nexus.targ_lun);
685 #endif
686                         io->scsiio.tag_num = msg_info.scsi.tag_num;
687                         io->scsiio.tag_type = msg_info.scsi.tag_type;
688                         memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
689                                CTL_MAX_CDBLEN);
690                         if (softc->ha_mode == CTL_HA_MODE_XFER) {
691                                 const struct ctl_cmd_entry *entry;
692
693                                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
694                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
695                                 io->io_hdr.flags |=
696                                         entry->flags & CTL_FLAG_DATA_MASK;
697                         }
698                         ctl_enqueue_isc(io);
699                         break;
700
701                 /* Performed on the Originating SC, XFER mode only */
702                 case CTL_MSG_DATAMOVE: {
703                         struct ctl_sg_entry *sgl;
704                         int i, j;
705
706                         io = msg_info.hdr.original_sc;
707                         if (io == NULL) {
708                                 printf("%s: original_sc == NULL!\n", __func__);
709                                 /* XXX KDM do something here */
710                                 break;
711                         }
712                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
713                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
714                         /*
715                          * Keep track of this, we need to send it back over
716                          * when the datamove is complete.
717                          */
718                         io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
719
720                         if (msg_info.dt.sg_sequence == 0) {
721                                 /*
722                                  * XXX KDM we use the preallocated S/G list
723                                  * here, but we'll need to change this to
724                                  * dynamic allocation if we need larger S/G
725                                  * lists.
726                                  */
727                                 if (msg_info.dt.kern_sg_entries >
728                                     sizeof(io->io_hdr.remote_sglist) /
729                                     sizeof(io->io_hdr.remote_sglist[0])) {
730                                         printf("%s: number of S/G entries "
731                                             "needed %u > allocated num %zd\n",
732                                             __func__,
733                                             msg_info.dt.kern_sg_entries,
734                                             sizeof(io->io_hdr.remote_sglist)/
735                                             sizeof(io->io_hdr.remote_sglist[0]));
736                                 
737                                         /*
738                                          * XXX KDM send a message back to
739                                          * the other side to shut down the
740                                          * DMA.  The error will come back
741                                          * through via the normal channel.
742                                          */
743                                         break;
744                                 }
745                                 sgl = io->io_hdr.remote_sglist;
746                                 memset(sgl, 0,
747                                        sizeof(io->io_hdr.remote_sglist));
748
749                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
750
751                                 io->scsiio.kern_sg_entries =
752                                         msg_info.dt.kern_sg_entries;
753                                 io->scsiio.rem_sg_entries =
754                                         msg_info.dt.kern_sg_entries;
755                                 io->scsiio.kern_data_len =
756                                         msg_info.dt.kern_data_len;
757                                 io->scsiio.kern_total_len =
758                                         msg_info.dt.kern_total_len;
759                                 io->scsiio.kern_data_resid =
760                                         msg_info.dt.kern_data_resid;
761                                 io->scsiio.kern_rel_offset =
762                                         msg_info.dt.kern_rel_offset;
763                                 /*
764                                  * Clear out per-DMA flags.
765                                  */
766                                 io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
767                                 /*
768                                  * Add per-DMA flags that are set for this
769                                  * particular DMA request.
770                                  */
771                                 io->io_hdr.flags |= msg_info.dt.flags &
772                                                     CTL_FLAG_RDMA_MASK;
773                         } else
774                                 sgl = (struct ctl_sg_entry *)
775                                         io->scsiio.kern_data_ptr;
776
777                         for (i = msg_info.dt.sent_sg_entries, j = 0;
778                              i < (msg_info.dt.sent_sg_entries +
779                              msg_info.dt.cur_sg_entries); i++, j++) {
780                                 sgl[i].addr = msg_info.dt.sg_list[j].addr;
781                                 sgl[i].len = msg_info.dt.sg_list[j].len;
782
783 #if 0
784                                 printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
785                                        __func__,
786                                        msg_info.dt.sg_list[j].addr,
787                                        msg_info.dt.sg_list[j].len,
788                                        sgl[i].addr, sgl[i].len, j, i);
789 #endif
790                         }
791 #if 0
792                         memcpy(&sgl[msg_info.dt.sent_sg_entries],
793                                msg_info.dt.sg_list,
794                                sizeof(*sgl) * msg_info.dt.cur_sg_entries);
795 #endif
796
797                         /*
798                          * If this is the last piece of the I/O, we've got
799                          * the full S/G list.  Queue processing in the thread.
800                          * Otherwise wait for the next piece.
801                          */
802                         if (msg_info.dt.sg_last != 0)
803                                 ctl_enqueue_isc(io);
804                         break;
805                 }
806                 /* Performed on the Serializing (primary) SC, XFER mode only */
807                 case CTL_MSG_DATAMOVE_DONE: {
808                         if (msg_info.hdr.serializing_sc == NULL) {
809                                 printf("%s: serializing_sc == NULL!\n",
810                                        __func__);
811                                 /* XXX KDM now what? */
812                                 break;
813                         }
814                         /*
815                          * We grab the sense information here in case
816                          * there was a failure, so we can return status
817                          * back to the initiator.
818                          */
819                         io = msg_info.hdr.serializing_sc;
820                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
821                         io->io_hdr.status = msg_info.hdr.status;
822                         io->scsiio.scsi_status = msg_info.scsi.scsi_status;
823                         io->scsiio.sense_len = msg_info.scsi.sense_len;
824                         io->scsiio.sense_residual =msg_info.scsi.sense_residual;
825                         io->io_hdr.port_status = msg_info.scsi.fetd_status;
826                         io->scsiio.residual = msg_info.scsi.residual;
827                         memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
828                                sizeof(io->scsiio.sense_data));
829                         ctl_enqueue_isc(io);
830                         break;
831                 }
832
833                 /* Preformed on Originating SC, SER_ONLY mode */
834                 case CTL_MSG_R2R:
835                         io = msg_info.hdr.original_sc;
836                         if (io == NULL) {
837                                 printf("%s: Major Bummer\n", __func__);
838                                 return;
839                         } else {
840 #if 0
841                                 printf("pOrig %x\n",(int) ctsio);
842 #endif
843                         }
844                         io->io_hdr.msg_type = CTL_MSG_R2R;
845                         io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
846                         ctl_enqueue_isc(io);
847                         break;
848
849                 /*
850                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
851                  * mode.
852                  * Performed on the Originating (i.e. secondary) SC in XFER
853                  * mode
854                  */
855                 case CTL_MSG_FINISH_IO:
856                         if (softc->ha_mode == CTL_HA_MODE_XFER)
857                                 ctl_isc_handler_finish_xfer(softc,
858                                                             &msg_info);
859                         else
860                                 ctl_isc_handler_finish_ser_only(softc,
861                                                                 &msg_info);
862                         break;
863
864                 /* Preformed on Originating SC */
865                 case CTL_MSG_BAD_JUJU:
866                         io = msg_info.hdr.original_sc;
867                         if (io == NULL) {
868                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
869                                        __func__);
870                                 break;
871                         }
872                         ctl_copy_sense_data(&msg_info, io);
873                         /*
874                          * IO should have already been cleaned up on other
875                          * SC so clear this flag so we won't send a message
876                          * back to finish the IO there.
877                          */
878                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
879                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
880
881                         /* io = msg_info.hdr.serializing_sc; */
882                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
883                         ctl_enqueue_isc(io);
884                         break;
885
886                 /* Handle resets sent from the other side */
887                 case CTL_MSG_MANAGE_TASKS: {
888                         struct ctl_taskio *taskio;
889                         taskio = (struct ctl_taskio *)ctl_alloc_io_nowait(
890                             softc->othersc_pool);
891                         if (taskio == NULL) {
892                                 printf("ctl_isc_event_handler: can't allocate "
893                                        "ctl_io!\n");
894                                 /* Bad Juju */
895                                 /* should I just call the proper reset func
896                                    here??? */
897                                 goto bailout;
898                         }
899                         ctl_zero_io((union ctl_io *)taskio);
900                         taskio->io_hdr.io_type = CTL_IO_TASK;
901                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
902                         taskio->io_hdr.nexus = msg_info.hdr.nexus;
903                         taskio->task_action = msg_info.task.task_action;
904                         taskio->tag_num = msg_info.task.tag_num;
905                         taskio->tag_type = msg_info.task.tag_type;
906 #ifdef CTL_TIME_IO
907                         taskio->io_hdr.start_time = time_uptime;
908                         getbintime(&taskio->io_hdr.start_bt);
909 #if 0
910                         cs_prof_gettime(&taskio->io_hdr.start_ticks);
911 #endif
912 #endif /* CTL_TIME_IO */
913                         ctl_run_task((union ctl_io *)taskio);
914                         break;
915                 }
916                 /* Persistent Reserve action which needs attention */
917                 case CTL_MSG_PERS_ACTION:
918                         presio = (struct ctl_prio *)ctl_alloc_io_nowait(
919                             softc->othersc_pool);
920                         if (presio == NULL) {
921                                 printf("ctl_isc_event_handler: can't allocate "
922                                        "ctl_io!\n");
923                                 /* Bad Juju */
924                                 /* Need to set busy and send msg back */
925                                 goto bailout;
926                         }
927                         ctl_zero_io((union ctl_io *)presio);
928                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
929                         presio->pr_msg = msg_info.pr;
930                         ctl_enqueue_isc((union ctl_io *)presio);
931                         break;
932                 case CTL_MSG_SYNC_FE:
933                         rcv_sync_msg = 1;
934                         break;
935                 default:
936                         printf("How did I get here?\n");
937                 }
938         } else if (event == CTL_HA_EVT_MSG_SENT) {
939                 if (param != CTL_HA_STATUS_SUCCESS) {
940                         printf("Bad status from ctl_ha_msg_send status %d\n",
941                                param);
942                 }
943                 return;
944         } else if (event == CTL_HA_EVT_DISCONNECT) {
945                 printf("CTL: Got a disconnect from Isc\n");
946                 return;
947         } else {
948                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
949                 return;
950         }
951
952 bailout:
953         return;
954 }
955
956 static void
957 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
958 {
959         struct scsi_sense_data *sense;
960
961         sense = &dest->scsiio.sense_data;
962         bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
963         dest->scsiio.scsi_status = src->scsi.scsi_status;
964         dest->scsiio.sense_len = src->scsi.sense_len;
965         dest->io_hdr.status = src->hdr.status;
966 }
967
968 static void
969 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
970 {
971         ctl_ua_type *pu;
972
973         mtx_assert(&lun->lun_lock, MA_OWNED);
974         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
975         if (pu == NULL)
976                 return;
977         pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
978 }
979
980 static void
981 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
982 {
983         int i, j;
984
985         mtx_assert(&lun->lun_lock, MA_OWNED);
986         for (i = 0; i < CTL_MAX_PORTS; i++) {
987                 if (lun->pending_ua[i] == NULL)
988                         continue;
989                 for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
990                         if (i * CTL_MAX_INIT_PER_PORT + j == except)
991                                 continue;
992                         lun->pending_ua[i][j] |= ua;
993                 }
994         }
995 }
996
997 static void
998 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
999 {
1000         ctl_ua_type *pu;
1001
1002         mtx_assert(&lun->lun_lock, MA_OWNED);
1003         pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1004         if (pu == NULL)
1005                 return;
1006         pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1007 }
1008
1009 static void
1010 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1011 {
1012         int i, j;
1013
1014         mtx_assert(&lun->lun_lock, MA_OWNED);
1015         for (i = 0; i < CTL_MAX_PORTS; i++) {
1016                 if (lun->pending_ua[i] == NULL)
1017                         continue;
1018                 for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1019                         if (i * CTL_MAX_INIT_PER_PORT + j == except)
1020                                 continue;
1021                         lun->pending_ua[i][j] &= ~ua;
1022                 }
1023         }
1024 }
1025
1026 static int
1027 ctl_ha_state_sysctl(SYSCTL_HANDLER_ARGS)
1028 {
1029         struct ctl_softc *softc = (struct ctl_softc *)arg1;
1030         struct ctl_lun *lun;
1031         int error, value;
1032
1033         if (softc->flags & CTL_FLAG_ACTIVE_SHELF)
1034                 value = 0;
1035         else
1036                 value = 1;
1037
1038         error = sysctl_handle_int(oidp, &value, 0, req);
1039         if ((error != 0) || (req->newptr == NULL))
1040                 return (error);
1041
1042         mtx_lock(&softc->ctl_lock);
1043         if (value == 0)
1044                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1045         else
1046                 softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1047         STAILQ_FOREACH(lun, &softc->lun_list, links) {
1048                 mtx_lock(&lun->lun_lock);
1049                 ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1050                 mtx_unlock(&lun->lun_lock);
1051         }
1052         mtx_unlock(&softc->ctl_lock);
1053         return (0);
1054 }
1055
1056 static int
1057 ctl_init(void)
1058 {
1059         struct ctl_softc *softc;
1060         void *other_pool;
1061         struct ctl_port *port;
1062         int i, error, retval;
1063         //int isc_retval;
1064
1065         retval = 0;
1066         ctl_pause_rtr = 0;
1067         rcv_sync_msg = 0;
1068
1069         control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1070                                M_WAITOK | M_ZERO);
1071         softc = control_softc;
1072
1073         softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1074                               "cam/ctl");
1075
1076         softc->dev->si_drv1 = softc;
1077
1078         /*
1079          * By default, return a "bad LUN" peripheral qualifier for unknown
1080          * LUNs.  The user can override this default using the tunable or
1081          * sysctl.  See the comment in ctl_inquiry_std() for more details.
1082          */
1083         softc->inquiry_pq_no_lun = 1;
1084         TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
1085                           &softc->inquiry_pq_no_lun);
1086         sysctl_ctx_init(&softc->sysctl_ctx);
1087         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1088                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1089                 CTLFLAG_RD, 0, "CAM Target Layer");
1090
1091         if (softc->sysctl_tree == NULL) {
1092                 printf("%s: unable to allocate sysctl tree\n", __func__);
1093                 destroy_dev(softc->dev);
1094                 free(control_softc, M_DEVBUF);
1095                 control_softc = NULL;
1096                 return (ENOMEM);
1097         }
1098
1099         SYSCTL_ADD_INT(&softc->sysctl_ctx,
1100                        SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1101                        "inquiry_pq_no_lun", CTLFLAG_RW,
1102                        &softc->inquiry_pq_no_lun, 0,
1103                        "Report no lun possible for invalid LUNs");
1104
1105         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1106         softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1107             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1108         softc->open_count = 0;
1109
1110         /*
1111          * Default to actually sending a SYNCHRONIZE CACHE command down to
1112          * the drive.
1113          */
1114         softc->flags = CTL_FLAG_REAL_SYNC;
1115
1116         /*
1117          * In Copan's HA scheme, the "master" and "slave" roles are
1118          * figured out through the slot the controller is in.  Although it
1119          * is an active/active system, someone has to be in charge.
1120          */
1121         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1122             OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1123             "HA head ID (0 - no HA)");
1124         if (softc->ha_id == 0) {
1125                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1126                 softc->is_single = 1;
1127                 softc->port_offset = 0;
1128         } else
1129                 softc->port_offset = (softc->ha_id - 1) * CTL_MAX_PORTS;
1130         softc->persis_offset = softc->port_offset * CTL_MAX_INIT_PER_PORT;
1131
1132         /*
1133          * XXX KDM need to figure out where we want to get our target ID
1134          * and WWID.  Is it different on each port?
1135          */
1136         softc->target.id = 0;
1137         softc->target.wwid[0] = 0x12345678;
1138         softc->target.wwid[1] = 0x87654321;
1139         STAILQ_INIT(&softc->lun_list);
1140         STAILQ_INIT(&softc->pending_lun_queue);
1141         STAILQ_INIT(&softc->fe_list);
1142         STAILQ_INIT(&softc->port_list);
1143         STAILQ_INIT(&softc->be_list);
1144         ctl_tpc_init(softc);
1145
1146         if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1147                             &other_pool) != 0)
1148         {
1149                 printf("ctl: can't allocate %d entry other SC pool, "
1150                        "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1151                 return (ENOMEM);
1152         }
1153         softc->othersc_pool = other_pool;
1154
1155         if (worker_threads <= 0)
1156                 worker_threads = max(1, mp_ncpus / 4);
1157         if (worker_threads > CTL_MAX_THREADS)
1158                 worker_threads = CTL_MAX_THREADS;
1159
1160         for (i = 0; i < worker_threads; i++) {
1161                 struct ctl_thread *thr = &softc->threads[i];
1162
1163                 mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1164                 thr->ctl_softc = softc;
1165                 STAILQ_INIT(&thr->incoming_queue);
1166                 STAILQ_INIT(&thr->rtr_queue);
1167                 STAILQ_INIT(&thr->done_queue);
1168                 STAILQ_INIT(&thr->isc_queue);
1169
1170                 error = kproc_kthread_add(ctl_work_thread, thr,
1171                     &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1172                 if (error != 0) {
1173                         printf("error creating CTL work thread!\n");
1174                         ctl_pool_free(other_pool);
1175                         return (error);
1176                 }
1177         }
1178         error = kproc_kthread_add(ctl_lun_thread, softc,
1179             &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1180         if (error != 0) {
1181                 printf("error creating CTL lun thread!\n");
1182                 ctl_pool_free(other_pool);
1183                 return (error);
1184         }
1185         error = kproc_kthread_add(ctl_thresh_thread, softc,
1186             &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1187         if (error != 0) {
1188                 printf("error creating CTL threshold thread!\n");
1189                 ctl_pool_free(other_pool);
1190                 return (error);
1191         }
1192         if (bootverbose)
1193                 printf("ctl: CAM Target Layer loaded\n");
1194
1195         /*
1196          * Initialize the ioctl front end.
1197          */
1198         ctl_frontend_register(&ioctl_frontend);
1199         port = &softc->ioctl_info.port;
1200         port->frontend = &ioctl_frontend;
1201         sprintf(softc->ioctl_info.port_name, "ioctl");
1202         port->port_type = CTL_PORT_IOCTL;
1203         port->num_requested_ctl_io = 100;
1204         port->port_name = softc->ioctl_info.port_name;
1205         port->port_online = ctl_ioctl_online;
1206         port->port_offline = ctl_ioctl_offline;
1207         port->onoff_arg = &softc->ioctl_info;
1208         port->lun_enable = ctl_ioctl_lun_enable;
1209         port->lun_disable = ctl_ioctl_lun_disable;
1210         port->targ_lun_arg = &softc->ioctl_info;
1211         port->fe_datamove = ctl_ioctl_datamove;
1212         port->fe_done = ctl_ioctl_done;
1213         port->max_targets = 15;
1214         port->max_target_id = 15;
1215
1216         if (ctl_port_register(&softc->ioctl_info.port) != 0) {
1217                 printf("ctl: ioctl front end registration failed, will "
1218                        "continue anyway\n");
1219         }
1220
1221         SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1222             OID_AUTO, "ha_state", CTLTYPE_INT | CTLFLAG_RWTUN,
1223             softc, 0, ctl_ha_state_sysctl, "I", "HA state for this head");
1224
1225 #ifdef CTL_IO_DELAY
1226         if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1227                 printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1228                        sizeof(struct callout), CTL_TIMER_BYTES);
1229                 return (EINVAL);
1230         }
1231 #endif /* CTL_IO_DELAY */
1232
1233         return (0);
1234 }
1235
1236 void
1237 ctl_shutdown(void)
1238 {
1239         struct ctl_softc *softc;
1240         struct ctl_lun *lun, *next_lun;
1241
1242         softc = (struct ctl_softc *)control_softc;
1243
1244         if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1245                 printf("ctl: ioctl front end deregistration failed\n");
1246
1247         mtx_lock(&softc->ctl_lock);
1248
1249         /*
1250          * Free up each LUN.
1251          */
1252         for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1253                 next_lun = STAILQ_NEXT(lun, links);
1254                 ctl_free_lun(lun);
1255         }
1256
1257         mtx_unlock(&softc->ctl_lock);
1258
1259         ctl_frontend_deregister(&ioctl_frontend);
1260
1261 #if 0
1262         ctl_shutdown_thread(softc->work_thread);
1263         mtx_destroy(&softc->queue_lock);
1264 #endif
1265
1266         ctl_tpc_shutdown(softc);
1267         uma_zdestroy(softc->io_zone);
1268         mtx_destroy(&softc->ctl_lock);
1269
1270         destroy_dev(softc->dev);
1271
1272         sysctl_ctx_free(&softc->sysctl_ctx);
1273
1274         free(control_softc, M_DEVBUF);
1275         control_softc = NULL;
1276
1277         if (bootverbose)
1278                 printf("ctl: CAM Target Layer unloaded\n");
1279 }
1280
1281 static int
1282 ctl_module_event_handler(module_t mod, int what, void *arg)
1283 {
1284
1285         switch (what) {
1286         case MOD_LOAD:
1287                 return (ctl_init());
1288         case MOD_UNLOAD:
1289                 return (EBUSY);
1290         default:
1291                 return (EOPNOTSUPP);
1292         }
1293 }
1294
1295 /*
1296  * XXX KDM should we do some access checks here?  Bump a reference count to
1297  * prevent a CTL module from being unloaded while someone has it open?
1298  */
1299 static int
1300 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1301 {
1302         return (0);
1303 }
1304
1305 static int
1306 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1307 {
1308         return (0);
1309 }
1310
1311 int
1312 ctl_port_enable(ctl_port_type port_type)
1313 {
1314         struct ctl_softc *softc = control_softc;
1315         struct ctl_port *port;
1316
1317         if (softc->is_single == 0) {
1318                 union ctl_ha_msg msg_info;
1319                 int isc_retval;
1320
1321 #if 0
1322                 printf("%s: HA mode, synchronizing frontend enable\n",
1323                         __func__);
1324 #endif
1325                 msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1326                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1327                         sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1328                         printf("Sync msg send error retval %d\n", isc_retval);
1329                 }
1330                 if (!rcv_sync_msg) {
1331                         isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1332                                 sizeof(msg_info), 1);
1333                 }
1334 #if 0
1335                 printf("CTL:Frontend Enable\n");
1336         } else {
1337                 printf("%s: single mode, skipping frontend synchronization\n",
1338                         __func__);
1339 #endif
1340         }
1341
1342         STAILQ_FOREACH(port, &softc->port_list, links) {
1343                 if (port_type & port->port_type)
1344                 {
1345 #if 0
1346                         printf("port %d\n", port->targ_port);
1347 #endif
1348                         ctl_port_online(port);
1349                 }
1350         }
1351
1352         return (0);
1353 }
1354
1355 int
1356 ctl_port_disable(ctl_port_type port_type)
1357 {
1358         struct ctl_softc *softc;
1359         struct ctl_port *port;
1360
1361         softc = control_softc;
1362
1363         STAILQ_FOREACH(port, &softc->port_list, links) {
1364                 if (port_type & port->port_type)
1365                         ctl_port_offline(port);
1366         }
1367
1368         return (0);
1369 }
1370
1371 /*
1372  * Returns 0 for success, 1 for failure.
1373  * Currently the only failure mode is if there aren't enough entries
1374  * allocated.  So, in case of a failure, look at num_entries_dropped,
1375  * reallocate and try again.
1376  */
1377 int
1378 ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1379               int *num_entries_filled, int *num_entries_dropped,
1380               ctl_port_type port_type, int no_virtual)
1381 {
1382         struct ctl_softc *softc;
1383         struct ctl_port *port;
1384         int entries_dropped, entries_filled;
1385         int retval;
1386         int i;
1387
1388         softc = control_softc;
1389
1390         retval = 0;
1391         entries_filled = 0;
1392         entries_dropped = 0;
1393
1394         i = 0;
1395         mtx_lock(&softc->ctl_lock);
1396         STAILQ_FOREACH(port, &softc->port_list, links) {
1397                 struct ctl_port_entry *entry;
1398
1399                 if ((port->port_type & port_type) == 0)
1400                         continue;
1401
1402                 if ((no_virtual != 0)
1403                  && (port->virtual_port != 0))
1404                         continue;
1405
1406                 if (entries_filled >= num_entries_alloced) {
1407                         entries_dropped++;
1408                         continue;
1409                 }
1410                 entry = &entries[i];
1411
1412                 entry->port_type = port->port_type;
1413                 strlcpy(entry->port_name, port->port_name,
1414                         sizeof(entry->port_name));
1415                 entry->physical_port = port->physical_port;
1416                 entry->virtual_port = port->virtual_port;
1417                 entry->wwnn = port->wwnn;
1418                 entry->wwpn = port->wwpn;
1419
1420                 i++;
1421                 entries_filled++;
1422         }
1423
1424         mtx_unlock(&softc->ctl_lock);
1425
1426         if (entries_dropped > 0)
1427                 retval = 1;
1428
1429         *num_entries_dropped = entries_dropped;
1430         *num_entries_filled = entries_filled;
1431
1432         return (retval);
1433 }
1434
1435 static void
1436 ctl_ioctl_online(void *arg)
1437 {
1438         struct ctl_ioctl_info *ioctl_info;
1439
1440         ioctl_info = (struct ctl_ioctl_info *)arg;
1441
1442         ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1443 }
1444
1445 static void
1446 ctl_ioctl_offline(void *arg)
1447 {
1448         struct ctl_ioctl_info *ioctl_info;
1449
1450         ioctl_info = (struct ctl_ioctl_info *)arg;
1451
1452         ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1453 }
1454
1455 /*
1456  * Remove an initiator by port number and initiator ID.
1457  * Returns 0 for success, -1 for failure.
1458  */
1459 int
1460 ctl_remove_initiator(struct ctl_port *port, int iid)
1461 {
1462         struct ctl_softc *softc = control_softc;
1463
1464         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1465
1466         if (iid > CTL_MAX_INIT_PER_PORT) {
1467                 printf("%s: initiator ID %u > maximun %u!\n",
1468                        __func__, iid, CTL_MAX_INIT_PER_PORT);
1469                 return (-1);
1470         }
1471
1472         mtx_lock(&softc->ctl_lock);
1473         port->wwpn_iid[iid].in_use--;
1474         port->wwpn_iid[iid].last_use = time_uptime;
1475         mtx_unlock(&softc->ctl_lock);
1476
1477         return (0);
1478 }
1479
1480 /*
1481  * Add an initiator to the initiator map.
1482  * Returns iid for success, < 0 for failure.
1483  */
1484 int
1485 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1486 {
1487         struct ctl_softc *softc = control_softc;
1488         time_t best_time;
1489         int i, best;
1490
1491         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1492
1493         if (iid >= CTL_MAX_INIT_PER_PORT) {
1494                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1495                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1496                 free(name, M_CTL);
1497                 return (-1);
1498         }
1499
1500         mtx_lock(&softc->ctl_lock);
1501
1502         if (iid < 0 && (wwpn != 0 || name != NULL)) {
1503                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1504                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1505                                 iid = i;
1506                                 break;
1507                         }
1508                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
1509                             strcmp(name, port->wwpn_iid[i].name) == 0) {
1510                                 iid = i;
1511                                 break;
1512                         }
1513                 }
1514         }
1515
1516         if (iid < 0) {
1517                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1518                         if (port->wwpn_iid[i].in_use == 0 &&
1519                             port->wwpn_iid[i].wwpn == 0 &&
1520                             port->wwpn_iid[i].name == NULL) {
1521                                 iid = i;
1522                                 break;
1523                         }
1524                 }
1525         }
1526
1527         if (iid < 0) {
1528                 best = -1;
1529                 best_time = INT32_MAX;
1530                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1531                         if (port->wwpn_iid[i].in_use == 0) {
1532                                 if (port->wwpn_iid[i].last_use < best_time) {
1533                                         best = i;
1534                                         best_time = port->wwpn_iid[i].last_use;
1535                                 }
1536                         }
1537                 }
1538                 iid = best;
1539         }
1540
1541         if (iid < 0) {
1542                 mtx_unlock(&softc->ctl_lock);
1543                 free(name, M_CTL);
1544                 return (-2);
1545         }
1546
1547         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1548                 /*
1549                  * This is not an error yet.
1550                  */
1551                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1552 #if 0
1553                         printf("%s: port %d iid %u WWPN %#jx arrived"
1554                             " again\n", __func__, port->targ_port,
1555                             iid, (uintmax_t)wwpn);
1556 #endif
1557                         goto take;
1558                 }
1559                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1560                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
1561 #if 0
1562                         printf("%s: port %d iid %u name '%s' arrived"
1563                             " again\n", __func__, port->targ_port,
1564                             iid, name);
1565 #endif
1566                         goto take;
1567                 }
1568
1569                 /*
1570                  * This is an error, but what do we do about it?  The
1571                  * driver is telling us we have a new WWPN for this
1572                  * initiator ID, so we pretty much need to use it.
1573                  */
1574                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1575                     " but WWPN %#jx '%s' is still at that address\n",
1576                     __func__, port->targ_port, iid, wwpn, name,
1577                     (uintmax_t)port->wwpn_iid[iid].wwpn,
1578                     port->wwpn_iid[iid].name);
1579
1580                 /*
1581                  * XXX KDM clear have_ca and ua_pending on each LUN for
1582                  * this initiator.
1583                  */
1584         }
1585 take:
1586         free(port->wwpn_iid[iid].name, M_CTL);
1587         port->wwpn_iid[iid].name = name;
1588         port->wwpn_iid[iid].wwpn = wwpn;
1589         port->wwpn_iid[iid].in_use++;
1590         mtx_unlock(&softc->ctl_lock);
1591
1592         return (iid);
1593 }
1594
1595 static int
1596 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1597 {
1598         int len;
1599
1600         switch (port->port_type) {
1601         case CTL_PORT_FC:
1602         {
1603                 struct scsi_transportid_fcp *id =
1604                     (struct scsi_transportid_fcp *)buf;
1605                 if (port->wwpn_iid[iid].wwpn == 0)
1606                         return (0);
1607                 memset(id, 0, sizeof(*id));
1608                 id->format_protocol = SCSI_PROTO_FC;
1609                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1610                 return (sizeof(*id));
1611         }
1612         case CTL_PORT_ISCSI:
1613         {
1614                 struct scsi_transportid_iscsi_port *id =
1615                     (struct scsi_transportid_iscsi_port *)buf;
1616                 if (port->wwpn_iid[iid].name == NULL)
1617                         return (0);
1618                 memset(id, 0, 256);
1619                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1620                     SCSI_PROTO_ISCSI;
1621                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1622                 len = roundup2(min(len, 252), 4);
1623                 scsi_ulto2b(len, id->additional_length);
1624                 return (sizeof(*id) + len);
1625         }
1626         case CTL_PORT_SAS:
1627         {
1628                 struct scsi_transportid_sas *id =
1629                     (struct scsi_transportid_sas *)buf;
1630                 if (port->wwpn_iid[iid].wwpn == 0)
1631                         return (0);
1632                 memset(id, 0, sizeof(*id));
1633                 id->format_protocol = SCSI_PROTO_SAS;
1634                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1635                 return (sizeof(*id));
1636         }
1637         default:
1638         {
1639                 struct scsi_transportid_spi *id =
1640                     (struct scsi_transportid_spi *)buf;
1641                 memset(id, 0, sizeof(*id));
1642                 id->format_protocol = SCSI_PROTO_SPI;
1643                 scsi_ulto2b(iid, id->scsi_addr);
1644                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1645                 return (sizeof(*id));
1646         }
1647         }
1648 }
1649
1650 static int
1651 ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1652 {
1653         return (0);
1654 }
1655
1656 static int
1657 ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1658 {
1659         return (0);
1660 }
1661
1662 /*
1663  * Data movement routine for the CTL ioctl frontend port.
1664  */
1665 static int
1666 ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1667 {
1668         struct ctl_sg_entry *ext_sglist, *kern_sglist;
1669         struct ctl_sg_entry ext_entry, kern_entry;
1670         int ext_sglen, ext_sg_entries, kern_sg_entries;
1671         int ext_sg_start, ext_offset;
1672         int len_to_copy, len_copied;
1673         int kern_watermark, ext_watermark;
1674         int ext_sglist_malloced;
1675         int i, j;
1676
1677         ext_sglist_malloced = 0;
1678         ext_sg_start = 0;
1679         ext_offset = 0;
1680
1681         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1682
1683         /*
1684          * If this flag is set, fake the data transfer.
1685          */
1686         if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1687                 ctsio->ext_data_filled = ctsio->ext_data_len;
1688                 goto bailout;
1689         }
1690
1691         /*
1692          * To simplify things here, if we have a single buffer, stick it in
1693          * a S/G entry and just make it a single entry S/G list.
1694          */
1695         if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1696                 int len_seen;
1697
1698                 ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1699
1700                 ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1701                                                            M_WAITOK);
1702                 ext_sglist_malloced = 1;
1703                 if (copyin(ctsio->ext_data_ptr, ext_sglist,
1704                                    ext_sglen) != 0) {
1705                         ctl_set_internal_failure(ctsio,
1706                                                  /*sks_valid*/ 0,
1707                                                  /*retry_count*/ 0);
1708                         goto bailout;
1709                 }
1710                 ext_sg_entries = ctsio->ext_sg_entries;
1711                 len_seen = 0;
1712                 for (i = 0; i < ext_sg_entries; i++) {
1713                         if ((len_seen + ext_sglist[i].len) >=
1714                              ctsio->ext_data_filled) {
1715                                 ext_sg_start = i;
1716                                 ext_offset = ctsio->ext_data_filled - len_seen;
1717                                 break;
1718                         }
1719                         len_seen += ext_sglist[i].len;
1720                 }
1721         } else {
1722                 ext_sglist = &ext_entry;
1723                 ext_sglist->addr = ctsio->ext_data_ptr;
1724                 ext_sglist->len = ctsio->ext_data_len;
1725                 ext_sg_entries = 1;
1726                 ext_sg_start = 0;
1727                 ext_offset = ctsio->ext_data_filled;
1728         }
1729
1730         if (ctsio->kern_sg_entries > 0) {
1731                 kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1732                 kern_sg_entries = ctsio->kern_sg_entries;
1733         } else {
1734                 kern_sglist = &kern_entry;
1735                 kern_sglist->addr = ctsio->kern_data_ptr;
1736                 kern_sglist->len = ctsio->kern_data_len;
1737                 kern_sg_entries = 1;
1738         }
1739
1740
1741         kern_watermark = 0;
1742         ext_watermark = ext_offset;
1743         len_copied = 0;
1744         for (i = ext_sg_start, j = 0;
1745              i < ext_sg_entries && j < kern_sg_entries;) {
1746                 uint8_t *ext_ptr, *kern_ptr;
1747
1748                 len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1749                                       kern_sglist[j].len - kern_watermark);
1750
1751                 ext_ptr = (uint8_t *)ext_sglist[i].addr;
1752                 ext_ptr = ext_ptr + ext_watermark;
1753                 if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1754                         /*
1755                          * XXX KDM fix this!
1756                          */
1757                         panic("need to implement bus address support");
1758 #if 0
1759                         kern_ptr = bus_to_virt(kern_sglist[j].addr);
1760 #endif
1761                 } else
1762                         kern_ptr = (uint8_t *)kern_sglist[j].addr;
1763                 kern_ptr = kern_ptr + kern_watermark;
1764
1765                 kern_watermark += len_to_copy;
1766                 ext_watermark += len_to_copy;
1767
1768                 if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1769                      CTL_FLAG_DATA_IN) {
1770                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1771                                          "bytes to user\n", len_to_copy));
1772                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1773                                          "to %p\n", kern_ptr, ext_ptr));
1774                         if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1775                                 ctl_set_internal_failure(ctsio,
1776                                                          /*sks_valid*/ 0,
1777                                                          /*retry_count*/ 0);
1778                                 goto bailout;
1779                         }
1780                 } else {
1781                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1782                                          "bytes from user\n", len_to_copy));
1783                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1784                                          "to %p\n", ext_ptr, kern_ptr));
1785                         if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1786                                 ctl_set_internal_failure(ctsio,
1787                                                          /*sks_valid*/ 0,
1788                                                          /*retry_count*/0);
1789                                 goto bailout;
1790                         }
1791                 }
1792
1793                 len_copied += len_to_copy;
1794
1795                 if (ext_sglist[i].len == ext_watermark) {
1796                         i++;
1797                         ext_watermark = 0;
1798                 }
1799
1800                 if (kern_sglist[j].len == kern_watermark) {
1801                         j++;
1802                         kern_watermark = 0;
1803                 }
1804         }
1805
1806         ctsio->ext_data_filled += len_copied;
1807
1808         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1809                          "kern_sg_entries: %d\n", ext_sg_entries,
1810                          kern_sg_entries));
1811         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1812                          "kern_data_len = %d\n", ctsio->ext_data_len,
1813                          ctsio->kern_data_len));
1814
1815
1816         /* XXX KDM set residual?? */
1817 bailout:
1818
1819         if (ext_sglist_malloced != 0)
1820                 free(ext_sglist, M_CTL);
1821
1822         return (CTL_RETVAL_COMPLETE);
1823 }
1824
1825 /*
1826  * Serialize a command that went down the "wrong" side, and so was sent to
1827  * this controller for execution.  The logic is a little different than the
1828  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1829  * sent back to the other side, but in the success case, we execute the
1830  * command on this side (XFER mode) or tell the other side to execute it
1831  * (SER_ONLY mode).
1832  */
1833 static int
1834 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1835 {
1836         struct ctl_softc *softc;
1837         union ctl_ha_msg msg_info;
1838         struct ctl_lun *lun;
1839         int retval = 0;
1840         uint32_t targ_lun;
1841
1842         softc = control_softc;
1843
1844         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1845         lun = softc->ctl_luns[targ_lun];
1846         if (lun==NULL)
1847         {
1848                 /*
1849                  * Why isn't LUN defined? The other side wouldn't
1850                  * send a cmd if the LUN is undefined.
1851                  */
1852                 printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1853
1854                 /* "Logical unit not supported" */
1855                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1856                                    lun,
1857                                    /*sense_format*/SSD_TYPE_NONE,
1858                                    /*current_error*/ 1,
1859                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1860                                    /*asc*/ 0x25,
1861                                    /*ascq*/ 0x00,
1862                                    SSD_ELEM_NONE);
1863
1864                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1865                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1866                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1867                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1868                 msg_info.hdr.serializing_sc = NULL;
1869                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1870                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1871                                 sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1872                 }
1873                 return(1);
1874
1875         }
1876
1877         mtx_lock(&lun->lun_lock);
1878         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1879
1880         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1881                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1882                  ooa_links))) {
1883         case CTL_ACTION_BLOCK:
1884                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1885                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1886                                   blocked_links);
1887                 break;
1888         case CTL_ACTION_PASS:
1889         case CTL_ACTION_SKIP:
1890                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
1891                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1892                         ctl_enqueue_rtr((union ctl_io *)ctsio);
1893                 } else {
1894
1895                         /* send msg back to other side */
1896                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1897                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1898                         msg_info.hdr.msg_type = CTL_MSG_R2R;
1899 #if 0
1900                         printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1901 #endif
1902                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1903                             sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1904                         }
1905                 }
1906                 break;
1907         case CTL_ACTION_OVERLAP:
1908                 /* OVERLAPPED COMMANDS ATTEMPTED */
1909                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1910                                    lun,
1911                                    /*sense_format*/SSD_TYPE_NONE,
1912                                    /*current_error*/ 1,
1913                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1914                                    /*asc*/ 0x4E,
1915                                    /*ascq*/ 0x00,
1916                                    SSD_ELEM_NONE);
1917
1918                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1919                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1920                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1921                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1922                 msg_info.hdr.serializing_sc = NULL;
1923                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1924 #if 0
1925                 printf("BAD JUJU:Major Bummer Overlap\n");
1926 #endif
1927                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1928                 retval = 1;
1929                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1930                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1931                 }
1932                 break;
1933         case CTL_ACTION_OVERLAP_TAG:
1934                 /* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1935                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1936                                    lun,
1937                                    /*sense_format*/SSD_TYPE_NONE,
1938                                    /*current_error*/ 1,
1939                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1940                                    /*asc*/ 0x4D,
1941                                    /*ascq*/ ctsio->tag_num & 0xff,
1942                                    SSD_ELEM_NONE);
1943
1944                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1945                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1946                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1947                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1948                 msg_info.hdr.serializing_sc = NULL;
1949                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1950 #if 0
1951                 printf("BAD JUJU:Major Bummer Overlap Tag\n");
1952 #endif
1953                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1954                 retval = 1;
1955                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1956                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1957                 }
1958                 break;
1959         case CTL_ACTION_ERROR:
1960         default:
1961                 /* "Internal target failure" */
1962                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1963                                    lun,
1964                                    /*sense_format*/SSD_TYPE_NONE,
1965                                    /*current_error*/ 1,
1966                                    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1967                                    /*asc*/ 0x44,
1968                                    /*ascq*/ 0x00,
1969                                    SSD_ELEM_NONE);
1970
1971                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1972                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1973                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1974                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1975                 msg_info.hdr.serializing_sc = NULL;
1976                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1977 #if 0
1978                 printf("BAD JUJU:Major Bummer HW Error\n");
1979 #endif
1980                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1981                 retval = 1;
1982                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1983                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1984                 }
1985                 break;
1986         }
1987         mtx_unlock(&lun->lun_lock);
1988         return (retval);
1989 }
1990
1991 static int
1992 ctl_ioctl_submit_wait(union ctl_io *io)
1993 {
1994         struct ctl_fe_ioctl_params params;
1995         ctl_fe_ioctl_state last_state;
1996         int done, retval;
1997
1998         retval = 0;
1999
2000         bzero(&params, sizeof(params));
2001
2002         mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
2003         cv_init(&params.sem, "ctlioccv");
2004         params.state = CTL_IOCTL_INPROG;
2005         last_state = params.state;
2006
2007         io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
2008
2009         CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
2010
2011         /* This shouldn't happen */
2012         if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
2013                 return (retval);
2014
2015         done = 0;
2016
2017         do {
2018                 mtx_lock(&params.ioctl_mtx);
2019                 /*
2020                  * Check the state here, and don't sleep if the state has
2021                  * already changed (i.e. wakeup has already occured, but we
2022                  * weren't waiting yet).
2023                  */
2024                 if (params.state == last_state) {
2025                         /* XXX KDM cv_wait_sig instead? */
2026                         cv_wait(&params.sem, &params.ioctl_mtx);
2027                 }
2028                 last_state = params.state;
2029
2030                 switch (params.state) {
2031                 case CTL_IOCTL_INPROG:
2032                         /* Why did we wake up? */
2033                         /* XXX KDM error here? */
2034                         mtx_unlock(&params.ioctl_mtx);
2035                         break;
2036                 case CTL_IOCTL_DATAMOVE:
2037                         CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
2038
2039                         /*
2040                          * change last_state back to INPROG to avoid
2041                          * deadlock on subsequent data moves.
2042                          */
2043                         params.state = last_state = CTL_IOCTL_INPROG;
2044
2045                         mtx_unlock(&params.ioctl_mtx);
2046                         ctl_ioctl_do_datamove(&io->scsiio);
2047                         /*
2048                          * Note that in some cases, most notably writes,
2049                          * this will queue the I/O and call us back later.
2050                          * In other cases, generally reads, this routine
2051                          * will immediately call back and wake us up,
2052                          * probably using our own context.
2053                          */
2054                         io->scsiio.be_move_done(io);
2055                         break;
2056                 case CTL_IOCTL_DONE:
2057                         mtx_unlock(&params.ioctl_mtx);
2058                         CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
2059                         done = 1;
2060                         break;
2061                 default:
2062                         mtx_unlock(&params.ioctl_mtx);
2063                         /* XXX KDM error here? */
2064                         break;
2065                 }
2066         } while (done == 0);
2067
2068         mtx_destroy(&params.ioctl_mtx);
2069         cv_destroy(&params.sem);
2070
2071         return (CTL_RETVAL_COMPLETE);
2072 }
2073
2074 static void
2075 ctl_ioctl_datamove(union ctl_io *io)
2076 {
2077         struct ctl_fe_ioctl_params *params;
2078
2079         params = (struct ctl_fe_ioctl_params *)
2080                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2081
2082         mtx_lock(&params->ioctl_mtx);
2083         params->state = CTL_IOCTL_DATAMOVE;
2084         cv_broadcast(&params->sem);
2085         mtx_unlock(&params->ioctl_mtx);
2086 }
2087
2088 static void
2089 ctl_ioctl_done(union ctl_io *io)
2090 {
2091         struct ctl_fe_ioctl_params *params;
2092
2093         params = (struct ctl_fe_ioctl_params *)
2094                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2095
2096         mtx_lock(&params->ioctl_mtx);
2097         params->state = CTL_IOCTL_DONE;
2098         cv_broadcast(&params->sem);
2099         mtx_unlock(&params->ioctl_mtx);
2100 }
2101
2102 static void
2103 ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2104 {
2105         struct ctl_fe_ioctl_startstop_info *sd_info;
2106
2107         sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2108
2109         sd_info->hs_info.status = metatask->status;
2110         sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2111         sd_info->hs_info.luns_complete =
2112                 metatask->taskinfo.startstop.luns_complete;
2113         sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2114
2115         cv_broadcast(&sd_info->sem);
2116 }
2117
2118 static void
2119 ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2120 {
2121         struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2122
2123         fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2124
2125         mtx_lock(fe_bbr_info->lock);
2126         fe_bbr_info->bbr_info->status = metatask->status;
2127         fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2128         fe_bbr_info->wakeup_done = 1;
2129         mtx_unlock(fe_bbr_info->lock);
2130
2131         cv_broadcast(&fe_bbr_info->sem);
2132 }
2133
2134 /*
2135  * Returns 0 for success, errno for failure.
2136  */
2137 static int
2138 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2139                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2140 {
2141         union ctl_io *io;
2142         int retval;
2143
2144         retval = 0;
2145
2146         mtx_lock(&lun->lun_lock);
2147         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2148              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2149              ooa_links)) {
2150                 struct ctl_ooa_entry *entry;
2151
2152                 /*
2153                  * If we've got more than we can fit, just count the
2154                  * remaining entries.
2155                  */
2156                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2157                         continue;
2158
2159                 entry = &kern_entries[*cur_fill_num];
2160
2161                 entry->tag_num = io->scsiio.tag_num;
2162                 entry->lun_num = lun->lun;
2163 #ifdef CTL_TIME_IO
2164                 entry->start_bt = io->io_hdr.start_bt;
2165 #endif
2166                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2167                 entry->cdb_len = io->scsiio.cdb_len;
2168                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2169                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2170
2171                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2172                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2173
2174                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2175                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2176
2177                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2178                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2179
2180                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2181                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2182         }
2183         mtx_unlock(&lun->lun_lock);
2184
2185         return (retval);
2186 }
2187
2188 static void *
2189 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2190                  size_t error_str_len)
2191 {
2192         void *kptr;
2193
2194         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2195
2196         if (copyin(user_addr, kptr, len) != 0) {
2197                 snprintf(error_str, error_str_len, "Error copying %d bytes "
2198                          "from user address %p to kernel address %p", len,
2199                          user_addr, kptr);
2200                 free(kptr, M_CTL);
2201                 return (NULL);
2202         }
2203
2204         return (kptr);
2205 }
2206
2207 static void
2208 ctl_free_args(int num_args, struct ctl_be_arg *args)
2209 {
2210         int i;
2211
2212         if (args == NULL)
2213                 return;
2214
2215         for (i = 0; i < num_args; i++) {
2216                 free(args[i].kname, M_CTL);
2217                 free(args[i].kvalue, M_CTL);
2218         }
2219
2220         free(args, M_CTL);
2221 }
2222
2223 static struct ctl_be_arg *
2224 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2225                 char *error_str, size_t error_str_len)
2226 {
2227         struct ctl_be_arg *args;
2228         int i;
2229
2230         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2231                                 error_str, error_str_len);
2232
2233         if (args == NULL)
2234                 goto bailout;
2235
2236         for (i = 0; i < num_args; i++) {
2237                 args[i].kname = NULL;
2238                 args[i].kvalue = NULL;
2239         }
2240
2241         for (i = 0; i < num_args; i++) {
2242                 uint8_t *tmpptr;
2243
2244                 args[i].kname = ctl_copyin_alloc(args[i].name,
2245                         args[i].namelen, error_str, error_str_len);
2246                 if (args[i].kname == NULL)
2247                         goto bailout;
2248
2249                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2250                         snprintf(error_str, error_str_len, "Argument %d "
2251                                  "name is not NUL-terminated", i);
2252                         goto bailout;
2253                 }
2254
2255                 if (args[i].flags & CTL_BEARG_RD) {
2256                         tmpptr = ctl_copyin_alloc(args[i].value,
2257                                 args[i].vallen, error_str, error_str_len);
2258                         if (tmpptr == NULL)
2259                                 goto bailout;
2260                         if ((args[i].flags & CTL_BEARG_ASCII)
2261                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2262                                 snprintf(error_str, error_str_len, "Argument "
2263                                     "%d value is not NUL-terminated", i);
2264                                 goto bailout;
2265                         }
2266                         args[i].kvalue = tmpptr;
2267                 } else {
2268                         args[i].kvalue = malloc(args[i].vallen,
2269                             M_CTL, M_WAITOK | M_ZERO);
2270                 }
2271         }
2272
2273         return (args);
2274 bailout:
2275
2276         ctl_free_args(num_args, args);
2277
2278         return (NULL);
2279 }
2280
2281 static void
2282 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2283 {
2284         int i;
2285
2286         for (i = 0; i < num_args; i++) {
2287                 if (args[i].flags & CTL_BEARG_WR)
2288                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2289         }
2290 }
2291
2292 /*
2293  * Escape characters that are illegal or not recommended in XML.
2294  */
2295 int
2296 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2297 {
2298         char *end = str + size;
2299         int retval;
2300
2301         retval = 0;
2302
2303         for (; *str && str < end; str++) {
2304                 switch (*str) {
2305                 case '&':
2306                         retval = sbuf_printf(sb, "&amp;");
2307                         break;
2308                 case '>':
2309                         retval = sbuf_printf(sb, "&gt;");
2310                         break;
2311                 case '<':
2312                         retval = sbuf_printf(sb, "&lt;");
2313                         break;
2314                 default:
2315                         retval = sbuf_putc(sb, *str);
2316                         break;
2317                 }
2318
2319                 if (retval != 0)
2320                         break;
2321
2322         }
2323
2324         return (retval);
2325 }
2326
2327 static void
2328 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2329 {
2330         struct scsi_vpd_id_descriptor *desc;
2331         int i;
2332
2333         if (id == NULL || id->len < 4)
2334                 return;
2335         desc = (struct scsi_vpd_id_descriptor *)id->data;
2336         switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2337         case SVPD_ID_TYPE_T10:
2338                 sbuf_printf(sb, "t10.");
2339                 break;
2340         case SVPD_ID_TYPE_EUI64:
2341                 sbuf_printf(sb, "eui.");
2342                 break;
2343         case SVPD_ID_TYPE_NAA:
2344                 sbuf_printf(sb, "naa.");
2345                 break;
2346         case SVPD_ID_TYPE_SCSI_NAME:
2347                 break;
2348         }
2349         switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2350         case SVPD_ID_CODESET_BINARY:
2351                 for (i = 0; i < desc->length; i++)
2352                         sbuf_printf(sb, "%02x", desc->identifier[i]);
2353                 break;
2354         case SVPD_ID_CODESET_ASCII:
2355                 sbuf_printf(sb, "%.*s", (int)desc->length,
2356                     (char *)desc->identifier);
2357                 break;
2358         case SVPD_ID_CODESET_UTF8:
2359                 sbuf_printf(sb, "%s", (char *)desc->identifier);
2360                 break;
2361         }
2362 }
2363
2364 static int
2365 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2366           struct thread *td)
2367 {
2368         struct ctl_softc *softc;
2369         int retval;
2370
2371         softc = control_softc;
2372
2373         retval = 0;
2374
2375         switch (cmd) {
2376         case CTL_IO: {
2377                 union ctl_io *io;
2378                 void *pool_tmp;
2379
2380                 /*
2381                  * If we haven't been "enabled", don't allow any SCSI I/O
2382                  * to this FETD.
2383                  */
2384                 if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2385                         retval = EPERM;
2386                         break;
2387                 }
2388
2389                 io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2390
2391                 /*
2392                  * Need to save the pool reference so it doesn't get
2393                  * spammed by the user's ctl_io.
2394                  */
2395                 pool_tmp = io->io_hdr.pool;
2396                 memcpy(io, (void *)addr, sizeof(*io));
2397                 io->io_hdr.pool = pool_tmp;
2398
2399                 /*
2400                  * No status yet, so make sure the status is set properly.
2401                  */
2402                 io->io_hdr.status = CTL_STATUS_NONE;
2403
2404                 /*
2405                  * The user sets the initiator ID, target and LUN IDs.
2406                  */
2407                 io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2408                 io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2409                 if ((io->io_hdr.io_type == CTL_IO_SCSI)
2410                  && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2411                         io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2412
2413                 retval = ctl_ioctl_submit_wait(io);
2414
2415                 if (retval != 0) {
2416                         ctl_free_io(io);
2417                         break;
2418                 }
2419
2420                 memcpy((void *)addr, io, sizeof(*io));
2421
2422                 /* return this to our pool */
2423                 ctl_free_io(io);
2424
2425                 break;
2426         }
2427         case CTL_ENABLE_PORT:
2428         case CTL_DISABLE_PORT:
2429         case CTL_SET_PORT_WWNS: {
2430                 struct ctl_port *port;
2431                 struct ctl_port_entry *entry;
2432
2433                 entry = (struct ctl_port_entry *)addr;
2434                 
2435                 mtx_lock(&softc->ctl_lock);
2436                 STAILQ_FOREACH(port, &softc->port_list, links) {
2437                         int action, done;
2438
2439                         action = 0;
2440                         done = 0;
2441
2442                         if ((entry->port_type == CTL_PORT_NONE)
2443                          && (entry->targ_port == port->targ_port)) {
2444                                 /*
2445                                  * If the user only wants to enable or
2446                                  * disable or set WWNs on a specific port,
2447                                  * do the operation and we're done.
2448                                  */
2449                                 action = 1;
2450                                 done = 1;
2451                         } else if (entry->port_type & port->port_type) {
2452                                 /*
2453                                  * Compare the user's type mask with the
2454                                  * particular frontend type to see if we
2455                                  * have a match.
2456                                  */
2457                                 action = 1;
2458                                 done = 0;
2459
2460                                 /*
2461                                  * Make sure the user isn't trying to set
2462                                  * WWNs on multiple ports at the same time.
2463                                  */
2464                                 if (cmd == CTL_SET_PORT_WWNS) {
2465                                         printf("%s: Can't set WWNs on "
2466                                                "multiple ports\n", __func__);
2467                                         retval = EINVAL;
2468                                         break;
2469                                 }
2470                         }
2471                         if (action != 0) {
2472                                 /*
2473                                  * XXX KDM we have to drop the lock here,
2474                                  * because the online/offline operations
2475                                  * can potentially block.  We need to
2476                                  * reference count the frontends so they
2477                                  * can't go away,
2478                                  */
2479                                 mtx_unlock(&softc->ctl_lock);
2480
2481                                 if (cmd == CTL_ENABLE_PORT) {
2482                                         struct ctl_lun *lun;
2483
2484                                         STAILQ_FOREACH(lun, &softc->lun_list,
2485                                                        links) {
2486                                                 port->lun_enable(port->targ_lun_arg,
2487                                                     lun->target,
2488                                                     lun->lun);
2489                                         }
2490
2491                                         ctl_port_online(port);
2492                                 } else if (cmd == CTL_DISABLE_PORT) {
2493                                         struct ctl_lun *lun;
2494
2495                                         ctl_port_offline(port);
2496
2497                                         STAILQ_FOREACH(lun, &softc->lun_list,
2498                                                        links) {
2499                                                 port->lun_disable(
2500                                                     port->targ_lun_arg,
2501                                                     lun->target,
2502                                                     lun->lun);
2503                                         }
2504                                 }
2505
2506                                 mtx_lock(&softc->ctl_lock);
2507
2508                                 if (cmd == CTL_SET_PORT_WWNS)
2509                                         ctl_port_set_wwns(port,
2510                                             (entry->flags & CTL_PORT_WWNN_VALID) ?
2511                                             1 : 0, entry->wwnn,
2512                                             (entry->flags & CTL_PORT_WWPN_VALID) ?
2513                                             1 : 0, entry->wwpn);
2514                         }
2515                         if (done != 0)
2516                                 break;
2517                 }
2518                 mtx_unlock(&softc->ctl_lock);
2519                 break;
2520         }
2521         case CTL_GET_PORT_LIST: {
2522                 struct ctl_port *port;
2523                 struct ctl_port_list *list;
2524                 int i;
2525
2526                 list = (struct ctl_port_list *)addr;
2527
2528                 if (list->alloc_len != (list->alloc_num *
2529                     sizeof(struct ctl_port_entry))) {
2530                         printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2531                                "alloc_num %u * sizeof(struct ctl_port_entry) "
2532                                "%zu\n", __func__, list->alloc_len,
2533                                list->alloc_num, sizeof(struct ctl_port_entry));
2534                         retval = EINVAL;
2535                         break;
2536                 }
2537                 list->fill_len = 0;
2538                 list->fill_num = 0;
2539                 list->dropped_num = 0;
2540                 i = 0;
2541                 mtx_lock(&softc->ctl_lock);
2542                 STAILQ_FOREACH(port, &softc->port_list, links) {
2543                         struct ctl_port_entry entry, *list_entry;
2544
2545                         if (list->fill_num >= list->alloc_num) {
2546                                 list->dropped_num++;
2547                                 continue;
2548                         }
2549
2550                         entry.port_type = port->port_type;
2551                         strlcpy(entry.port_name, port->port_name,
2552                                 sizeof(entry.port_name));
2553                         entry.targ_port = port->targ_port;
2554                         entry.physical_port = port->physical_port;
2555                         entry.virtual_port = port->virtual_port;
2556                         entry.wwnn = port->wwnn;
2557                         entry.wwpn = port->wwpn;
2558                         if (port->status & CTL_PORT_STATUS_ONLINE)
2559                                 entry.online = 1;
2560                         else
2561                                 entry.online = 0;
2562
2563                         list_entry = &list->entries[i];
2564
2565                         retval = copyout(&entry, list_entry, sizeof(entry));
2566                         if (retval != 0) {
2567                                 printf("%s: CTL_GET_PORT_LIST: copyout "
2568                                        "returned %d\n", __func__, retval);
2569                                 break;
2570                         }
2571                         i++;
2572                         list->fill_num++;
2573                         list->fill_len += sizeof(entry);
2574                 }
2575                 mtx_unlock(&softc->ctl_lock);
2576
2577                 /*
2578                  * If this is non-zero, we had a copyout fault, so there's
2579                  * probably no point in attempting to set the status inside
2580                  * the structure.
2581                  */
2582                 if (retval != 0)
2583                         break;
2584
2585                 if (list->dropped_num > 0)
2586                         list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2587                 else
2588                         list->status = CTL_PORT_LIST_OK;
2589                 break;
2590         }
2591         case CTL_DUMP_OOA: {
2592                 struct ctl_lun *lun;
2593                 union ctl_io *io;
2594                 char printbuf[128];
2595                 struct sbuf sb;
2596
2597                 mtx_lock(&softc->ctl_lock);
2598                 printf("Dumping OOA queues:\n");
2599                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2600                         mtx_lock(&lun->lun_lock);
2601                         for (io = (union ctl_io *)TAILQ_FIRST(
2602                              &lun->ooa_queue); io != NULL;
2603                              io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2604                              ooa_links)) {
2605                                 sbuf_new(&sb, printbuf, sizeof(printbuf),
2606                                          SBUF_FIXEDLEN);
2607                                 sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2608                                             (intmax_t)lun->lun,
2609                                             io->scsiio.tag_num,
2610                                             (io->io_hdr.flags &
2611                                             CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2612                                             (io->io_hdr.flags &
2613                                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2614                                             (io->io_hdr.flags &
2615                                             CTL_FLAG_ABORT) ? " ABORT" : "",
2616                                             (io->io_hdr.flags &
2617                                         CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2618                                 ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2619                                 sbuf_finish(&sb);
2620                                 printf("%s\n", sbuf_data(&sb));
2621                         }
2622                         mtx_unlock(&lun->lun_lock);
2623                 }
2624                 printf("OOA queues dump done\n");
2625                 mtx_unlock(&softc->ctl_lock);
2626                 break;
2627         }
2628         case CTL_GET_OOA: {
2629                 struct ctl_lun *lun;
2630                 struct ctl_ooa *ooa_hdr;
2631                 struct ctl_ooa_entry *entries;
2632                 uint32_t cur_fill_num;
2633
2634                 ooa_hdr = (struct ctl_ooa *)addr;
2635
2636                 if ((ooa_hdr->alloc_len == 0)
2637                  || (ooa_hdr->alloc_num == 0)) {
2638                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2639                                "must be non-zero\n", __func__,
2640                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2641                         retval = EINVAL;
2642                         break;
2643                 }
2644
2645                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2646                     sizeof(struct ctl_ooa_entry))) {
2647                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2648                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2649                                __func__, ooa_hdr->alloc_len,
2650                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2651                         retval = EINVAL;
2652                         break;
2653                 }
2654
2655                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2656                 if (entries == NULL) {
2657                         printf("%s: could not allocate %d bytes for OOA "
2658                                "dump\n", __func__, ooa_hdr->alloc_len);
2659                         retval = ENOMEM;
2660                         break;
2661                 }
2662
2663                 mtx_lock(&softc->ctl_lock);
2664                 if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2665                  && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2666                   || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2667                         mtx_unlock(&softc->ctl_lock);
2668                         free(entries, M_CTL);
2669                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2670                                __func__, (uintmax_t)ooa_hdr->lun_num);
2671                         retval = EINVAL;
2672                         break;
2673                 }
2674
2675                 cur_fill_num = 0;
2676
2677                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2678                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2679                                 retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2680                                         ooa_hdr, entries);
2681                                 if (retval != 0)
2682                                         break;
2683                         }
2684                         if (retval != 0) {
2685                                 mtx_unlock(&softc->ctl_lock);
2686                                 free(entries, M_CTL);
2687                                 break;
2688                         }
2689                 } else {
2690                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2691
2692                         retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2693                                                     entries);
2694                 }
2695                 mtx_unlock(&softc->ctl_lock);
2696
2697                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2698                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2699                         sizeof(struct ctl_ooa_entry);
2700                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2701                 if (retval != 0) {
2702                         printf("%s: error copying out %d bytes for OOA dump\n", 
2703                                __func__, ooa_hdr->fill_len);
2704                 }
2705
2706                 getbintime(&ooa_hdr->cur_bt);
2707
2708                 if (cur_fill_num > ooa_hdr->alloc_num) {
2709                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2710                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2711                 } else {
2712                         ooa_hdr->dropped_num = 0;
2713                         ooa_hdr->status = CTL_OOA_OK;
2714                 }
2715
2716                 free(entries, M_CTL);
2717                 break;
2718         }
2719         case CTL_CHECK_OOA: {
2720                 union ctl_io *io;
2721                 struct ctl_lun *lun;
2722                 struct ctl_ooa_info *ooa_info;
2723
2724
2725                 ooa_info = (struct ctl_ooa_info *)addr;
2726
2727                 if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2728                         ooa_info->status = CTL_OOA_INVALID_LUN;
2729                         break;
2730                 }
2731                 mtx_lock(&softc->ctl_lock);
2732                 lun = softc->ctl_luns[ooa_info->lun_id];
2733                 if (lun == NULL) {
2734                         mtx_unlock(&softc->ctl_lock);
2735                         ooa_info->status = CTL_OOA_INVALID_LUN;
2736                         break;
2737                 }
2738                 mtx_lock(&lun->lun_lock);
2739                 mtx_unlock(&softc->ctl_lock);
2740                 ooa_info->num_entries = 0;
2741                 for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2742                      io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2743                      &io->io_hdr, ooa_links)) {
2744                         ooa_info->num_entries++;
2745                 }
2746                 mtx_unlock(&lun->lun_lock);
2747
2748                 ooa_info->status = CTL_OOA_SUCCESS;
2749
2750                 break;
2751         }
2752         case CTL_HARD_START:
2753         case CTL_HARD_STOP: {
2754                 struct ctl_fe_ioctl_startstop_info ss_info;
2755                 struct cfi_metatask *metatask;
2756                 struct mtx hs_mtx;
2757
2758                 mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2759
2760                 cv_init(&ss_info.sem, "hard start/stop cv" );
2761
2762                 metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2763                 if (metatask == NULL) {
2764                         retval = ENOMEM;
2765                         mtx_destroy(&hs_mtx);
2766                         break;
2767                 }
2768
2769                 if (cmd == CTL_HARD_START)
2770                         metatask->tasktype = CFI_TASK_STARTUP;
2771                 else
2772                         metatask->tasktype = CFI_TASK_SHUTDOWN;
2773
2774                 metatask->callback = ctl_ioctl_hard_startstop_callback;
2775                 metatask->callback_arg = &ss_info;
2776
2777                 cfi_action(metatask);
2778
2779                 /* Wait for the callback */
2780                 mtx_lock(&hs_mtx);
2781                 cv_wait_sig(&ss_info.sem, &hs_mtx);
2782                 mtx_unlock(&hs_mtx);
2783
2784                 /*
2785                  * All information has been copied from the metatask by the
2786                  * time cv_broadcast() is called, so we free the metatask here.
2787                  */
2788                 cfi_free_metatask(metatask);
2789
2790                 memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2791
2792                 mtx_destroy(&hs_mtx);
2793                 break;
2794         }
2795         case CTL_BBRREAD: {
2796                 struct ctl_bbrread_info *bbr_info;
2797                 struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2798                 struct mtx bbr_mtx;
2799                 struct cfi_metatask *metatask;
2800
2801                 bbr_info = (struct ctl_bbrread_info *)addr;
2802
2803                 bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2804
2805                 bzero(&bbr_mtx, sizeof(bbr_mtx));
2806                 mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2807
2808                 fe_bbr_info.bbr_info = bbr_info;
2809                 fe_bbr_info.lock = &bbr_mtx;
2810
2811                 cv_init(&fe_bbr_info.sem, "BBR read cv");
2812                 metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2813
2814                 if (metatask == NULL) {
2815                         mtx_destroy(&bbr_mtx);
2816                         cv_destroy(&fe_bbr_info.sem);
2817                         retval = ENOMEM;
2818                         break;
2819                 }
2820                 metatask->tasktype = CFI_TASK_BBRREAD;
2821                 metatask->callback = ctl_ioctl_bbrread_callback;
2822                 metatask->callback_arg = &fe_bbr_info;
2823                 metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2824                 metatask->taskinfo.bbrread.lba = bbr_info->lba;
2825                 metatask->taskinfo.bbrread.len = bbr_info->len;
2826
2827                 cfi_action(metatask);
2828
2829                 mtx_lock(&bbr_mtx);
2830                 while (fe_bbr_info.wakeup_done == 0)
2831                         cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2832                 mtx_unlock(&bbr_mtx);
2833
2834                 bbr_info->status = metatask->status;
2835                 bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2836                 bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2837                 memcpy(&bbr_info->sense_data,
2838                        &metatask->taskinfo.bbrread.sense_data,
2839                        ctl_min(sizeof(bbr_info->sense_data),
2840                                sizeof(metatask->taskinfo.bbrread.sense_data)));
2841
2842                 cfi_free_metatask(metatask);
2843
2844                 mtx_destroy(&bbr_mtx);
2845                 cv_destroy(&fe_bbr_info.sem);
2846
2847                 break;
2848         }
2849         case CTL_DELAY_IO: {
2850                 struct ctl_io_delay_info *delay_info;
2851 #ifdef CTL_IO_DELAY
2852                 struct ctl_lun *lun;
2853 #endif /* CTL_IO_DELAY */
2854
2855                 delay_info = (struct ctl_io_delay_info *)addr;
2856
2857 #ifdef CTL_IO_DELAY
2858                 mtx_lock(&softc->ctl_lock);
2859
2860                 if ((delay_info->lun_id >= CTL_MAX_LUNS)
2861                  || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2862                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2863                 } else {
2864                         lun = softc->ctl_luns[delay_info->lun_id];
2865                         mtx_lock(&lun->lun_lock);
2866
2867                         delay_info->status = CTL_DELAY_STATUS_OK;
2868
2869                         switch (delay_info->delay_type) {
2870                         case CTL_DELAY_TYPE_CONT:
2871                                 break;
2872                         case CTL_DELAY_TYPE_ONESHOT:
2873                                 break;
2874                         default:
2875                                 delay_info->status =
2876                                         CTL_DELAY_STATUS_INVALID_TYPE;
2877                                 break;
2878                         }
2879
2880                         switch (delay_info->delay_loc) {
2881                         case CTL_DELAY_LOC_DATAMOVE:
2882                                 lun->delay_info.datamove_type =
2883                                         delay_info->delay_type;
2884                                 lun->delay_info.datamove_delay =
2885                                         delay_info->delay_secs;
2886                                 break;
2887                         case CTL_DELAY_LOC_DONE:
2888                                 lun->delay_info.done_type =
2889                                         delay_info->delay_type;
2890                                 lun->delay_info.done_delay =
2891                                         delay_info->delay_secs;
2892                                 break;
2893                         default:
2894                                 delay_info->status =
2895                                         CTL_DELAY_STATUS_INVALID_LOC;
2896                                 break;
2897                         }
2898                         mtx_unlock(&lun->lun_lock);
2899                 }
2900
2901                 mtx_unlock(&softc->ctl_lock);
2902 #else
2903                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2904 #endif /* CTL_IO_DELAY */
2905                 break;
2906         }
2907         case CTL_REALSYNC_SET: {
2908                 int *syncstate;
2909
2910                 syncstate = (int *)addr;
2911
2912                 mtx_lock(&softc->ctl_lock);
2913                 switch (*syncstate) {
2914                 case 0:
2915                         softc->flags &= ~CTL_FLAG_REAL_SYNC;
2916                         break;
2917                 case 1:
2918                         softc->flags |= CTL_FLAG_REAL_SYNC;
2919                         break;
2920                 default:
2921                         retval = EINVAL;
2922                         break;
2923                 }
2924                 mtx_unlock(&softc->ctl_lock);
2925                 break;
2926         }
2927         case CTL_REALSYNC_GET: {
2928                 int *syncstate;
2929
2930                 syncstate = (int*)addr;
2931
2932                 mtx_lock(&softc->ctl_lock);
2933                 if (softc->flags & CTL_FLAG_REAL_SYNC)
2934                         *syncstate = 1;
2935                 else
2936                         *syncstate = 0;
2937                 mtx_unlock(&softc->ctl_lock);
2938
2939                 break;
2940         }
2941         case CTL_SETSYNC:
2942         case CTL_GETSYNC: {
2943                 struct ctl_sync_info *sync_info;
2944                 struct ctl_lun *lun;
2945
2946                 sync_info = (struct ctl_sync_info *)addr;
2947
2948                 mtx_lock(&softc->ctl_lock);
2949                 lun = softc->ctl_luns[sync_info->lun_id];
2950                 if (lun == NULL) {
2951                         mtx_unlock(&softc->ctl_lock);
2952                         sync_info->status = CTL_GS_SYNC_NO_LUN;
2953                 }
2954                 /*
2955                  * Get or set the sync interval.  We're not bounds checking
2956                  * in the set case, hopefully the user won't do something
2957                  * silly.
2958                  */
2959                 mtx_lock(&lun->lun_lock);
2960                 mtx_unlock(&softc->ctl_lock);
2961                 if (cmd == CTL_GETSYNC)
2962                         sync_info->sync_interval = lun->sync_interval;
2963                 else
2964                         lun->sync_interval = sync_info->sync_interval;
2965                 mtx_unlock(&lun->lun_lock);
2966
2967                 sync_info->status = CTL_GS_SYNC_OK;
2968
2969                 break;
2970         }
2971         case CTL_GETSTATS: {
2972                 struct ctl_stats *stats;
2973                 struct ctl_lun *lun;
2974                 int i;
2975
2976                 stats = (struct ctl_stats *)addr;
2977
2978                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2979                      stats->alloc_len) {
2980                         stats->status = CTL_SS_NEED_MORE_SPACE;
2981                         stats->num_luns = softc->num_luns;
2982                         break;
2983                 }
2984                 /*
2985                  * XXX KDM no locking here.  If the LUN list changes,
2986                  * things can blow up.
2987                  */
2988                 for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2989                      i++, lun = STAILQ_NEXT(lun, links)) {
2990                         retval = copyout(&lun->stats, &stats->lun_stats[i],
2991                                          sizeof(lun->stats));
2992                         if (retval != 0)
2993                                 break;
2994                 }
2995                 stats->num_luns = softc->num_luns;
2996                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2997                                  softc->num_luns;
2998                 stats->status = CTL_SS_OK;
2999 #ifdef CTL_TIME_IO
3000                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
3001 #else
3002                 stats->flags = CTL_STATS_FLAG_NONE;
3003 #endif
3004                 getnanouptime(&stats->timestamp);
3005                 break;
3006         }
3007         case CTL_ERROR_INJECT: {
3008                 struct ctl_error_desc *err_desc, *new_err_desc;
3009                 struct ctl_lun *lun;
3010
3011                 err_desc = (struct ctl_error_desc *)addr;
3012
3013                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
3014                                       M_WAITOK | M_ZERO);
3015                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
3016
3017                 mtx_lock(&softc->ctl_lock);
3018                 lun = softc->ctl_luns[err_desc->lun_id];
3019                 if (lun == NULL) {
3020                         mtx_unlock(&softc->ctl_lock);
3021                         free(new_err_desc, M_CTL);
3022                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
3023                                __func__, (uintmax_t)err_desc->lun_id);
3024                         retval = EINVAL;
3025                         break;
3026                 }
3027                 mtx_lock(&lun->lun_lock);
3028                 mtx_unlock(&softc->ctl_lock);
3029
3030                 /*
3031                  * We could do some checking here to verify the validity
3032                  * of the request, but given the complexity of error
3033                  * injection requests, the checking logic would be fairly
3034                  * complex.
3035                  *
3036                  * For now, if the request is invalid, it just won't get
3037                  * executed and might get deleted.
3038                  */
3039                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
3040
3041                 /*
3042                  * XXX KDM check to make sure the serial number is unique,
3043                  * in case we somehow manage to wrap.  That shouldn't
3044                  * happen for a very long time, but it's the right thing to
3045                  * do.
3046                  */
3047                 new_err_desc->serial = lun->error_serial;
3048                 err_desc->serial = lun->error_serial;
3049                 lun->error_serial++;
3050
3051                 mtx_unlock(&lun->lun_lock);
3052                 break;
3053         }
3054         case CTL_ERROR_INJECT_DELETE: {
3055                 struct ctl_error_desc *delete_desc, *desc, *desc2;
3056                 struct ctl_lun *lun;
3057                 int delete_done;
3058
3059                 delete_desc = (struct ctl_error_desc *)addr;
3060                 delete_done = 0;
3061
3062                 mtx_lock(&softc->ctl_lock);
3063                 lun = softc->ctl_luns[delete_desc->lun_id];
3064                 if (lun == NULL) {
3065                         mtx_unlock(&softc->ctl_lock);
3066                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
3067                                __func__, (uintmax_t)delete_desc->lun_id);
3068                         retval = EINVAL;
3069                         break;
3070                 }
3071                 mtx_lock(&lun->lun_lock);
3072                 mtx_unlock(&softc->ctl_lock);
3073                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
3074                         if (desc->serial != delete_desc->serial)
3075                                 continue;
3076
3077                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
3078                                       links);
3079                         free(desc, M_CTL);
3080                         delete_done = 1;
3081                 }
3082                 mtx_unlock(&lun->lun_lock);
3083                 if (delete_done == 0) {
3084                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
3085                                "error serial %ju on LUN %u\n", __func__, 
3086                                delete_desc->serial, delete_desc->lun_id);
3087                         retval = EINVAL;
3088                         break;
3089                 }
3090                 break;
3091         }
3092         case CTL_DUMP_STRUCTS: {
3093                 int i, j, k;
3094                 struct ctl_port *port;
3095                 struct ctl_frontend *fe;
3096
3097                 mtx_lock(&softc->ctl_lock);
3098                 printf("CTL Persistent Reservation information start:\n");
3099                 for (i = 0; i < CTL_MAX_LUNS; i++) {
3100                         struct ctl_lun *lun;
3101
3102                         lun = softc->ctl_luns[i];
3103
3104                         if ((lun == NULL)
3105                          || ((lun->flags & CTL_LUN_DISABLED) != 0))
3106                                 continue;
3107
3108                         for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
3109                                 if (lun->pr_keys[j] == NULL)
3110                                         continue;
3111                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3112                                         if (lun->pr_keys[j][k] == 0)
3113                                                 continue;
3114                                         printf("  LUN %d port %d iid %d key "
3115                                                "%#jx\n", i, j, k,
3116                                                (uintmax_t)lun->pr_keys[j][k]);
3117                                 }
3118                         }
3119                 }
3120                 printf("CTL Persistent Reservation information end\n");
3121                 printf("CTL Ports:\n");
3122                 STAILQ_FOREACH(port, &softc->port_list, links) {
3123                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3124                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3125                                port->frontend->name, port->port_type,
3126                                port->physical_port, port->virtual_port,
3127                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3128                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3129                                 if (port->wwpn_iid[j].in_use == 0 &&
3130                                     port->wwpn_iid[j].wwpn == 0 &&
3131                                     port->wwpn_iid[j].name == NULL)
3132                                         continue;
3133
3134                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
3135                                     j, port->wwpn_iid[j].in_use,
3136                                     (uintmax_t)port->wwpn_iid[j].wwpn,
3137                                     port->wwpn_iid[j].name);
3138                         }
3139                 }
3140                 printf("CTL Port information end\n");
3141                 mtx_unlock(&softc->ctl_lock);
3142                 /*
3143                  * XXX KDM calling this without a lock.  We'd likely want
3144                  * to drop the lock before calling the frontend's dump
3145                  * routine anyway.
3146                  */
3147                 printf("CTL Frontends:\n");
3148                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
3149                         printf("  Frontend '%s'\n", fe->name);
3150                         if (fe->fe_dump != NULL)
3151                                 fe->fe_dump();
3152                 }
3153                 printf("CTL Frontend information end\n");
3154                 break;
3155         }
3156         case CTL_LUN_REQ: {
3157                 struct ctl_lun_req *lun_req;
3158                 struct ctl_backend_driver *backend;
3159
3160                 lun_req = (struct ctl_lun_req *)addr;
3161
3162                 backend = ctl_backend_find(lun_req->backend);
3163                 if (backend == NULL) {
3164                         lun_req->status = CTL_LUN_ERROR;
3165                         snprintf(lun_req->error_str,
3166                                  sizeof(lun_req->error_str),
3167                                  "Backend \"%s\" not found.",
3168                                  lun_req->backend);
3169                         break;
3170                 }
3171                 if (lun_req->num_be_args > 0) {
3172                         lun_req->kern_be_args = ctl_copyin_args(
3173                                 lun_req->num_be_args,
3174                                 lun_req->be_args,
3175                                 lun_req->error_str,
3176                                 sizeof(lun_req->error_str));
3177                         if (lun_req->kern_be_args == NULL) {
3178                                 lun_req->status = CTL_LUN_ERROR;
3179                                 break;
3180                         }
3181                 }
3182
3183                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3184
3185                 if (lun_req->num_be_args > 0) {
3186                         ctl_copyout_args(lun_req->num_be_args,
3187                                       lun_req->kern_be_args);
3188                         ctl_free_args(lun_req->num_be_args,
3189                                       lun_req->kern_be_args);
3190                 }
3191                 break;
3192         }
3193         case CTL_LUN_LIST: {
3194                 struct sbuf *sb;
3195                 struct ctl_lun *lun;
3196                 struct ctl_lun_list *list;
3197                 struct ctl_option *opt;
3198
3199                 list = (struct ctl_lun_list *)addr;
3200
3201                 /*
3202                  * Allocate a fixed length sbuf here, based on the length
3203                  * of the user's buffer.  We could allocate an auto-extending
3204                  * buffer, and then tell the user how much larger our
3205                  * amount of data is than his buffer, but that presents
3206                  * some problems:
3207                  *
3208                  * 1.  The sbuf(9) routines use a blocking malloc, and so
3209                  *     we can't hold a lock while calling them with an
3210                  *     auto-extending buffer.
3211                  *
3212                  * 2.  There is not currently a LUN reference counting
3213                  *     mechanism, outside of outstanding transactions on
3214                  *     the LUN's OOA queue.  So a LUN could go away on us
3215                  *     while we're getting the LUN number, backend-specific
3216                  *     information, etc.  Thus, given the way things
3217                  *     currently work, we need to hold the CTL lock while
3218                  *     grabbing LUN information.
3219                  *
3220                  * So, from the user's standpoint, the best thing to do is
3221                  * allocate what he thinks is a reasonable buffer length,
3222                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3223                  * double the buffer length and try again.  (And repeat
3224                  * that until he succeeds.)
3225                  */
3226                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3227                 if (sb == NULL) {
3228                         list->status = CTL_LUN_LIST_ERROR;
3229                         snprintf(list->error_str, sizeof(list->error_str),
3230                                  "Unable to allocate %d bytes for LUN list",
3231                                  list->alloc_len);
3232                         break;
3233                 }
3234
3235                 sbuf_printf(sb, "<ctllunlist>\n");
3236
3237                 mtx_lock(&softc->ctl_lock);
3238                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3239                         mtx_lock(&lun->lun_lock);
3240                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3241                                              (uintmax_t)lun->lun);
3242
3243                         /*
3244                          * Bail out as soon as we see that we've overfilled
3245                          * the buffer.
3246                          */
3247                         if (retval != 0)
3248                                 break;
3249
3250                         retval = sbuf_printf(sb, "\t<backend_type>%s"
3251                                              "</backend_type>\n",
3252                                              (lun->backend == NULL) ?  "none" :
3253                                              lun->backend->name);
3254
3255                         if (retval != 0)
3256                                 break;
3257
3258                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3259                                              lun->be_lun->lun_type);
3260
3261                         if (retval != 0)
3262                                 break;
3263
3264                         if (lun->backend == NULL) {
3265                                 retval = sbuf_printf(sb, "</lun>\n");
3266                                 if (retval != 0)
3267                                         break;
3268                                 continue;
3269                         }
3270
3271                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3272                                              (lun->be_lun->maxlba > 0) ?
3273                                              lun->be_lun->maxlba + 1 : 0);
3274
3275                         if (retval != 0)
3276                                 break;
3277
3278                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3279                                              lun->be_lun->blocksize);
3280
3281                         if (retval != 0)
3282                                 break;
3283
3284                         retval = sbuf_printf(sb, "\t<serial_number>");
3285
3286                         if (retval != 0)
3287                                 break;
3288
3289                         retval = ctl_sbuf_printf_esc(sb,
3290                             lun->be_lun->serial_num,
3291                             sizeof(lun->be_lun->serial_num));
3292
3293                         if (retval != 0)
3294                                 break;
3295
3296                         retval = sbuf_printf(sb, "</serial_number>\n");
3297                 
3298                         if (retval != 0)
3299                                 break;
3300
3301                         retval = sbuf_printf(sb, "\t<device_id>");
3302
3303                         if (retval != 0)
3304                                 break;
3305
3306                         retval = ctl_sbuf_printf_esc(sb,
3307                             lun->be_lun->device_id,
3308                             sizeof(lun->be_lun->device_id));
3309
3310                         if (retval != 0)
3311                                 break;
3312
3313                         retval = sbuf_printf(sb, "</device_id>\n");
3314
3315                         if (retval != 0)
3316                                 break;
3317
3318                         if (lun->backend->lun_info != NULL) {
3319                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3320                                 if (retval != 0)
3321                                         break;
3322                         }
3323                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3324                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3325                                     opt->name, opt->value, opt->name);
3326                                 if (retval != 0)
3327                                         break;
3328                         }
3329
3330                         retval = sbuf_printf(sb, "</lun>\n");
3331
3332                         if (retval != 0)
3333                                 break;
3334                         mtx_unlock(&lun->lun_lock);
3335                 }
3336                 if (lun != NULL)
3337                         mtx_unlock(&lun->lun_lock);
3338                 mtx_unlock(&softc->ctl_lock);
3339
3340                 if ((retval != 0)
3341                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3342                         retval = 0;
3343                         sbuf_delete(sb);
3344                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3345                         snprintf(list->error_str, sizeof(list->error_str),
3346                                  "Out of space, %d bytes is too small",
3347                                  list->alloc_len);
3348                         break;
3349                 }
3350
3351                 sbuf_finish(sb);
3352
3353                 retval = copyout(sbuf_data(sb), list->lun_xml,
3354                                  sbuf_len(sb) + 1);
3355
3356                 list->fill_len = sbuf_len(sb) + 1;
3357                 list->status = CTL_LUN_LIST_OK;
3358                 sbuf_delete(sb);
3359                 break;
3360         }
3361         case CTL_ISCSI: {
3362                 struct ctl_iscsi *ci;
3363                 struct ctl_frontend *fe;
3364
3365                 ci = (struct ctl_iscsi *)addr;
3366
3367                 fe = ctl_frontend_find("iscsi");
3368                 if (fe == NULL) {
3369                         ci->status = CTL_ISCSI_ERROR;
3370                         snprintf(ci->error_str, sizeof(ci->error_str),
3371                             "Frontend \"iscsi\" not found.");
3372                         break;
3373                 }
3374
3375                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3376                 break;
3377         }
3378         case CTL_PORT_REQ: {
3379                 struct ctl_req *req;
3380                 struct ctl_frontend *fe;
3381
3382                 req = (struct ctl_req *)addr;
3383
3384                 fe = ctl_frontend_find(req->driver);
3385                 if (fe == NULL) {
3386                         req->status = CTL_LUN_ERROR;
3387                         snprintf(req->error_str, sizeof(req->error_str),
3388                             "Frontend \"%s\" not found.", req->driver);
3389                         break;
3390                 }
3391                 if (req->num_args > 0) {
3392                         req->kern_args = ctl_copyin_args(req->num_args,
3393                             req->args, req->error_str, sizeof(req->error_str));
3394                         if (req->kern_args == NULL) {
3395                                 req->status = CTL_LUN_ERROR;
3396                                 break;
3397                         }
3398                 }
3399
3400                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3401
3402                 if (req->num_args > 0) {
3403                         ctl_copyout_args(req->num_args, req->kern_args);
3404                         ctl_free_args(req->num_args, req->kern_args);
3405                 }
3406                 break;
3407         }
3408         case CTL_PORT_LIST: {
3409                 struct sbuf *sb;
3410                 struct ctl_port *port;
3411                 struct ctl_lun_list *list;
3412                 struct ctl_option *opt;
3413                 int j;
3414
3415                 list = (struct ctl_lun_list *)addr;
3416
3417                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3418                 if (sb == NULL) {
3419                         list->status = CTL_LUN_LIST_ERROR;
3420                         snprintf(list->error_str, sizeof(list->error_str),
3421                                  "Unable to allocate %d bytes for LUN list",
3422                                  list->alloc_len);
3423                         break;
3424                 }
3425
3426                 sbuf_printf(sb, "<ctlportlist>\n");
3427
3428                 mtx_lock(&softc->ctl_lock);
3429                 STAILQ_FOREACH(port, &softc->port_list, links) {
3430                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3431                                              (uintmax_t)port->targ_port);
3432
3433                         /*
3434                          * Bail out as soon as we see that we've overfilled
3435                          * the buffer.
3436                          */
3437                         if (retval != 0)
3438                                 break;
3439
3440                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3441                             "</frontend_type>\n", port->frontend->name);
3442                         if (retval != 0)
3443                                 break;
3444
3445                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3446                                              port->port_type);
3447                         if (retval != 0)
3448                                 break;
3449
3450                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3451                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3452                         if (retval != 0)
3453                                 break;
3454
3455                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3456                             port->port_name);
3457                         if (retval != 0)
3458                                 break;
3459
3460                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3461                             port->physical_port);
3462                         if (retval != 0)
3463                                 break;
3464
3465                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3466                             port->virtual_port);
3467                         if (retval != 0)
3468                                 break;
3469
3470                         if (port->target_devid != NULL) {
3471                                 sbuf_printf(sb, "\t<target>");
3472                                 ctl_id_sbuf(port->target_devid, sb);
3473                                 sbuf_printf(sb, "</target>\n");
3474                         }
3475
3476                         if (port->port_devid != NULL) {
3477                                 sbuf_printf(sb, "\t<port>");
3478                                 ctl_id_sbuf(port->port_devid, sb);
3479                                 sbuf_printf(sb, "</port>\n");
3480                         }
3481
3482                         if (port->port_info != NULL) {
3483                                 retval = port->port_info(port->onoff_arg, sb);
3484                                 if (retval != 0)
3485                                         break;
3486                         }
3487                         STAILQ_FOREACH(opt, &port->options, links) {
3488                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3489                                     opt->name, opt->value, opt->name);
3490                                 if (retval != 0)
3491                                         break;
3492                         }
3493
3494                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3495                                 if (port->wwpn_iid[j].in_use == 0 ||
3496                                     (port->wwpn_iid[j].wwpn == 0 &&
3497                                      port->wwpn_iid[j].name == NULL))
3498                                         continue;
3499
3500                                 if (port->wwpn_iid[j].name != NULL)
3501                                         retval = sbuf_printf(sb,
3502                                             "\t<initiator id=\"%u\">%s</initiator>\n",
3503                                             j, port->wwpn_iid[j].name);
3504                                 else
3505                                         retval = sbuf_printf(sb,
3506                                             "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3507                                             j, port->wwpn_iid[j].wwpn);
3508                                 if (retval != 0)
3509                                         break;
3510                         }
3511                         if (retval != 0)
3512                                 break;
3513
3514                         retval = sbuf_printf(sb, "</targ_port>\n");
3515                         if (retval != 0)
3516                                 break;
3517                 }
3518                 mtx_unlock(&softc->ctl_lock);
3519
3520                 if ((retval != 0)
3521                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3522                         retval = 0;
3523                         sbuf_delete(sb);
3524                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3525                         snprintf(list->error_str, sizeof(list->error_str),
3526                                  "Out of space, %d bytes is too small",
3527                                  list->alloc_len);
3528                         break;
3529                 }
3530
3531                 sbuf_finish(sb);
3532
3533                 retval = copyout(sbuf_data(sb), list->lun_xml,
3534                                  sbuf_len(sb) + 1);
3535
3536                 list->fill_len = sbuf_len(sb) + 1;
3537                 list->status = CTL_LUN_LIST_OK;
3538                 sbuf_delete(sb);
3539                 break;
3540         }
3541         default: {
3542                 /* XXX KDM should we fix this? */
3543 #if 0
3544                 struct ctl_backend_driver *backend;
3545                 unsigned int type;
3546                 int found;
3547
3548                 found = 0;
3549
3550                 /*
3551                  * We encode the backend type as the ioctl type for backend
3552                  * ioctls.  So parse it out here, and then search for a
3553                  * backend of this type.
3554                  */
3555                 type = _IOC_TYPE(cmd);
3556
3557                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3558                         if (backend->type == type) {
3559                                 found = 1;
3560                                 break;
3561                         }
3562                 }
3563                 if (found == 0) {
3564                         printf("ctl: unknown ioctl command %#lx or backend "
3565                                "%d\n", cmd, type);
3566                         retval = EINVAL;
3567                         break;
3568                 }
3569                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3570 #endif
3571                 retval = ENOTTY;
3572                 break;
3573         }
3574         }
3575         return (retval);
3576 }
3577
3578 uint32_t
3579 ctl_get_initindex(struct ctl_nexus *nexus)
3580 {
3581         if (nexus->targ_port < CTL_MAX_PORTS)
3582                 return (nexus->initid.id +
3583                         (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3584         else
3585                 return (nexus->initid.id +
3586                        ((nexus->targ_port - CTL_MAX_PORTS) *
3587                         CTL_MAX_INIT_PER_PORT));
3588 }
3589
3590 uint32_t
3591 ctl_get_resindex(struct ctl_nexus *nexus)
3592 {
3593         return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3594 }
3595
3596 uint32_t
3597 ctl_port_idx(int port_num)
3598 {
3599         if (port_num < CTL_MAX_PORTS)
3600                 return(port_num);
3601         else
3602                 return(port_num - CTL_MAX_PORTS);
3603 }
3604
3605 static uint32_t
3606 ctl_map_lun(struct ctl_softc *softc, int port_num, uint32_t lun_id)
3607 {
3608         struct ctl_port *port;
3609
3610         port = softc->ctl_ports[ctl_port_idx(port_num)];
3611         if (port == NULL)
3612                 return (UINT32_MAX);
3613         if (port->lun_map == NULL)
3614                 return (lun_id);
3615         return (port->lun_map(port->targ_lun_arg, lun_id));
3616 }
3617
3618 static uint32_t
3619 ctl_map_lun_back(struct ctl_softc *softc, int port_num, uint32_t lun_id)
3620 {
3621         struct ctl_port *port;
3622         uint32_t i;
3623
3624         port = softc->ctl_ports[ctl_port_idx(port_num)];
3625         if (port->lun_map == NULL)
3626                 return (lun_id);
3627         for (i = 0; i < CTL_MAX_LUNS; i++) {
3628                 if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3629                         return (i);
3630         }
3631         return (UINT32_MAX);
3632 }
3633
3634 /*
3635  * Note:  This only works for bitmask sizes that are at least 32 bits, and
3636  * that are a power of 2.
3637  */
3638 int
3639 ctl_ffz(uint32_t *mask, uint32_t size)
3640 {
3641         uint32_t num_chunks, num_pieces;
3642         int i, j;
3643
3644         num_chunks = (size >> 5);
3645         if (num_chunks == 0)
3646                 num_chunks++;
3647         num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3648
3649         for (i = 0; i < num_chunks; i++) {
3650                 for (j = 0; j < num_pieces; j++) {
3651                         if ((mask[i] & (1 << j)) == 0)
3652                                 return ((i << 5) + j);
3653                 }
3654         }
3655
3656         return (-1);
3657 }
3658
3659 int
3660 ctl_set_mask(uint32_t *mask, uint32_t bit)
3661 {
3662         uint32_t chunk, piece;
3663
3664         chunk = bit >> 5;
3665         piece = bit % (sizeof(uint32_t) * 8);
3666
3667         if ((mask[chunk] & (1 << piece)) != 0)
3668                 return (-1);
3669         else
3670                 mask[chunk] |= (1 << piece);
3671
3672         return (0);
3673 }
3674
3675 int
3676 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3677 {
3678         uint32_t chunk, piece;
3679
3680         chunk = bit >> 5;
3681         piece = bit % (sizeof(uint32_t) * 8);
3682
3683         if ((mask[chunk] & (1 << piece)) == 0)
3684                 return (-1);
3685         else
3686                 mask[chunk] &= ~(1 << piece);
3687
3688         return (0);
3689 }
3690
3691 int
3692 ctl_is_set(uint32_t *mask, uint32_t bit)
3693 {
3694         uint32_t chunk, piece;
3695
3696         chunk = bit >> 5;
3697         piece = bit % (sizeof(uint32_t) * 8);
3698
3699         if ((mask[chunk] & (1 << piece)) == 0)
3700                 return (0);
3701         else
3702                 return (1);
3703 }
3704
3705 static uint64_t
3706 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3707 {
3708         uint64_t *t;
3709
3710         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3711         if (t == NULL)
3712                 return (0);
3713         return (t[residx % CTL_MAX_INIT_PER_PORT]);
3714 }
3715
3716 static void
3717 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3718 {
3719         uint64_t *t;
3720
3721         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3722         if (t == NULL)
3723                 return;
3724         t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3725 }
3726
3727 static void
3728 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3729 {
3730         uint64_t *p;
3731         u_int i;
3732
3733         i = residx/CTL_MAX_INIT_PER_PORT;
3734         if (lun->pr_keys[i] != NULL)
3735                 return;
3736         mtx_unlock(&lun->lun_lock);
3737         p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3738             M_WAITOK | M_ZERO);
3739         mtx_lock(&lun->lun_lock);
3740         if (lun->pr_keys[i] == NULL)
3741                 lun->pr_keys[i] = p;
3742         else
3743                 free(p, M_CTL);
3744 }
3745
3746 static void
3747 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3748 {
3749         uint64_t *t;
3750
3751         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3752         KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3753         t[residx % CTL_MAX_INIT_PER_PORT] = key;
3754 }
3755
3756 /*
3757  * ctl_softc, pool_name, total_ctl_io are passed in.
3758  * npool is passed out.
3759  */
3760 int
3761 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3762                 uint32_t total_ctl_io, void **npool)
3763 {
3764 #ifdef IO_POOLS
3765         struct ctl_io_pool *pool;
3766
3767         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3768                                             M_NOWAIT | M_ZERO);
3769         if (pool == NULL)
3770                 return (ENOMEM);
3771
3772         snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3773         pool->ctl_softc = ctl_softc;
3774         pool->zone = uma_zsecond_create(pool->name, NULL,
3775             NULL, NULL, NULL, ctl_softc->io_zone);
3776         /* uma_prealloc(pool->zone, total_ctl_io); */
3777
3778         *npool = pool;
3779 #else
3780         *npool = ctl_softc->io_zone;
3781 #endif
3782         return (0);
3783 }
3784
3785 void
3786 ctl_pool_free(struct ctl_io_pool *pool)
3787 {
3788
3789         if (pool == NULL)
3790                 return;
3791
3792 #ifdef IO_POOLS
3793         uma_zdestroy(pool->zone);
3794         free(pool, M_CTL);
3795 #endif
3796 }
3797
3798 union ctl_io *
3799 ctl_alloc_io(void *pool_ref)
3800 {
3801         union ctl_io *io;
3802 #ifdef IO_POOLS
3803         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3804
3805         io = uma_zalloc(pool->zone, M_WAITOK);
3806 #else
3807         io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3808 #endif
3809         if (io != NULL)
3810                 io->io_hdr.pool = pool_ref;
3811         return (io);
3812 }
3813
3814 union ctl_io *
3815 ctl_alloc_io_nowait(void *pool_ref)
3816 {
3817         union ctl_io *io;
3818 #ifdef IO_POOLS
3819         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3820
3821         io = uma_zalloc(pool->zone, M_NOWAIT);
3822 #else
3823         io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3824 #endif
3825         if (io != NULL)
3826                 io->io_hdr.pool = pool_ref;
3827         return (io);
3828 }
3829
3830 void
3831 ctl_free_io(union ctl_io *io)
3832 {
3833 #ifdef IO_POOLS
3834         struct ctl_io_pool *pool;
3835 #endif
3836
3837         if (io == NULL)
3838                 return;
3839
3840 #ifdef IO_POOLS
3841         pool = (struct ctl_io_pool *)io->io_hdr.pool;
3842         uma_zfree(pool->zone, io);
3843 #else
3844         uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3845 #endif
3846 }
3847
3848 void
3849 ctl_zero_io(union ctl_io *io)
3850 {
3851         void *pool_ref;
3852
3853         if (io == NULL)
3854                 return;
3855
3856         /*
3857          * May need to preserve linked list pointers at some point too.
3858          */
3859         pool_ref = io->io_hdr.pool;
3860         memset(io, 0, sizeof(*io));
3861         io->io_hdr.pool = pool_ref;
3862 }
3863
3864 /*
3865  * This routine is currently used for internal copies of ctl_ios that need
3866  * to persist for some reason after we've already returned status to the
3867  * FETD.  (Thus the flag set.)
3868  *
3869  * XXX XXX
3870  * Note that this makes a blind copy of all fields in the ctl_io, except
3871  * for the pool reference.  This includes any memory that has been
3872  * allocated!  That memory will no longer be valid after done has been
3873  * called, so this would be VERY DANGEROUS for command that actually does
3874  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3875  * start and stop commands, which don't transfer any data, so this is not a
3876  * problem.  If it is used for anything else, the caller would also need to
3877  * allocate data buffer space and this routine would need to be modified to
3878  * copy the data buffer(s) as well.
3879  */
3880 void
3881 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3882 {
3883         void *pool_ref;
3884
3885         if ((src == NULL)
3886          || (dest == NULL))
3887                 return;
3888
3889         /*
3890          * May need to preserve linked list pointers at some point too.
3891          */
3892         pool_ref = dest->io_hdr.pool;
3893
3894         memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3895
3896         dest->io_hdr.pool = pool_ref;
3897         /*
3898          * We need to know that this is an internal copy, and doesn't need
3899          * to get passed back to the FETD that allocated it.
3900          */
3901         dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3902 }
3903
3904 int
3905 ctl_expand_number(const char *buf, uint64_t *num)
3906 {
3907         char *endptr;
3908         uint64_t number;
3909         unsigned shift;
3910
3911         number = strtoq(buf, &endptr, 0);
3912
3913         switch (tolower((unsigned char)*endptr)) {
3914         case 'e':
3915                 shift = 60;
3916                 break;
3917         case 'p':
3918                 shift = 50;
3919                 break;
3920         case 't':
3921                 shift = 40;
3922                 break;
3923         case 'g':
3924                 shift = 30;
3925                 break;
3926         case 'm':
3927                 shift = 20;
3928                 break;
3929         case 'k':
3930                 shift = 10;
3931                 break;
3932         case 'b':
3933         case '\0': /* No unit. */
3934                 *num = number;
3935                 return (0);
3936         default:
3937                 /* Unrecognized unit. */
3938                 return (-1);
3939         }
3940
3941         if ((number << shift) >> shift != number) {
3942                 /* Overflow */
3943                 return (-1);
3944         }
3945         *num = number << shift;
3946         return (0);
3947 }
3948
3949
3950 /*
3951  * This routine could be used in the future to load default and/or saved
3952  * mode page parameters for a particuar lun.
3953  */
3954 static int
3955 ctl_init_page_index(struct ctl_lun *lun)
3956 {
3957         int i;
3958         struct ctl_page_index *page_index;
3959         const char *value;
3960         uint64_t ival;
3961
3962         memcpy(&lun->mode_pages.index, page_index_template,
3963                sizeof(page_index_template));
3964
3965         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3966
3967                 page_index = &lun->mode_pages.index[i];
3968                 /*
3969                  * If this is a disk-only mode page, there's no point in
3970                  * setting it up.  For some pages, we have to have some
3971                  * basic information about the disk in order to calculate the
3972                  * mode page data.
3973                  */
3974                 if ((lun->be_lun->lun_type != T_DIRECT)
3975                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3976                         continue;
3977
3978                 switch (page_index->page_code & SMPH_PC_MASK) {
3979                 case SMS_RW_ERROR_RECOVERY_PAGE: {
3980                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3981                                 panic("subpage is incorrect!");
3982                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3983                                &rw_er_page_default,
3984                                sizeof(rw_er_page_default));
3985                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3986                                &rw_er_page_changeable,
3987                                sizeof(rw_er_page_changeable));
3988                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3989                                &rw_er_page_default,
3990                                sizeof(rw_er_page_default));
3991                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3992                                &rw_er_page_default,
3993                                sizeof(rw_er_page_default));
3994                         page_index->page_data =
3995                                 (uint8_t *)lun->mode_pages.rw_er_page;
3996                         break;
3997                 }
3998                 case SMS_FORMAT_DEVICE_PAGE: {
3999                         struct scsi_format_page *format_page;
4000
4001                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4002                                 panic("subpage is incorrect!");
4003
4004                         /*
4005                          * Sectors per track are set above.  Bytes per
4006                          * sector need to be set here on a per-LUN basis.
4007                          */
4008                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4009                                &format_page_default,
4010                                sizeof(format_page_default));
4011                         memcpy(&lun->mode_pages.format_page[
4012                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
4013                                sizeof(format_page_changeable));
4014                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4015                                &format_page_default,
4016                                sizeof(format_page_default));
4017                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4018                                &format_page_default,
4019                                sizeof(format_page_default));
4020
4021                         format_page = &lun->mode_pages.format_page[
4022                                 CTL_PAGE_CURRENT];
4023                         scsi_ulto2b(lun->be_lun->blocksize,
4024                                     format_page->bytes_per_sector);
4025
4026                         format_page = &lun->mode_pages.format_page[
4027                                 CTL_PAGE_DEFAULT];
4028                         scsi_ulto2b(lun->be_lun->blocksize,
4029                                     format_page->bytes_per_sector);
4030
4031                         format_page = &lun->mode_pages.format_page[
4032                                 CTL_PAGE_SAVED];
4033                         scsi_ulto2b(lun->be_lun->blocksize,
4034                                     format_page->bytes_per_sector);
4035
4036                         page_index->page_data =
4037                                 (uint8_t *)lun->mode_pages.format_page;
4038                         break;
4039                 }
4040                 case SMS_RIGID_DISK_PAGE: {
4041                         struct scsi_rigid_disk_page *rigid_disk_page;
4042                         uint32_t sectors_per_cylinder;
4043                         uint64_t cylinders;
4044 #ifndef __XSCALE__
4045                         int shift;
4046 #endif /* !__XSCALE__ */
4047
4048                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4049                                 panic("invalid subpage value %d",
4050                                       page_index->subpage);
4051
4052                         /*
4053                          * Rotation rate and sectors per track are set
4054                          * above.  We calculate the cylinders here based on
4055                          * capacity.  Due to the number of heads and
4056                          * sectors per track we're using, smaller arrays
4057                          * may turn out to have 0 cylinders.  Linux and
4058                          * FreeBSD don't pay attention to these mode pages
4059                          * to figure out capacity, but Solaris does.  It
4060                          * seems to deal with 0 cylinders just fine, and
4061                          * works out a fake geometry based on the capacity.
4062                          */
4063                         memcpy(&lun->mode_pages.rigid_disk_page[
4064                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4065                                sizeof(rigid_disk_page_default));
4066                         memcpy(&lun->mode_pages.rigid_disk_page[
4067                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4068                                sizeof(rigid_disk_page_changeable));
4069
4070                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4071                                 CTL_DEFAULT_HEADS;
4072
4073                         /*
4074                          * The divide method here will be more accurate,
4075                          * probably, but results in floating point being
4076                          * used in the kernel on i386 (__udivdi3()).  On the
4077                          * XScale, though, __udivdi3() is implemented in
4078                          * software.
4079                          *
4080                          * The shift method for cylinder calculation is
4081                          * accurate if sectors_per_cylinder is a power of
4082                          * 2.  Otherwise it might be slightly off -- you
4083                          * might have a bit of a truncation problem.
4084                          */
4085 #ifdef  __XSCALE__
4086                         cylinders = (lun->be_lun->maxlba + 1) /
4087                                 sectors_per_cylinder;
4088 #else
4089                         for (shift = 31; shift > 0; shift--) {
4090                                 if (sectors_per_cylinder & (1 << shift))
4091                                         break;
4092                         }
4093                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
4094 #endif
4095
4096                         /*
4097                          * We've basically got 3 bytes, or 24 bits for the
4098                          * cylinder size in the mode page.  If we're over,
4099                          * just round down to 2^24.
4100                          */
4101                         if (cylinders > 0xffffff)
4102                                 cylinders = 0xffffff;
4103
4104                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4105                                 CTL_PAGE_DEFAULT];
4106                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4107
4108                         if ((value = ctl_get_opt(&lun->be_lun->options,
4109                             "rpm")) != NULL) {
4110                                 scsi_ulto2b(strtol(value, NULL, 0),
4111                                      rigid_disk_page->rotation_rate);
4112                         }
4113
4114                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4115                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4116                                sizeof(rigid_disk_page_default));
4117                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4118                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4119                                sizeof(rigid_disk_page_default));
4120
4121                         page_index->page_data =
4122                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
4123                         break;
4124                 }
4125                 case SMS_CACHING_PAGE: {
4126                         struct scsi_caching_page *caching_page;
4127
4128                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4129                                 panic("invalid subpage value %d",
4130                                       page_index->subpage);
4131                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4132                                &caching_page_default,
4133                                sizeof(caching_page_default));
4134                         memcpy(&lun->mode_pages.caching_page[
4135                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4136                                sizeof(caching_page_changeable));
4137                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4138                                &caching_page_default,
4139                                sizeof(caching_page_default));
4140                         caching_page = &lun->mode_pages.caching_page[
4141                             CTL_PAGE_SAVED];
4142                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
4143                         if (value != NULL && strcmp(value, "off") == 0)
4144                                 caching_page->flags1 &= ~SCP_WCE;
4145                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
4146                         if (value != NULL && strcmp(value, "off") == 0)
4147                                 caching_page->flags1 |= SCP_RCD;
4148                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4149                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4150                                sizeof(caching_page_default));
4151                         page_index->page_data =
4152                                 (uint8_t *)lun->mode_pages.caching_page;
4153                         break;
4154                 }
4155                 case SMS_CONTROL_MODE_PAGE: {
4156                         struct scsi_control_page *control_page;
4157
4158                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4159                                 panic("invalid subpage value %d",
4160                                       page_index->subpage);
4161
4162                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4163                                &control_page_default,
4164                                sizeof(control_page_default));
4165                         memcpy(&lun->mode_pages.control_page[
4166                                CTL_PAGE_CHANGEABLE], &control_page_changeable,
4167                                sizeof(control_page_changeable));
4168                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4169                                &control_page_default,
4170                                sizeof(control_page_default));
4171                         control_page = &lun->mode_pages.control_page[
4172                             CTL_PAGE_SAVED];
4173                         value = ctl_get_opt(&lun->be_lun->options, "reordering");
4174                         if (value != NULL && strcmp(value, "unrestricted") == 0) {
4175                                 control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4176                                 control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4177                         }
4178                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4179                                &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4180                                sizeof(control_page_default));
4181                         page_index->page_data =
4182                                 (uint8_t *)lun->mode_pages.control_page;
4183                         break;
4184
4185                 }
4186                 case SMS_INFO_EXCEPTIONS_PAGE: {
4187                         switch (page_index->subpage) {
4188                         case SMS_SUBPAGE_PAGE_0:
4189                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4190                                        &ie_page_default,
4191                                        sizeof(ie_page_default));
4192                                 memcpy(&lun->mode_pages.ie_page[
4193                                        CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4194                                        sizeof(ie_page_changeable));
4195                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4196                                        &ie_page_default,
4197                                        sizeof(ie_page_default));
4198                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4199                                        &ie_page_default,
4200                                        sizeof(ie_page_default));
4201                                 page_index->page_data =
4202                                         (uint8_t *)lun->mode_pages.ie_page;
4203                                 break;
4204                         case 0x02: {
4205                                 struct ctl_logical_block_provisioning_page *page;
4206
4207                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4208                                        &lbp_page_default,
4209                                        sizeof(lbp_page_default));
4210                                 memcpy(&lun->mode_pages.lbp_page[
4211                                        CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4212                                        sizeof(lbp_page_changeable));
4213                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4214                                        &lbp_page_default,
4215                                        sizeof(lbp_page_default));
4216                                 page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4217                                 value = ctl_get_opt(&lun->be_lun->options,
4218                                     "avail-threshold");
4219                                 if (value != NULL &&
4220                                     ctl_expand_number(value, &ival) == 0) {
4221                                         page->descr[0].flags |= SLBPPD_ENABLED |
4222                                             SLBPPD_ARMING_DEC;
4223                                         if (lun->be_lun->blocksize)
4224                                                 ival /= lun->be_lun->blocksize;
4225                                         else
4226                                                 ival /= 512;
4227                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4228                                             page->descr[0].count);
4229                                 }
4230                                 value = ctl_get_opt(&lun->be_lun->options,
4231                                     "used-threshold");
4232                                 if (value != NULL &&
4233                                     ctl_expand_number(value, &ival) == 0) {
4234                                         page->descr[1].flags |= SLBPPD_ENABLED |
4235                                             SLBPPD_ARMING_INC;
4236                                         if (lun->be_lun->blocksize)
4237                                                 ival /= lun->be_lun->blocksize;
4238                                         else
4239                                                 ival /= 512;
4240                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4241                                             page->descr[1].count);
4242                                 }
4243                                 value = ctl_get_opt(&lun->be_lun->options,
4244                                     "pool-avail-threshold");
4245                                 if (value != NULL &&
4246                                     ctl_expand_number(value, &ival) == 0) {
4247                                         page->descr[2].flags |= SLBPPD_ENABLED |
4248                                             SLBPPD_ARMING_DEC;
4249                                         if (lun->be_lun->blocksize)
4250                                                 ival /= lun->be_lun->blocksize;
4251                                         else
4252                                                 ival /= 512;
4253                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4254                                             page->descr[2].count);
4255                                 }
4256                                 value = ctl_get_opt(&lun->be_lun->options,
4257                                     "pool-used-threshold");
4258                                 if (value != NULL &&
4259                                     ctl_expand_number(value, &ival) == 0) {
4260                                         page->descr[3].flags |= SLBPPD_ENABLED |
4261                                             SLBPPD_ARMING_INC;
4262                                         if (lun->be_lun->blocksize)
4263                                                 ival /= lun->be_lun->blocksize;
4264                                         else
4265                                                 ival /= 512;
4266                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4267                                             page->descr[3].count);
4268                                 }
4269                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4270                                        &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4271                                        sizeof(lbp_page_default));
4272                                 page_index->page_data =
4273                                         (uint8_t *)lun->mode_pages.lbp_page;
4274                         }}
4275                         break;
4276                 }
4277                 case SMS_VENDOR_SPECIFIC_PAGE:{
4278                         switch (page_index->subpage) {
4279                         case DBGCNF_SUBPAGE_CODE: {
4280                                 struct copan_debugconf_subpage *current_page,
4281                                                                *saved_page;
4282
4283                                 memcpy(&lun->mode_pages.debugconf_subpage[
4284                                        CTL_PAGE_CURRENT],
4285                                        &debugconf_page_default,
4286                                        sizeof(debugconf_page_default));
4287                                 memcpy(&lun->mode_pages.debugconf_subpage[
4288                                        CTL_PAGE_CHANGEABLE],
4289                                        &debugconf_page_changeable,
4290                                        sizeof(debugconf_page_changeable));
4291                                 memcpy(&lun->mode_pages.debugconf_subpage[
4292                                        CTL_PAGE_DEFAULT],
4293                                        &debugconf_page_default,
4294                                        sizeof(debugconf_page_default));
4295                                 memcpy(&lun->mode_pages.debugconf_subpage[
4296                                        CTL_PAGE_SAVED],
4297                                        &debugconf_page_default,
4298                                        sizeof(debugconf_page_default));
4299                                 page_index->page_data =
4300                                         (uint8_t *)lun->mode_pages.debugconf_subpage;
4301
4302                                 current_page = (struct copan_debugconf_subpage *)
4303                                         (page_index->page_data +
4304                                          (page_index->page_len *
4305                                           CTL_PAGE_CURRENT));
4306                                 saved_page = (struct copan_debugconf_subpage *)
4307                                         (page_index->page_data +
4308                                          (page_index->page_len *
4309                                           CTL_PAGE_SAVED));
4310                                 break;
4311                         }
4312                         default:
4313                                 panic("invalid subpage value %d",
4314                                       page_index->subpage);
4315                                 break;
4316                         }
4317                         break;
4318                 }
4319                 default:
4320                         panic("invalid page value %d",
4321                               page_index->page_code & SMPH_PC_MASK);
4322                         break;
4323         }
4324         }
4325
4326         return (CTL_RETVAL_COMPLETE);
4327 }
4328
4329 static int
4330 ctl_init_log_page_index(struct ctl_lun *lun)
4331 {
4332         struct ctl_page_index *page_index;
4333         int i, j, k, prev;
4334
4335         memcpy(&lun->log_pages.index, log_page_index_template,
4336                sizeof(log_page_index_template));
4337
4338         prev = -1;
4339         for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4340
4341                 page_index = &lun->log_pages.index[i];
4342                 /*
4343                  * If this is a disk-only mode page, there's no point in
4344                  * setting it up.  For some pages, we have to have some
4345                  * basic information about the disk in order to calculate the
4346                  * mode page data.
4347                  */
4348                 if ((lun->be_lun->lun_type != T_DIRECT)
4349                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4350                         continue;
4351
4352                 if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4353                      lun->backend->lun_attr == NULL)
4354                         continue;
4355
4356                 if (page_index->page_code != prev) {
4357                         lun->log_pages.pages_page[j] = page_index->page_code;
4358                         prev = page_index->page_code;
4359                         j++;
4360                 }
4361                 lun->log_pages.subpages_page[k*2] = page_index->page_code;
4362                 lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4363                 k++;
4364         }
4365         lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4366         lun->log_pages.index[0].page_len = j;
4367         lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4368         lun->log_pages.index[1].page_len = k * 2;
4369         lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4370         lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4371
4372         return (CTL_RETVAL_COMPLETE);
4373 }
4374
4375 static int
4376 hex2bin(const char *str, uint8_t *buf, int buf_size)
4377 {
4378         int i;
4379         u_char c;
4380
4381         memset(buf, 0, buf_size);
4382         while (isspace(str[0]))
4383                 str++;
4384         if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4385                 str += 2;
4386         buf_size *= 2;
4387         for (i = 0; str[i] != 0 && i < buf_size; i++) {
4388                 c = str[i];
4389                 if (isdigit(c))
4390                         c -= '0';
4391                 else if (isalpha(c))
4392                         c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4393                 else
4394                         break;
4395                 if (c >= 16)
4396                         break;
4397                 if ((i & 1) == 0)
4398                         buf[i / 2] |= (c << 4);
4399                 else
4400                         buf[i / 2] |= c;
4401         }
4402         return ((i + 1) / 2);
4403 }
4404
4405 /*
4406  * LUN allocation.
4407  *
4408  * Requirements:
4409  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4410  *   wants us to allocate the LUN and he can block.
4411  * - ctl_softc is always set
4412  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4413  *
4414  * Returns 0 for success, non-zero (errno) for failure.
4415  */
4416 static int
4417 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4418               struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4419 {
4420         struct ctl_lun *nlun, *lun;
4421         struct ctl_port *port;
4422         struct scsi_vpd_id_descriptor *desc;
4423         struct scsi_vpd_id_t10 *t10id;
4424         const char *eui, *naa, *scsiname, *vendor, *value;
4425         int lun_number, i, lun_malloced;
4426         int devidlen, idlen1, idlen2 = 0, len;
4427
4428         if (be_lun == NULL)
4429                 return (EINVAL);
4430
4431         /*
4432          * We currently only support Direct Access or Processor LUN types.
4433          */
4434         switch (be_lun->lun_type) {
4435         case T_DIRECT:
4436                 break;
4437         case T_PROCESSOR:
4438                 break;
4439         case T_SEQUENTIAL:
4440         case T_CHANGER:
4441         default:
4442                 be_lun->lun_config_status(be_lun->be_lun,
4443                                           CTL_LUN_CONFIG_FAILURE);
4444                 break;
4445         }
4446         if (ctl_lun == NULL) {
4447                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4448                 lun_malloced = 1;
4449         } else {
4450                 lun_malloced = 0;
4451                 lun = ctl_lun;
4452         }
4453
4454         memset(lun, 0, sizeof(*lun));
4455         if (lun_malloced)
4456                 lun->flags = CTL_LUN_MALLOCED;
4457
4458         /* Generate LUN ID. */
4459         devidlen = max(CTL_DEVID_MIN_LEN,
4460             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4461         idlen1 = sizeof(*t10id) + devidlen;
4462         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4463         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4464         if (scsiname != NULL) {
4465                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4466                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4467         }
4468         eui = ctl_get_opt(&be_lun->options, "eui");
4469         if (eui != NULL) {
4470                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4471         }
4472         naa = ctl_get_opt(&be_lun->options, "naa");
4473         if (naa != NULL) {
4474                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4475         }
4476         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4477             M_CTL, M_WAITOK | M_ZERO);
4478         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4479         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4480         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4481         desc->length = idlen1;
4482         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4483         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4484         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4485                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4486         } else {
4487                 strncpy(t10id->vendor, vendor,
4488                     min(sizeof(t10id->vendor), strlen(vendor)));
4489         }
4490         strncpy((char *)t10id->vendor_spec_id,
4491             (char *)be_lun->device_id, devidlen);
4492         if (scsiname != NULL) {
4493                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4494                     desc->length);
4495                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4496                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4497                     SVPD_ID_TYPE_SCSI_NAME;
4498                 desc->length = idlen2;
4499                 strlcpy(desc->identifier, scsiname, idlen2);
4500         }
4501         if (eui != NULL) {
4502                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4503                     desc->length);
4504                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4505                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4506                     SVPD_ID_TYPE_EUI64;
4507                 desc->length = hex2bin(eui, desc->identifier, 16);
4508                 desc->length = desc->length > 12 ? 16 :
4509                     (desc->length > 8 ? 12 : 8);
4510                 len -= 16 - desc->length;
4511         }
4512         if (naa != NULL) {
4513                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4514                     desc->length);
4515                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4516                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4517                     SVPD_ID_TYPE_NAA;
4518                 desc->length = hex2bin(naa, desc->identifier, 16);
4519                 desc->length = desc->length > 8 ? 16 : 8;
4520                 len -= 16 - desc->length;
4521         }
4522         lun->lun_devid->len = len;
4523
4524         mtx_lock(&ctl_softc->ctl_lock);
4525         /*
4526          * See if the caller requested a particular LUN number.  If so, see
4527          * if it is available.  Otherwise, allocate the first available LUN.
4528          */
4529         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4530                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4531                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4532                         mtx_unlock(&ctl_softc->ctl_lock);
4533                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4534                                 printf("ctl: requested LUN ID %d is higher "
4535                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4536                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4537                         } else {
4538                                 /*
4539                                  * XXX KDM return an error, or just assign
4540                                  * another LUN ID in this case??
4541                                  */
4542                                 printf("ctl: requested LUN ID %d is already "
4543                                        "in use\n", be_lun->req_lun_id);
4544                         }
4545                         if (lun->flags & CTL_LUN_MALLOCED)
4546                                 free(lun, M_CTL);
4547                         be_lun->lun_config_status(be_lun->be_lun,
4548                                                   CTL_LUN_CONFIG_FAILURE);
4549                         return (ENOSPC);
4550                 }
4551                 lun_number = be_lun->req_lun_id;
4552         } else {
4553                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4554                 if (lun_number == -1) {
4555                         mtx_unlock(&ctl_softc->ctl_lock);
4556                         printf("ctl: can't allocate LUN on target %ju, out of "
4557                                "LUNs\n", (uintmax_t)target_id.id);
4558                         if (lun->flags & CTL_LUN_MALLOCED)
4559                                 free(lun, M_CTL);
4560                         be_lun->lun_config_status(be_lun->be_lun,
4561                                                   CTL_LUN_CONFIG_FAILURE);
4562                         return (ENOSPC);
4563                 }
4564         }
4565         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4566
4567         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4568         lun->target = target_id;
4569         lun->lun = lun_number;
4570         lun->be_lun = be_lun;
4571         /*
4572          * The processor LUN is always enabled.  Disk LUNs come on line
4573          * disabled, and must be enabled by the backend.
4574          */
4575         lun->flags |= CTL_LUN_DISABLED;
4576         lun->backend = be_lun->be;
4577         be_lun->ctl_lun = lun;
4578         be_lun->lun_id = lun_number;
4579         atomic_add_int(&be_lun->be->num_luns, 1);
4580         if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4581                 lun->flags |= CTL_LUN_OFFLINE;
4582
4583         if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4584                 lun->flags |= CTL_LUN_STOPPED;
4585
4586         if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4587                 lun->flags |= CTL_LUN_INOPERABLE;
4588
4589         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4590                 lun->flags |= CTL_LUN_PRIMARY_SC;
4591
4592         value = ctl_get_opt(&be_lun->options, "readonly");
4593         if (value != NULL && strcmp(value, "on") == 0)
4594                 lun->flags |= CTL_LUN_READONLY;
4595
4596         lun->serseq = CTL_LUN_SERSEQ_OFF;
4597         if (be_lun->flags & CTL_LUN_FLAG_SERSEQ_READ)
4598                 lun->serseq = CTL_LUN_SERSEQ_READ;
4599         value = ctl_get_opt(&be_lun->options, "serseq");
4600         if (value != NULL && strcmp(value, "on") == 0)
4601                 lun->serseq = CTL_LUN_SERSEQ_ON;
4602         else if (value != NULL && strcmp(value, "read") == 0)
4603                 lun->serseq = CTL_LUN_SERSEQ_READ;
4604         else if (value != NULL && strcmp(value, "off") == 0)
4605                 lun->serseq = CTL_LUN_SERSEQ_OFF;
4606
4607         lun->ctl_softc = ctl_softc;
4608         TAILQ_INIT(&lun->ooa_queue);
4609         TAILQ_INIT(&lun->blocked_queue);
4610         STAILQ_INIT(&lun->error_list);
4611         ctl_tpc_lun_init(lun);
4612
4613         /*
4614          * Initialize the mode and log page index.
4615          */
4616         ctl_init_page_index(lun);
4617         ctl_init_log_page_index(lun);
4618
4619         /*
4620          * Now, before we insert this lun on the lun list, set the lun
4621          * inventory changed UA for all other luns.
4622          */
4623         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4624                 mtx_lock(&nlun->lun_lock);
4625                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4626                 mtx_unlock(&nlun->lun_lock);
4627         }
4628
4629         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4630
4631         ctl_softc->ctl_luns[lun_number] = lun;
4632
4633         ctl_softc->num_luns++;
4634
4635         /* Setup statistics gathering */
4636         lun->stats.device_type = be_lun->lun_type;
4637         lun->stats.lun_number = lun_number;
4638         if (lun->stats.device_type == T_DIRECT)
4639                 lun->stats.blocksize = be_lun->blocksize;
4640         else
4641                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4642         for (i = 0;i < CTL_MAX_PORTS;i++)
4643                 lun->stats.ports[i].targ_port = i;
4644
4645         mtx_unlock(&ctl_softc->ctl_lock);
4646
4647         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4648
4649         /*
4650          * Run through each registered FETD and bring it online if it isn't
4651          * already.  Enable the target ID if it hasn't been enabled, and
4652          * enable this particular LUN.
4653          */
4654         STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4655                 int retval;
4656
4657                 retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4658                 if (retval != 0) {
4659                         printf("ctl_alloc_lun: FETD %s port %d returned error "
4660                                "%d for lun_enable on target %ju lun %d\n",
4661                                port->port_name, port->targ_port, retval,
4662                                (uintmax_t)target_id.id, lun_number);
4663                 } else
4664                         port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4665         }
4666         return (0);
4667 }
4668
4669 /*
4670  * Delete a LUN.
4671  * Assumptions:
4672  * - LUN has already been marked invalid and any pending I/O has been taken
4673  *   care of.
4674  */
4675 static int
4676 ctl_free_lun(struct ctl_lun *lun)
4677 {
4678         struct ctl_softc *softc;
4679 #if 0
4680         struct ctl_port *port;
4681 #endif
4682         struct ctl_lun *nlun;
4683         int i;
4684
4685         softc = lun->ctl_softc;
4686
4687         mtx_assert(&softc->ctl_lock, MA_OWNED);
4688
4689         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4690
4691         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4692
4693         softc->ctl_luns[lun->lun] = NULL;
4694
4695         if (!TAILQ_EMPTY(&lun->ooa_queue))
4696                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4697
4698         softc->num_luns--;
4699
4700         /*
4701          * XXX KDM this scheme only works for a single target/multiple LUN
4702          * setup.  It needs to be revamped for a multiple target scheme.
4703          *
4704          * XXX KDM this results in port->lun_disable() getting called twice,
4705          * once when ctl_disable_lun() is called, and a second time here.
4706          * We really need to re-think the LUN disable semantics.  There
4707          * should probably be several steps/levels to LUN removal:
4708          *  - disable
4709          *  - invalidate
4710          *  - free
4711          *
4712          * Right now we only have a disable method when communicating to
4713          * the front end ports, at least for individual LUNs.
4714          */
4715 #if 0
4716         STAILQ_FOREACH(port, &softc->port_list, links) {
4717                 int retval;
4718
4719                 retval = port->lun_disable(port->targ_lun_arg, lun->target,
4720                                          lun->lun);
4721                 if (retval != 0) {
4722                         printf("ctl_free_lun: FETD %s port %d returned error "
4723                                "%d for lun_disable on target %ju lun %jd\n",
4724                                port->port_name, port->targ_port, retval,
4725                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4726                 }
4727
4728                 if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4729                         port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4730
4731                         retval = port->targ_disable(port->targ_lun_arg,lun->target);
4732                         if (retval != 0) {
4733                                 printf("ctl_free_lun: FETD %s port %d "
4734                                        "returned error %d for targ_disable on "
4735                                        "target %ju\n", port->port_name,
4736                                        port->targ_port, retval,
4737                                        (uintmax_t)lun->target.id);
4738                         } else
4739                                 port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4740
4741                         if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4742                                 continue;
4743
4744 #if 0
4745                         port->port_offline(port->onoff_arg);
4746                         port->status &= ~CTL_PORT_STATUS_ONLINE;
4747 #endif
4748                 }
4749         }
4750 #endif
4751
4752         /*
4753          * Tell the backend to free resources, if this LUN has a backend.
4754          */
4755         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4756         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4757
4758         ctl_tpc_lun_shutdown(lun);
4759         mtx_destroy(&lun->lun_lock);
4760         free(lun->lun_devid, M_CTL);
4761         for (i = 0; i < CTL_MAX_PORTS; i++)
4762                 free(lun->pending_ua[i], M_CTL);
4763         for (i = 0; i < 2 * CTL_MAX_PORTS; i++)
4764                 free(lun->pr_keys[i], M_CTL);
4765         free(lun->write_buffer, M_CTL);
4766         if (lun->flags & CTL_LUN_MALLOCED)
4767                 free(lun, M_CTL);
4768
4769         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4770                 mtx_lock(&nlun->lun_lock);
4771                 ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4772                 mtx_unlock(&nlun->lun_lock);
4773         }
4774
4775         return (0);
4776 }
4777
4778 static void
4779 ctl_create_lun(struct ctl_be_lun *be_lun)
4780 {
4781         struct ctl_softc *softc;
4782
4783         softc = control_softc;
4784
4785         /*
4786          * ctl_alloc_lun() should handle all potential failure cases.
4787          */
4788         ctl_alloc_lun(softc, NULL, be_lun, softc->target);
4789 }
4790
4791 int
4792 ctl_add_lun(struct ctl_be_lun *be_lun)
4793 {
4794         struct ctl_softc *softc = control_softc;
4795
4796         mtx_lock(&softc->ctl_lock);
4797         STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4798         mtx_unlock(&softc->ctl_lock);
4799         wakeup(&softc->pending_lun_queue);
4800
4801         return (0);
4802 }
4803
4804 int
4805 ctl_enable_lun(struct ctl_be_lun *be_lun)
4806 {
4807         struct ctl_softc *softc;
4808         struct ctl_port *port, *nport;
4809         struct ctl_lun *lun;
4810         int retval;
4811
4812         lun = (struct ctl_lun *)be_lun->ctl_lun;
4813         softc = lun->ctl_softc;
4814
4815         mtx_lock(&softc->ctl_lock);
4816         mtx_lock(&lun->lun_lock);
4817         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4818                 /*
4819                  * eh?  Why did we get called if the LUN is already
4820                  * enabled?
4821                  */
4822                 mtx_unlock(&lun->lun_lock);
4823                 mtx_unlock(&softc->ctl_lock);
4824                 return (0);
4825         }
4826         lun->flags &= ~CTL_LUN_DISABLED;
4827         mtx_unlock(&lun->lun_lock);
4828
4829         for (port = STAILQ_FIRST(&softc->port_list); port != NULL; port = nport) {
4830                 nport = STAILQ_NEXT(port, links);
4831
4832                 /*
4833                  * Drop the lock while we call the FETD's enable routine.
4834                  * This can lead to a callback into CTL (at least in the
4835                  * case of the internal initiator frontend.
4836                  */
4837                 mtx_unlock(&softc->ctl_lock);
4838                 retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4839                 mtx_lock(&softc->ctl_lock);
4840                 if (retval != 0) {
4841                         printf("%s: FETD %s port %d returned error "
4842                                "%d for lun_enable on target %ju lun %jd\n",
4843                                __func__, port->port_name, port->targ_port, retval,
4844                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4845                 }
4846 #if 0
4847                  else {
4848             /* NOTE:  TODO:  why does lun enable affect port status? */
4849                         port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4850                 }
4851 #endif
4852         }
4853
4854         mtx_unlock(&softc->ctl_lock);
4855
4856         return (0);
4857 }
4858
4859 int
4860 ctl_disable_lun(struct ctl_be_lun *be_lun)
4861 {
4862         struct ctl_softc *softc;
4863         struct ctl_port *port;
4864         struct ctl_lun *lun;
4865         int retval;
4866
4867         lun = (struct ctl_lun *)be_lun->ctl_lun;
4868         softc = lun->ctl_softc;
4869
4870         mtx_lock(&softc->ctl_lock);
4871         mtx_lock(&lun->lun_lock);
4872         if (lun->flags & CTL_LUN_DISABLED) {
4873                 mtx_unlock(&lun->lun_lock);
4874                 mtx_unlock(&softc->ctl_lock);
4875                 return (0);
4876         }
4877         lun->flags |= CTL_LUN_DISABLED;
4878         mtx_unlock(&lun->lun_lock);
4879
4880         STAILQ_FOREACH(port, &softc->port_list, links) {
4881                 mtx_unlock(&softc->ctl_lock);
4882                 /*
4883                  * Drop the lock before we call the frontend's disable
4884                  * routine, to avoid lock order reversals.
4885                  *
4886                  * XXX KDM what happens if the frontend list changes while
4887                  * we're traversing it?  It's unlikely, but should be handled.
4888                  */
4889                 retval = port->lun_disable(port->targ_lun_arg, lun->target,
4890                                          lun->lun);
4891                 mtx_lock(&softc->ctl_lock);
4892                 if (retval != 0) {
4893                         printf("ctl_alloc_lun: FETD %s port %d returned error "
4894                                "%d for lun_disable on target %ju lun %jd\n",
4895                                port->port_name, port->targ_port, retval,
4896                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4897                 }
4898         }
4899
4900         mtx_unlock(&softc->ctl_lock);
4901
4902         return (0);
4903 }
4904
4905 int
4906 ctl_start_lun(struct ctl_be_lun *be_lun)
4907 {
4908         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4909
4910         mtx_lock(&lun->lun_lock);
4911         lun->flags &= ~CTL_LUN_STOPPED;
4912         mtx_unlock(&lun->lun_lock);
4913         return (0);
4914 }
4915
4916 int
4917 ctl_stop_lun(struct ctl_be_lun *be_lun)
4918 {
4919         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4920
4921         mtx_lock(&lun->lun_lock);
4922         lun->flags |= CTL_LUN_STOPPED;
4923         mtx_unlock(&lun->lun_lock);
4924         return (0);
4925 }
4926
4927 int
4928 ctl_lun_offline(struct ctl_be_lun *be_lun)
4929 {
4930         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4931
4932         mtx_lock(&lun->lun_lock);
4933         lun->flags |= CTL_LUN_OFFLINE;
4934         mtx_unlock(&lun->lun_lock);
4935         return (0);
4936 }
4937
4938 int
4939 ctl_lun_online(struct ctl_be_lun *be_lun)
4940 {
4941         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4942
4943         mtx_lock(&lun->lun_lock);
4944         lun->flags &= ~CTL_LUN_OFFLINE;
4945         mtx_unlock(&lun->lun_lock);
4946         return (0);
4947 }
4948
4949 int
4950 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4951 {
4952         struct ctl_softc *softc;
4953         struct ctl_lun *lun;
4954
4955         lun = (struct ctl_lun *)be_lun->ctl_lun;
4956         softc = lun->ctl_softc;
4957
4958         mtx_lock(&lun->lun_lock);
4959
4960         /*
4961          * The LUN needs to be disabled before it can be marked invalid.
4962          */
4963         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4964                 mtx_unlock(&lun->lun_lock);
4965                 return (-1);
4966         }
4967         /*
4968          * Mark the LUN invalid.
4969          */
4970         lun->flags |= CTL_LUN_INVALID;
4971
4972         /*
4973          * If there is nothing in the OOA queue, go ahead and free the LUN.
4974          * If we have something in the OOA queue, we'll free it when the
4975          * last I/O completes.
4976          */
4977         if (TAILQ_EMPTY(&lun->ooa_queue)) {
4978                 mtx_unlock(&lun->lun_lock);
4979                 mtx_lock(&softc->ctl_lock);
4980                 ctl_free_lun(lun);
4981                 mtx_unlock(&softc->ctl_lock);
4982         } else
4983                 mtx_unlock(&lun->lun_lock);
4984
4985         return (0);
4986 }
4987
4988 int
4989 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4990 {
4991         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4992
4993         mtx_lock(&lun->lun_lock);
4994         lun->flags |= CTL_LUN_INOPERABLE;
4995         mtx_unlock(&lun->lun_lock);
4996         return (0);
4997 }
4998
4999 int
5000 ctl_lun_operable(struct ctl_be_lun *be_lun)
5001 {
5002         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5003
5004         mtx_lock(&lun->lun_lock);
5005         lun->flags &= ~CTL_LUN_INOPERABLE;
5006         mtx_unlock(&lun->lun_lock);
5007         return (0);
5008 }
5009
5010 void
5011 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5012 {
5013         struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5014
5015         mtx_lock(&lun->lun_lock);
5016         ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGED);
5017         mtx_unlock(&lun->lun_lock);
5018 }
5019
5020 /*
5021  * Backend "memory move is complete" callback for requests that never
5022  * make it down to say RAIDCore's configuration code.
5023  */
5024 int
5025 ctl_config_move_done(union ctl_io *io)
5026 {
5027         int retval;
5028
5029         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5030         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5031             ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5032
5033         if ((io->io_hdr.port_status != 0) &&
5034             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5035              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5036                 /*
5037                  * For hardware error sense keys, the sense key
5038                  * specific value is defined to be a retry count,
5039                  * but we use it to pass back an internal FETD
5040                  * error code.  XXX KDM  Hopefully the FETD is only
5041                  * using 16 bits for an error code, since that's
5042                  * all the space we have in the sks field.
5043                  */
5044                 ctl_set_internal_failure(&io->scsiio,
5045                                          /*sks_valid*/ 1,
5046                                          /*retry_count*/
5047                                          io->io_hdr.port_status);
5048         }
5049
5050         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5051             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5052              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5053             ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5054                 /*
5055                  * XXX KDM just assuming a single pointer here, and not a
5056                  * S/G list.  If we start using S/G lists for config data,
5057                  * we'll need to know how to clean them up here as well.
5058                  */
5059                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5060                         free(io->scsiio.kern_data_ptr, M_CTL);
5061                 ctl_done(io);
5062                 retval = CTL_RETVAL_COMPLETE;
5063         } else {
5064                 /*
5065                  * XXX KDM now we need to continue data movement.  Some
5066                  * options:
5067                  * - call ctl_scsiio() again?  We don't do this for data
5068                  *   writes, because for those at least we know ahead of
5069                  *   time where the write will go and how long it is.  For
5070                  *   config writes, though, that information is largely
5071                  *   contained within the write itself, thus we need to
5072                  *   parse out the data again.
5073                  *
5074                  * - Call some other function once the data is in?
5075                  */
5076                 if (ctl_debug & CTL_DEBUG_CDB_DATA)
5077                         ctl_data_print(io);
5078
5079                 /*
5080                  * XXX KDM call ctl_scsiio() again for now, and check flag
5081                  * bits to see whether we're allocated or not.
5082                  */
5083                 retval = ctl_scsiio(&io->scsiio);
5084         }
5085         return (retval);
5086 }
5087
5088 /*
5089  * This gets called by a backend driver when it is done with a
5090  * data_submit method.
5091  */
5092 void
5093 ctl_data_submit_done(union ctl_io *io)
5094 {
5095         /*
5096          * If the IO_CONT flag is set, we need to call the supplied
5097          * function to continue processing the I/O, instead of completing
5098          * the I/O just yet.
5099          *
5100          * If there is an error, though, we don't want to keep processing.
5101          * Instead, just send status back to the initiator.
5102          */
5103         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5104             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5105             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5106              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5107                 io->scsiio.io_cont(io);
5108                 return;
5109         }
5110         ctl_done(io);
5111 }
5112
5113 /*
5114  * This gets called by a backend driver when it is done with a
5115  * configuration write.
5116  */
5117 void
5118 ctl_config_write_done(union ctl_io *io)
5119 {
5120         uint8_t *buf;
5121
5122         /*
5123          * If the IO_CONT flag is set, we need to call the supplied
5124          * function to continue processing the I/O, instead of completing
5125          * the I/O just yet.
5126          *
5127          * If there is an error, though, we don't want to keep processing.
5128          * Instead, just send status back to the initiator.
5129          */
5130         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5131             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5132             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5133              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5134                 io->scsiio.io_cont(io);
5135                 return;
5136         }
5137         /*
5138          * Since a configuration write can be done for commands that actually
5139          * have data allocated, like write buffer, and commands that have
5140          * no data, like start/stop unit, we need to check here.
5141          */
5142         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5143                 buf = io->scsiio.kern_data_ptr;
5144         else
5145                 buf = NULL;
5146         ctl_done(io);
5147         if (buf)
5148                 free(buf, M_CTL);
5149 }
5150
5151 void
5152 ctl_config_read_done(union ctl_io *io)
5153 {
5154         uint8_t *buf;
5155
5156         /*
5157          * If there is some error -- we are done, skip data transfer.
5158          */
5159         if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5160             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5161              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5162                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5163                         buf = io->scsiio.kern_data_ptr;
5164                 else
5165                         buf = NULL;
5166                 ctl_done(io);
5167                 if (buf)
5168                         free(buf, M_CTL);
5169                 return;
5170         }
5171
5172         /*
5173          * If the IO_CONT flag is set, we need to call the supplied
5174          * function to continue processing the I/O, instead of completing
5175          * the I/O just yet.
5176          */
5177         if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5178                 io->scsiio.io_cont(io);
5179                 return;
5180         }
5181
5182         ctl_datamove(io);
5183 }
5184
5185 /*
5186  * SCSI release command.
5187  */
5188 int
5189 ctl_scsi_release(struct ctl_scsiio *ctsio)
5190 {
5191         int length, longid, thirdparty_id, resv_id;
5192         struct ctl_lun *lun;
5193         uint32_t residx;
5194
5195         length = 0;
5196         resv_id = 0;
5197
5198         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5199
5200         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5201         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5202
5203         switch (ctsio->cdb[0]) {
5204         case RELEASE_10: {
5205                 struct scsi_release_10 *cdb;
5206
5207                 cdb = (struct scsi_release_10 *)ctsio->cdb;
5208
5209                 if (cdb->byte2 & SR10_LONGID)
5210                         longid = 1;
5211                 else
5212                         thirdparty_id = cdb->thirdparty_id;
5213
5214                 resv_id = cdb->resv_id;
5215                 length = scsi_2btoul(cdb->length);
5216                 break;
5217         }
5218         }
5219
5220
5221         /*
5222          * XXX KDM right now, we only support LUN reservation.  We don't
5223          * support 3rd party reservations, or extent reservations, which
5224          * might actually need the parameter list.  If we've gotten this
5225          * far, we've got a LUN reservation.  Anything else got kicked out
5226          * above.  So, according to SPC, ignore the length.
5227          */
5228         length = 0;
5229
5230         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5231          && (length > 0)) {
5232                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5233                 ctsio->kern_data_len = length;
5234                 ctsio->kern_total_len = length;
5235                 ctsio->kern_data_resid = 0;
5236                 ctsio->kern_rel_offset = 0;
5237                 ctsio->kern_sg_entries = 0;
5238                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5239                 ctsio->be_move_done = ctl_config_move_done;
5240                 ctl_datamove((union ctl_io *)ctsio);
5241
5242                 return (CTL_RETVAL_COMPLETE);
5243         }
5244
5245         if (length > 0)
5246                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5247
5248         mtx_lock(&lun->lun_lock);
5249
5250         /*
5251          * According to SPC, it is not an error for an intiator to attempt
5252          * to release a reservation on a LUN that isn't reserved, or that
5253          * is reserved by another initiator.  The reservation can only be
5254          * released, though, by the initiator who made it or by one of
5255          * several reset type events.
5256          */
5257         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5258                         lun->flags &= ~CTL_LUN_RESERVED;
5259
5260         mtx_unlock(&lun->lun_lock);
5261
5262         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5263                 free(ctsio->kern_data_ptr, M_CTL);
5264                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5265         }
5266
5267         ctl_set_success(ctsio);
5268         ctl_done((union ctl_io *)ctsio);
5269         return (CTL_RETVAL_COMPLETE);
5270 }
5271
5272 int
5273 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5274 {
5275         int extent, thirdparty, longid;
5276         int resv_id, length;
5277         uint64_t thirdparty_id;
5278         struct ctl_lun *lun;
5279         uint32_t residx;
5280
5281         extent = 0;
5282         thirdparty = 0;
5283         longid = 0;
5284         resv_id = 0;
5285         length = 0;
5286         thirdparty_id = 0;
5287
5288         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5289
5290         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5291         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5292
5293         switch (ctsio->cdb[0]) {
5294         case RESERVE_10: {
5295                 struct scsi_reserve_10 *cdb;
5296
5297                 cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5298
5299                 if (cdb->byte2 & SR10_LONGID)
5300                         longid = 1;
5301                 else
5302                         thirdparty_id = cdb->thirdparty_id;
5303
5304                 resv_id = cdb->resv_id;
5305                 length = scsi_2btoul(cdb->length);
5306                 break;
5307         }
5308         }
5309
5310         /*
5311          * XXX KDM right now, we only support LUN reservation.  We don't
5312          * support 3rd party reservations, or extent reservations, which
5313          * might actually need the parameter list.  If we've gotten this
5314          * far, we've got a LUN reservation.  Anything else got kicked out
5315          * above.  So, according to SPC, ignore the length.
5316          */
5317         length = 0;
5318
5319         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5320          && (length > 0)) {
5321                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5322                 ctsio->kern_data_len = length;
5323                 ctsio->kern_total_len = length;
5324                 ctsio->kern_data_resid = 0;
5325                 ctsio->kern_rel_offset = 0;
5326                 ctsio->kern_sg_entries = 0;
5327                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5328                 ctsio->be_move_done = ctl_config_move_done;
5329                 ctl_datamove((union ctl_io *)ctsio);
5330
5331                 return (CTL_RETVAL_COMPLETE);
5332         }
5333
5334         if (length > 0)
5335                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5336
5337         mtx_lock(&lun->lun_lock);
5338         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5339                 ctl_set_reservation_conflict(ctsio);
5340                 goto bailout;
5341         }
5342
5343         lun->flags |= CTL_LUN_RESERVED;
5344         lun->res_idx = residx;
5345
5346         ctl_set_success(ctsio);
5347
5348 bailout:
5349         mtx_unlock(&lun->lun_lock);
5350
5351         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5352                 free(ctsio->kern_data_ptr, M_CTL);
5353                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5354         }
5355
5356         ctl_done((union ctl_io *)ctsio);
5357         return (CTL_RETVAL_COMPLETE);
5358 }
5359
5360 int
5361 ctl_start_stop(struct ctl_scsiio *ctsio)
5362 {
5363         struct scsi_start_stop_unit *cdb;
5364         struct ctl_lun *lun;
5365         int retval;
5366
5367         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5368
5369         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5370         retval = 0;
5371
5372         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5373
5374         /*
5375          * XXX KDM
5376          * We don't support the immediate bit on a stop unit.  In order to
5377          * do that, we would need to code up a way to know that a stop is
5378          * pending, and hold off any new commands until it completes, one
5379          * way or another.  Then we could accept or reject those commands
5380          * depending on its status.  We would almost need to do the reverse
5381          * of what we do below for an immediate start -- return the copy of
5382          * the ctl_io to the FETD with status to send to the host (and to
5383          * free the copy!) and then free the original I/O once the stop
5384          * actually completes.  That way, the OOA queue mechanism can work
5385          * to block commands that shouldn't proceed.  Another alternative
5386          * would be to put the copy in the queue in place of the original,
5387          * and return the original back to the caller.  That could be
5388          * slightly safer..
5389          */
5390         if ((cdb->byte2 & SSS_IMMED)
5391          && ((cdb->how & SSS_START) == 0)) {
5392                 ctl_set_invalid_field(ctsio,
5393                                       /*sks_valid*/ 1,
5394                                       /*command*/ 1,
5395                                       /*field*/ 1,
5396                                       /*bit_valid*/ 1,
5397                                       /*bit*/ 0);
5398                 ctl_done((union ctl_io *)ctsio);
5399                 return (CTL_RETVAL_COMPLETE);
5400         }
5401
5402         if ((lun->flags & CTL_LUN_PR_RESERVED)
5403          && ((cdb->how & SSS_START)==0)) {
5404                 uint32_t residx;
5405
5406                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5407                 if (ctl_get_prkey(lun, residx) == 0
5408                  || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5409
5410                         ctl_set_reservation_conflict(ctsio);
5411                         ctl_done((union ctl_io *)ctsio);
5412                         return (CTL_RETVAL_COMPLETE);
5413                 }
5414         }
5415
5416         /*
5417          * If there is no backend on this device, we can't start or stop
5418          * it.  In theory we shouldn't get any start/stop commands in the
5419          * first place at this level if the LUN doesn't have a backend.
5420          * That should get stopped by the command decode code.
5421          */
5422         if (lun->backend == NULL) {
5423                 ctl_set_invalid_opcode(ctsio);
5424                 ctl_done((union ctl_io *)ctsio);
5425                 return (CTL_RETVAL_COMPLETE);
5426         }
5427
5428         /*
5429          * XXX KDM Copan-specific offline behavior.
5430          * Figure out a reasonable way to port this?
5431          */
5432 #ifdef NEEDTOPORT
5433         mtx_lock(&lun->lun_lock);
5434
5435         if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5436          && (lun->flags & CTL_LUN_OFFLINE)) {
5437                 /*
5438                  * If the LUN is offline, and the on/offline bit isn't set,
5439                  * reject the start or stop.  Otherwise, let it through.
5440                  */
5441                 mtx_unlock(&lun->lun_lock);
5442                 ctl_set_lun_not_ready(ctsio);
5443                 ctl_done((union ctl_io *)ctsio);
5444         } else {
5445                 mtx_unlock(&lun->lun_lock);
5446 #endif /* NEEDTOPORT */
5447                 /*
5448                  * This could be a start or a stop when we're online,
5449                  * or a stop/offline or start/online.  A start or stop when
5450                  * we're offline is covered in the case above.
5451                  */
5452                 /*
5453                  * In the non-immediate case, we send the request to
5454                  * the backend and return status to the user when
5455                  * it is done.
5456                  *
5457                  * In the immediate case, we allocate a new ctl_io
5458                  * to hold a copy of the request, and send that to
5459                  * the backend.  We then set good status on the
5460                  * user's request and return it immediately.
5461                  */
5462                 if (cdb->byte2 & SSS_IMMED) {
5463                         union ctl_io *new_io;
5464
5465                         new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5466                         ctl_copy_io((union ctl_io *)ctsio, new_io);
5467                         retval = lun->backend->config_write(new_io);
5468                         ctl_set_success(ctsio);
5469                         ctl_done((union ctl_io *)ctsio);
5470                 } else {
5471                         retval = lun->backend->config_write(
5472                                 (union ctl_io *)ctsio);
5473                 }
5474 #ifdef NEEDTOPORT
5475         }
5476 #endif
5477         return (retval);
5478 }
5479
5480 /*
5481  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5482  * we don't really do anything with the LBA and length fields if the user
5483  * passes them in.  Instead we'll just flush out the cache for the entire
5484  * LUN.
5485  */
5486 int
5487 ctl_sync_cache(struct ctl_scsiio *ctsio)
5488 {
5489         struct ctl_lun *lun;
5490         struct ctl_softc *softc;
5491         uint64_t starting_lba;
5492         uint32_t block_count;
5493         int retval;
5494
5495         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5496
5497         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5498         softc = lun->ctl_softc;
5499         retval = 0;
5500
5501         switch (ctsio->cdb[0]) {
5502         case SYNCHRONIZE_CACHE: {
5503                 struct scsi_sync_cache *cdb;
5504                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5505
5506                 starting_lba = scsi_4btoul(cdb->begin_lba);
5507                 block_count = scsi_2btoul(cdb->lb_count);
5508                 break;
5509         }
5510         case SYNCHRONIZE_CACHE_16: {
5511                 struct scsi_sync_cache_16 *cdb;
5512                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5513
5514                 starting_lba = scsi_8btou64(cdb->begin_lba);
5515                 block_count = scsi_4btoul(cdb->lb_count);
5516                 break;
5517         }
5518         default:
5519                 ctl_set_invalid_opcode(ctsio);
5520                 ctl_done((union ctl_io *)ctsio);
5521                 goto bailout;
5522                 break; /* NOTREACHED */
5523         }
5524
5525         /*
5526          * We check the LBA and length, but don't do anything with them.
5527          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5528          * get flushed.  This check will just help satisfy anyone who wants
5529          * to see an error for an out of range LBA.
5530          */
5531         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5532                 ctl_set_lba_out_of_range(ctsio);
5533                 ctl_done((union ctl_io *)ctsio);
5534                 goto bailout;
5535         }
5536
5537         /*
5538          * If this LUN has no backend, we can't flush the cache anyway.
5539          */
5540         if (lun->backend == NULL) {
5541                 ctl_set_invalid_opcode(ctsio);
5542                 ctl_done((union ctl_io *)ctsio);
5543                 goto bailout;
5544         }
5545
5546         /*
5547          * Check to see whether we're configured to send the SYNCHRONIZE
5548          * CACHE command directly to the back end.
5549          */
5550         mtx_lock(&lun->lun_lock);
5551         if ((softc->flags & CTL_FLAG_REAL_SYNC)
5552          && (++(lun->sync_count) >= lun->sync_interval)) {
5553                 lun->sync_count = 0;
5554                 mtx_unlock(&lun->lun_lock);
5555                 retval = lun->backend->config_write((union ctl_io *)ctsio);
5556         } else {
5557                 mtx_unlock(&lun->lun_lock);
5558                 ctl_set_success(ctsio);
5559                 ctl_done((union ctl_io *)ctsio);
5560         }
5561
5562 bailout:
5563
5564         return (retval);
5565 }
5566
5567 int
5568 ctl_format(struct ctl_scsiio *ctsio)
5569 {
5570         struct scsi_format *cdb;
5571         struct ctl_lun *lun;
5572         int length, defect_list_len;
5573
5574         CTL_DEBUG_PRINT(("ctl_format\n"));
5575
5576         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5577
5578         cdb = (struct scsi_format *)ctsio->cdb;
5579
5580         length = 0;
5581         if (cdb->byte2 & SF_FMTDATA) {
5582                 if (cdb->byte2 & SF_LONGLIST)
5583                         length = sizeof(struct scsi_format_header_long);
5584                 else
5585                         length = sizeof(struct scsi_format_header_short);
5586         }
5587
5588         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5589          && (length > 0)) {
5590                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5591                 ctsio->kern_data_len = length;
5592                 ctsio->kern_total_len = length;
5593                 ctsio->kern_data_resid = 0;
5594                 ctsio->kern_rel_offset = 0;
5595                 ctsio->kern_sg_entries = 0;
5596                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5597                 ctsio->be_move_done = ctl_config_move_done;
5598                 ctl_datamove((union ctl_io *)ctsio);
5599
5600                 return (CTL_RETVAL_COMPLETE);
5601         }
5602
5603         defect_list_len = 0;
5604
5605         if (cdb->byte2 & SF_FMTDATA) {
5606                 if (cdb->byte2 & SF_LONGLIST) {
5607                         struct scsi_format_header_long *header;
5608
5609                         header = (struct scsi_format_header_long *)
5610                                 ctsio->kern_data_ptr;
5611
5612                         defect_list_len = scsi_4btoul(header->defect_list_len);
5613                         if (defect_list_len != 0) {
5614                                 ctl_set_invalid_field(ctsio,
5615                                                       /*sks_valid*/ 1,
5616                                                       /*command*/ 0,
5617                                                       /*field*/ 2,
5618                                                       /*bit_valid*/ 0,
5619                                                       /*bit*/ 0);
5620                                 goto bailout;
5621                         }
5622                 } else {
5623                         struct scsi_format_header_short *header;
5624
5625                         header = (struct scsi_format_header_short *)
5626                                 ctsio->kern_data_ptr;
5627
5628                         defect_list_len = scsi_2btoul(header->defect_list_len);
5629                         if (defect_list_len != 0) {
5630                                 ctl_set_invalid_field(ctsio,
5631                                                       /*sks_valid*/ 1,
5632                                                       /*command*/ 0,
5633                                                       /*field*/ 2,
5634                                                       /*bit_valid*/ 0,
5635                                                       /*bit*/ 0);
5636                                 goto bailout;
5637                         }
5638                 }
5639         }
5640
5641         /*
5642          * The format command will clear out the "Medium format corrupted"
5643          * status if set by the configuration code.  That status is really
5644          * just a way to notify the host that we have lost the media, and
5645          * get them to issue a command that will basically make them think
5646          * they're blowing away the media.
5647          */
5648         mtx_lock(&lun->lun_lock);
5649         lun->flags &= ~CTL_LUN_INOPERABLE;
5650         mtx_unlock(&lun->lun_lock);
5651
5652         ctl_set_success(ctsio);
5653 bailout:
5654
5655         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5656                 free(ctsio->kern_data_ptr, M_CTL);
5657                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5658         }
5659
5660         ctl_done((union ctl_io *)ctsio);
5661         return (CTL_RETVAL_COMPLETE);
5662 }
5663
5664 int
5665 ctl_read_buffer(struct ctl_scsiio *ctsio)
5666 {
5667         struct scsi_read_buffer *cdb;
5668         struct ctl_lun *lun;
5669         int buffer_offset, len;
5670         static uint8_t descr[4];
5671         static uint8_t echo_descr[4] = { 0 };
5672
5673         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5674
5675         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5676         cdb = (struct scsi_read_buffer *)ctsio->cdb;
5677
5678         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5679             (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5680             (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5681                 ctl_set_invalid_field(ctsio,
5682                                       /*sks_valid*/ 1,
5683                                       /*command*/ 1,
5684                                       /*field*/ 1,
5685                                       /*bit_valid*/ 1,
5686                                       /*bit*/ 4);
5687                 ctl_done((union ctl_io *)ctsio);
5688                 return (CTL_RETVAL_COMPLETE);
5689         }
5690
5691         len = scsi_3btoul(cdb->length);
5692         buffer_offset = scsi_3btoul(cdb->offset);
5693
5694         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5695                 ctl_set_invalid_field(ctsio,
5696                                       /*sks_valid*/ 1,
5697                                       /*command*/ 1,
5698                                       /*field*/ 6,
5699                                       /*bit_valid*/ 0,
5700                                       /*bit*/ 0);
5701                 ctl_done((union ctl_io *)ctsio);
5702                 return (CTL_RETVAL_COMPLETE);
5703         }
5704
5705         if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5706                 descr[0] = 0;
5707                 scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5708                 ctsio->kern_data_ptr = descr;
5709                 len = min(len, sizeof(descr));
5710         } else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5711                 ctsio->kern_data_ptr = echo_descr;
5712                 len = min(len, sizeof(echo_descr));
5713         } else {
5714                 if (lun->write_buffer == NULL) {
5715                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5716                             M_CTL, M_WAITOK);
5717                 }
5718                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5719         }
5720         ctsio->kern_data_len = len;
5721         ctsio->kern_total_len = len;
5722         ctsio->kern_data_resid = 0;
5723         ctsio->kern_rel_offset = 0;
5724         ctsio->kern_sg_entries = 0;
5725         ctl_set_success(ctsio);
5726         ctsio->be_move_done = ctl_config_move_done;
5727         ctl_datamove((union ctl_io *)ctsio);
5728         return (CTL_RETVAL_COMPLETE);
5729 }
5730
5731 int
5732 ctl_write_buffer(struct ctl_scsiio *ctsio)
5733 {
5734         struct scsi_write_buffer *cdb;
5735         struct ctl_lun *lun;
5736         int buffer_offset, len;
5737
5738         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5739
5740         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5741         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5742
5743         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5744                 ctl_set_invalid_field(ctsio,
5745                                       /*sks_valid*/ 1,
5746                                       /*command*/ 1,
5747                                       /*field*/ 1,
5748                                       /*bit_valid*/ 1,
5749                                       /*bit*/ 4);
5750                 ctl_done((union ctl_io *)ctsio);
5751                 return (CTL_RETVAL_COMPLETE);
5752         }
5753
5754         len = scsi_3btoul(cdb->length);
5755         buffer_offset = scsi_3btoul(cdb->offset);
5756
5757         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5758                 ctl_set_invalid_field(ctsio,
5759                                       /*sks_valid*/ 1,
5760                                       /*command*/ 1,
5761                                       /*field*/ 6,
5762                                       /*bit_valid*/ 0,
5763                                       /*bit*/ 0);
5764                 ctl_done((union ctl_io *)ctsio);
5765                 return (CTL_RETVAL_COMPLETE);
5766         }
5767
5768         /*
5769          * If we've got a kernel request that hasn't been malloced yet,
5770          * malloc it and tell the caller the data buffer is here.
5771          */
5772         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5773                 if (lun->write_buffer == NULL) {
5774                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5775                             M_CTL, M_WAITOK);
5776                 }
5777                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5778                 ctsio->kern_data_len = len;
5779                 ctsio->kern_total_len = len;
5780                 ctsio->kern_data_resid = 0;
5781                 ctsio->kern_rel_offset = 0;
5782                 ctsio->kern_sg_entries = 0;
5783                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5784                 ctsio->be_move_done = ctl_config_move_done;
5785                 ctl_datamove((union ctl_io *)ctsio);
5786
5787                 return (CTL_RETVAL_COMPLETE);
5788         }
5789
5790         ctl_set_success(ctsio);
5791         ctl_done((union ctl_io *)ctsio);
5792         return (CTL_RETVAL_COMPLETE);
5793 }
5794
5795 int
5796 ctl_write_same(struct ctl_scsiio *ctsio)
5797 {
5798         struct ctl_lun *lun;
5799         struct ctl_lba_len_flags *lbalen;
5800         uint64_t lba;
5801         uint32_t num_blocks;
5802         int len, retval;
5803         uint8_t byte2;
5804
5805         retval = CTL_RETVAL_COMPLETE;
5806
5807         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5808
5809         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5810
5811         switch (ctsio->cdb[0]) {
5812         case WRITE_SAME_10: {
5813                 struct scsi_write_same_10 *cdb;
5814
5815                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5816
5817                 lba = scsi_4btoul(cdb->addr);
5818                 num_blocks = scsi_2btoul(cdb->length);
5819                 byte2 = cdb->byte2;
5820                 break;
5821         }
5822         case WRITE_SAME_16: {
5823                 struct scsi_write_same_16 *cdb;
5824
5825                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5826
5827                 lba = scsi_8btou64(cdb->addr);
5828                 num_blocks = scsi_4btoul(cdb->length);
5829                 byte2 = cdb->byte2;
5830                 break;
5831         }
5832         default:
5833                 /*
5834                  * We got a command we don't support.  This shouldn't
5835                  * happen, commands should be filtered out above us.
5836                  */
5837                 ctl_set_invalid_opcode(ctsio);
5838                 ctl_done((union ctl_io *)ctsio);
5839
5840                 return (CTL_RETVAL_COMPLETE);
5841                 break; /* NOTREACHED */
5842         }
5843
5844         /* NDOB and ANCHOR flags can be used only together with UNMAP */
5845         if ((byte2 & SWS_UNMAP) == 0 &&
5846             (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5847                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5848                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5849                 ctl_done((union ctl_io *)ctsio);
5850                 return (CTL_RETVAL_COMPLETE);
5851         }
5852
5853         /*
5854          * The first check is to make sure we're in bounds, the second
5855          * check is to catch wrap-around problems.  If the lba + num blocks
5856          * is less than the lba, then we've wrapped around and the block
5857          * range is invalid anyway.
5858          */
5859         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5860          || ((lba + num_blocks) < lba)) {
5861                 ctl_set_lba_out_of_range(ctsio);
5862                 ctl_done((union ctl_io *)ctsio);
5863                 return (CTL_RETVAL_COMPLETE);
5864         }
5865
5866         /* Zero number of blocks means "to the last logical block" */
5867         if (num_blocks == 0) {
5868                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5869                         ctl_set_invalid_field(ctsio,
5870                                               /*sks_valid*/ 0,
5871                                               /*command*/ 1,
5872                                               /*field*/ 0,
5873                                               /*bit_valid*/ 0,
5874                                               /*bit*/ 0);
5875                         ctl_done((union ctl_io *)ctsio);
5876                         return (CTL_RETVAL_COMPLETE);
5877                 }
5878                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
5879         }
5880
5881         len = lun->be_lun->blocksize;
5882
5883         /*
5884          * If we've got a kernel request that hasn't been malloced yet,
5885          * malloc it and tell the caller the data buffer is here.
5886          */
5887         if ((byte2 & SWS_NDOB) == 0 &&
5888             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5889                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5890                 ctsio->kern_data_len = len;
5891                 ctsio->kern_total_len = len;
5892                 ctsio->kern_data_resid = 0;
5893                 ctsio->kern_rel_offset = 0;
5894                 ctsio->kern_sg_entries = 0;
5895                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5896                 ctsio->be_move_done = ctl_config_move_done;
5897                 ctl_datamove((union ctl_io *)ctsio);
5898
5899                 return (CTL_RETVAL_COMPLETE);
5900         }
5901
5902         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5903         lbalen->lba = lba;
5904         lbalen->len = num_blocks;
5905         lbalen->flags = byte2;
5906         retval = lun->backend->config_write((union ctl_io *)ctsio);
5907
5908         return (retval);
5909 }
5910
5911 int
5912 ctl_unmap(struct ctl_scsiio *ctsio)
5913 {
5914         struct ctl_lun *lun;
5915         struct scsi_unmap *cdb;
5916         struct ctl_ptr_len_flags *ptrlen;
5917         struct scsi_unmap_header *hdr;
5918         struct scsi_unmap_desc *buf, *end, *endnz, *range;
5919         uint64_t lba;
5920         uint32_t num_blocks;
5921         int len, retval;
5922         uint8_t byte2;
5923
5924         retval = CTL_RETVAL_COMPLETE;
5925
5926         CTL_DEBUG_PRINT(("ctl_unmap\n"));
5927
5928         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5929         cdb = (struct scsi_unmap *)ctsio->cdb;
5930
5931         len = scsi_2btoul(cdb->length);
5932         byte2 = cdb->byte2;
5933
5934         /*
5935          * If we've got a kernel request that hasn't been malloced yet,
5936          * malloc it and tell the caller the data buffer is here.
5937          */
5938         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5939                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5940                 ctsio->kern_data_len = len;
5941                 ctsio->kern_total_len = len;
5942                 ctsio->kern_data_resid = 0;
5943                 ctsio->kern_rel_offset = 0;
5944                 ctsio->kern_sg_entries = 0;
5945                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5946                 ctsio->be_move_done = ctl_config_move_done;
5947                 ctl_datamove((union ctl_io *)ctsio);
5948
5949                 return (CTL_RETVAL_COMPLETE);
5950         }
5951
5952         len = ctsio->kern_total_len - ctsio->kern_data_resid;
5953         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5954         if (len < sizeof (*hdr) ||
5955             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5956             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5957             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5958                 ctl_set_invalid_field(ctsio,
5959                                       /*sks_valid*/ 0,
5960                                       /*command*/ 0,
5961                                       /*field*/ 0,
5962                                       /*bit_valid*/ 0,
5963                                       /*bit*/ 0);
5964                 goto done;
5965         }
5966         len = scsi_2btoul(hdr->desc_length);
5967         buf = (struct scsi_unmap_desc *)(hdr + 1);
5968         end = buf + len / sizeof(*buf);
5969
5970         endnz = buf;
5971         for (range = buf; range < end; range++) {
5972                 lba = scsi_8btou64(range->lba);
5973                 num_blocks = scsi_4btoul(range->length);
5974                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5975                  || ((lba + num_blocks) < lba)) {
5976                         ctl_set_lba_out_of_range(ctsio);
5977                         ctl_done((union ctl_io *)ctsio);
5978                         return (CTL_RETVAL_COMPLETE);
5979                 }
5980                 if (num_blocks != 0)
5981                         endnz = range + 1;
5982         }
5983
5984         /*
5985          * Block backend can not handle zero last range.
5986          * Filter it out and return if there is nothing left.
5987          */
5988         len = (uint8_t *)endnz - (uint8_t *)buf;
5989         if (len == 0) {
5990                 ctl_set_success(ctsio);
5991                 goto done;
5992         }
5993
5994         mtx_lock(&lun->lun_lock);
5995         ptrlen = (struct ctl_ptr_len_flags *)
5996             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5997         ptrlen->ptr = (void *)buf;
5998         ptrlen->len = len;
5999         ptrlen->flags = byte2;
6000         ctl_check_blocked(lun);
6001         mtx_unlock(&lun->lun_lock);
6002
6003         retval = lun->backend->config_write((union ctl_io *)ctsio);
6004         return (retval);
6005
6006 done:
6007         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
6008                 free(ctsio->kern_data_ptr, M_CTL);
6009                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
6010         }
6011         ctl_done((union ctl_io *)ctsio);
6012         return (CTL_RETVAL_COMPLETE);
6013 }
6014
6015 /*
6016  * Note that this function currently doesn't actually do anything inside
6017  * CTL to enforce things if the DQue bit is turned on.
6018  *
6019  * Also note that this function can't be used in the default case, because
6020  * the DQue bit isn't set in the changeable mask for the control mode page
6021  * anyway.  This is just here as an example for how to implement a page
6022  * handler, and a placeholder in case we want to allow the user to turn
6023  * tagged queueing on and off.
6024  *
6025  * The D_SENSE bit handling is functional, however, and will turn
6026  * descriptor sense on and off for a given LUN.
6027  */
6028 int
6029 ctl_control_page_handler(struct ctl_scsiio *ctsio,
6030                          struct ctl_page_index *page_index, uint8_t *page_ptr)
6031 {
6032         struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6033         struct ctl_lun *lun;
6034         int set_ua;
6035         uint32_t initidx;
6036
6037         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6038         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6039         set_ua = 0;
6040
6041         user_cp = (struct scsi_control_page *)page_ptr;
6042         current_cp = (struct scsi_control_page *)
6043                 (page_index->page_data + (page_index->page_len *
6044                 CTL_PAGE_CURRENT));
6045         saved_cp = (struct scsi_control_page *)
6046                 (page_index->page_data + (page_index->page_len *
6047                 CTL_PAGE_SAVED));
6048
6049         mtx_lock(&lun->lun_lock);
6050         if (((current_cp->rlec & SCP_DSENSE) == 0)
6051          && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6052                 /*
6053                  * Descriptor sense is currently turned off and the user
6054                  * wants to turn it on.
6055                  */
6056                 current_cp->rlec |= SCP_DSENSE;
6057                 saved_cp->rlec |= SCP_DSENSE;
6058                 lun->flags |= CTL_LUN_SENSE_DESC;
6059                 set_ua = 1;
6060         } else if (((current_cp->rlec & SCP_DSENSE) != 0)
6061                 && ((user_cp->rlec & SCP_DSENSE) == 0)) {
6062                 /*
6063                  * Descriptor sense is currently turned on, and the user
6064                  * wants to turn it off.
6065                  */
6066                 current_cp->rlec &= ~SCP_DSENSE;
6067                 saved_cp->rlec &= ~SCP_DSENSE;
6068                 lun->flags &= ~CTL_LUN_SENSE_DESC;
6069                 set_ua = 1;
6070         }
6071         if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6072             (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6073                 current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6074                 current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6075                 saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6076                 saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6077                 set_ua = 1;
6078         }
6079         if ((current_cp->eca_and_aen & SCP_SWP) !=
6080             (user_cp->eca_and_aen & SCP_SWP)) {
6081                 current_cp->eca_and_aen &= ~SCP_SWP;
6082                 current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6083                 saved_cp->eca_and_aen &= ~SCP_SWP;
6084                 saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6085                 set_ua = 1;
6086         }
6087         if (set_ua != 0)
6088                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6089         mtx_unlock(&lun->lun_lock);
6090
6091         return (0);
6092 }
6093
6094 int
6095 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6096                      struct ctl_page_index *page_index, uint8_t *page_ptr)
6097 {
6098         struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6099         struct ctl_lun *lun;
6100         int set_ua;
6101         uint32_t initidx;
6102
6103         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6104         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6105         set_ua = 0;
6106
6107         user_cp = (struct scsi_caching_page *)page_ptr;
6108         current_cp = (struct scsi_caching_page *)
6109                 (page_index->page_data + (page_index->page_len *
6110                 CTL_PAGE_CURRENT));
6111         saved_cp = (struct scsi_caching_page *)
6112                 (page_index->page_data + (page_index->page_len *
6113                 CTL_PAGE_SAVED));
6114
6115         mtx_lock(&lun->lun_lock);
6116         if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6117             (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6118                 current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6119                 current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6120                 saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6121                 saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6122                 set_ua = 1;
6123         }
6124         if (set_ua != 0)
6125                 ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6126         mtx_unlock(&lun->lun_lock);
6127
6128         return (0);
6129 }
6130
6131 int
6132 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6133                                 struct ctl_page_index *page_index,
6134                                 uint8_t *page_ptr)
6135 {
6136         uint8_t *c;
6137         int i;
6138
6139         c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6140         ctl_time_io_secs =
6141                 (c[0] << 8) |
6142                 (c[1] << 0) |
6143                 0;
6144         CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6145         printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6146         printf("page data:");
6147         for (i=0; i<8; i++)
6148                 printf(" %.2x",page_ptr[i]);
6149         printf("\n");
6150         return (0);
6151 }
6152
6153 int
6154 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6155                                struct ctl_page_index *page_index,
6156                                int pc)
6157 {
6158         struct copan_debugconf_subpage *page;
6159
6160         page = (struct copan_debugconf_subpage *)page_index->page_data +
6161                 (page_index->page_len * pc);
6162
6163         switch (pc) {
6164         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6165         case SMS_PAGE_CTRL_DEFAULT >> 6:
6166         case SMS_PAGE_CTRL_SAVED >> 6:
6167                 /*
6168                  * We don't update the changable or default bits for this page.
6169                  */
6170                 break;
6171         case SMS_PAGE_CTRL_CURRENT >> 6:
6172                 page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6173                 page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6174                 break;
6175         default:
6176 #ifdef NEEDTOPORT
6177                 EPRINT(0, "Invalid PC %d!!", pc);
6178 #endif /* NEEDTOPORT */
6179                 break;
6180         }
6181         return (0);
6182 }
6183
6184
6185 static int
6186 ctl_do_mode_select(union ctl_io *io)
6187 {
6188         struct scsi_mode_page_header *page_header;
6189         struct ctl_page_index *page_index;
6190         struct ctl_scsiio *ctsio;
6191         int control_dev, page_len;
6192         int page_len_offset, page_len_size;
6193         union ctl_modepage_info *modepage_info;
6194         struct ctl_lun *lun;
6195         int *len_left, *len_used;
6196         int retval, i;
6197
6198         ctsio = &io->scsiio;
6199         page_index = NULL;
6200         page_len = 0;
6201         retval = CTL_RETVAL_COMPLETE;
6202
6203         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6204
6205         if (lun->be_lun->lun_type != T_DIRECT)
6206                 control_dev = 1;
6207         else
6208                 control_dev = 0;
6209
6210         modepage_info = (union ctl_modepage_info *)
6211                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6212         len_left = &modepage_info->header.len_left;
6213         len_used = &modepage_info->header.len_used;
6214
6215 do_next_page:
6216
6217         page_header = (struct scsi_mode_page_header *)
6218                 (ctsio->kern_data_ptr + *len_used);
6219
6220         if (*len_left == 0) {
6221                 free(ctsio->kern_data_ptr, M_CTL);
6222                 ctl_set_success(ctsio);
6223                 ctl_done((union ctl_io *)ctsio);
6224                 return (CTL_RETVAL_COMPLETE);
6225         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6226
6227                 free(ctsio->kern_data_ptr, M_CTL);
6228                 ctl_set_param_len_error(ctsio);
6229                 ctl_done((union ctl_io *)ctsio);
6230                 return (CTL_RETVAL_COMPLETE);
6231
6232         } else if ((page_header->page_code & SMPH_SPF)
6233                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6234
6235                 free(ctsio->kern_data_ptr, M_CTL);
6236                 ctl_set_param_len_error(ctsio);
6237                 ctl_done((union ctl_io *)ctsio);
6238                 return (CTL_RETVAL_COMPLETE);
6239         }
6240
6241
6242         /*
6243          * XXX KDM should we do something with the block descriptor?
6244          */
6245         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6246
6247                 if ((control_dev != 0)
6248                  && (lun->mode_pages.index[i].page_flags &
6249                      CTL_PAGE_FLAG_DISK_ONLY))
6250                         continue;
6251
6252                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6253                     (page_header->page_code & SMPH_PC_MASK))
6254                         continue;
6255
6256                 /*
6257                  * If neither page has a subpage code, then we've got a
6258                  * match.
6259                  */
6260                 if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6261                  && ((page_header->page_code & SMPH_SPF) == 0)) {
6262                         page_index = &lun->mode_pages.index[i];
6263                         page_len = page_header->page_length;
6264                         break;
6265                 }
6266
6267                 /*
6268                  * If both pages have subpages, then the subpage numbers
6269                  * have to match.
6270                  */
6271                 if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6272                   && (page_header->page_code & SMPH_SPF)) {
6273                         struct scsi_mode_page_header_sp *sph;
6274
6275                         sph = (struct scsi_mode_page_header_sp *)page_header;
6276
6277                         if (lun->mode_pages.index[i].subpage ==
6278                             sph->subpage) {
6279                                 page_index = &lun->mode_pages.index[i];
6280                                 page_len = scsi_2btoul(sph->page_length);
6281                                 break;
6282                         }
6283                 }
6284         }
6285
6286         /*
6287          * If we couldn't find the page, or if we don't have a mode select
6288          * handler for it, send back an error to the user.
6289          */
6290         if ((page_index == NULL)
6291          || (page_index->select_handler == NULL)) {
6292                 ctl_set_invalid_field(ctsio,
6293                                       /*sks_valid*/ 1,
6294                                       /*command*/ 0,
6295                                       /*field*/ *len_used,
6296                                       /*bit_valid*/ 0,
6297                                       /*bit*/ 0);
6298                 free(ctsio->kern_data_ptr, M_CTL);
6299                 ctl_done((union ctl_io *)ctsio);
6300                 return (CTL_RETVAL_COMPLETE);
6301         }
6302
6303         if (page_index->page_code & SMPH_SPF) {
6304                 page_len_offset = 2;
6305                 page_len_size = 2;
6306         } else {
6307                 page_len_size = 1;
6308                 page_len_offset = 1;
6309         }
6310
6311         /*
6312          * If the length the initiator gives us isn't the one we specify in
6313          * the mode page header, or if they didn't specify enough data in
6314          * the CDB to avoid truncating this page, kick out the request.
6315          */
6316         if ((page_len != (page_index->page_len - page_len_offset -
6317                           page_len_size))
6318          || (*len_left < page_index->page_len)) {
6319
6320
6321                 ctl_set_invalid_field(ctsio,
6322                                       /*sks_valid*/ 1,
6323                                       /*command*/ 0,
6324                                       /*field*/ *len_used + page_len_offset,
6325                                       /*bit_valid*/ 0,
6326                                       /*bit*/ 0);
6327                 free(ctsio->kern_data_ptr, M_CTL);
6328                 ctl_done((union ctl_io *)ctsio);
6329                 return (CTL_RETVAL_COMPLETE);
6330         }
6331
6332         /*
6333          * Run through the mode page, checking to make sure that the bits
6334          * the user changed are actually legal for him to change.
6335          */
6336         for (i = 0; i < page_index->page_len; i++) {
6337                 uint8_t *user_byte, *change_mask, *current_byte;
6338                 int bad_bit;
6339                 int j;
6340
6341                 user_byte = (uint8_t *)page_header + i;
6342                 change_mask = page_index->page_data +
6343                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6344                 current_byte = page_index->page_data +
6345                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6346
6347                 /*
6348                  * Check to see whether the user set any bits in this byte
6349                  * that he is not allowed to set.
6350                  */
6351                 if ((*user_byte & ~(*change_mask)) ==
6352                     (*current_byte & ~(*change_mask)))
6353                         continue;
6354
6355                 /*
6356                  * Go through bit by bit to determine which one is illegal.
6357                  */
6358                 bad_bit = 0;
6359                 for (j = 7; j >= 0; j--) {
6360                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6361                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6362                                 bad_bit = i;
6363                                 break;
6364                         }
6365                 }
6366                 ctl_set_invalid_field(ctsio,
6367                                       /*sks_valid*/ 1,
6368                                       /*command*/ 0,
6369                                       /*field*/ *len_used + i,
6370                                       /*bit_valid*/ 1,
6371                                       /*bit*/ bad_bit);
6372                 free(ctsio->kern_data_ptr, M_CTL);
6373                 ctl_done((union ctl_io *)ctsio);
6374                 return (CTL_RETVAL_COMPLETE);
6375         }
6376
6377         /*
6378          * Decrement these before we call the page handler, since we may
6379          * end up getting called back one way or another before the handler
6380          * returns to this context.
6381          */
6382         *len_left -= page_index->page_len;
6383         *len_used += page_index->page_len;
6384
6385         retval = page_index->select_handler(ctsio, page_index,
6386                                             (uint8_t *)page_header);
6387
6388         /*
6389          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6390          * wait until this queued command completes to finish processing
6391          * the mode page.  If it returns anything other than
6392          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6393          * already set the sense information, freed the data pointer, and
6394          * completed the io for us.
6395          */
6396         if (retval != CTL_RETVAL_COMPLETE)
6397                 goto bailout_no_done;
6398
6399         /*
6400          * If the initiator sent us more than one page, parse the next one.
6401          */
6402         if (*len_left > 0)
6403                 goto do_next_page;
6404
6405         ctl_set_success(ctsio);
6406         free(ctsio->kern_data_ptr, M_CTL);
6407         ctl_done((union ctl_io *)ctsio);
6408
6409 bailout_no_done:
6410
6411         return (CTL_RETVAL_COMPLETE);
6412
6413 }
6414
6415 int
6416 ctl_mode_select(struct ctl_scsiio *ctsio)
6417 {
6418         int param_len, pf, sp;
6419         int header_size, bd_len;
6420         int len_left, len_used;
6421         struct ctl_page_index *page_index;
6422         struct ctl_lun *lun;
6423         int control_dev, page_len;
6424         union ctl_modepage_info *modepage_info;
6425         int retval;
6426
6427         pf = 0;
6428         sp = 0;
6429         page_len = 0;
6430         len_used = 0;
6431         len_left = 0;
6432         retval = 0;
6433         bd_len = 0;
6434         page_index = NULL;
6435
6436         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6437
6438         if (lun->be_lun->lun_type != T_DIRECT)
6439                 control_dev = 1;
6440         else
6441                 control_dev = 0;
6442
6443         switch (ctsio->cdb[0]) {
6444         case MODE_SELECT_6: {
6445                 struct scsi_mode_select_6 *cdb;
6446
6447                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6448
6449                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6450                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6451
6452                 param_len = cdb->length;
6453                 header_size = sizeof(struct scsi_mode_header_6);
6454                 break;
6455         }
6456         case MODE_SELECT_10: {
6457                 struct scsi_mode_select_10 *cdb;
6458
6459                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6460
6461                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6462                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6463
6464                 param_len = scsi_2btoul(cdb->length);
6465                 header_size = sizeof(struct scsi_mode_header_10);
6466                 break;
6467         }
6468         default:
6469                 ctl_set_invalid_opcode(ctsio);
6470                 ctl_done((union ctl_io *)ctsio);
6471                 return (CTL_RETVAL_COMPLETE);
6472                 break; /* NOTREACHED */
6473         }
6474
6475         /*
6476          * From SPC-3:
6477          * "A parameter list length of zero indicates that the Data-Out Buffer
6478          * shall be empty. This condition shall not be considered as an error."
6479          */
6480         if (param_len == 0) {
6481                 ctl_set_success(ctsio);
6482                 ctl_done((union ctl_io *)ctsio);
6483                 return (CTL_RETVAL_COMPLETE);
6484         }
6485
6486         /*
6487          * Since we'll hit this the first time through, prior to
6488          * allocation, we don't need to free a data buffer here.
6489          */
6490         if (param_len < header_size) {
6491                 ctl_set_param_len_error(ctsio);
6492                 ctl_done((union ctl_io *)ctsio);
6493                 return (CTL_RETVAL_COMPLETE);
6494         }
6495
6496         /*
6497          * Allocate the data buffer and grab the user's data.  In theory,
6498          * we shouldn't have to sanity check the parameter list length here
6499          * because the maximum size is 64K.  We should be able to malloc
6500          * that much without too many problems.
6501          */
6502         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6503                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6504                 ctsio->kern_data_len = param_len;
6505                 ctsio->kern_total_len = param_len;
6506                 ctsio->kern_data_resid = 0;
6507                 ctsio->kern_rel_offset = 0;
6508                 ctsio->kern_sg_entries = 0;
6509                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6510                 ctsio->be_move_done = ctl_config_move_done;
6511                 ctl_datamove((union ctl_io *)ctsio);
6512
6513                 return (CTL_RETVAL_COMPLETE);
6514         }
6515
6516         switch (ctsio->cdb[0]) {
6517         case MODE_SELECT_6: {
6518                 struct scsi_mode_header_6 *mh6;
6519
6520                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6521                 bd_len = mh6->blk_desc_len;
6522                 break;
6523         }
6524         case MODE_SELECT_10: {
6525                 struct scsi_mode_header_10 *mh10;
6526
6527                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6528                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6529                 break;
6530         }
6531         default:
6532                 panic("Invalid CDB type %#x", ctsio->cdb[0]);
6533                 break;
6534         }
6535
6536         if (param_len < (header_size + bd_len)) {
6537                 free(ctsio->kern_data_ptr, M_CTL);
6538                 ctl_set_param_len_error(ctsio);
6539                 ctl_done((union ctl_io *)ctsio);
6540                 return (CTL_RETVAL_COMPLETE);
6541         }
6542
6543         /*
6544          * Set the IO_CONT flag, so that if this I/O gets passed to
6545          * ctl_config_write_done(), it'll get passed back to
6546          * ctl_do_mode_select() for further processing, or completion if
6547          * we're all done.
6548          */
6549         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6550         ctsio->io_cont = ctl_do_mode_select;
6551
6552         modepage_info = (union ctl_modepage_info *)
6553                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6554
6555         memset(modepage_info, 0, sizeof(*modepage_info));
6556
6557         len_left = param_len - header_size - bd_len;
6558         len_used = header_size + bd_len;
6559
6560         modepage_info->header.len_left = len_left;
6561         modepage_info->header.len_used = len_used;
6562
6563         return (ctl_do_mode_select((union ctl_io *)ctsio));
6564 }
6565
6566 int
6567 ctl_mode_sense(struct ctl_scsiio *ctsio)
6568 {
6569         struct ctl_lun *lun;
6570         int pc, page_code, dbd, llba, subpage;
6571         int alloc_len, page_len, header_len, total_len;
6572         struct scsi_mode_block_descr *block_desc;
6573         struct ctl_page_index *page_index;
6574         int control_dev;
6575
6576         dbd = 0;
6577         llba = 0;
6578         block_desc = NULL;
6579         page_index = NULL;
6580
6581         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6582
6583         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6584
6585         if (lun->be_lun->lun_type != T_DIRECT)
6586                 control_dev = 1;
6587         else
6588                 control_dev = 0;
6589
6590         switch (ctsio->cdb[0]) {
6591         case MODE_SENSE_6: {
6592                 struct scsi_mode_sense_6 *cdb;
6593
6594                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6595
6596                 header_len = sizeof(struct scsi_mode_hdr_6);
6597                 if (cdb->byte2 & SMS_DBD)
6598                         dbd = 1;
6599                 else
6600                         header_len += sizeof(struct scsi_mode_block_descr);
6601
6602                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6603                 page_code = cdb->page & SMS_PAGE_CODE;
6604                 subpage = cdb->subpage;
6605                 alloc_len = cdb->length;
6606                 break;
6607         }
6608         case MODE_SENSE_10: {
6609                 struct scsi_mode_sense_10 *cdb;
6610
6611                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6612
6613                 header_len = sizeof(struct scsi_mode_hdr_10);
6614
6615                 if (cdb->byte2 & SMS_DBD)
6616                         dbd = 1;
6617                 else
6618                         header_len += sizeof(struct scsi_mode_block_descr);
6619                 if (cdb->byte2 & SMS10_LLBAA)
6620                         llba = 1;
6621                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6622                 page_code = cdb->page & SMS_PAGE_CODE;
6623                 subpage = cdb->subpage;
6624                 alloc_len = scsi_2btoul(cdb->length);
6625                 break;
6626         }
6627         default:
6628                 ctl_set_invalid_opcode(ctsio);
6629                 ctl_done((union ctl_io *)ctsio);
6630                 return (CTL_RETVAL_COMPLETE);
6631                 break; /* NOTREACHED */
6632         }
6633
6634         /*
6635          * We have to make a first pass through to calculate the size of
6636          * the pages that match the user's query.  Then we allocate enough
6637          * memory to hold it, and actually copy the data into the buffer.
6638          */
6639         switch (page_code) {
6640         case SMS_ALL_PAGES_PAGE: {
6641                 int i;
6642
6643                 page_len = 0;
6644
6645                 /*
6646                  * At the moment, values other than 0 and 0xff here are
6647                  * reserved according to SPC-3.
6648                  */
6649                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6650                  && (subpage != SMS_SUBPAGE_ALL)) {
6651                         ctl_set_invalid_field(ctsio,
6652                                               /*sks_valid*/ 1,
6653                                               /*command*/ 1,
6654                                               /*field*/ 3,
6655                                               /*bit_valid*/ 0,
6656                                               /*bit*/ 0);
6657                         ctl_done((union ctl_io *)ctsio);
6658                         return (CTL_RETVAL_COMPLETE);
6659                 }
6660
6661                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6662                         if ((control_dev != 0)
6663                          && (lun->mode_pages.index[i].page_flags &
6664                              CTL_PAGE_FLAG_DISK_ONLY))
6665                                 continue;
6666
6667                         /*
6668                          * We don't use this subpage if the user didn't
6669                          * request all subpages.
6670                          */
6671                         if ((lun->mode_pages.index[i].subpage != 0)
6672                          && (subpage == SMS_SUBPAGE_PAGE_0))
6673                                 continue;
6674
6675 #if 0
6676                         printf("found page %#x len %d\n",
6677                                lun->mode_pages.index[i].page_code &
6678                                SMPH_PC_MASK,
6679                                lun->mode_pages.index[i].page_len);
6680 #endif
6681                         page_len += lun->mode_pages.index[i].page_len;
6682                 }
6683                 break;
6684         }
6685         default: {
6686                 int i;
6687
6688                 page_len = 0;
6689
6690                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6691                         /* Look for the right page code */
6692                         if ((lun->mode_pages.index[i].page_code &
6693                              SMPH_PC_MASK) != page_code)
6694                                 continue;
6695
6696                         /* Look for the right subpage or the subpage wildcard*/
6697                         if ((lun->mode_pages.index[i].subpage != subpage)
6698                          && (subpage != SMS_SUBPAGE_ALL))
6699                                 continue;
6700
6701                         /* Make sure the page is supported for this dev type */
6702                         if ((control_dev != 0)
6703                          && (lun->mode_pages.index[i].page_flags &
6704                              CTL_PAGE_FLAG_DISK_ONLY))
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
6714                         page_len += lun->mode_pages.index[i].page_len;
6715                 }
6716
6717                 if (page_len == 0) {
6718                         ctl_set_invalid_field(ctsio,
6719                                               /*sks_valid*/ 1,
6720                                               /*command*/ 1,
6721                                               /*field*/ 2,
6722                                               /*bit_valid*/ 1,
6723                                               /*bit*/ 5);
6724                         ctl_done((union ctl_io *)ctsio);
6725                         return (CTL_RETVAL_COMPLETE);
6726                 }
6727                 break;
6728         }
6729         }
6730
6731         total_len = header_len + page_len;
6732 #if 0
6733         printf("header_len = %d, page_len = %d, total_len = %d\n",
6734                header_len, page_len, total_len);
6735 #endif
6736
6737         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6738         ctsio->kern_sg_entries = 0;
6739         ctsio->kern_data_resid = 0;
6740         ctsio->kern_rel_offset = 0;
6741         if (total_len < alloc_len) {
6742                 ctsio->residual = alloc_len - total_len;
6743                 ctsio->kern_data_len = total_len;
6744                 ctsio->kern_total_len = total_len;
6745         } else {
6746                 ctsio->residual = 0;
6747                 ctsio->kern_data_len = alloc_len;
6748                 ctsio->kern_total_len = alloc_len;
6749         }
6750
6751         switch (ctsio->cdb[0]) {
6752         case MODE_SENSE_6: {
6753                 struct scsi_mode_hdr_6 *header;
6754
6755                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6756
6757                 header->datalen = ctl_min(total_len - 1, 254);
6758                 if (control_dev == 0) {
6759                         header->dev_specific = 0x10; /* DPOFUA */
6760                         if ((lun->flags & CTL_LUN_READONLY) ||
6761                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6762                             .eca_and_aen & SCP_SWP) != 0)
6763                                     header->dev_specific |= 0x80; /* WP */
6764                 }
6765                 if (dbd)
6766                         header->block_descr_len = 0;
6767                 else
6768                         header->block_descr_len =
6769                                 sizeof(struct scsi_mode_block_descr);
6770                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6771                 break;
6772         }
6773         case MODE_SENSE_10: {
6774                 struct scsi_mode_hdr_10 *header;
6775                 int datalen;
6776
6777                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6778
6779                 datalen = ctl_min(total_len - 2, 65533);
6780                 scsi_ulto2b(datalen, header->datalen);
6781                 if (control_dev == 0) {
6782                         header->dev_specific = 0x10; /* DPOFUA */
6783                         if ((lun->flags & CTL_LUN_READONLY) ||
6784                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6785                             .eca_and_aen & SCP_SWP) != 0)
6786                                     header->dev_specific |= 0x80; /* WP */
6787                 }
6788                 if (dbd)
6789                         scsi_ulto2b(0, header->block_descr_len);
6790                 else
6791                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6792                                     header->block_descr_len);
6793                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6794                 break;
6795         }
6796         default:
6797                 panic("invalid CDB type %#x", ctsio->cdb[0]);
6798                 break; /* NOTREACHED */
6799         }
6800
6801         /*
6802          * If we've got a disk, use its blocksize in the block
6803          * descriptor.  Otherwise, just set it to 0.
6804          */
6805         if (dbd == 0) {
6806                 if (control_dev == 0)
6807                         scsi_ulto3b(lun->be_lun->blocksize,
6808                                     block_desc->block_len);
6809                 else
6810                         scsi_ulto3b(0, block_desc->block_len);
6811         }
6812
6813         switch (page_code) {
6814         case SMS_ALL_PAGES_PAGE: {
6815                 int i, data_used;
6816
6817                 data_used = header_len;
6818                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6819                         struct ctl_page_index *page_index;
6820
6821                         page_index = &lun->mode_pages.index[i];
6822
6823                         if ((control_dev != 0)
6824                          && (page_index->page_flags &
6825                             CTL_PAGE_FLAG_DISK_ONLY))
6826                                 continue;
6827
6828                         /*
6829                          * We don't use this subpage if the user didn't
6830                          * request all subpages.  We already checked (above)
6831                          * to make sure the user only specified a subpage
6832                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6833                          */
6834                         if ((page_index->subpage != 0)
6835                          && (subpage == SMS_SUBPAGE_PAGE_0))
6836                                 continue;
6837
6838                         /*
6839                          * Call the handler, if it exists, to update the
6840                          * page to the latest values.
6841                          */
6842                         if (page_index->sense_handler != NULL)
6843                                 page_index->sense_handler(ctsio, page_index,pc);
6844
6845                         memcpy(ctsio->kern_data_ptr + data_used,
6846                                page_index->page_data +
6847                                (page_index->page_len * pc),
6848                                page_index->page_len);
6849                         data_used += page_index->page_len;
6850                 }
6851                 break;
6852         }
6853         default: {
6854                 int i, data_used;
6855
6856                 data_used = header_len;
6857
6858                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6859                         struct ctl_page_index *page_index;
6860
6861                         page_index = &lun->mode_pages.index[i];
6862
6863                         /* Look for the right page code */
6864                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6865                                 continue;
6866
6867                         /* Look for the right subpage or the subpage wildcard*/
6868                         if ((page_index->subpage != subpage)
6869                          && (subpage != SMS_SUBPAGE_ALL))
6870                                 continue;
6871
6872                         /* Make sure the page is supported for this dev type */
6873                         if ((control_dev != 0)
6874                          && (page_index->page_flags &
6875                              CTL_PAGE_FLAG_DISK_ONLY))
6876                                 continue;
6877
6878                         /*
6879                          * Call the handler, if it exists, to update the
6880                          * page to the latest values.
6881                          */
6882                         if (page_index->sense_handler != NULL)
6883                                 page_index->sense_handler(ctsio, page_index,pc);
6884
6885                         memcpy(ctsio->kern_data_ptr + data_used,
6886                                page_index->page_data +
6887                                (page_index->page_len * pc),
6888                                page_index->page_len);
6889                         data_used += page_index->page_len;
6890                 }
6891                 break;
6892         }
6893         }
6894
6895         ctl_set_success(ctsio);
6896         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6897         ctsio->be_move_done = ctl_config_move_done;
6898         ctl_datamove((union ctl_io *)ctsio);
6899         return (CTL_RETVAL_COMPLETE);
6900 }
6901
6902 int
6903 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6904                                struct ctl_page_index *page_index,
6905                                int pc)
6906 {
6907         struct ctl_lun *lun;
6908         struct scsi_log_param_header *phdr;
6909         uint8_t *data;
6910         uint64_t val;
6911
6912         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6913         data = page_index->page_data;
6914
6915         if (lun->backend->lun_attr != NULL &&
6916             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6917              != UINT64_MAX) {
6918                 phdr = (struct scsi_log_param_header *)data;
6919                 scsi_ulto2b(0x0001, phdr->param_code);
6920                 phdr->param_control = SLP_LBIN | SLP_LP;
6921                 phdr->param_len = 8;
6922                 data = (uint8_t *)(phdr + 1);
6923                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6924                 data[4] = 0x02; /* per-pool */
6925                 data += phdr->param_len;
6926         }
6927
6928         if (lun->backend->lun_attr != NULL &&
6929             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6930              != UINT64_MAX) {
6931                 phdr = (struct scsi_log_param_header *)data;
6932                 scsi_ulto2b(0x0002, phdr->param_code);
6933                 phdr->param_control = SLP_LBIN | SLP_LP;
6934                 phdr->param_len = 8;
6935                 data = (uint8_t *)(phdr + 1);
6936                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6937                 data[4] = 0x01; /* per-LUN */
6938                 data += phdr->param_len;
6939         }
6940
6941         if (lun->backend->lun_attr != NULL &&
6942             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6943              != UINT64_MAX) {
6944                 phdr = (struct scsi_log_param_header *)data;
6945                 scsi_ulto2b(0x00f1, phdr->param_code);
6946                 phdr->param_control = SLP_LBIN | SLP_LP;
6947                 phdr->param_len = 8;
6948                 data = (uint8_t *)(phdr + 1);
6949                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6950                 data[4] = 0x02; /* per-pool */
6951                 data += phdr->param_len;
6952         }
6953
6954         if (lun->backend->lun_attr != NULL &&
6955             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6956              != UINT64_MAX) {
6957                 phdr = (struct scsi_log_param_header *)data;
6958                 scsi_ulto2b(0x00f2, phdr->param_code);
6959                 phdr->param_control = SLP_LBIN | SLP_LP;
6960                 phdr->param_len = 8;
6961                 data = (uint8_t *)(phdr + 1);
6962                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6963                 data[4] = 0x02; /* per-pool */
6964                 data += phdr->param_len;
6965         }
6966
6967         page_index->page_len = data - page_index->page_data;
6968         return (0);
6969 }
6970
6971 int
6972 ctl_log_sense(struct ctl_scsiio *ctsio)
6973 {
6974         struct ctl_lun *lun;
6975         int i, pc, page_code, subpage;
6976         int alloc_len, total_len;
6977         struct ctl_page_index *page_index;
6978         struct scsi_log_sense *cdb;
6979         struct scsi_log_header *header;
6980
6981         CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6982
6983         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6984         cdb = (struct scsi_log_sense *)ctsio->cdb;
6985         pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6986         page_code = cdb->page & SLS_PAGE_CODE;
6987         subpage = cdb->subpage;
6988         alloc_len = scsi_2btoul(cdb->length);
6989
6990         page_index = NULL;
6991         for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6992                 page_index = &lun->log_pages.index[i];
6993
6994                 /* Look for the right page code */
6995                 if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6996                         continue;
6997
6998                 /* Look for the right subpage or the subpage wildcard*/
6999                 if (page_index->subpage != subpage)
7000                         continue;
7001
7002                 break;
7003         }
7004         if (i >= CTL_NUM_LOG_PAGES) {
7005                 ctl_set_invalid_field(ctsio,
7006                                       /*sks_valid*/ 1,
7007                                       /*command*/ 1,
7008                                       /*field*/ 2,
7009                                       /*bit_valid*/ 0,
7010                                       /*bit*/ 0);
7011                 ctl_done((union ctl_io *)ctsio);
7012                 return (CTL_RETVAL_COMPLETE);
7013         }
7014
7015         total_len = sizeof(struct scsi_log_header) + page_index->page_len;
7016
7017         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7018         ctsio->kern_sg_entries = 0;
7019         ctsio->kern_data_resid = 0;
7020         ctsio->kern_rel_offset = 0;
7021         if (total_len < alloc_len) {
7022                 ctsio->residual = alloc_len - total_len;
7023                 ctsio->kern_data_len = total_len;
7024                 ctsio->kern_total_len = total_len;
7025         } else {
7026                 ctsio->residual = 0;
7027                 ctsio->kern_data_len = alloc_len;
7028                 ctsio->kern_total_len = alloc_len;
7029         }
7030
7031         header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7032         header->page = page_index->page_code;
7033         if (page_index->subpage) {
7034                 header->page |= SL_SPF;
7035                 header->subpage = page_index->subpage;
7036         }
7037         scsi_ulto2b(page_index->page_len, header->datalen);
7038
7039         /*
7040          * Call the handler, if it exists, to update the
7041          * page to the latest values.
7042          */
7043         if (page_index->sense_handler != NULL)
7044                 page_index->sense_handler(ctsio, page_index, pc);
7045
7046         memcpy(header + 1, page_index->page_data, page_index->page_len);
7047
7048         ctl_set_success(ctsio);
7049         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7050         ctsio->be_move_done = ctl_config_move_done;
7051         ctl_datamove((union ctl_io *)ctsio);
7052         return (CTL_RETVAL_COMPLETE);
7053 }
7054
7055 int
7056 ctl_read_capacity(struct ctl_scsiio *ctsio)
7057 {
7058         struct scsi_read_capacity *cdb;
7059         struct scsi_read_capacity_data *data;
7060         struct ctl_lun *lun;
7061         uint32_t lba;
7062
7063         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7064
7065         cdb = (struct scsi_read_capacity *)ctsio->cdb;
7066
7067         lba = scsi_4btoul(cdb->addr);
7068         if (((cdb->pmi & SRC_PMI) == 0)
7069          && (lba != 0)) {
7070                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7071                                       /*sks_valid*/ 1,
7072                                       /*command*/ 1,
7073                                       /*field*/ 2,
7074                                       /*bit_valid*/ 0,
7075                                       /*bit*/ 0);
7076                 ctl_done((union ctl_io *)ctsio);
7077                 return (CTL_RETVAL_COMPLETE);
7078         }
7079
7080         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7081
7082         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7083         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7084         ctsio->residual = 0;
7085         ctsio->kern_data_len = sizeof(*data);
7086         ctsio->kern_total_len = sizeof(*data);
7087         ctsio->kern_data_resid = 0;
7088         ctsio->kern_rel_offset = 0;
7089         ctsio->kern_sg_entries = 0;
7090
7091         /*
7092          * If the maximum LBA is greater than 0xfffffffe, the user must
7093          * issue a SERVICE ACTION IN (16) command, with the read capacity
7094          * serivce action set.
7095          */
7096         if (lun->be_lun->maxlba > 0xfffffffe)
7097                 scsi_ulto4b(0xffffffff, data->addr);
7098         else
7099                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7100
7101         /*
7102          * XXX KDM this may not be 512 bytes...
7103          */
7104         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7105
7106         ctl_set_success(ctsio);
7107         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7108         ctsio->be_move_done = ctl_config_move_done;
7109         ctl_datamove((union ctl_io *)ctsio);
7110         return (CTL_RETVAL_COMPLETE);
7111 }
7112
7113 int
7114 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7115 {
7116         struct scsi_read_capacity_16 *cdb;
7117         struct scsi_read_capacity_data_long *data;
7118         struct ctl_lun *lun;
7119         uint64_t lba;
7120         uint32_t alloc_len;
7121
7122         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7123
7124         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7125
7126         alloc_len = scsi_4btoul(cdb->alloc_len);
7127         lba = scsi_8btou64(cdb->addr);
7128
7129         if ((cdb->reladr & SRC16_PMI)
7130          && (lba != 0)) {
7131                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7132                                       /*sks_valid*/ 1,
7133                                       /*command*/ 1,
7134                                       /*field*/ 2,
7135                                       /*bit_valid*/ 0,
7136                                       /*bit*/ 0);
7137                 ctl_done((union ctl_io *)ctsio);
7138                 return (CTL_RETVAL_COMPLETE);
7139         }
7140
7141         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7142
7143         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7144         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7145
7146         if (sizeof(*data) < alloc_len) {
7147                 ctsio->residual = alloc_len - sizeof(*data);
7148                 ctsio->kern_data_len = sizeof(*data);
7149                 ctsio->kern_total_len = sizeof(*data);
7150         } else {
7151                 ctsio->residual = 0;
7152                 ctsio->kern_data_len = alloc_len;
7153                 ctsio->kern_total_len = alloc_len;
7154         }
7155         ctsio->kern_data_resid = 0;
7156         ctsio->kern_rel_offset = 0;
7157         ctsio->kern_sg_entries = 0;
7158
7159         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7160         /* XXX KDM this may not be 512 bytes... */
7161         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7162         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7163         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7164         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7165                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7166
7167         ctl_set_success(ctsio);
7168         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7169         ctsio->be_move_done = ctl_config_move_done;
7170         ctl_datamove((union ctl_io *)ctsio);
7171         return (CTL_RETVAL_COMPLETE);
7172 }
7173
7174 int
7175 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7176 {
7177         struct scsi_get_lba_status *cdb;
7178         struct scsi_get_lba_status_data *data;
7179         struct ctl_lun *lun;
7180         struct ctl_lba_len_flags *lbalen;
7181         uint64_t lba;
7182         uint32_t alloc_len, total_len;
7183         int retval;
7184
7185         CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7186
7187         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7188         cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7189         lba = scsi_8btou64(cdb->addr);
7190         alloc_len = scsi_4btoul(cdb->alloc_len);
7191
7192         if (lba > lun->be_lun->maxlba) {
7193                 ctl_set_lba_out_of_range(ctsio);
7194                 ctl_done((union ctl_io *)ctsio);
7195                 return (CTL_RETVAL_COMPLETE);
7196         }
7197
7198         total_len = sizeof(*data) + sizeof(data->descr[0]);
7199         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7200         data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7201
7202         if (total_len < alloc_len) {
7203                 ctsio->residual = alloc_len - total_len;
7204                 ctsio->kern_data_len = total_len;
7205                 ctsio->kern_total_len = total_len;
7206         } else {
7207                 ctsio->residual = 0;
7208                 ctsio->kern_data_len = alloc_len;
7209                 ctsio->kern_total_len = alloc_len;
7210         }
7211         ctsio->kern_data_resid = 0;
7212         ctsio->kern_rel_offset = 0;
7213         ctsio->kern_sg_entries = 0;
7214
7215         /* Fill dummy data in case backend can't tell anything. */
7216         scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7217         scsi_u64to8b(lba, data->descr[0].addr);
7218         scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7219             data->descr[0].length);
7220         data->descr[0].status = 0; /* Mapped or unknown. */
7221
7222         ctl_set_success(ctsio);
7223         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7224         ctsio->be_move_done = ctl_config_move_done;
7225
7226         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7227         lbalen->lba = lba;
7228         lbalen->len = total_len;
7229         lbalen->flags = 0;
7230         retval = lun->backend->config_read((union ctl_io *)ctsio);
7231         return (CTL_RETVAL_COMPLETE);
7232 }
7233
7234 int
7235 ctl_read_defect(struct ctl_scsiio *ctsio)
7236 {
7237         struct scsi_read_defect_data_10 *ccb10;
7238         struct scsi_read_defect_data_12 *ccb12;
7239         struct scsi_read_defect_data_hdr_10 *data10;
7240         struct scsi_read_defect_data_hdr_12 *data12;
7241         uint32_t alloc_len, data_len;
7242         uint8_t format;
7243
7244         CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7245
7246         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7247                 ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7248                 format = ccb10->format;
7249                 alloc_len = scsi_2btoul(ccb10->alloc_length);
7250                 data_len = sizeof(*data10);
7251         } else {
7252                 ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7253                 format = ccb12->format;
7254                 alloc_len = scsi_4btoul(ccb12->alloc_length);
7255                 data_len = sizeof(*data12);
7256         }
7257         if (alloc_len == 0) {
7258                 ctl_set_success(ctsio);
7259                 ctl_done((union ctl_io *)ctsio);
7260                 return (CTL_RETVAL_COMPLETE);
7261         }
7262
7263         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7264         if (data_len < alloc_len) {
7265                 ctsio->residual = alloc_len - data_len;
7266                 ctsio->kern_data_len = data_len;
7267                 ctsio->kern_total_len = data_len;
7268         } else {
7269                 ctsio->residual = 0;
7270                 ctsio->kern_data_len = alloc_len;
7271                 ctsio->kern_total_len = alloc_len;
7272         }
7273         ctsio->kern_data_resid = 0;
7274         ctsio->kern_rel_offset = 0;
7275         ctsio->kern_sg_entries = 0;
7276
7277         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7278                 data10 = (struct scsi_read_defect_data_hdr_10 *)
7279                     ctsio->kern_data_ptr;
7280                 data10->format = format;
7281                 scsi_ulto2b(0, data10->length);
7282         } else {
7283                 data12 = (struct scsi_read_defect_data_hdr_12 *)
7284                     ctsio->kern_data_ptr;
7285                 data12->format = format;
7286                 scsi_ulto2b(0, data12->generation);
7287                 scsi_ulto4b(0, data12->length);
7288         }
7289
7290         ctl_set_success(ctsio);
7291         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7292         ctsio->be_move_done = ctl_config_move_done;
7293         ctl_datamove((union ctl_io *)ctsio);
7294         return (CTL_RETVAL_COMPLETE);
7295 }
7296
7297 int
7298 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7299 {
7300         struct scsi_maintenance_in *cdb;
7301         int retval;
7302         int alloc_len, ext, total_len = 0, g, p, pc, pg, gs, os;
7303         int num_target_port_groups, num_target_ports;
7304         struct ctl_lun *lun;
7305         struct ctl_softc *softc;
7306         struct ctl_port *port;
7307         struct scsi_target_group_data *rtg_ptr;
7308         struct scsi_target_group_data_extended *rtg_ext_ptr;
7309         struct scsi_target_port_group_descriptor *tpg_desc;
7310
7311         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7312
7313         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7314         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7315         softc = lun->ctl_softc;
7316
7317         retval = CTL_RETVAL_COMPLETE;
7318
7319         switch (cdb->byte2 & STG_PDF_MASK) {
7320         case STG_PDF_LENGTH:
7321                 ext = 0;
7322                 break;
7323         case STG_PDF_EXTENDED:
7324                 ext = 1;
7325                 break;
7326         default:
7327                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7328                                       /*sks_valid*/ 1,
7329                                       /*command*/ 1,
7330                                       /*field*/ 2,
7331                                       /*bit_valid*/ 1,
7332                                       /*bit*/ 5);
7333                 ctl_done((union ctl_io *)ctsio);
7334                 return(retval);
7335         }
7336
7337         if (softc->is_single)
7338                 num_target_port_groups = 1;
7339         else
7340                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7341         num_target_ports = 0;
7342         mtx_lock(&softc->ctl_lock);
7343         STAILQ_FOREACH(port, &softc->port_list, links) {
7344                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7345                         continue;
7346                 if (ctl_map_lun_back(softc, port->targ_port, lun->lun) >=
7347                     CTL_MAX_LUNS)
7348                         continue;
7349                 num_target_ports++;
7350         }
7351         mtx_unlock(&softc->ctl_lock);
7352
7353         if (ext)
7354                 total_len = sizeof(struct scsi_target_group_data_extended);
7355         else
7356                 total_len = sizeof(struct scsi_target_group_data);
7357         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7358                 num_target_port_groups +
7359             sizeof(struct scsi_target_port_descriptor) *
7360                 num_target_ports * num_target_port_groups;
7361
7362         alloc_len = scsi_4btoul(cdb->length);
7363
7364         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7365
7366         ctsio->kern_sg_entries = 0;
7367
7368         if (total_len < alloc_len) {
7369                 ctsio->residual = alloc_len - total_len;
7370                 ctsio->kern_data_len = total_len;
7371                 ctsio->kern_total_len = total_len;
7372         } else {
7373                 ctsio->residual = 0;
7374                 ctsio->kern_data_len = alloc_len;
7375                 ctsio->kern_total_len = alloc_len;
7376         }
7377         ctsio->kern_data_resid = 0;
7378         ctsio->kern_rel_offset = 0;
7379
7380         if (ext) {
7381                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7382                     ctsio->kern_data_ptr;
7383                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7384                 rtg_ext_ptr->format_type = 0x10;
7385                 rtg_ext_ptr->implicit_transition_time = 0;
7386                 tpg_desc = &rtg_ext_ptr->groups[0];
7387         } else {
7388                 rtg_ptr = (struct scsi_target_group_data *)
7389                     ctsio->kern_data_ptr;
7390                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7391                 tpg_desc = &rtg_ptr->groups[0];
7392         }
7393
7394         mtx_lock(&softc->ctl_lock);
7395         pg = softc->port_offset / CTL_MAX_PORTS;
7396         if (softc->flags & CTL_FLAG_ACTIVE_SHELF) {
7397                 if (softc->ha_mode == CTL_HA_MODE_ACT_STBY) {
7398                         gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7399                         os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7400                 } else if (lun->flags & CTL_LUN_PRIMARY_SC) {
7401                         gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7402                         os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7403                 } else {
7404                         gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7405                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7406                 }
7407         } else {
7408                 gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7409                 os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7410         }
7411         for (g = 0; g < num_target_port_groups; g++) {
7412                 tpg_desc->pref_state = (g == pg) ? gs : os;
7413                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP;
7414                 scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7415                 tpg_desc->status = TPG_IMPLICIT;
7416                 pc = 0;
7417                 STAILQ_FOREACH(port, &softc->port_list, links) {
7418                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7419                                 continue;
7420                         if (ctl_map_lun_back(softc, port->targ_port, lun->lun)
7421                             >= CTL_MAX_LUNS)
7422                                 continue;
7423                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7424                         scsi_ulto2b(p, tpg_desc->descriptors[pc].
7425                             relative_target_port_identifier);
7426                         pc++;
7427                 }
7428                 tpg_desc->target_port_count = pc;
7429                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7430                     &tpg_desc->descriptors[pc];
7431         }
7432         mtx_unlock(&softc->ctl_lock);
7433
7434         ctl_set_success(ctsio);
7435         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7436         ctsio->be_move_done = ctl_config_move_done;
7437         ctl_datamove((union ctl_io *)ctsio);
7438         return(retval);
7439 }
7440
7441 int
7442 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7443 {
7444         struct ctl_lun *lun;
7445         struct scsi_report_supported_opcodes *cdb;
7446         const struct ctl_cmd_entry *entry, *sentry;
7447         struct scsi_report_supported_opcodes_all *all;
7448         struct scsi_report_supported_opcodes_descr *descr;
7449         struct scsi_report_supported_opcodes_one *one;
7450         int retval;
7451         int alloc_len, total_len;
7452         int opcode, service_action, i, j, num;
7453
7454         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7455
7456         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7457         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7458
7459         retval = CTL_RETVAL_COMPLETE;
7460
7461         opcode = cdb->requested_opcode;
7462         service_action = scsi_2btoul(cdb->requested_service_action);
7463         switch (cdb->options & RSO_OPTIONS_MASK) {
7464         case RSO_OPTIONS_ALL:
7465                 num = 0;
7466                 for (i = 0; i < 256; i++) {
7467                         entry = &ctl_cmd_table[i];
7468                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7469                                 for (j = 0; j < 32; j++) {
7470                                         sentry = &((const struct ctl_cmd_entry *)
7471                                             entry->execute)[j];
7472                                         if (ctl_cmd_applicable(
7473                                             lun->be_lun->lun_type, sentry))
7474                                                 num++;
7475                                 }
7476                         } else {
7477                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7478                                     entry))
7479                                         num++;
7480                         }
7481                 }
7482                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7483                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7484                 break;
7485         case RSO_OPTIONS_OC:
7486                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7487                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7488                                               /*sks_valid*/ 1,
7489                                               /*command*/ 1,
7490                                               /*field*/ 2,
7491                                               /*bit_valid*/ 1,
7492                                               /*bit*/ 2);
7493                         ctl_done((union ctl_io *)ctsio);
7494                         return (CTL_RETVAL_COMPLETE);
7495                 }
7496                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7497                 break;
7498         case RSO_OPTIONS_OC_SA:
7499                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7500                     service_action >= 32) {
7501                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7502                                               /*sks_valid*/ 1,
7503                                               /*command*/ 1,
7504                                               /*field*/ 2,
7505                                               /*bit_valid*/ 1,
7506                                               /*bit*/ 2);
7507                         ctl_done((union ctl_io *)ctsio);
7508                         return (CTL_RETVAL_COMPLETE);
7509                 }
7510                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7511                 break;
7512         default:
7513                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7514                                       /*sks_valid*/ 1,
7515                                       /*command*/ 1,
7516                                       /*field*/ 2,
7517                                       /*bit_valid*/ 1,
7518                                       /*bit*/ 2);
7519                 ctl_done((union ctl_io *)ctsio);
7520                 return (CTL_RETVAL_COMPLETE);
7521         }
7522
7523         alloc_len = scsi_4btoul(cdb->length);
7524
7525         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7526
7527         ctsio->kern_sg_entries = 0;
7528
7529         if (total_len < alloc_len) {
7530                 ctsio->residual = alloc_len - total_len;
7531                 ctsio->kern_data_len = total_len;
7532                 ctsio->kern_total_len = total_len;
7533         } else {
7534                 ctsio->residual = 0;
7535                 ctsio->kern_data_len = alloc_len;
7536                 ctsio->kern_total_len = alloc_len;
7537         }
7538         ctsio->kern_data_resid = 0;
7539         ctsio->kern_rel_offset = 0;
7540
7541         switch (cdb->options & RSO_OPTIONS_MASK) {
7542         case RSO_OPTIONS_ALL:
7543                 all = (struct scsi_report_supported_opcodes_all *)
7544                     ctsio->kern_data_ptr;
7545                 num = 0;
7546                 for (i = 0; i < 256; i++) {
7547                         entry = &ctl_cmd_table[i];
7548                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7549                                 for (j = 0; j < 32; j++) {
7550                                         sentry = &((const struct ctl_cmd_entry *)
7551                                             entry->execute)[j];
7552                                         if (!ctl_cmd_applicable(
7553                                             lun->be_lun->lun_type, sentry))
7554                                                 continue;
7555                                         descr = &all->descr[num++];
7556                                         descr->opcode = i;
7557                                         scsi_ulto2b(j, descr->service_action);
7558                                         descr->flags = RSO_SERVACTV;
7559                                         scsi_ulto2b(sentry->length,
7560                                             descr->cdb_length);
7561                                 }
7562                         } else {
7563                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7564                                     entry))
7565                                         continue;
7566                                 descr = &all->descr[num++];
7567                                 descr->opcode = i;
7568                                 scsi_ulto2b(0, descr->service_action);
7569                                 descr->flags = 0;
7570                                 scsi_ulto2b(entry->length, descr->cdb_length);
7571                         }
7572                 }
7573                 scsi_ulto4b(
7574                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7575                     all->length);
7576                 break;
7577         case RSO_OPTIONS_OC:
7578                 one = (struct scsi_report_supported_opcodes_one *)
7579                     ctsio->kern_data_ptr;
7580                 entry = &ctl_cmd_table[opcode];
7581                 goto fill_one;
7582         case RSO_OPTIONS_OC_SA:
7583                 one = (struct scsi_report_supported_opcodes_one *)
7584                     ctsio->kern_data_ptr;
7585                 entry = &ctl_cmd_table[opcode];
7586                 entry = &((const struct ctl_cmd_entry *)
7587                     entry->execute)[service_action];
7588 fill_one:
7589                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7590                         one->support = 3;
7591                         scsi_ulto2b(entry->length, one->cdb_length);
7592                         one->cdb_usage[0] = opcode;
7593                         memcpy(&one->cdb_usage[1], entry->usage,
7594                             entry->length - 1);
7595                 } else
7596                         one->support = 1;
7597                 break;
7598         }
7599
7600         ctl_set_success(ctsio);
7601         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7602         ctsio->be_move_done = ctl_config_move_done;
7603         ctl_datamove((union ctl_io *)ctsio);
7604         return(retval);
7605 }
7606
7607 int
7608 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7609 {
7610         struct scsi_report_supported_tmf *cdb;
7611         struct scsi_report_supported_tmf_data *data;
7612         int retval;
7613         int alloc_len, total_len;
7614
7615         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7616
7617         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7618
7619         retval = CTL_RETVAL_COMPLETE;
7620
7621         total_len = sizeof(struct scsi_report_supported_tmf_data);
7622         alloc_len = scsi_4btoul(cdb->length);
7623
7624         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7625
7626         ctsio->kern_sg_entries = 0;
7627
7628         if (total_len < alloc_len) {
7629                 ctsio->residual = alloc_len - total_len;
7630                 ctsio->kern_data_len = total_len;
7631                 ctsio->kern_total_len = total_len;
7632         } else {
7633                 ctsio->residual = 0;
7634                 ctsio->kern_data_len = alloc_len;
7635                 ctsio->kern_total_len = alloc_len;
7636         }
7637         ctsio->kern_data_resid = 0;
7638         ctsio->kern_rel_offset = 0;
7639
7640         data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7641         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7642         data->byte2 |= RST_ITNRS;
7643
7644         ctl_set_success(ctsio);
7645         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7646         ctsio->be_move_done = ctl_config_move_done;
7647         ctl_datamove((union ctl_io *)ctsio);
7648         return (retval);
7649 }
7650
7651 int
7652 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7653 {
7654         struct scsi_report_timestamp *cdb;
7655         struct scsi_report_timestamp_data *data;
7656         struct timeval tv;
7657         int64_t timestamp;
7658         int retval;
7659         int alloc_len, total_len;
7660
7661         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7662
7663         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7664
7665         retval = CTL_RETVAL_COMPLETE;
7666
7667         total_len = sizeof(struct scsi_report_timestamp_data);
7668         alloc_len = scsi_4btoul(cdb->length);
7669
7670         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7671
7672         ctsio->kern_sg_entries = 0;
7673
7674         if (total_len < alloc_len) {
7675                 ctsio->residual = alloc_len - total_len;
7676                 ctsio->kern_data_len = total_len;
7677                 ctsio->kern_total_len = total_len;
7678         } else {
7679                 ctsio->residual = 0;
7680                 ctsio->kern_data_len = alloc_len;
7681                 ctsio->kern_total_len = alloc_len;
7682         }
7683         ctsio->kern_data_resid = 0;
7684         ctsio->kern_rel_offset = 0;
7685
7686         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7687         scsi_ulto2b(sizeof(*data) - 2, data->length);
7688         data->origin = RTS_ORIG_OUTSIDE;
7689         getmicrotime(&tv);
7690         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7691         scsi_ulto4b(timestamp >> 16, data->timestamp);
7692         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7693
7694         ctl_set_success(ctsio);
7695         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7696         ctsio->be_move_done = ctl_config_move_done;
7697         ctl_datamove((union ctl_io *)ctsio);
7698         return (retval);
7699 }
7700
7701 int
7702 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7703 {
7704         struct scsi_per_res_in *cdb;
7705         int alloc_len, total_len = 0;
7706         /* struct scsi_per_res_in_rsrv in_data; */
7707         struct ctl_lun *lun;
7708         struct ctl_softc *softc;
7709         uint64_t key;
7710
7711         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7712
7713         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7714
7715         alloc_len = scsi_2btoul(cdb->length);
7716
7717         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7718         softc = lun->ctl_softc;
7719
7720 retry:
7721         mtx_lock(&lun->lun_lock);
7722         switch (cdb->action) {
7723         case SPRI_RK: /* read keys */
7724                 total_len = sizeof(struct scsi_per_res_in_keys) +
7725                         lun->pr_key_count *
7726                         sizeof(struct scsi_per_res_key);
7727                 break;
7728         case SPRI_RR: /* read reservation */
7729                 if (lun->flags & CTL_LUN_PR_RESERVED)
7730                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7731                 else
7732                         total_len = sizeof(struct scsi_per_res_in_header);
7733                 break;
7734         case SPRI_RC: /* report capabilities */
7735                 total_len = sizeof(struct scsi_per_res_cap);
7736                 break;
7737         case SPRI_RS: /* read full status */
7738                 total_len = sizeof(struct scsi_per_res_in_header) +
7739                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7740                     lun->pr_key_count;
7741                 break;
7742         default:
7743                 panic("Invalid PR type %x", cdb->action);
7744         }
7745         mtx_unlock(&lun->lun_lock);
7746
7747         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7748
7749         if (total_len < alloc_len) {
7750                 ctsio->residual = alloc_len - total_len;
7751                 ctsio->kern_data_len = total_len;
7752                 ctsio->kern_total_len = total_len;
7753         } else {
7754                 ctsio->residual = 0;
7755                 ctsio->kern_data_len = alloc_len;
7756                 ctsio->kern_total_len = alloc_len;
7757         }
7758
7759         ctsio->kern_data_resid = 0;
7760         ctsio->kern_rel_offset = 0;
7761         ctsio->kern_sg_entries = 0;
7762
7763         mtx_lock(&lun->lun_lock);
7764         switch (cdb->action) {
7765         case SPRI_RK: { // read keys
7766         struct scsi_per_res_in_keys *res_keys;
7767                 int i, key_count;
7768
7769                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7770
7771                 /*
7772                  * We had to drop the lock to allocate our buffer, which
7773                  * leaves time for someone to come in with another
7774                  * persistent reservation.  (That is unlikely, though,
7775                  * since this should be the only persistent reservation
7776                  * command active right now.)
7777                  */
7778                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7779                     (lun->pr_key_count *
7780                      sizeof(struct scsi_per_res_key)))){
7781                         mtx_unlock(&lun->lun_lock);
7782                         free(ctsio->kern_data_ptr, M_CTL);
7783                         printf("%s: reservation length changed, retrying\n",
7784                                __func__);
7785                         goto retry;
7786                 }
7787
7788                 scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7789
7790                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7791                              lun->pr_key_count, res_keys->header.length);
7792
7793                 for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7794                         if ((key = ctl_get_prkey(lun, i)) == 0)
7795                                 continue;
7796
7797                         /*
7798                          * We used lun->pr_key_count to calculate the
7799                          * size to allocate.  If it turns out the number of
7800                          * initiators with the registered flag set is
7801                          * larger than that (i.e. they haven't been kept in
7802                          * sync), we've got a problem.
7803                          */
7804                         if (key_count >= lun->pr_key_count) {
7805 #ifdef NEEDTOPORT
7806                                 csevent_log(CSC_CTL | CSC_SHELF_SW |
7807                                             CTL_PR_ERROR,
7808                                             csevent_LogType_Fault,
7809                                             csevent_AlertLevel_Yellow,
7810                                             csevent_FRU_ShelfController,
7811                                             csevent_FRU_Firmware,
7812                                         csevent_FRU_Unknown,
7813                                             "registered keys %d >= key "
7814                                             "count %d", key_count,
7815                                             lun->pr_key_count);
7816 #endif
7817                                 key_count++;
7818                                 continue;
7819                         }
7820                         scsi_u64to8b(key, res_keys->keys[key_count].key);
7821                         key_count++;
7822                 }
7823                 break;
7824         }
7825         case SPRI_RR: { // read reservation
7826                 struct scsi_per_res_in_rsrv *res;
7827                 int tmp_len, header_only;
7828
7829                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7830
7831                 scsi_ulto4b(lun->PRGeneration, res->header.generation);
7832
7833                 if (lun->flags & CTL_LUN_PR_RESERVED)
7834                 {
7835                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7836                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7837                                     res->header.length);
7838                         header_only = 0;
7839                 } else {
7840                         tmp_len = sizeof(struct scsi_per_res_in_header);
7841                         scsi_ulto4b(0, res->header.length);
7842                         header_only = 1;
7843                 }
7844
7845                 /*
7846                  * We had to drop the lock to allocate our buffer, which
7847                  * leaves time for someone to come in with another
7848                  * persistent reservation.  (That is unlikely, though,
7849                  * since this should be the only persistent reservation
7850                  * command active right now.)
7851                  */
7852                 if (tmp_len != total_len) {
7853                         mtx_unlock(&lun->lun_lock);
7854                         free(ctsio->kern_data_ptr, M_CTL);
7855                         printf("%s: reservation status changed, retrying\n",
7856                                __func__);
7857                         goto retry;
7858                 }
7859
7860                 /*
7861                  * No reservation held, so we're done.
7862                  */
7863                 if (header_only != 0)
7864                         break;
7865
7866                 /*
7867                  * If the registration is an All Registrants type, the key
7868                  * is 0, since it doesn't really matter.
7869                  */
7870                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7871                         scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7872                             res->data.reservation);
7873                 }
7874                 res->data.scopetype = lun->res_type;
7875                 break;
7876         }
7877         case SPRI_RC:     //report capabilities
7878         {
7879                 struct scsi_per_res_cap *res_cap;
7880                 uint16_t type_mask;
7881
7882                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7883                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7884                 res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7885                 type_mask = SPRI_TM_WR_EX_AR |
7886                             SPRI_TM_EX_AC_RO |
7887                             SPRI_TM_WR_EX_RO |
7888                             SPRI_TM_EX_AC |
7889                             SPRI_TM_WR_EX |
7890                             SPRI_TM_EX_AC_AR;
7891                 scsi_ulto2b(type_mask, res_cap->type_mask);
7892                 break;
7893         }
7894         case SPRI_RS: { // read full status
7895                 struct scsi_per_res_in_full *res_status;
7896                 struct scsi_per_res_in_full_desc *res_desc;
7897                 struct ctl_port *port;
7898                 int i, len;
7899
7900                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7901
7902                 /*
7903                  * We had to drop the lock to allocate our buffer, which
7904                  * leaves time for someone to come in with another
7905                  * persistent reservation.  (That is unlikely, though,
7906                  * since this should be the only persistent reservation
7907                  * command active right now.)
7908                  */
7909                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
7910                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7911                      lun->pr_key_count)){
7912                         mtx_unlock(&lun->lun_lock);
7913                         free(ctsio->kern_data_ptr, M_CTL);
7914                         printf("%s: reservation length changed, retrying\n",
7915                                __func__);
7916                         goto retry;
7917                 }
7918
7919                 scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7920
7921                 res_desc = &res_status->desc[0];
7922                 for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7923                         if ((key = ctl_get_prkey(lun, i)) == 0)
7924                                 continue;
7925
7926                         scsi_u64to8b(key, res_desc->res_key.key);
7927                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7928                             (lun->pr_res_idx == i ||
7929                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7930                                 res_desc->flags = SPRI_FULL_R_HOLDER;
7931                                 res_desc->scopetype = lun->res_type;
7932                         }
7933                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7934                             res_desc->rel_trgt_port_id);
7935                         len = 0;
7936                         port = softc->ctl_ports[
7937                             ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
7938                         if (port != NULL)
7939                                 len = ctl_create_iid(port,
7940                                     i % CTL_MAX_INIT_PER_PORT,
7941                                     res_desc->transport_id);
7942                         scsi_ulto4b(len, res_desc->additional_length);
7943                         res_desc = (struct scsi_per_res_in_full_desc *)
7944                             &res_desc->transport_id[len];
7945                 }
7946                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7947                     res_status->header.length);
7948                 break;
7949         }
7950         default:
7951                 /*
7952                  * This is a bug, because we just checked for this above,
7953                  * and should have returned an error.
7954                  */
7955                 panic("Invalid PR type %x", cdb->action);
7956                 break; /* NOTREACHED */
7957         }
7958         mtx_unlock(&lun->lun_lock);
7959
7960         ctl_set_success(ctsio);
7961         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7962         ctsio->be_move_done = ctl_config_move_done;
7963         ctl_datamove((union ctl_io *)ctsio);
7964         return (CTL_RETVAL_COMPLETE);
7965 }
7966
7967 static void
7968 ctl_est_res_ua(struct ctl_lun *lun, uint32_t residx, ctl_ua_type ua)
7969 {
7970         int off = lun->ctl_softc->persis_offset;
7971
7972         if (residx >= off && residx < off + CTL_MAX_INITIATORS)
7973                 ctl_est_ua(lun, residx - off, ua);
7974 }
7975
7976 /*
7977  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7978  * it should return.
7979  */
7980 static int
7981 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7982                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
7983                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7984                 struct scsi_per_res_out_parms* param)
7985 {
7986         union ctl_ha_msg persis_io;
7987         int retval, i;
7988         int isc_retval;
7989
7990         retval = 0;
7991
7992         mtx_lock(&lun->lun_lock);
7993         if (sa_res_key == 0) {
7994                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7995                         /* validate scope and type */
7996                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7997                              SPR_LU_SCOPE) {
7998                                 mtx_unlock(&lun->lun_lock);
7999                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8000                                                       /*sks_valid*/ 1,
8001                                                       /*command*/ 1,
8002                                                       /*field*/ 2,
8003                                                       /*bit_valid*/ 1,
8004                                                       /*bit*/ 4);
8005                                 ctl_done((union ctl_io *)ctsio);
8006                                 return (1);
8007                         }
8008
8009                         if (type>8 || type==2 || type==4 || type==0) {
8010                                 mtx_unlock(&lun->lun_lock);
8011                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8012                                                       /*sks_valid*/ 1,
8013                                                       /*command*/ 1,
8014                                                       /*field*/ 2,
8015                                                       /*bit_valid*/ 1,
8016                                                       /*bit*/ 0);
8017                                 ctl_done((union ctl_io *)ctsio);
8018                                 return (1);
8019                         }
8020
8021                         /*
8022                          * Unregister everybody else and build UA for
8023                          * them
8024                          */
8025                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8026                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8027                                         continue;
8028
8029                                 ctl_clr_prkey(lun, i);
8030                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8031                         }
8032                         lun->pr_key_count = 1;
8033                         lun->res_type = type;
8034                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8035                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8036                                 lun->pr_res_idx = residx;
8037
8038                         /* send msg to other side */
8039                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8040                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8041                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8042                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8043                         persis_io.pr.pr_info.res_type = type;
8044                         memcpy(persis_io.pr.pr_info.sa_res_key,
8045                                param->serv_act_res_key,
8046                                sizeof(param->serv_act_res_key));
8047                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8048                              &persis_io, sizeof(persis_io), 0)) >
8049                              CTL_HA_STATUS_SUCCESS) {
8050                                 printf("CTL:Persis Out error returned "
8051                                        "from ctl_ha_msg_send %d\n",
8052                                        isc_retval);
8053                         }
8054                 } else {
8055                         /* not all registrants */
8056                         mtx_unlock(&lun->lun_lock);
8057                         free(ctsio->kern_data_ptr, M_CTL);
8058                         ctl_set_invalid_field(ctsio,
8059                                               /*sks_valid*/ 1,
8060                                               /*command*/ 0,
8061                                               /*field*/ 8,
8062                                               /*bit_valid*/ 0,
8063                                               /*bit*/ 0);
8064                         ctl_done((union ctl_io *)ctsio);
8065                         return (1);
8066                 }
8067         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8068                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
8069                 int found = 0;
8070
8071                 if (res_key == sa_res_key) {
8072                         /* special case */
8073                         /*
8074                          * The spec implies this is not good but doesn't
8075                          * say what to do. There are two choices either
8076                          * generate a res conflict or check condition
8077                          * with illegal field in parameter data. Since
8078                          * that is what is done when the sa_res_key is
8079                          * zero I'll take that approach since this has
8080                          * to do with the sa_res_key.
8081                          */
8082                         mtx_unlock(&lun->lun_lock);
8083                         free(ctsio->kern_data_ptr, M_CTL);
8084                         ctl_set_invalid_field(ctsio,
8085                                               /*sks_valid*/ 1,
8086                                               /*command*/ 0,
8087                                               /*field*/ 8,
8088                                               /*bit_valid*/ 0,
8089                                               /*bit*/ 0);
8090                         ctl_done((union ctl_io *)ctsio);
8091                         return (1);
8092                 }
8093
8094                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8095                         if (ctl_get_prkey(lun, i) != sa_res_key)
8096                                 continue;
8097
8098                         found = 1;
8099                         ctl_clr_prkey(lun, i);
8100                         lun->pr_key_count--;
8101                         ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8102                 }
8103                 if (!found) {
8104                         mtx_unlock(&lun->lun_lock);
8105                         free(ctsio->kern_data_ptr, M_CTL);
8106                         ctl_set_reservation_conflict(ctsio);
8107                         ctl_done((union ctl_io *)ctsio);
8108                         return (CTL_RETVAL_COMPLETE);
8109                 }
8110                 /* send msg to other side */
8111                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8112                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8113                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8114                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
8115                 persis_io.pr.pr_info.res_type = type;
8116                 memcpy(persis_io.pr.pr_info.sa_res_key,
8117                        param->serv_act_res_key,
8118                        sizeof(param->serv_act_res_key));
8119                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8120                      &persis_io, sizeof(persis_io), 0)) >
8121                      CTL_HA_STATUS_SUCCESS) {
8122                         printf("CTL:Persis Out error returned from "
8123                                "ctl_ha_msg_send %d\n", isc_retval);
8124                 }
8125         } else {
8126                 /* Reserved but not all registrants */
8127                 /* sa_res_key is res holder */
8128                 if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8129                         /* validate scope and type */
8130                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8131                              SPR_LU_SCOPE) {
8132                                 mtx_unlock(&lun->lun_lock);
8133                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8134                                                       /*sks_valid*/ 1,
8135                                                       /*command*/ 1,
8136                                                       /*field*/ 2,
8137                                                       /*bit_valid*/ 1,
8138                                                       /*bit*/ 4);
8139                                 ctl_done((union ctl_io *)ctsio);
8140                                 return (1);
8141                         }
8142
8143                         if (type>8 || type==2 || type==4 || type==0) {
8144                                 mtx_unlock(&lun->lun_lock);
8145                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8146                                                       /*sks_valid*/ 1,
8147                                                       /*command*/ 1,
8148                                                       /*field*/ 2,
8149                                                       /*bit_valid*/ 1,
8150                                                       /*bit*/ 0);
8151                                 ctl_done((union ctl_io *)ctsio);
8152                                 return (1);
8153                         }
8154
8155                         /*
8156                          * Do the following:
8157                          * if sa_res_key != res_key remove all
8158                          * registrants w/sa_res_key and generate UA
8159                          * for these registrants(Registrations
8160                          * Preempted) if it wasn't an exclusive
8161                          * reservation generate UA(Reservations
8162                          * Preempted) for all other registered nexuses
8163                          * if the type has changed. Establish the new
8164                          * reservation and holder. If res_key and
8165                          * sa_res_key are the same do the above
8166                          * except don't unregister the res holder.
8167                          */
8168
8169                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8170                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8171                                         continue;
8172
8173                                 if (sa_res_key == ctl_get_prkey(lun, i)) {
8174                                         ctl_clr_prkey(lun, i);
8175                                         lun->pr_key_count--;
8176                                         ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8177                                 } else if (type != lun->res_type
8178                                         && (lun->res_type == SPR_TYPE_WR_EX_RO
8179                                          || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8180                                         ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
8181                                 }
8182                         }
8183                         lun->res_type = type;
8184                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8185                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8186                                 lun->pr_res_idx = residx;
8187                         else
8188                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8189
8190                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8191                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8192                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8193                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8194                         persis_io.pr.pr_info.res_type = type;
8195                         memcpy(persis_io.pr.pr_info.sa_res_key,
8196                                param->serv_act_res_key,
8197                                sizeof(param->serv_act_res_key));
8198                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8199                              &persis_io, sizeof(persis_io), 0)) >
8200                              CTL_HA_STATUS_SUCCESS) {
8201                                 printf("CTL:Persis Out error returned "
8202                                        "from ctl_ha_msg_send %d\n",
8203                                        isc_retval);
8204                         }
8205                 } else {
8206                         /*
8207                          * sa_res_key is not the res holder just
8208                          * remove registrants
8209                          */
8210                         int found=0;
8211
8212                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8213                                 if (sa_res_key != ctl_get_prkey(lun, i))
8214                                         continue;
8215
8216                                 found = 1;
8217                                 ctl_clr_prkey(lun, i);
8218                                 lun->pr_key_count--;
8219                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8220                         }
8221
8222                         if (!found) {
8223                                 mtx_unlock(&lun->lun_lock);
8224                                 free(ctsio->kern_data_ptr, M_CTL);
8225                                 ctl_set_reservation_conflict(ctsio);
8226                                 ctl_done((union ctl_io *)ctsio);
8227                                 return (1);
8228                         }
8229                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8230                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8231                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8232                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8233                         persis_io.pr.pr_info.res_type = type;
8234                         memcpy(persis_io.pr.pr_info.sa_res_key,
8235                                param->serv_act_res_key,
8236                                sizeof(param->serv_act_res_key));
8237                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8238                              &persis_io, sizeof(persis_io), 0)) >
8239                              CTL_HA_STATUS_SUCCESS) {
8240                                 printf("CTL:Persis Out error returned "
8241                                        "from ctl_ha_msg_send %d\n",
8242                                 isc_retval);
8243                         }
8244                 }
8245         }
8246
8247         lun->PRGeneration++;
8248         mtx_unlock(&lun->lun_lock);
8249
8250         return (retval);
8251 }
8252
8253 static void
8254 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8255 {
8256         uint64_t sa_res_key;
8257         int i;
8258
8259         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8260
8261         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8262          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8263          || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8264                 if (sa_res_key == 0) {
8265                         /*
8266                          * Unregister everybody else and build UA for
8267                          * them
8268                          */
8269                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8270                                 if (i == msg->pr.pr_info.residx ||
8271                                     ctl_get_prkey(lun, i) == 0)
8272                                         continue;
8273
8274                                 ctl_clr_prkey(lun, i);
8275                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8276                         }
8277
8278                         lun->pr_key_count = 1;
8279                         lun->res_type = msg->pr.pr_info.res_type;
8280                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8281                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8282                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8283                 } else {
8284                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8285                                 if (sa_res_key == ctl_get_prkey(lun, i))
8286                                         continue;
8287
8288                                 ctl_clr_prkey(lun, i);
8289                                 lun->pr_key_count--;
8290                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8291                         }
8292                 }
8293         } else {
8294                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8295                         if (i == msg->pr.pr_info.residx ||
8296                             ctl_get_prkey(lun, i) == 0)
8297                                 continue;
8298
8299                         if (sa_res_key == ctl_get_prkey(lun, i)) {
8300                                 ctl_clr_prkey(lun, i);
8301                                 lun->pr_key_count--;
8302                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8303                         } else if (msg->pr.pr_info.res_type != lun->res_type
8304                                 && (lun->res_type == SPR_TYPE_WR_EX_RO
8305                                  || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8306                                 ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
8307                         }
8308                 }
8309                 lun->res_type = msg->pr.pr_info.res_type;
8310                 if (lun->res_type != SPR_TYPE_WR_EX_AR
8311                  && lun->res_type != SPR_TYPE_EX_AC_AR)
8312                         lun->pr_res_idx = msg->pr.pr_info.residx;
8313                 else
8314                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8315         }
8316         lun->PRGeneration++;
8317
8318 }
8319
8320
8321 int
8322 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8323 {
8324         int retval;
8325         int isc_retval;
8326         u_int32_t param_len;
8327         struct scsi_per_res_out *cdb;
8328         struct ctl_lun *lun;
8329         struct scsi_per_res_out_parms* param;
8330         struct ctl_softc *softc;
8331         uint32_t residx;
8332         uint64_t res_key, sa_res_key, key;
8333         uint8_t type;
8334         union ctl_ha_msg persis_io;
8335         int    i;
8336
8337         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8338
8339         retval = CTL_RETVAL_COMPLETE;
8340
8341         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8342         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8343         softc = lun->ctl_softc;
8344
8345         /*
8346          * We only support whole-LUN scope.  The scope & type are ignored for
8347          * register, register and ignore existing key and clear.
8348          * We sometimes ignore scope and type on preempts too!!
8349          * Verify reservation type here as well.
8350          */
8351         type = cdb->scope_type & SPR_TYPE_MASK;
8352         if ((cdb->action == SPRO_RESERVE)
8353          || (cdb->action == SPRO_RELEASE)) {
8354                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8355                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8356                                               /*sks_valid*/ 1,
8357                                               /*command*/ 1,
8358                                               /*field*/ 2,
8359                                               /*bit_valid*/ 1,
8360                                               /*bit*/ 4);
8361                         ctl_done((union ctl_io *)ctsio);
8362                         return (CTL_RETVAL_COMPLETE);
8363                 }
8364
8365                 if (type>8 || type==2 || type==4 || type==0) {
8366                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8367                                               /*sks_valid*/ 1,
8368                                               /*command*/ 1,
8369                                               /*field*/ 2,
8370                                               /*bit_valid*/ 1,
8371                                               /*bit*/ 0);
8372                         ctl_done((union ctl_io *)ctsio);
8373                         return (CTL_RETVAL_COMPLETE);
8374                 }
8375         }
8376
8377         param_len = scsi_4btoul(cdb->length);
8378
8379         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8380                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8381                 ctsio->kern_data_len = param_len;
8382                 ctsio->kern_total_len = param_len;
8383                 ctsio->kern_data_resid = 0;
8384                 ctsio->kern_rel_offset = 0;
8385                 ctsio->kern_sg_entries = 0;
8386                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8387                 ctsio->be_move_done = ctl_config_move_done;
8388                 ctl_datamove((union ctl_io *)ctsio);
8389
8390                 return (CTL_RETVAL_COMPLETE);
8391         }
8392
8393         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8394
8395         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8396         res_key = scsi_8btou64(param->res_key.key);
8397         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8398
8399         /*
8400          * Validate the reservation key here except for SPRO_REG_IGNO
8401          * This must be done for all other service actions
8402          */
8403         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8404                 mtx_lock(&lun->lun_lock);
8405                 if ((key = ctl_get_prkey(lun, residx)) != 0) {
8406                         if (res_key != key) {
8407                                 /*
8408                                  * The current key passed in doesn't match
8409                                  * the one the initiator previously
8410                                  * registered.
8411                                  */
8412                                 mtx_unlock(&lun->lun_lock);
8413                                 free(ctsio->kern_data_ptr, M_CTL);
8414                                 ctl_set_reservation_conflict(ctsio);
8415                                 ctl_done((union ctl_io *)ctsio);
8416                                 return (CTL_RETVAL_COMPLETE);
8417                         }
8418                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8419                         /*
8420                          * We are not registered
8421                          */
8422                         mtx_unlock(&lun->lun_lock);
8423                         free(ctsio->kern_data_ptr, M_CTL);
8424                         ctl_set_reservation_conflict(ctsio);
8425                         ctl_done((union ctl_io *)ctsio);
8426                         return (CTL_RETVAL_COMPLETE);
8427                 } else if (res_key != 0) {
8428                         /*
8429                          * We are not registered and trying to register but
8430                          * the register key isn't zero.
8431                          */
8432                         mtx_unlock(&lun->lun_lock);
8433                         free(ctsio->kern_data_ptr, M_CTL);
8434                         ctl_set_reservation_conflict(ctsio);
8435                         ctl_done((union ctl_io *)ctsio);
8436                         return (CTL_RETVAL_COMPLETE);
8437                 }
8438                 mtx_unlock(&lun->lun_lock);
8439         }
8440
8441         switch (cdb->action & SPRO_ACTION_MASK) {
8442         case SPRO_REGISTER:
8443         case SPRO_REG_IGNO: {
8444
8445 #if 0
8446                 printf("Registration received\n");
8447 #endif
8448
8449                 /*
8450                  * We don't support any of these options, as we report in
8451                  * the read capabilities request (see
8452                  * ctl_persistent_reserve_in(), above).
8453                  */
8454                 if ((param->flags & SPR_SPEC_I_PT)
8455                  || (param->flags & SPR_ALL_TG_PT)
8456                  || (param->flags & SPR_APTPL)) {
8457                         int bit_ptr;
8458
8459                         if (param->flags & SPR_APTPL)
8460                                 bit_ptr = 0;
8461                         else if (param->flags & SPR_ALL_TG_PT)
8462                                 bit_ptr = 2;
8463                         else /* SPR_SPEC_I_PT */
8464                                 bit_ptr = 3;
8465
8466                         free(ctsio->kern_data_ptr, M_CTL);
8467                         ctl_set_invalid_field(ctsio,
8468                                               /*sks_valid*/ 1,
8469                                               /*command*/ 0,
8470                                               /*field*/ 20,
8471                                               /*bit_valid*/ 1,
8472                                               /*bit*/ bit_ptr);
8473                         ctl_done((union ctl_io *)ctsio);
8474                         return (CTL_RETVAL_COMPLETE);
8475                 }
8476
8477                 mtx_lock(&lun->lun_lock);
8478
8479                 /*
8480                  * The initiator wants to clear the
8481                  * key/unregister.
8482                  */
8483                 if (sa_res_key == 0) {
8484                         if ((res_key == 0
8485                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8486                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8487                           && ctl_get_prkey(lun, residx) == 0)) {
8488                                 mtx_unlock(&lun->lun_lock);
8489                                 goto done;
8490                         }
8491
8492                         ctl_clr_prkey(lun, residx);
8493                         lun->pr_key_count--;
8494
8495                         if (residx == lun->pr_res_idx) {
8496                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8497                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8498
8499                                 if ((lun->res_type == SPR_TYPE_WR_EX_RO
8500                                   || lun->res_type == SPR_TYPE_EX_AC_RO)
8501                                  && lun->pr_key_count) {
8502                                         /*
8503                                          * If the reservation is a registrants
8504                                          * only type we need to generate a UA
8505                                          * for other registered inits.  The
8506                                          * sense code should be RESERVATIONS
8507                                          * RELEASED
8508                                          */
8509
8510                                         for (i = 0; i < CTL_MAX_INITIATORS;i++){
8511                                                 if (ctl_get_prkey(lun, i +
8512                                                     softc->persis_offset) == 0)
8513                                                         continue;
8514                                                 ctl_est_ua(lun, i,
8515                                                     CTL_UA_RES_RELEASE);
8516                                         }
8517                                 }
8518                                 lun->res_type = 0;
8519                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8520                                 if (lun->pr_key_count==0) {
8521                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8522                                         lun->res_type = 0;
8523                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8524                                 }
8525                         }
8526                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8527                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8528                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8529                         persis_io.pr.pr_info.residx = residx;
8530                         if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8531                              &persis_io, sizeof(persis_io), 0 )) >
8532                              CTL_HA_STATUS_SUCCESS) {
8533                                 printf("CTL:Persis Out error returned from "
8534                                        "ctl_ha_msg_send %d\n", isc_retval);
8535                         }
8536                 } else /* sa_res_key != 0 */ {
8537
8538                         /*
8539                          * If we aren't registered currently then increment
8540                          * the key count and set the registered flag.
8541                          */
8542                         ctl_alloc_prkey(lun, residx);
8543                         if (ctl_get_prkey(lun, residx) == 0)
8544                                 lun->pr_key_count++;
8545                         ctl_set_prkey(lun, residx, sa_res_key);
8546
8547                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8548                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8549                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8550                         persis_io.pr.pr_info.residx = residx;
8551                         memcpy(persis_io.pr.pr_info.sa_res_key,
8552                                param->serv_act_res_key,
8553                                sizeof(param->serv_act_res_key));
8554                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8555                              &persis_io, sizeof(persis_io), 0)) >
8556                              CTL_HA_STATUS_SUCCESS) {
8557                                 printf("CTL:Persis Out error returned from "
8558                                        "ctl_ha_msg_send %d\n", isc_retval);
8559                         }
8560                 }
8561                 lun->PRGeneration++;
8562                 mtx_unlock(&lun->lun_lock);
8563
8564                 break;
8565         }
8566         case SPRO_RESERVE:
8567 #if 0
8568                 printf("Reserve executed type %d\n", type);
8569 #endif
8570                 mtx_lock(&lun->lun_lock);
8571                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8572                         /*
8573                          * if this isn't the reservation holder and it's
8574                          * not a "all registrants" type or if the type is
8575                          * different then we have a conflict
8576                          */
8577                         if ((lun->pr_res_idx != residx
8578                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8579                          || lun->res_type != type) {
8580                                 mtx_unlock(&lun->lun_lock);
8581                                 free(ctsio->kern_data_ptr, M_CTL);
8582                                 ctl_set_reservation_conflict(ctsio);
8583                                 ctl_done((union ctl_io *)ctsio);
8584                                 return (CTL_RETVAL_COMPLETE);
8585                         }
8586                         mtx_unlock(&lun->lun_lock);
8587                 } else /* create a reservation */ {
8588                         /*
8589                          * If it's not an "all registrants" type record
8590                          * reservation holder
8591                          */
8592                         if (type != SPR_TYPE_WR_EX_AR
8593                          && type != SPR_TYPE_EX_AC_AR)
8594                                 lun->pr_res_idx = residx; /* Res holder */
8595                         else
8596                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8597
8598                         lun->flags |= CTL_LUN_PR_RESERVED;
8599                         lun->res_type = type;
8600
8601                         mtx_unlock(&lun->lun_lock);
8602
8603                         /* send msg to other side */
8604                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8605                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8606                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8607                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8608                         persis_io.pr.pr_info.res_type = type;
8609                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8610                              &persis_io, sizeof(persis_io), 0)) >
8611                              CTL_HA_STATUS_SUCCESS) {
8612                                 printf("CTL:Persis Out error returned from "
8613                                        "ctl_ha_msg_send %d\n", isc_retval);
8614                         }
8615                 }
8616                 break;
8617
8618         case SPRO_RELEASE:
8619                 mtx_lock(&lun->lun_lock);
8620                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8621                         /* No reservation exists return good status */
8622                         mtx_unlock(&lun->lun_lock);
8623                         goto done;
8624                 }
8625                 /*
8626                  * Is this nexus a reservation holder?
8627                  */
8628                 if (lun->pr_res_idx != residx
8629                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8630                         /*
8631                          * not a res holder return good status but
8632                          * do nothing
8633                          */
8634                         mtx_unlock(&lun->lun_lock);
8635                         goto done;
8636                 }
8637
8638                 if (lun->res_type != type) {
8639                         mtx_unlock(&lun->lun_lock);
8640                         free(ctsio->kern_data_ptr, M_CTL);
8641                         ctl_set_illegal_pr_release(ctsio);
8642                         ctl_done((union ctl_io *)ctsio);
8643                         return (CTL_RETVAL_COMPLETE);
8644                 }
8645
8646                 /* okay to release */
8647                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8648                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8649                 lun->res_type = 0;
8650
8651                 /*
8652                  * if this isn't an exclusive access
8653                  * res generate UA for all other
8654                  * registrants.
8655                  */
8656                 if (type != SPR_TYPE_EX_AC
8657                  && type != SPR_TYPE_WR_EX) {
8658                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8659                                 if (i == residx ||
8660                                     ctl_get_prkey(lun,
8661                                      i + softc->persis_offset) == 0)
8662                                         continue;
8663                                 ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8664                         }
8665                 }
8666                 mtx_unlock(&lun->lun_lock);
8667                 /* Send msg to other side */
8668                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8669                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8670                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8671                 if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8672                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8673                         printf("CTL:Persis Out error returned from "
8674                                "ctl_ha_msg_send %d\n", isc_retval);
8675                 }
8676                 break;
8677
8678         case SPRO_CLEAR:
8679                 /* send msg to other side */
8680
8681                 mtx_lock(&lun->lun_lock);
8682                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8683                 lun->res_type = 0;
8684                 lun->pr_key_count = 0;
8685                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8686
8687                 ctl_clr_prkey(lun, residx);
8688                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8689                         if (ctl_get_prkey(lun, i) != 0) {
8690                                 ctl_clr_prkey(lun, i);
8691                                 ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8692                         }
8693                 lun->PRGeneration++;
8694                 mtx_unlock(&lun->lun_lock);
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_CLEAR;
8698                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8699                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8700                         printf("CTL:Persis Out error returned from "
8701                                "ctl_ha_msg_send %d\n", isc_retval);
8702                 }
8703                 break;
8704
8705         case SPRO_PREEMPT:
8706         case SPRO_PRE_ABO: {
8707                 int nretval;
8708
8709                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8710                                           residx, ctsio, cdb, param);
8711                 if (nretval != 0)
8712                         return (CTL_RETVAL_COMPLETE);
8713                 break;
8714         }
8715         default:
8716                 panic("Invalid PR type %x", cdb->action);
8717         }
8718
8719 done:
8720         free(ctsio->kern_data_ptr, M_CTL);
8721         ctl_set_success(ctsio);
8722         ctl_done((union ctl_io *)ctsio);
8723
8724         return (retval);
8725 }
8726
8727 /*
8728  * This routine is for handling a message from the other SC pertaining to
8729  * persistent reserve out. All the error checking will have been done
8730  * so only perorming the action need be done here to keep the two
8731  * in sync.
8732  */
8733 static void
8734 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8735 {
8736         struct ctl_lun *lun;
8737         struct ctl_softc *softc;
8738         int i;
8739         uint32_t targ_lun;
8740
8741         softc = control_softc;
8742
8743         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8744         lun = softc->ctl_luns[targ_lun];
8745         mtx_lock(&lun->lun_lock);
8746         switch(msg->pr.pr_info.action) {
8747         case CTL_PR_REG_KEY:
8748                 ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8749                 if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8750                         lun->pr_key_count++;
8751                 ctl_set_prkey(lun, msg->pr.pr_info.residx,
8752                     scsi_8btou64(msg->pr.pr_info.sa_res_key));
8753                 lun->PRGeneration++;
8754                 break;
8755
8756         case CTL_PR_UNREG_KEY:
8757                 ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8758                 lun->pr_key_count--;
8759
8760                 /* XXX Need to see if the reservation has been released */
8761                 /* if so do we need to generate UA? */
8762                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8763                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8764                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8765
8766                         if ((lun->res_type == SPR_TYPE_WR_EX_RO
8767                           || lun->res_type == SPR_TYPE_EX_AC_RO)
8768                          && lun->pr_key_count) {
8769                                 /*
8770                                  * If the reservation is a registrants
8771                                  * only type we need to generate a UA
8772                                  * for other registered inits.  The
8773                                  * sense code should be RESERVATIONS
8774                                  * RELEASED
8775                                  */
8776
8777                                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8778                                         if (ctl_get_prkey(lun, i +
8779                                             softc->persis_offset) == 0)
8780                                                 continue;
8781
8782                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8783                                 }
8784                         }
8785                         lun->res_type = 0;
8786                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8787                         if (lun->pr_key_count==0) {
8788                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8789                                 lun->res_type = 0;
8790                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8791                         }
8792                 }
8793                 lun->PRGeneration++;
8794                 break;
8795
8796         case CTL_PR_RESERVE:
8797                 lun->flags |= CTL_LUN_PR_RESERVED;
8798                 lun->res_type = msg->pr.pr_info.res_type;
8799                 lun->pr_res_idx = msg->pr.pr_info.residx;
8800
8801                 break;
8802
8803         case CTL_PR_RELEASE:
8804                 /*
8805                  * if this isn't an exclusive access res generate UA for all
8806                  * other registrants.
8807                  */
8808                 if (lun->res_type != SPR_TYPE_EX_AC
8809                  && lun->res_type != SPR_TYPE_WR_EX) {
8810                         for (i = 0; i < CTL_MAX_INITIATORS; i++)
8811                                 if (ctl_get_prkey(lun, i + softc->persis_offset) != 0)
8812                                         ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8813                 }
8814
8815                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8816                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8817                 lun->res_type = 0;
8818                 break;
8819
8820         case CTL_PR_PREEMPT:
8821                 ctl_pro_preempt_other(lun, msg);
8822                 break;
8823         case CTL_PR_CLEAR:
8824                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8825                 lun->res_type = 0;
8826                 lun->pr_key_count = 0;
8827                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8828
8829                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8830                         if (ctl_get_prkey(lun, i) == 0)
8831                                 continue;
8832                         ctl_clr_prkey(lun, i);
8833                         ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8834                 }
8835                 lun->PRGeneration++;
8836                 break;
8837         }
8838
8839         mtx_unlock(&lun->lun_lock);
8840 }
8841
8842 int
8843 ctl_read_write(struct ctl_scsiio *ctsio)
8844 {
8845         struct ctl_lun *lun;
8846         struct ctl_lba_len_flags *lbalen;
8847         uint64_t lba;
8848         uint32_t num_blocks;
8849         int flags, retval;
8850         int isread;
8851
8852         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8853
8854         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8855
8856         flags = 0;
8857         retval = CTL_RETVAL_COMPLETE;
8858
8859         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8860               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8861         switch (ctsio->cdb[0]) {
8862         case READ_6:
8863         case WRITE_6: {
8864                 struct scsi_rw_6 *cdb;
8865
8866                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
8867
8868                 lba = scsi_3btoul(cdb->addr);
8869                 /* only 5 bits are valid in the most significant address byte */
8870                 lba &= 0x1fffff;
8871                 num_blocks = cdb->length;
8872                 /*
8873                  * This is correct according to SBC-2.
8874                  */
8875                 if (num_blocks == 0)
8876                         num_blocks = 256;
8877                 break;
8878         }
8879         case READ_10:
8880         case WRITE_10: {
8881                 struct scsi_rw_10 *cdb;
8882
8883                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
8884                 if (cdb->byte2 & SRW10_FUA)
8885                         flags |= CTL_LLF_FUA;
8886                 if (cdb->byte2 & SRW10_DPO)
8887                         flags |= CTL_LLF_DPO;
8888                 lba = scsi_4btoul(cdb->addr);
8889                 num_blocks = scsi_2btoul(cdb->length);
8890                 break;
8891         }
8892         case WRITE_VERIFY_10: {
8893                 struct scsi_write_verify_10 *cdb;
8894
8895                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8896                 flags |= CTL_LLF_FUA;
8897                 if (cdb->byte2 & SWV_DPO)
8898                         flags |= CTL_LLF_DPO;
8899                 lba = scsi_4btoul(cdb->addr);
8900                 num_blocks = scsi_2btoul(cdb->length);
8901                 break;
8902         }
8903         case READ_12:
8904         case WRITE_12: {
8905                 struct scsi_rw_12 *cdb;
8906
8907                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
8908                 if (cdb->byte2 & SRW12_FUA)
8909                         flags |= CTL_LLF_FUA;
8910                 if (cdb->byte2 & SRW12_DPO)
8911                         flags |= CTL_LLF_DPO;
8912                 lba = scsi_4btoul(cdb->addr);
8913                 num_blocks = scsi_4btoul(cdb->length);
8914                 break;
8915         }
8916         case WRITE_VERIFY_12: {
8917                 struct scsi_write_verify_12 *cdb;
8918
8919                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8920                 flags |= CTL_LLF_FUA;
8921                 if (cdb->byte2 & SWV_DPO)
8922                         flags |= CTL_LLF_DPO;
8923                 lba = scsi_4btoul(cdb->addr);
8924                 num_blocks = scsi_4btoul(cdb->length);
8925                 break;
8926         }
8927         case READ_16:
8928         case WRITE_16: {
8929                 struct scsi_rw_16 *cdb;
8930
8931                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8932                 if (cdb->byte2 & SRW12_FUA)
8933                         flags |= CTL_LLF_FUA;
8934                 if (cdb->byte2 & SRW12_DPO)
8935                         flags |= CTL_LLF_DPO;
8936                 lba = scsi_8btou64(cdb->addr);
8937                 num_blocks = scsi_4btoul(cdb->length);
8938                 break;
8939         }
8940         case WRITE_ATOMIC_16: {
8941                 struct scsi_rw_16 *cdb;
8942
8943                 if (lun->be_lun->atomicblock == 0) {
8944                         ctl_set_invalid_opcode(ctsio);
8945                         ctl_done((union ctl_io *)ctsio);
8946                         return (CTL_RETVAL_COMPLETE);
8947                 }
8948
8949                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8950                 if (cdb->byte2 & SRW12_FUA)
8951                         flags |= CTL_LLF_FUA;
8952                 if (cdb->byte2 & SRW12_DPO)
8953                         flags |= CTL_LLF_DPO;
8954                 lba = scsi_8btou64(cdb->addr);
8955                 num_blocks = scsi_4btoul(cdb->length);
8956                 if (num_blocks > lun->be_lun->atomicblock) {
8957                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8958                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8959                             /*bit*/ 0);
8960                         ctl_done((union ctl_io *)ctsio);
8961                         return (CTL_RETVAL_COMPLETE);
8962                 }
8963                 break;
8964         }
8965         case WRITE_VERIFY_16: {
8966                 struct scsi_write_verify_16 *cdb;
8967
8968                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8969                 flags |= CTL_LLF_FUA;
8970                 if (cdb->byte2 & SWV_DPO)
8971                         flags |= CTL_LLF_DPO;
8972                 lba = scsi_8btou64(cdb->addr);
8973                 num_blocks = scsi_4btoul(cdb->length);
8974                 break;
8975         }
8976         default:
8977                 /*
8978                  * We got a command we don't support.  This shouldn't
8979                  * happen, commands should be filtered out above us.
8980                  */
8981                 ctl_set_invalid_opcode(ctsio);
8982                 ctl_done((union ctl_io *)ctsio);
8983
8984                 return (CTL_RETVAL_COMPLETE);
8985                 break; /* NOTREACHED */
8986         }
8987
8988         /*
8989          * The first check is to make sure we're in bounds, the second
8990          * check is to catch wrap-around problems.  If the lba + num blocks
8991          * is less than the lba, then we've wrapped around and the block
8992          * range is invalid anyway.
8993          */
8994         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8995          || ((lba + num_blocks) < lba)) {
8996                 ctl_set_lba_out_of_range(ctsio);
8997                 ctl_done((union ctl_io *)ctsio);
8998                 return (CTL_RETVAL_COMPLETE);
8999         }
9000
9001         /*
9002          * According to SBC-3, a transfer length of 0 is not an error.
9003          * Note that this cannot happen with WRITE(6) or READ(6), since 0
9004          * translates to 256 blocks for those commands.
9005          */
9006         if (num_blocks == 0) {
9007                 ctl_set_success(ctsio);
9008                 ctl_done((union ctl_io *)ctsio);
9009                 return (CTL_RETVAL_COMPLETE);
9010         }
9011
9012         /* Set FUA and/or DPO if caches are disabled. */
9013         if (isread) {
9014                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9015                     SCP_RCD) != 0)
9016                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9017         } else {
9018                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9019                     SCP_WCE) == 0)
9020                         flags |= CTL_LLF_FUA;
9021         }
9022
9023         lbalen = (struct ctl_lba_len_flags *)
9024             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9025         lbalen->lba = lba;
9026         lbalen->len = num_blocks;
9027         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9028
9029         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9030         ctsio->kern_rel_offset = 0;
9031
9032         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9033
9034         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9035
9036         return (retval);
9037 }
9038
9039 static int
9040 ctl_cnw_cont(union ctl_io *io)
9041 {
9042         struct ctl_scsiio *ctsio;
9043         struct ctl_lun *lun;
9044         struct ctl_lba_len_flags *lbalen;
9045         int retval;
9046
9047         ctsio = &io->scsiio;
9048         ctsio->io_hdr.status = CTL_STATUS_NONE;
9049         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9050         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9051         lbalen = (struct ctl_lba_len_flags *)
9052             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9053         lbalen->flags &= ~CTL_LLF_COMPARE;
9054         lbalen->flags |= CTL_LLF_WRITE;
9055
9056         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9057         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9058         return (retval);
9059 }
9060
9061 int
9062 ctl_cnw(struct ctl_scsiio *ctsio)
9063 {
9064         struct ctl_lun *lun;
9065         struct ctl_lba_len_flags *lbalen;
9066         uint64_t lba;
9067         uint32_t num_blocks;
9068         int flags, retval;
9069
9070         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9071
9072         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9073
9074         flags = 0;
9075         retval = CTL_RETVAL_COMPLETE;
9076
9077         switch (ctsio->cdb[0]) {
9078         case COMPARE_AND_WRITE: {
9079                 struct scsi_compare_and_write *cdb;
9080
9081                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9082                 if (cdb->byte2 & SRW10_FUA)
9083                         flags |= CTL_LLF_FUA;
9084                 if (cdb->byte2 & SRW10_DPO)
9085                         flags |= CTL_LLF_DPO;
9086                 lba = scsi_8btou64(cdb->addr);
9087                 num_blocks = cdb->length;
9088                 break;
9089         }
9090         default:
9091                 /*
9092                  * We got a command we don't support.  This shouldn't
9093                  * happen, commands should be filtered out above us.
9094                  */
9095                 ctl_set_invalid_opcode(ctsio);
9096                 ctl_done((union ctl_io *)ctsio);
9097
9098                 return (CTL_RETVAL_COMPLETE);
9099                 break; /* NOTREACHED */
9100         }
9101
9102         /*
9103          * The first check is to make sure we're in bounds, the second
9104          * check is to catch wrap-around problems.  If the lba + num blocks
9105          * is less than the lba, then we've wrapped around and the block
9106          * range is invalid anyway.
9107          */
9108         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9109          || ((lba + num_blocks) < lba)) {
9110                 ctl_set_lba_out_of_range(ctsio);
9111                 ctl_done((union ctl_io *)ctsio);
9112                 return (CTL_RETVAL_COMPLETE);
9113         }
9114
9115         /*
9116          * According to SBC-3, a transfer length of 0 is not an error.
9117          */
9118         if (num_blocks == 0) {
9119                 ctl_set_success(ctsio);
9120                 ctl_done((union ctl_io *)ctsio);
9121                 return (CTL_RETVAL_COMPLETE);
9122         }
9123
9124         /* Set FUA if write cache is disabled. */
9125         if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9126             SCP_WCE) == 0)
9127                 flags |= CTL_LLF_FUA;
9128
9129         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9130         ctsio->kern_rel_offset = 0;
9131
9132         /*
9133          * Set the IO_CONT flag, so that if this I/O gets passed to
9134          * ctl_data_submit_done(), it'll get passed back to
9135          * ctl_ctl_cnw_cont() for further processing.
9136          */
9137         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9138         ctsio->io_cont = ctl_cnw_cont;
9139
9140         lbalen = (struct ctl_lba_len_flags *)
9141             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9142         lbalen->lba = lba;
9143         lbalen->len = num_blocks;
9144         lbalen->flags = CTL_LLF_COMPARE | flags;
9145
9146         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9147         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9148         return (retval);
9149 }
9150
9151 int
9152 ctl_verify(struct ctl_scsiio *ctsio)
9153 {
9154         struct ctl_lun *lun;
9155         struct ctl_lba_len_flags *lbalen;
9156         uint64_t lba;
9157         uint32_t num_blocks;
9158         int bytchk, flags;
9159         int retval;
9160
9161         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9162
9163         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9164
9165         bytchk = 0;
9166         flags = CTL_LLF_FUA;
9167         retval = CTL_RETVAL_COMPLETE;
9168
9169         switch (ctsio->cdb[0]) {
9170         case VERIFY_10: {
9171                 struct scsi_verify_10 *cdb;
9172
9173                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
9174                 if (cdb->byte2 & SVFY_BYTCHK)
9175                         bytchk = 1;
9176                 if (cdb->byte2 & SVFY_DPO)
9177                         flags |= CTL_LLF_DPO;
9178                 lba = scsi_4btoul(cdb->addr);
9179                 num_blocks = scsi_2btoul(cdb->length);
9180                 break;
9181         }
9182         case VERIFY_12: {
9183                 struct scsi_verify_12 *cdb;
9184
9185                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
9186                 if (cdb->byte2 & SVFY_BYTCHK)
9187                         bytchk = 1;
9188                 if (cdb->byte2 & SVFY_DPO)
9189                         flags |= CTL_LLF_DPO;
9190                 lba = scsi_4btoul(cdb->addr);
9191                 num_blocks = scsi_4btoul(cdb->length);
9192                 break;
9193         }
9194         case VERIFY_16: {
9195                 struct scsi_rw_16 *cdb;
9196
9197                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9198                 if (cdb->byte2 & SVFY_BYTCHK)
9199                         bytchk = 1;
9200                 if (cdb->byte2 & SVFY_DPO)
9201                         flags |= CTL_LLF_DPO;
9202                 lba = scsi_8btou64(cdb->addr);
9203                 num_blocks = scsi_4btoul(cdb->length);
9204                 break;
9205         }
9206         default:
9207                 /*
9208                  * We got a command we don't support.  This shouldn't
9209                  * happen, commands should be filtered out above us.
9210                  */
9211                 ctl_set_invalid_opcode(ctsio);
9212                 ctl_done((union ctl_io *)ctsio);
9213                 return (CTL_RETVAL_COMPLETE);
9214         }
9215
9216         /*
9217          * The first check is to make sure we're in bounds, the second
9218          * check is to catch wrap-around problems.  If the lba + num blocks
9219          * is less than the lba, then we've wrapped around and the block
9220          * range is invalid anyway.
9221          */
9222         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9223          || ((lba + num_blocks) < lba)) {
9224                 ctl_set_lba_out_of_range(ctsio);
9225                 ctl_done((union ctl_io *)ctsio);
9226                 return (CTL_RETVAL_COMPLETE);
9227         }
9228
9229         /*
9230          * According to SBC-3, a transfer length of 0 is not an error.
9231          */
9232         if (num_blocks == 0) {
9233                 ctl_set_success(ctsio);
9234                 ctl_done((union ctl_io *)ctsio);
9235                 return (CTL_RETVAL_COMPLETE);
9236         }
9237
9238         lbalen = (struct ctl_lba_len_flags *)
9239             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9240         lbalen->lba = lba;
9241         lbalen->len = num_blocks;
9242         if (bytchk) {
9243                 lbalen->flags = CTL_LLF_COMPARE | flags;
9244                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9245         } else {
9246                 lbalen->flags = CTL_LLF_VERIFY | flags;
9247                 ctsio->kern_total_len = 0;
9248         }
9249         ctsio->kern_rel_offset = 0;
9250
9251         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9252         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9253         return (retval);
9254 }
9255
9256 int
9257 ctl_report_luns(struct ctl_scsiio *ctsio)
9258 {
9259         struct ctl_softc *softc = control_softc;
9260         struct scsi_report_luns *cdb;
9261         struct scsi_report_luns_data *lun_data;
9262         struct ctl_lun *lun, *request_lun;
9263         int num_luns, retval;
9264         uint32_t alloc_len, lun_datalen;
9265         int num_filled, well_known;
9266         uint32_t initidx, targ_lun_id, lun_id;
9267
9268         retval = CTL_RETVAL_COMPLETE;
9269         well_known = 0;
9270
9271         cdb = (struct scsi_report_luns *)ctsio->cdb;
9272
9273         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9274
9275         mtx_lock(&softc->ctl_lock);
9276         num_luns = softc->num_luns;
9277         mtx_unlock(&softc->ctl_lock);
9278
9279         switch (cdb->select_report) {
9280         case RPL_REPORT_DEFAULT:
9281         case RPL_REPORT_ALL:
9282                 break;
9283         case RPL_REPORT_WELLKNOWN:
9284                 well_known = 1;
9285                 num_luns = 0;
9286                 break;
9287         default:
9288                 ctl_set_invalid_field(ctsio,
9289                                       /*sks_valid*/ 1,
9290                                       /*command*/ 1,
9291                                       /*field*/ 2,
9292                                       /*bit_valid*/ 0,
9293                                       /*bit*/ 0);
9294                 ctl_done((union ctl_io *)ctsio);
9295                 return (retval);
9296                 break; /* NOTREACHED */
9297         }
9298
9299         alloc_len = scsi_4btoul(cdb->length);
9300         /*
9301          * The initiator has to allocate at least 16 bytes for this request,
9302          * so he can at least get the header and the first LUN.  Otherwise
9303          * we reject the request (per SPC-3 rev 14, section 6.21).
9304          */
9305         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9306             sizeof(struct scsi_report_luns_lundata))) {
9307                 ctl_set_invalid_field(ctsio,
9308                                       /*sks_valid*/ 1,
9309                                       /*command*/ 1,
9310                                       /*field*/ 6,
9311                                       /*bit_valid*/ 0,
9312                                       /*bit*/ 0);
9313                 ctl_done((union ctl_io *)ctsio);
9314                 return (retval);
9315         }
9316
9317         request_lun = (struct ctl_lun *)
9318                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9319
9320         lun_datalen = sizeof(*lun_data) +
9321                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9322
9323         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9324         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9325         ctsio->kern_sg_entries = 0;
9326
9327         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9328
9329         mtx_lock(&softc->ctl_lock);
9330         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9331                 lun_id = ctl_map_lun(softc, ctsio->io_hdr.nexus.targ_port,
9332                     targ_lun_id);
9333                 if (lun_id >= CTL_MAX_LUNS)
9334                         continue;
9335                 lun = softc->ctl_luns[lun_id];
9336                 if (lun == NULL)
9337                         continue;
9338
9339                 if (targ_lun_id <= 0xff) {
9340                         /*
9341                          * Peripheral addressing method, bus number 0.
9342                          */
9343                         lun_data->luns[num_filled].lundata[0] =
9344                                 RPL_LUNDATA_ATYP_PERIPH;
9345                         lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9346                         num_filled++;
9347                 } else if (targ_lun_id <= 0x3fff) {
9348                         /*
9349                          * Flat addressing method.
9350                          */
9351                         lun_data->luns[num_filled].lundata[0] =
9352                                 RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9353                         lun_data->luns[num_filled].lundata[1] =
9354                                 (targ_lun_id & 0xff);
9355                         num_filled++;
9356                 } else if (targ_lun_id <= 0xffffff) {
9357                         /*
9358                          * Extended flat addressing method.
9359                          */
9360                         lun_data->luns[num_filled].lundata[0] =
9361                             RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9362                         scsi_ulto3b(targ_lun_id,
9363                             &lun_data->luns[num_filled].lundata[1]);
9364                         num_filled++;
9365                 } else {
9366                         printf("ctl_report_luns: bogus LUN number %jd, "
9367                                "skipping\n", (intmax_t)targ_lun_id);
9368                 }
9369                 /*
9370                  * According to SPC-3, rev 14 section 6.21:
9371                  *
9372                  * "The execution of a REPORT LUNS command to any valid and
9373                  * installed logical unit shall clear the REPORTED LUNS DATA
9374                  * HAS CHANGED unit attention condition for all logical
9375                  * units of that target with respect to the requesting
9376                  * initiator. A valid and installed logical unit is one
9377                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9378                  * INQUIRY data (see 6.4.2)."
9379                  *
9380                  * If request_lun is NULL, the LUN this report luns command
9381                  * was issued to is either disabled or doesn't exist. In that
9382                  * case, we shouldn't clear any pending lun change unit
9383                  * attention.
9384                  */
9385                 if (request_lun != NULL) {
9386                         mtx_lock(&lun->lun_lock);
9387                         ctl_clr_ua(lun, initidx, CTL_UA_RES_RELEASE);
9388                         mtx_unlock(&lun->lun_lock);
9389                 }
9390         }
9391         mtx_unlock(&softc->ctl_lock);
9392
9393         /*
9394          * It's quite possible that we've returned fewer LUNs than we allocated
9395          * space for.  Trim it.
9396          */
9397         lun_datalen = sizeof(*lun_data) +
9398                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9399
9400         if (lun_datalen < alloc_len) {
9401                 ctsio->residual = alloc_len - lun_datalen;
9402                 ctsio->kern_data_len = lun_datalen;
9403                 ctsio->kern_total_len = lun_datalen;
9404         } else {
9405                 ctsio->residual = 0;
9406                 ctsio->kern_data_len = alloc_len;
9407                 ctsio->kern_total_len = alloc_len;
9408         }
9409         ctsio->kern_data_resid = 0;
9410         ctsio->kern_rel_offset = 0;
9411         ctsio->kern_sg_entries = 0;
9412
9413         /*
9414          * We set this to the actual data length, regardless of how much
9415          * space we actually have to return results.  If the user looks at
9416          * this value, he'll know whether or not he allocated enough space
9417          * and reissue the command if necessary.  We don't support well
9418          * known logical units, so if the user asks for that, return none.
9419          */
9420         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9421
9422         /*
9423          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9424          * this request.
9425          */
9426         ctl_set_success(ctsio);
9427         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9428         ctsio->be_move_done = ctl_config_move_done;
9429         ctl_datamove((union ctl_io *)ctsio);
9430         return (retval);
9431 }
9432
9433 int
9434 ctl_request_sense(struct ctl_scsiio *ctsio)
9435 {
9436         struct scsi_request_sense *cdb;
9437         struct scsi_sense_data *sense_ptr;
9438         struct ctl_lun *lun;
9439         uint32_t initidx;
9440         int have_error;
9441         scsi_sense_data_type sense_format;
9442         ctl_ua_type ua_type;
9443
9444         cdb = (struct scsi_request_sense *)ctsio->cdb;
9445
9446         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9447
9448         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9449
9450         /*
9451          * Determine which sense format the user wants.
9452          */
9453         if (cdb->byte2 & SRS_DESC)
9454                 sense_format = SSD_TYPE_DESC;
9455         else
9456                 sense_format = SSD_TYPE_FIXED;
9457
9458         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9459         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9460         ctsio->kern_sg_entries = 0;
9461
9462         /*
9463          * struct scsi_sense_data, which is currently set to 256 bytes, is
9464          * larger than the largest allowed value for the length field in the
9465          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9466          */
9467         ctsio->residual = 0;
9468         ctsio->kern_data_len = cdb->length;
9469         ctsio->kern_total_len = cdb->length;
9470
9471         ctsio->kern_data_resid = 0;
9472         ctsio->kern_rel_offset = 0;
9473         ctsio->kern_sg_entries = 0;
9474
9475         /*
9476          * If we don't have a LUN, we don't have any pending sense.
9477          */
9478         if (lun == NULL)
9479                 goto no_sense;
9480
9481         have_error = 0;
9482         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9483         /*
9484          * Check for pending sense, and then for pending unit attentions.
9485          * Pending sense gets returned first, then pending unit attentions.
9486          */
9487         mtx_lock(&lun->lun_lock);
9488 #ifdef CTL_WITH_CA
9489         if (ctl_is_set(lun->have_ca, initidx)) {
9490                 scsi_sense_data_type stored_format;
9491
9492                 /*
9493                  * Check to see which sense format was used for the stored
9494                  * sense data.
9495                  */
9496                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9497
9498                 /*
9499                  * If the user requested a different sense format than the
9500                  * one we stored, then we need to convert it to the other
9501                  * format.  If we're going from descriptor to fixed format
9502                  * sense data, we may lose things in translation, depending
9503                  * on what options were used.
9504                  *
9505                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9506                  * for some reason we'll just copy it out as-is.
9507                  */
9508                 if ((stored_format == SSD_TYPE_FIXED)
9509                  && (sense_format == SSD_TYPE_DESC))
9510                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9511                             &lun->pending_sense[initidx],
9512                             (struct scsi_sense_data_desc *)sense_ptr);
9513                 else if ((stored_format == SSD_TYPE_DESC)
9514                       && (sense_format == SSD_TYPE_FIXED))
9515                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9516                             &lun->pending_sense[initidx],
9517                             (struct scsi_sense_data_fixed *)sense_ptr);
9518                 else
9519                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9520                                ctl_min(sizeof(*sense_ptr),
9521                                sizeof(lun->pending_sense[initidx])));
9522
9523                 ctl_clear_mask(lun->have_ca, initidx);
9524                 have_error = 1;
9525         } else
9526 #endif
9527         {
9528                 ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9529                 if (ua_type != CTL_UA_NONE)
9530                         have_error = 1;
9531         }
9532         mtx_unlock(&lun->lun_lock);
9533
9534         /*
9535          * We already have a pending error, return it.
9536          */
9537         if (have_error != 0) {
9538                 /*
9539                  * We report the SCSI status as OK, since the status of the
9540                  * request sense command itself is OK.
9541                  * We report 0 for the sense length, because we aren't doing
9542                  * autosense in this case.  We're reporting sense as
9543                  * parameter data.
9544                  */
9545                 ctl_set_success(ctsio);
9546                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9547                 ctsio->be_move_done = ctl_config_move_done;
9548                 ctl_datamove((union ctl_io *)ctsio);
9549                 return (CTL_RETVAL_COMPLETE);
9550         }
9551
9552 no_sense:
9553
9554         /*
9555          * No sense information to report, so we report that everything is
9556          * okay.
9557          */
9558         ctl_set_sense_data(sense_ptr,
9559                            lun,
9560                            sense_format,
9561                            /*current_error*/ 1,
9562                            /*sense_key*/ SSD_KEY_NO_SENSE,
9563                            /*asc*/ 0x00,
9564                            /*ascq*/ 0x00,
9565                            SSD_ELEM_NONE);
9566
9567         /*
9568          * We report 0 for the sense length, because we aren't doing
9569          * autosense in this case.  We're reporting sense as parameter data.
9570          */
9571         ctl_set_success(ctsio);
9572         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9573         ctsio->be_move_done = ctl_config_move_done;
9574         ctl_datamove((union ctl_io *)ctsio);
9575         return (CTL_RETVAL_COMPLETE);
9576 }
9577
9578 int
9579 ctl_tur(struct ctl_scsiio *ctsio)
9580 {
9581
9582         CTL_DEBUG_PRINT(("ctl_tur\n"));
9583
9584         ctl_set_success(ctsio);
9585         ctl_done((union ctl_io *)ctsio);
9586
9587         return (CTL_RETVAL_COMPLETE);
9588 }
9589
9590 #ifdef notyet
9591 static int
9592 ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9593 {
9594
9595 }
9596 #endif
9597
9598 static int
9599 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9600 {
9601         struct scsi_vpd_supported_pages *pages;
9602         int sup_page_size;
9603         struct ctl_lun *lun;
9604
9605         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9606
9607         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9608             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9609         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9610         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9611         ctsio->kern_sg_entries = 0;
9612
9613         if (sup_page_size < alloc_len) {
9614                 ctsio->residual = alloc_len - sup_page_size;
9615                 ctsio->kern_data_len = sup_page_size;
9616                 ctsio->kern_total_len = sup_page_size;
9617         } else {
9618                 ctsio->residual = 0;
9619                 ctsio->kern_data_len = alloc_len;
9620                 ctsio->kern_total_len = alloc_len;
9621         }
9622         ctsio->kern_data_resid = 0;
9623         ctsio->kern_rel_offset = 0;
9624         ctsio->kern_sg_entries = 0;
9625
9626         /*
9627          * The control device is always connected.  The disk device, on the
9628          * other hand, may not be online all the time.  Need to change this
9629          * to figure out whether the disk device is actually online or not.
9630          */
9631         if (lun != NULL)
9632                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9633                                 lun->be_lun->lun_type;
9634         else
9635                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9636
9637         pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9638         /* Supported VPD pages */
9639         pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9640         /* Serial Number */
9641         pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9642         /* Device Identification */
9643         pages->page_list[2] = SVPD_DEVICE_ID;
9644         /* Extended INQUIRY Data */
9645         pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9646         /* Mode Page Policy */
9647         pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9648         /* SCSI Ports */
9649         pages->page_list[5] = SVPD_SCSI_PORTS;
9650         /* Third-party Copy */
9651         pages->page_list[6] = SVPD_SCSI_TPC;
9652         /* Block limits */
9653         pages->page_list[7] = SVPD_BLOCK_LIMITS;
9654         /* Block Device Characteristics */
9655         pages->page_list[8] = SVPD_BDC;
9656         /* Logical Block Provisioning */
9657         pages->page_list[9] = SVPD_LBP;
9658
9659         ctl_set_success(ctsio);
9660         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9661         ctsio->be_move_done = ctl_config_move_done;
9662         ctl_datamove((union ctl_io *)ctsio);
9663         return (CTL_RETVAL_COMPLETE);
9664 }
9665
9666 static int
9667 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9668 {
9669         struct scsi_vpd_unit_serial_number *sn_ptr;
9670         struct ctl_lun *lun;
9671         int data_len;
9672
9673         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9674
9675         data_len = 4 + CTL_SN_LEN;
9676         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9677         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9678         if (data_len < alloc_len) {
9679                 ctsio->residual = alloc_len - data_len;
9680                 ctsio->kern_data_len = data_len;
9681                 ctsio->kern_total_len = data_len;
9682         } else {
9683                 ctsio->residual = 0;
9684                 ctsio->kern_data_len = alloc_len;
9685                 ctsio->kern_total_len = alloc_len;
9686         }
9687         ctsio->kern_data_resid = 0;
9688         ctsio->kern_rel_offset = 0;
9689         ctsio->kern_sg_entries = 0;
9690
9691         /*
9692          * The control device is always connected.  The disk device, on the
9693          * other hand, may not be online all the time.  Need to change this
9694          * to figure out whether the disk device is actually online or not.
9695          */
9696         if (lun != NULL)
9697                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9698                                   lun->be_lun->lun_type;
9699         else
9700                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9701
9702         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9703         sn_ptr->length = CTL_SN_LEN;
9704         /*
9705          * If we don't have a LUN, we just leave the serial number as
9706          * all spaces.
9707          */
9708         if (lun != NULL) {
9709                 strncpy((char *)sn_ptr->serial_num,
9710                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9711         } else
9712                 memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9713
9714         ctl_set_success(ctsio);
9715         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9716         ctsio->be_move_done = ctl_config_move_done;
9717         ctl_datamove((union ctl_io *)ctsio);
9718         return (CTL_RETVAL_COMPLETE);
9719 }
9720
9721
9722 static int
9723 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9724 {
9725         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9726         struct ctl_lun *lun;
9727         int data_len;
9728
9729         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9730
9731         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9732         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9733         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9734         ctsio->kern_sg_entries = 0;
9735
9736         if (data_len < alloc_len) {
9737                 ctsio->residual = alloc_len - data_len;
9738                 ctsio->kern_data_len = data_len;
9739                 ctsio->kern_total_len = data_len;
9740         } else {
9741                 ctsio->residual = 0;
9742                 ctsio->kern_data_len = alloc_len;
9743                 ctsio->kern_total_len = alloc_len;
9744         }
9745         ctsio->kern_data_resid = 0;
9746         ctsio->kern_rel_offset = 0;
9747         ctsio->kern_sg_entries = 0;
9748
9749         /*
9750          * The control device is always connected.  The disk device, on the
9751          * other hand, may not be online all the time.
9752          */
9753         if (lun != NULL)
9754                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9755                                      lun->be_lun->lun_type;
9756         else
9757                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9758         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9759         eid_ptr->page_length = data_len - 4;
9760         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9761         eid_ptr->flags3 = SVPD_EID_V_SUP;
9762
9763         ctl_set_success(ctsio);
9764         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9765         ctsio->be_move_done = ctl_config_move_done;
9766         ctl_datamove((union ctl_io *)ctsio);
9767         return (CTL_RETVAL_COMPLETE);
9768 }
9769
9770 static int
9771 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9772 {
9773         struct scsi_vpd_mode_page_policy *mpp_ptr;
9774         struct ctl_lun *lun;
9775         int data_len;
9776
9777         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9778
9779         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9780             sizeof(struct scsi_vpd_mode_page_policy_descr);
9781
9782         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9783         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9784         ctsio->kern_sg_entries = 0;
9785
9786         if (data_len < alloc_len) {
9787                 ctsio->residual = alloc_len - data_len;
9788                 ctsio->kern_data_len = data_len;
9789                 ctsio->kern_total_len = data_len;
9790         } else {
9791                 ctsio->residual = 0;
9792                 ctsio->kern_data_len = alloc_len;
9793                 ctsio->kern_total_len = alloc_len;
9794         }
9795         ctsio->kern_data_resid = 0;
9796         ctsio->kern_rel_offset = 0;
9797         ctsio->kern_sg_entries = 0;
9798
9799         /*
9800          * The control device is always connected.  The disk device, on the
9801          * other hand, may not be online all the time.
9802          */
9803         if (lun != NULL)
9804                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9805                                      lun->be_lun->lun_type;
9806         else
9807                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9808         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9809         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9810         mpp_ptr->descr[0].page_code = 0x3f;
9811         mpp_ptr->descr[0].subpage_code = 0xff;
9812         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9813
9814         ctl_set_success(ctsio);
9815         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9816         ctsio->be_move_done = ctl_config_move_done;
9817         ctl_datamove((union ctl_io *)ctsio);
9818         return (CTL_RETVAL_COMPLETE);
9819 }
9820
9821 static int
9822 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9823 {
9824         struct scsi_vpd_device_id *devid_ptr;
9825         struct scsi_vpd_id_descriptor *desc;
9826         struct ctl_softc *softc;
9827         struct ctl_lun *lun;
9828         struct ctl_port *port;
9829         int data_len;
9830         uint8_t proto;
9831
9832         softc = control_softc;
9833
9834         port = softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9835         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9836
9837         data_len = sizeof(struct scsi_vpd_device_id) +
9838             sizeof(struct scsi_vpd_id_descriptor) +
9839                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9840             sizeof(struct scsi_vpd_id_descriptor) +
9841                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9842         if (lun && lun->lun_devid)
9843                 data_len += lun->lun_devid->len;
9844         if (port->port_devid)
9845                 data_len += port->port_devid->len;
9846         if (port->target_devid)
9847                 data_len += port->target_devid->len;
9848
9849         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9850         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9851         ctsio->kern_sg_entries = 0;
9852
9853         if (data_len < alloc_len) {
9854                 ctsio->residual = alloc_len - data_len;
9855                 ctsio->kern_data_len = data_len;
9856                 ctsio->kern_total_len = data_len;
9857         } else {
9858                 ctsio->residual = 0;
9859                 ctsio->kern_data_len = alloc_len;
9860                 ctsio->kern_total_len = alloc_len;
9861         }
9862         ctsio->kern_data_resid = 0;
9863         ctsio->kern_rel_offset = 0;
9864         ctsio->kern_sg_entries = 0;
9865
9866         /*
9867          * The control device is always connected.  The disk device, on the
9868          * other hand, may not be online all the time.
9869          */
9870         if (lun != NULL)
9871                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9872                                      lun->be_lun->lun_type;
9873         else
9874                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9875         devid_ptr->page_code = SVPD_DEVICE_ID;
9876         scsi_ulto2b(data_len - 4, devid_ptr->length);
9877
9878         if (port->port_type == CTL_PORT_FC)
9879                 proto = SCSI_PROTO_FC << 4;
9880         else if (port->port_type == CTL_PORT_ISCSI)
9881                 proto = SCSI_PROTO_ISCSI << 4;
9882         else
9883                 proto = SCSI_PROTO_SPI << 4;
9884         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9885
9886         /*
9887          * We're using a LUN association here.  i.e., this device ID is a
9888          * per-LUN identifier.
9889          */
9890         if (lun && lun->lun_devid) {
9891                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9892                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9893                     lun->lun_devid->len);
9894         }
9895
9896         /*
9897          * This is for the WWPN which is a port association.
9898          */
9899         if (port->port_devid) {
9900                 memcpy(desc, port->port_devid->data, port->port_devid->len);
9901                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9902                     port->port_devid->len);
9903         }
9904
9905         /*
9906          * This is for the Relative Target Port(type 4h) identifier
9907          */
9908         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9909         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9910             SVPD_ID_TYPE_RELTARG;
9911         desc->length = 4;
9912         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9913         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9914             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9915
9916         /*
9917          * This is for the Target Port Group(type 5h) identifier
9918          */
9919         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9920         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9921             SVPD_ID_TYPE_TPORTGRP;
9922         desc->length = 4;
9923         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
9924             &desc->identifier[2]);
9925         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9926             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9927
9928         /*
9929          * This is for the Target identifier
9930          */
9931         if (port->target_devid) {
9932                 memcpy(desc, port->target_devid->data, port->target_devid->len);
9933         }
9934
9935         ctl_set_success(ctsio);
9936         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9937         ctsio->be_move_done = ctl_config_move_done;
9938         ctl_datamove((union ctl_io *)ctsio);
9939         return (CTL_RETVAL_COMPLETE);
9940 }
9941
9942 static int
9943 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9944 {
9945         struct ctl_softc *softc = control_softc;
9946         struct scsi_vpd_scsi_ports *sp;
9947         struct scsi_vpd_port_designation *pd;
9948         struct scsi_vpd_port_designation_cont *pdc;
9949         struct ctl_lun *lun;
9950         struct ctl_port *port;
9951         int data_len, num_target_ports, iid_len, id_len, g, pg, p;
9952         int num_target_port_groups;
9953
9954         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9955
9956         if (softc->is_single)
9957                 num_target_port_groups = 1;
9958         else
9959                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
9960         num_target_ports = 0;
9961         iid_len = 0;
9962         id_len = 0;
9963         mtx_lock(&softc->ctl_lock);
9964         STAILQ_FOREACH(port, &softc->port_list, links) {
9965                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9966                         continue;
9967                 if (lun != NULL &&
9968                     ctl_map_lun_back(softc, port->targ_port, lun->lun) >=
9969                     CTL_MAX_LUNS)
9970                         continue;
9971                 num_target_ports++;
9972                 if (port->init_devid)
9973                         iid_len += port->init_devid->len;
9974                 if (port->port_devid)
9975                         id_len += port->port_devid->len;
9976         }
9977         mtx_unlock(&softc->ctl_lock);
9978
9979         data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
9980             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9981              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9982         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9983         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9984         ctsio->kern_sg_entries = 0;
9985
9986         if (data_len < alloc_len) {
9987                 ctsio->residual = alloc_len - data_len;
9988                 ctsio->kern_data_len = data_len;
9989                 ctsio->kern_total_len = data_len;
9990         } else {
9991                 ctsio->residual = 0;
9992                 ctsio->kern_data_len = alloc_len;
9993                 ctsio->kern_total_len = alloc_len;
9994         }
9995         ctsio->kern_data_resid = 0;
9996         ctsio->kern_rel_offset = 0;
9997         ctsio->kern_sg_entries = 0;
9998
9999         /*
10000          * The control device is always connected.  The disk device, on the
10001          * other hand, may not be online all the time.  Need to change this
10002          * to figure out whether the disk device is actually online or not.
10003          */
10004         if (lun != NULL)
10005                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10006                                   lun->be_lun->lun_type;
10007         else
10008                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10009
10010         sp->page_code = SVPD_SCSI_PORTS;
10011         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10012             sp->page_length);
10013         pd = &sp->design[0];
10014
10015         mtx_lock(&softc->ctl_lock);
10016         pg = softc->port_offset / CTL_MAX_PORTS;
10017         for (g = 0; g < num_target_port_groups; g++) {
10018                 STAILQ_FOREACH(port, &softc->port_list, links) {
10019                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10020                                 continue;
10021                         if (lun != NULL &&
10022                             ctl_map_lun_back(softc, port->targ_port, lun->lun)
10023                             >= CTL_MAX_LUNS)
10024                                 continue;
10025                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10026                         scsi_ulto2b(p, pd->relative_port_id);
10027                         if (port->init_devid && g == pg) {
10028                                 iid_len = port->init_devid->len;
10029                                 memcpy(pd->initiator_transportid,
10030                                     port->init_devid->data, port->init_devid->len);
10031                         } else
10032                                 iid_len = 0;
10033                         scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10034                         pdc = (struct scsi_vpd_port_designation_cont *)
10035                             (&pd->initiator_transportid[iid_len]);
10036                         if (port->port_devid && g == pg) {
10037                                 id_len = port->port_devid->len;
10038                                 memcpy(pdc->target_port_descriptors,
10039                                     port->port_devid->data, port->port_devid->len);
10040                         } else
10041                                 id_len = 0;
10042                         scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10043                         pd = (struct scsi_vpd_port_designation *)
10044                             ((uint8_t *)pdc->target_port_descriptors + id_len);
10045                 }
10046         }
10047         mtx_unlock(&softc->ctl_lock);
10048
10049         ctl_set_success(ctsio);
10050         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10051         ctsio->be_move_done = ctl_config_move_done;
10052         ctl_datamove((union ctl_io *)ctsio);
10053         return (CTL_RETVAL_COMPLETE);
10054 }
10055
10056 static int
10057 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10058 {
10059         struct scsi_vpd_block_limits *bl_ptr;
10060         struct ctl_lun *lun;
10061         int bs;
10062
10063         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10064
10065         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10066         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10067         ctsio->kern_sg_entries = 0;
10068
10069         if (sizeof(*bl_ptr) < alloc_len) {
10070                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
10071                 ctsio->kern_data_len = sizeof(*bl_ptr);
10072                 ctsio->kern_total_len = sizeof(*bl_ptr);
10073         } else {
10074                 ctsio->residual = 0;
10075                 ctsio->kern_data_len = alloc_len;
10076                 ctsio->kern_total_len = alloc_len;
10077         }
10078         ctsio->kern_data_resid = 0;
10079         ctsio->kern_rel_offset = 0;
10080         ctsio->kern_sg_entries = 0;
10081
10082         /*
10083          * The control device is always connected.  The disk device, on the
10084          * other hand, may not be online all the time.  Need to change this
10085          * to figure out whether the disk device is actually online or not.
10086          */
10087         if (lun != NULL)
10088                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10089                                   lun->be_lun->lun_type;
10090         else
10091                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10092
10093         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10094         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10095         bl_ptr->max_cmp_write_len = 0xff;
10096         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10097         if (lun != NULL) {
10098                 bs = lun->be_lun->blocksize;
10099                 scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
10100                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10101                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10102                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10103                         if (lun->be_lun->ublockexp != 0) {
10104                                 scsi_ulto4b((1 << lun->be_lun->ublockexp),
10105                                     bl_ptr->opt_unmap_grain);
10106                                 scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
10107                                     bl_ptr->unmap_grain_align);
10108                         }
10109                 }
10110                 scsi_ulto4b(lun->be_lun->atomicblock,
10111                     bl_ptr->max_atomic_transfer_length);
10112                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
10113                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10114         }
10115         scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10116
10117         ctl_set_success(ctsio);
10118         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10119         ctsio->be_move_done = ctl_config_move_done;
10120         ctl_datamove((union ctl_io *)ctsio);
10121         return (CTL_RETVAL_COMPLETE);
10122 }
10123
10124 static int
10125 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10126 {
10127         struct scsi_vpd_block_device_characteristics *bdc_ptr;
10128         struct ctl_lun *lun;
10129         const char *value;
10130         u_int i;
10131
10132         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10133
10134         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10135         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10136         ctsio->kern_sg_entries = 0;
10137
10138         if (sizeof(*bdc_ptr) < alloc_len) {
10139                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10140                 ctsio->kern_data_len = sizeof(*bdc_ptr);
10141                 ctsio->kern_total_len = sizeof(*bdc_ptr);
10142         } else {
10143                 ctsio->residual = 0;
10144                 ctsio->kern_data_len = alloc_len;
10145                 ctsio->kern_total_len = alloc_len;
10146         }
10147         ctsio->kern_data_resid = 0;
10148         ctsio->kern_rel_offset = 0;
10149         ctsio->kern_sg_entries = 0;
10150
10151         /*
10152          * The control device is always connected.  The disk device, on the
10153          * other hand, may not be online all the time.  Need to change this
10154          * to figure out whether the disk device is actually online or not.
10155          */
10156         if (lun != NULL)
10157                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10158                                   lun->be_lun->lun_type;
10159         else
10160                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10161         bdc_ptr->page_code = SVPD_BDC;
10162         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10163         if (lun != NULL &&
10164             (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10165                 i = strtol(value, NULL, 0);
10166         else
10167                 i = CTL_DEFAULT_ROTATION_RATE;
10168         scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10169         if (lun != NULL &&
10170             (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10171                 i = strtol(value, NULL, 0);
10172         else
10173                 i = 0;
10174         bdc_ptr->wab_wac_ff = (i & 0x0f);
10175         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10176
10177         ctl_set_success(ctsio);
10178         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10179         ctsio->be_move_done = ctl_config_move_done;
10180         ctl_datamove((union ctl_io *)ctsio);
10181         return (CTL_RETVAL_COMPLETE);
10182 }
10183
10184 static int
10185 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10186 {
10187         struct scsi_vpd_logical_block_prov *lbp_ptr;
10188         struct ctl_lun *lun;
10189
10190         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10191
10192         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10193         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10194         ctsio->kern_sg_entries = 0;
10195
10196         if (sizeof(*lbp_ptr) < alloc_len) {
10197                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10198                 ctsio->kern_data_len = sizeof(*lbp_ptr);
10199                 ctsio->kern_total_len = sizeof(*lbp_ptr);
10200         } else {
10201                 ctsio->residual = 0;
10202                 ctsio->kern_data_len = alloc_len;
10203                 ctsio->kern_total_len = alloc_len;
10204         }
10205         ctsio->kern_data_resid = 0;
10206         ctsio->kern_rel_offset = 0;
10207         ctsio->kern_sg_entries = 0;
10208
10209         /*
10210          * The control device is always connected.  The disk device, on the
10211          * other hand, may not be online all the time.  Need to change this
10212          * to figure out whether the disk device is actually online or not.
10213          */
10214         if (lun != NULL)
10215                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10216                                   lun->be_lun->lun_type;
10217         else
10218                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10219
10220         lbp_ptr->page_code = SVPD_LBP;
10221         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10222         lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10223         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10224                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10225                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10226                 lbp_ptr->prov_type = SVPD_LBP_THIN;
10227         }
10228
10229         ctl_set_success(ctsio);
10230         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10231         ctsio->be_move_done = ctl_config_move_done;
10232         ctl_datamove((union ctl_io *)ctsio);
10233         return (CTL_RETVAL_COMPLETE);
10234 }
10235
10236 static int
10237 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10238 {
10239         struct scsi_inquiry *cdb;
10240         int alloc_len, retval;
10241
10242         cdb = (struct scsi_inquiry *)ctsio->cdb;
10243
10244         retval = CTL_RETVAL_COMPLETE;
10245
10246         alloc_len = scsi_2btoul(cdb->length);
10247
10248         switch (cdb->page_code) {
10249         case SVPD_SUPPORTED_PAGES:
10250                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10251                 break;
10252         case SVPD_UNIT_SERIAL_NUMBER:
10253                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10254                 break;
10255         case SVPD_DEVICE_ID:
10256                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10257                 break;
10258         case SVPD_EXTENDED_INQUIRY_DATA:
10259                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10260                 break;
10261         case SVPD_MODE_PAGE_POLICY:
10262                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10263                 break;
10264         case SVPD_SCSI_PORTS:
10265                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10266                 break;
10267         case SVPD_SCSI_TPC:
10268                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10269                 break;
10270         case SVPD_BLOCK_LIMITS:
10271                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10272                 break;
10273         case SVPD_BDC:
10274                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10275                 break;
10276         case SVPD_LBP:
10277                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10278                 break;
10279         default:
10280                 ctl_set_invalid_field(ctsio,
10281                                       /*sks_valid*/ 1,
10282                                       /*command*/ 1,
10283                                       /*field*/ 2,
10284                                       /*bit_valid*/ 0,
10285                                       /*bit*/ 0);
10286                 ctl_done((union ctl_io *)ctsio);
10287                 retval = CTL_RETVAL_COMPLETE;
10288                 break;
10289         }
10290
10291         return (retval);
10292 }
10293
10294 static int
10295 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10296 {
10297         struct scsi_inquiry_data *inq_ptr;
10298         struct scsi_inquiry *cdb;
10299         struct ctl_softc *softc;
10300         struct ctl_lun *lun;
10301         char *val;
10302         uint32_t alloc_len, data_len;
10303         ctl_port_type port_type;
10304
10305         softc = control_softc;
10306
10307         /*
10308          * Figure out whether we're talking to a Fibre Channel port or not.
10309          * We treat the ioctl front end, and any SCSI adapters, as packetized
10310          * SCSI front ends.
10311          */
10312         port_type = softc->ctl_ports[
10313             ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10314         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10315                 port_type = CTL_PORT_SCSI;
10316
10317         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10318         cdb = (struct scsi_inquiry *)ctsio->cdb;
10319         alloc_len = scsi_2btoul(cdb->length);
10320
10321         /*
10322          * We malloc the full inquiry data size here and fill it
10323          * in.  If the user only asks for less, we'll give him
10324          * that much.
10325          */
10326         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10327         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10328         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10329         ctsio->kern_sg_entries = 0;
10330         ctsio->kern_data_resid = 0;
10331         ctsio->kern_rel_offset = 0;
10332
10333         if (data_len < alloc_len) {
10334                 ctsio->residual = alloc_len - data_len;
10335                 ctsio->kern_data_len = data_len;
10336                 ctsio->kern_total_len = data_len;
10337         } else {
10338                 ctsio->residual = 0;
10339                 ctsio->kern_data_len = alloc_len;
10340                 ctsio->kern_total_len = alloc_len;
10341         }
10342
10343         /*
10344          * If we have a LUN configured, report it as connected.  Otherwise,
10345          * report that it is offline or no device is supported, depending 
10346          * on the value of inquiry_pq_no_lun.
10347          *
10348          * According to the spec (SPC-4 r34), the peripheral qualifier
10349          * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10350          *
10351          * "A peripheral device having the specified peripheral device type 
10352          * is not connected to this logical unit. However, the device
10353          * server is capable of supporting the specified peripheral device
10354          * type on this logical unit."
10355          *
10356          * According to the same spec, the peripheral qualifier
10357          * SID_QUAL_BAD_LU (011b) is used in this scenario:
10358          *
10359          * "The device server is not capable of supporting a peripheral
10360          * device on this logical unit. For this peripheral qualifier the
10361          * peripheral device type shall be set to 1Fh. All other peripheral
10362          * device type values are reserved for this peripheral qualifier."
10363          *
10364          * Given the text, it would seem that we probably want to report that
10365          * the LUN is offline here.  There is no LUN connected, but we can
10366          * support a LUN at the given LUN number.
10367          *
10368          * In the real world, though, it sounds like things are a little
10369          * different:
10370          *
10371          * - Linux, when presented with a LUN with the offline peripheral
10372          *   qualifier, will create an sg driver instance for it.  So when
10373          *   you attach it to CTL, you wind up with a ton of sg driver
10374          *   instances.  (One for every LUN that Linux bothered to probe.)
10375          *   Linux does this despite the fact that it issues a REPORT LUNs
10376          *   to LUN 0 to get the inventory of supported LUNs.
10377          *
10378          * - There is other anecdotal evidence (from Emulex folks) about
10379          *   arrays that use the offline peripheral qualifier for LUNs that
10380          *   are on the "passive" path in an active/passive array.
10381          *
10382          * So the solution is provide a hopefully reasonable default
10383          * (return bad/no LUN) and allow the user to change the behavior
10384          * with a tunable/sysctl variable.
10385          */
10386         if (lun != NULL)
10387                 inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10388                                   lun->be_lun->lun_type;
10389         else if (softc->inquiry_pq_no_lun == 0)
10390                 inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10391         else
10392                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10393
10394         /* RMB in byte 2 is 0 */
10395         inq_ptr->version = SCSI_REV_SPC4;
10396
10397         /*
10398          * According to SAM-3, even if a device only supports a single
10399          * level of LUN addressing, it should still set the HISUP bit:
10400          *
10401          * 4.9.1 Logical unit numbers overview
10402          *
10403          * All logical unit number formats described in this standard are
10404          * hierarchical in structure even when only a single level in that
10405          * hierarchy is used. The HISUP bit shall be set to one in the
10406          * standard INQUIRY data (see SPC-2) when any logical unit number
10407          * format described in this standard is used.  Non-hierarchical
10408          * formats are outside the scope of this standard.
10409          *
10410          * Therefore we set the HiSup bit here.
10411          *
10412          * The reponse format is 2, per SPC-3.
10413          */
10414         inq_ptr->response_format = SID_HiSup | 2;
10415
10416         inq_ptr->additional_length = data_len -
10417             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10418         CTL_DEBUG_PRINT(("additional_length = %d\n",
10419                          inq_ptr->additional_length));
10420
10421         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10422         /* 16 bit addressing */
10423         if (port_type == CTL_PORT_SCSI)
10424                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10425         /* XXX set the SID_MultiP bit here if we're actually going to
10426            respond on multiple ports */
10427         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10428
10429         /* 16 bit data bus, synchronous transfers */
10430         if (port_type == CTL_PORT_SCSI)
10431                 inq_ptr->flags = SID_WBus16 | SID_Sync;
10432         /*
10433          * XXX KDM do we want to support tagged queueing on the control
10434          * device at all?
10435          */
10436         if ((lun == NULL)
10437          || (lun->be_lun->lun_type != T_PROCESSOR))
10438                 inq_ptr->flags |= SID_CmdQue;
10439         /*
10440          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10441          * We have 8 bytes for the vendor name, and 16 bytes for the device
10442          * name and 4 bytes for the revision.
10443          */
10444         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10445             "vendor")) == NULL) {
10446                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10447         } else {
10448                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10449                 strncpy(inq_ptr->vendor, val,
10450                     min(sizeof(inq_ptr->vendor), strlen(val)));
10451         }
10452         if (lun == NULL) {
10453                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10454                     sizeof(inq_ptr->product));
10455         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10456                 switch (lun->be_lun->lun_type) {
10457                 case T_DIRECT:
10458                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10459                             sizeof(inq_ptr->product));
10460                         break;
10461                 case T_PROCESSOR:
10462                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10463                             sizeof(inq_ptr->product));
10464                         break;
10465                 default:
10466                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10467                             sizeof(inq_ptr->product));
10468                         break;
10469                 }
10470         } else {
10471                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10472                 strncpy(inq_ptr->product, val,
10473                     min(sizeof(inq_ptr->product), strlen(val)));
10474         }
10475
10476         /*
10477          * XXX make this a macro somewhere so it automatically gets
10478          * incremented when we make changes.
10479          */
10480         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10481             "revision")) == NULL) {
10482                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10483         } else {
10484                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10485                 strncpy(inq_ptr->revision, val,
10486                     min(sizeof(inq_ptr->revision), strlen(val)));
10487         }
10488
10489         /*
10490          * For parallel SCSI, we support double transition and single
10491          * transition clocking.  We also support QAS (Quick Arbitration
10492          * and Selection) and Information Unit transfers on both the
10493          * control and array devices.
10494          */
10495         if (port_type == CTL_PORT_SCSI)
10496                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10497                                     SID_SPI_IUS;
10498
10499         /* SAM-5 (no version claimed) */
10500         scsi_ulto2b(0x00A0, inq_ptr->version1);
10501         /* SPC-4 (no version claimed) */
10502         scsi_ulto2b(0x0460, inq_ptr->version2);
10503         if (port_type == CTL_PORT_FC) {
10504                 /* FCP-2 ANSI INCITS.350:2003 */
10505                 scsi_ulto2b(0x0917, inq_ptr->version3);
10506         } else if (port_type == CTL_PORT_SCSI) {
10507                 /* SPI-4 ANSI INCITS.362:200x */
10508                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10509         } else if (port_type == CTL_PORT_ISCSI) {
10510                 /* iSCSI (no version claimed) */
10511                 scsi_ulto2b(0x0960, inq_ptr->version3);
10512         } else if (port_type == CTL_PORT_SAS) {
10513                 /* SAS (no version claimed) */
10514                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10515         }
10516
10517         if (lun == NULL) {
10518                 /* SBC-4 (no version claimed) */
10519                 scsi_ulto2b(0x0600, inq_ptr->version4);
10520         } else {
10521                 switch (lun->be_lun->lun_type) {
10522                 case T_DIRECT:
10523                         /* SBC-4 (no version claimed) */
10524                         scsi_ulto2b(0x0600, inq_ptr->version4);
10525                         break;
10526                 case T_PROCESSOR:
10527                 default:
10528                         break;
10529                 }
10530         }
10531
10532         ctl_set_success(ctsio);
10533         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10534         ctsio->be_move_done = ctl_config_move_done;
10535         ctl_datamove((union ctl_io *)ctsio);
10536         return (CTL_RETVAL_COMPLETE);
10537 }
10538
10539 int
10540 ctl_inquiry(struct ctl_scsiio *ctsio)
10541 {
10542         struct scsi_inquiry *cdb;
10543         int retval;
10544
10545         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10546
10547         cdb = (struct scsi_inquiry *)ctsio->cdb;
10548         if (cdb->byte2 & SI_EVPD)
10549                 retval = ctl_inquiry_evpd(ctsio);
10550         else if (cdb->page_code == 0)
10551                 retval = ctl_inquiry_std(ctsio);
10552         else {
10553                 ctl_set_invalid_field(ctsio,
10554                                       /*sks_valid*/ 1,
10555                                       /*command*/ 1,
10556                                       /*field*/ 2,
10557                                       /*bit_valid*/ 0,
10558                                       /*bit*/ 0);
10559                 ctl_done((union ctl_io *)ctsio);
10560                 return (CTL_RETVAL_COMPLETE);
10561         }
10562
10563         return (retval);
10564 }
10565
10566 /*
10567  * For known CDB types, parse the LBA and length.
10568  */
10569 static int
10570 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10571 {
10572         if (io->io_hdr.io_type != CTL_IO_SCSI)
10573                 return (1);
10574
10575         switch (io->scsiio.cdb[0]) {
10576         case COMPARE_AND_WRITE: {
10577                 struct scsi_compare_and_write *cdb;
10578
10579                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10580
10581                 *lba = scsi_8btou64(cdb->addr);
10582                 *len = cdb->length;
10583                 break;
10584         }
10585         case READ_6:
10586         case WRITE_6: {
10587                 struct scsi_rw_6 *cdb;
10588
10589                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10590
10591                 *lba = scsi_3btoul(cdb->addr);
10592                 /* only 5 bits are valid in the most significant address byte */
10593                 *lba &= 0x1fffff;
10594                 *len = cdb->length;
10595                 break;
10596         }
10597         case READ_10:
10598         case WRITE_10: {
10599                 struct scsi_rw_10 *cdb;
10600
10601                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10602
10603                 *lba = scsi_4btoul(cdb->addr);
10604                 *len = scsi_2btoul(cdb->length);
10605                 break;
10606         }
10607         case WRITE_VERIFY_10: {
10608                 struct scsi_write_verify_10 *cdb;
10609
10610                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10611
10612                 *lba = scsi_4btoul(cdb->addr);
10613                 *len = scsi_2btoul(cdb->length);
10614                 break;
10615         }
10616         case READ_12:
10617         case WRITE_12: {
10618                 struct scsi_rw_12 *cdb;
10619
10620                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10621
10622                 *lba = scsi_4btoul(cdb->addr);
10623                 *len = scsi_4btoul(cdb->length);
10624                 break;
10625         }
10626         case WRITE_VERIFY_12: {
10627                 struct scsi_write_verify_12 *cdb;
10628
10629                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10630
10631                 *lba = scsi_4btoul(cdb->addr);
10632                 *len = scsi_4btoul(cdb->length);
10633                 break;
10634         }
10635         case READ_16:
10636         case WRITE_16:
10637         case WRITE_ATOMIC_16: {
10638                 struct scsi_rw_16 *cdb;
10639
10640                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10641
10642                 *lba = scsi_8btou64(cdb->addr);
10643                 *len = scsi_4btoul(cdb->length);
10644                 break;
10645         }
10646         case WRITE_VERIFY_16: {
10647                 struct scsi_write_verify_16 *cdb;
10648
10649                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10650
10651                 *lba = scsi_8btou64(cdb->addr);
10652                 *len = scsi_4btoul(cdb->length);
10653                 break;
10654         }
10655         case WRITE_SAME_10: {
10656                 struct scsi_write_same_10 *cdb;
10657
10658                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10659
10660                 *lba = scsi_4btoul(cdb->addr);
10661                 *len = scsi_2btoul(cdb->length);
10662                 break;
10663         }
10664         case WRITE_SAME_16: {
10665                 struct scsi_write_same_16 *cdb;
10666
10667                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10668
10669                 *lba = scsi_8btou64(cdb->addr);
10670                 *len = scsi_4btoul(cdb->length);
10671                 break;
10672         }
10673         case VERIFY_10: {
10674                 struct scsi_verify_10 *cdb;
10675
10676                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10677
10678                 *lba = scsi_4btoul(cdb->addr);
10679                 *len = scsi_2btoul(cdb->length);
10680                 break;
10681         }
10682         case VERIFY_12: {
10683                 struct scsi_verify_12 *cdb;
10684
10685                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10686
10687                 *lba = scsi_4btoul(cdb->addr);
10688                 *len = scsi_4btoul(cdb->length);
10689                 break;
10690         }
10691         case VERIFY_16: {
10692                 struct scsi_verify_16 *cdb;
10693
10694                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10695
10696                 *lba = scsi_8btou64(cdb->addr);
10697                 *len = scsi_4btoul(cdb->length);
10698                 break;
10699         }
10700         case UNMAP: {
10701                 *lba = 0;
10702                 *len = UINT64_MAX;
10703                 break;
10704         }
10705         case SERVICE_ACTION_IN: {       /* GET LBA STATUS */
10706                 struct scsi_get_lba_status *cdb;
10707
10708                 cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10709                 *lba = scsi_8btou64(cdb->addr);
10710                 *len = UINT32_MAX;
10711                 break;
10712         }
10713         default:
10714                 return (1);
10715                 break; /* NOTREACHED */
10716         }
10717
10718         return (0);
10719 }
10720
10721 static ctl_action
10722 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10723     bool seq)
10724 {
10725         uint64_t endlba1, endlba2;
10726
10727         endlba1 = lba1 + len1 - (seq ? 0 : 1);
10728         endlba2 = lba2 + len2 - 1;
10729
10730         if ((endlba1 < lba2) || (endlba2 < lba1))
10731                 return (CTL_ACTION_PASS);
10732         else
10733                 return (CTL_ACTION_BLOCK);
10734 }
10735
10736 static int
10737 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10738 {
10739         struct ctl_ptr_len_flags *ptrlen;
10740         struct scsi_unmap_desc *buf, *end, *range;
10741         uint64_t lba;
10742         uint32_t len;
10743
10744         /* If not UNMAP -- go other way. */
10745         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10746             io->scsiio.cdb[0] != UNMAP)
10747                 return (CTL_ACTION_ERROR);
10748
10749         /* If UNMAP without data -- block and wait for data. */
10750         ptrlen = (struct ctl_ptr_len_flags *)
10751             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10752         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10753             ptrlen->ptr == NULL)
10754                 return (CTL_ACTION_BLOCK);
10755
10756         /* UNMAP with data -- check for collision. */
10757         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10758         end = buf + ptrlen->len / sizeof(*buf);
10759         for (range = buf; range < end; range++) {
10760                 lba = scsi_8btou64(range->lba);
10761                 len = scsi_4btoul(range->length);
10762                 if ((lba < lba2 + len2) && (lba + len > lba2))
10763                         return (CTL_ACTION_BLOCK);
10764         }
10765         return (CTL_ACTION_PASS);
10766 }
10767
10768 static ctl_action
10769 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10770 {
10771         uint64_t lba1, lba2;
10772         uint64_t len1, len2;
10773         int retval;
10774
10775         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10776                 return (CTL_ACTION_ERROR);
10777
10778         retval = ctl_extent_check_unmap(io1, lba2, len2);
10779         if (retval != CTL_ACTION_ERROR)
10780                 return (retval);
10781
10782         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10783                 return (CTL_ACTION_ERROR);
10784
10785         return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10786 }
10787
10788 static ctl_action
10789 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10790 {
10791         uint64_t lba1, lba2;
10792         uint64_t len1, len2;
10793
10794         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10795                 return (CTL_ACTION_ERROR);
10796         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10797                 return (CTL_ACTION_ERROR);
10798
10799         if (lba1 + len1 == lba2)
10800                 return (CTL_ACTION_BLOCK);
10801         return (CTL_ACTION_PASS);
10802 }
10803
10804 static ctl_action
10805 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10806     union ctl_io *ooa_io)
10807 {
10808         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10809         ctl_serialize_action *serialize_row;
10810
10811         /*
10812          * The initiator attempted multiple untagged commands at the same
10813          * time.  Can't do that.
10814          */
10815         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10816          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10817          && ((pending_io->io_hdr.nexus.targ_port ==
10818               ooa_io->io_hdr.nexus.targ_port)
10819           && (pending_io->io_hdr.nexus.initid.id ==
10820               ooa_io->io_hdr.nexus.initid.id))
10821          && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10822                 return (CTL_ACTION_OVERLAP);
10823
10824         /*
10825          * The initiator attempted to send multiple tagged commands with
10826          * the same ID.  (It's fine if different initiators have the same
10827          * tag ID.)
10828          *
10829          * Even if all of those conditions are true, we don't kill the I/O
10830          * if the command ahead of us has been aborted.  We won't end up
10831          * sending it to the FETD, and it's perfectly legal to resend a
10832          * command with the same tag number as long as the previous
10833          * instance of this tag number has been aborted somehow.
10834          */
10835         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10836          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10837          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10838          && ((pending_io->io_hdr.nexus.targ_port ==
10839               ooa_io->io_hdr.nexus.targ_port)
10840           && (pending_io->io_hdr.nexus.initid.id ==
10841               ooa_io->io_hdr.nexus.initid.id))
10842          && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10843                 return (CTL_ACTION_OVERLAP_TAG);
10844
10845         /*
10846          * If we get a head of queue tag, SAM-3 says that we should
10847          * immediately execute it.
10848          *
10849          * What happens if this command would normally block for some other
10850          * reason?  e.g. a request sense with a head of queue tag
10851          * immediately after a write.  Normally that would block, but this
10852          * will result in its getting executed immediately...
10853          *
10854          * We currently return "pass" instead of "skip", so we'll end up
10855          * going through the rest of the queue to check for overlapped tags.
10856          *
10857          * XXX KDM check for other types of blockage first??
10858          */
10859         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10860                 return (CTL_ACTION_PASS);
10861
10862         /*
10863          * Ordered tags have to block until all items ahead of them
10864          * have completed.  If we get called with an ordered tag, we always
10865          * block, if something else is ahead of us in the queue.
10866          */
10867         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10868                 return (CTL_ACTION_BLOCK);
10869
10870         /*
10871          * Simple tags get blocked until all head of queue and ordered tags
10872          * ahead of them have completed.  I'm lumping untagged commands in
10873          * with simple tags here.  XXX KDM is that the right thing to do?
10874          */
10875         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10876           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10877          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10878           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10879                 return (CTL_ACTION_BLOCK);
10880
10881         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10882         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10883
10884         serialize_row = ctl_serialize_table[ooa_entry->seridx];
10885
10886         switch (serialize_row[pending_entry->seridx]) {
10887         case CTL_SER_BLOCK:
10888                 return (CTL_ACTION_BLOCK);
10889         case CTL_SER_EXTENT:
10890                 return (ctl_extent_check(ooa_io, pending_io,
10891                     (lun->serseq == CTL_LUN_SERSEQ_ON)));
10892         case CTL_SER_EXTENTOPT:
10893                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10894                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10895                         return (ctl_extent_check(ooa_io, pending_io,
10896                             (lun->serseq == CTL_LUN_SERSEQ_ON)));
10897                 return (CTL_ACTION_PASS);
10898         case CTL_SER_EXTENTSEQ:
10899                 if (lun->serseq != CTL_LUN_SERSEQ_OFF)
10900                         return (ctl_extent_check_seq(ooa_io, pending_io));
10901                 return (CTL_ACTION_PASS);
10902         case CTL_SER_PASS:
10903                 return (CTL_ACTION_PASS);
10904         case CTL_SER_BLOCKOPT:
10905                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10906                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10907                         return (CTL_ACTION_BLOCK);
10908                 return (CTL_ACTION_PASS);
10909         case CTL_SER_SKIP:
10910                 return (CTL_ACTION_SKIP);
10911         default:
10912                 panic("invalid serialization value %d",
10913                       serialize_row[pending_entry->seridx]);
10914         }
10915
10916         return (CTL_ACTION_ERROR);
10917 }
10918
10919 /*
10920  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10921  * Assumptions:
10922  * - pending_io is generally either incoming, or on the blocked queue
10923  * - starting I/O is the I/O we want to start the check with.
10924  */
10925 static ctl_action
10926 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10927               union ctl_io *starting_io)
10928 {
10929         union ctl_io *ooa_io;
10930         ctl_action action;
10931
10932         mtx_assert(&lun->lun_lock, MA_OWNED);
10933
10934         /*
10935          * Run back along the OOA queue, starting with the current
10936          * blocked I/O and going through every I/O before it on the
10937          * queue.  If starting_io is NULL, we'll just end up returning
10938          * CTL_ACTION_PASS.
10939          */
10940         for (ooa_io = starting_io; ooa_io != NULL;
10941              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10942              ooa_links)){
10943
10944                 /*
10945                  * This routine just checks to see whether
10946                  * cur_blocked is blocked by ooa_io, which is ahead
10947                  * of it in the queue.  It doesn't queue/dequeue
10948                  * cur_blocked.
10949                  */
10950                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10951                 switch (action) {
10952                 case CTL_ACTION_BLOCK:
10953                 case CTL_ACTION_OVERLAP:
10954                 case CTL_ACTION_OVERLAP_TAG:
10955                 case CTL_ACTION_SKIP:
10956                 case CTL_ACTION_ERROR:
10957                         return (action);
10958                         break; /* NOTREACHED */
10959                 case CTL_ACTION_PASS:
10960                         break;
10961                 default:
10962                         panic("invalid action %d", action);
10963                         break;  /* NOTREACHED */
10964                 }
10965         }
10966
10967         return (CTL_ACTION_PASS);
10968 }
10969
10970 /*
10971  * Assumptions:
10972  * - An I/O has just completed, and has been removed from the per-LUN OOA
10973  *   queue, so some items on the blocked queue may now be unblocked.
10974  */
10975 static int
10976 ctl_check_blocked(struct ctl_lun *lun)
10977 {
10978         union ctl_io *cur_blocked, *next_blocked;
10979
10980         mtx_assert(&lun->lun_lock, MA_OWNED);
10981
10982         /*
10983          * Run forward from the head of the blocked queue, checking each
10984          * entry against the I/Os prior to it on the OOA queue to see if
10985          * there is still any blockage.
10986          *
10987          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10988          * with our removing a variable on it while it is traversing the
10989          * list.
10990          */
10991         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10992              cur_blocked != NULL; cur_blocked = next_blocked) {
10993                 union ctl_io *prev_ooa;
10994                 ctl_action action;
10995
10996                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10997                                                           blocked_links);
10998
10999                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11000                                                       ctl_ooaq, ooa_links);
11001
11002                 /*
11003                  * If cur_blocked happens to be the first item in the OOA
11004                  * queue now, prev_ooa will be NULL, and the action
11005                  * returned will just be CTL_ACTION_PASS.
11006                  */
11007                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11008
11009                 switch (action) {
11010                 case CTL_ACTION_BLOCK:
11011                         /* Nothing to do here, still blocked */
11012                         break;
11013                 case CTL_ACTION_OVERLAP:
11014                 case CTL_ACTION_OVERLAP_TAG:
11015                         /*
11016                          * This shouldn't happen!  In theory we've already
11017                          * checked this command for overlap...
11018                          */
11019                         break;
11020                 case CTL_ACTION_PASS:
11021                 case CTL_ACTION_SKIP: {
11022                         const struct ctl_cmd_entry *entry;
11023                         int isc_retval;
11024
11025                         /*
11026                          * The skip case shouldn't happen, this transaction
11027                          * should have never made it onto the blocked queue.
11028                          */
11029                         /*
11030                          * This I/O is no longer blocked, we can remove it
11031                          * from the blocked queue.  Since this is a TAILQ
11032                          * (doubly linked list), we can do O(1) removals
11033                          * from any place on the list.
11034                          */
11035                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11036                                      blocked_links);
11037                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11038
11039                         if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11040                                 /*
11041                                  * Need to send IO back to original side to
11042                                  * run
11043                                  */
11044                                 union ctl_ha_msg msg_info;
11045
11046                                 msg_info.hdr.original_sc =
11047                                         cur_blocked->io_hdr.original_sc;
11048                                 msg_info.hdr.serializing_sc = cur_blocked;
11049                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
11050                                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11051                                      &msg_info, sizeof(msg_info), 0)) >
11052                                      CTL_HA_STATUS_SUCCESS) {
11053                                         printf("CTL:Check Blocked error from "
11054                                                "ctl_ha_msg_send %d\n",
11055                                                isc_retval);
11056                                 }
11057                                 break;
11058                         }
11059                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11060
11061                         /*
11062                          * Check this I/O for LUN state changes that may
11063                          * have happened while this command was blocked.
11064                          * The LUN state may have been changed by a command
11065                          * ahead of us in the queue, so we need to re-check
11066                          * for any states that can be caused by SCSI
11067                          * commands.
11068                          */
11069                         if (ctl_scsiio_lun_check(lun, entry,
11070                                                  &cur_blocked->scsiio) == 0) {
11071                                 cur_blocked->io_hdr.flags |=
11072                                                       CTL_FLAG_IS_WAS_ON_RTR;
11073                                 ctl_enqueue_rtr(cur_blocked);
11074                         } else
11075                                 ctl_done(cur_blocked);
11076                         break;
11077                 }
11078                 default:
11079                         /*
11080                          * This probably shouldn't happen -- we shouldn't
11081                          * get CTL_ACTION_ERROR, or anything else.
11082                          */
11083                         break;
11084                 }
11085         }
11086
11087         return (CTL_RETVAL_COMPLETE);
11088 }
11089
11090 /*
11091  * This routine (with one exception) checks LUN flags that can be set by
11092  * commands ahead of us in the OOA queue.  These flags have to be checked
11093  * when a command initially comes in, and when we pull a command off the
11094  * blocked queue and are preparing to execute it.  The reason we have to
11095  * check these flags for commands on the blocked queue is that the LUN
11096  * state may have been changed by a command ahead of us while we're on the
11097  * blocked queue.
11098  *
11099  * Ordering is somewhat important with these checks, so please pay
11100  * careful attention to the placement of any new checks.
11101  */
11102 static int
11103 ctl_scsiio_lun_check(struct ctl_lun *lun,
11104     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11105 {
11106         struct ctl_softc *softc = lun->ctl_softc;
11107         int retval;
11108         uint32_t residx;
11109
11110         retval = 0;
11111
11112         mtx_assert(&lun->lun_lock, MA_OWNED);
11113
11114         /*
11115          * If this shelf is a secondary shelf controller, we have to reject
11116          * any media access commands.
11117          */
11118         if ((softc->flags & CTL_FLAG_ACTIVE_SHELF) == 0 &&
11119             (entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0) {
11120                 ctl_set_lun_standby(ctsio);
11121                 retval = 1;
11122                 goto bailout;
11123         }
11124
11125         if (entry->pattern & CTL_LUN_PAT_WRITE) {
11126                 if (lun->flags & CTL_LUN_READONLY) {
11127                         ctl_set_sense(ctsio, /*current_error*/ 1,
11128                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11129                             /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11130                         retval = 1;
11131                         goto bailout;
11132                 }
11133                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11134                     .eca_and_aen & SCP_SWP) != 0) {
11135                         ctl_set_sense(ctsio, /*current_error*/ 1,
11136                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11137                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11138                         retval = 1;
11139                         goto bailout;
11140                 }
11141         }
11142
11143         /*
11144          * Check for a reservation conflict.  If this command isn't allowed
11145          * even on reserved LUNs, and if this initiator isn't the one who
11146          * reserved us, reject the command with a reservation conflict.
11147          */
11148         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11149         if ((lun->flags & CTL_LUN_RESERVED)
11150          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11151                 if (lun->res_idx != residx) {
11152                         ctl_set_reservation_conflict(ctsio);
11153                         retval = 1;
11154                         goto bailout;
11155                 }
11156         }
11157
11158         if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11159             (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11160                 /* No reservation or command is allowed. */;
11161         } else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11162             (lun->res_type == SPR_TYPE_WR_EX ||
11163              lun->res_type == SPR_TYPE_WR_EX_RO ||
11164              lun->res_type == SPR_TYPE_WR_EX_AR)) {
11165                 /* The command is allowed for Write Exclusive resv. */;
11166         } else {
11167                 /*
11168                  * if we aren't registered or it's a res holder type
11169                  * reservation and this isn't the res holder then set a
11170                  * conflict.
11171                  */
11172                 if (ctl_get_prkey(lun, residx) == 0
11173                  || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11174                         ctl_set_reservation_conflict(ctsio);
11175                         retval = 1;
11176                         goto bailout;
11177                 }
11178
11179         }
11180
11181         if ((lun->flags & CTL_LUN_OFFLINE)
11182          && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11183                 ctl_set_lun_not_ready(ctsio);
11184                 retval = 1;
11185                 goto bailout;
11186         }
11187
11188         /*
11189          * If the LUN is stopped, see if this particular command is allowed
11190          * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11191          */
11192         if ((lun->flags & CTL_LUN_STOPPED)
11193          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11194                 /* "Logical unit not ready, initializing cmd. required" */
11195                 ctl_set_lun_stopped(ctsio);
11196                 retval = 1;
11197                 goto bailout;
11198         }
11199
11200         if ((lun->flags & CTL_LUN_INOPERABLE)
11201          && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11202                 /* "Medium format corrupted" */
11203                 ctl_set_medium_format_corrupted(ctsio);
11204                 retval = 1;
11205                 goto bailout;
11206         }
11207
11208 bailout:
11209         return (retval);
11210
11211 }
11212
11213 static void
11214 ctl_failover_io(union ctl_io *io, int have_lock)
11215 {
11216         ctl_set_busy(&io->scsiio);
11217         ctl_done(io);
11218 }
11219
11220 static void
11221 ctl_failover(void)
11222 {
11223         struct ctl_lun *lun;
11224         struct ctl_softc *softc;
11225         union ctl_io *next_io, *pending_io;
11226         union ctl_io *io;
11227         int lun_idx;
11228
11229         softc = control_softc;
11230
11231         mtx_lock(&softc->ctl_lock);
11232         /*
11233          * Remove any cmds from the other SC from the rtr queue.  These
11234          * will obviously only be for LUNs for which we're the primary.
11235          * We can't send status or get/send data for these commands.
11236          * Since they haven't been executed yet, we can just remove them.
11237          * We'll either abort them or delete them below, depending on
11238          * which HA mode we're in.
11239          */
11240 #ifdef notyet
11241         mtx_lock(&softc->queue_lock);
11242         for (io = (union ctl_io *)STAILQ_FIRST(&softc->rtr_queue);
11243              io != NULL; io = next_io) {
11244                 next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11245                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11246                         STAILQ_REMOVE(&softc->rtr_queue, &io->io_hdr,
11247                                       ctl_io_hdr, links);
11248         }
11249         mtx_unlock(&softc->queue_lock);
11250 #endif
11251
11252         for (lun_idx=0; lun_idx < softc->num_luns; lun_idx++) {
11253                 lun = softc->ctl_luns[lun_idx];
11254                 if (lun==NULL)
11255                         continue;
11256
11257                 /*
11258                  * Processor LUNs are primary on both sides.
11259                  * XXX will this always be true?
11260                  */
11261                 if (lun->be_lun->lun_type == T_PROCESSOR)
11262                         continue;
11263
11264                 if ((lun->flags & CTL_LUN_PRIMARY_SC)
11265                  && (softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11266                         printf("FAILOVER: primary lun %d\n", lun_idx);
11267                         /*
11268                          * Remove all commands from the other SC. First from the
11269                          * blocked queue then from the ooa queue. Once we have
11270                          * removed them. Call ctl_check_blocked to see if there
11271                          * is anything that can run.
11272                          */
11273                         for (io = (union ctl_io *)TAILQ_FIRST(
11274                              &lun->blocked_queue); io != NULL; io = next_io) {
11275
11276                                 next_io = (union ctl_io *)TAILQ_NEXT(
11277                                     &io->io_hdr, blocked_links);
11278
11279                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11280                                         TAILQ_REMOVE(&lun->blocked_queue,
11281                                                      &io->io_hdr,blocked_links);
11282                                         io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11283                                         TAILQ_REMOVE(&lun->ooa_queue,
11284                                                      &io->io_hdr, ooa_links);
11285
11286                                         ctl_free_io(io);
11287                                 }
11288                         }
11289
11290                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11291                              io != NULL; io = next_io) {
11292
11293                                 next_io = (union ctl_io *)TAILQ_NEXT(
11294                                     &io->io_hdr, ooa_links);
11295
11296                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11297
11298                                         TAILQ_REMOVE(&lun->ooa_queue,
11299                                                 &io->io_hdr,
11300                                                 ooa_links);
11301
11302                                         ctl_free_io(io);
11303                                 }
11304                         }
11305                         ctl_check_blocked(lun);
11306                 } else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11307                         && (softc->ha_mode == CTL_HA_MODE_XFER)) {
11308
11309                         printf("FAILOVER: primary lun %d\n", lun_idx);
11310                         /*
11311                          * Abort all commands from the other SC.  We can't
11312                          * send status back for them now.  These should get
11313                          * cleaned up when they are completed or come out
11314                          * for a datamove operation.
11315                          */
11316                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11317                              io != NULL; io = next_io) {
11318                                 next_io = (union ctl_io *)TAILQ_NEXT(
11319                                         &io->io_hdr, ooa_links);
11320
11321                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11322                                         io->io_hdr.flags |= CTL_FLAG_ABORT;
11323                         }
11324                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11325                         && (softc->ha_mode == CTL_HA_MODE_XFER)) {
11326
11327                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11328
11329                         lun->flags |= CTL_LUN_PRIMARY_SC;
11330
11331                         /*
11332                          * We send all I/O that was sent to this controller
11333                          * and redirected to the other side back with
11334                          * busy status, and have the initiator retry it.
11335                          * Figuring out how much data has been transferred,
11336                          * etc. and picking up where we left off would be 
11337                          * very tricky.
11338                          *
11339                          * XXX KDM need to remove I/O from the blocked
11340                          * queue as well!
11341                          */
11342                         for (pending_io = (union ctl_io *)TAILQ_FIRST(
11343                              &lun->ooa_queue); pending_io != NULL;
11344                              pending_io = next_io) {
11345
11346                                 next_io =  (union ctl_io *)TAILQ_NEXT(
11347                                         &pending_io->io_hdr, ooa_links);
11348
11349                                 pending_io->io_hdr.flags &=
11350                                         ~CTL_FLAG_SENT_2OTHER_SC;
11351
11352                                 if (pending_io->io_hdr.flags &
11353                                     CTL_FLAG_IO_ACTIVE) {
11354                                         pending_io->io_hdr.flags |=
11355                                                 CTL_FLAG_FAILOVER;
11356                                 } else {
11357                                         ctl_set_busy(&pending_io->scsiio);
11358                                         ctl_done(pending_io);
11359                                 }
11360                         }
11361
11362                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11363                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11364                         && (softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11365                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11366                         /*
11367                          * if the first io on the OOA is not on the RtR queue
11368                          * add it.
11369                          */
11370                         lun->flags |= CTL_LUN_PRIMARY_SC;
11371
11372                         pending_io = (union ctl_io *)TAILQ_FIRST(
11373                             &lun->ooa_queue);
11374                         if (pending_io==NULL) {
11375                                 printf("Nothing on OOA queue\n");
11376                                 continue;
11377                         }
11378
11379                         pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11380                         if ((pending_io->io_hdr.flags &
11381                              CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11382                                 pending_io->io_hdr.flags |=
11383                                     CTL_FLAG_IS_WAS_ON_RTR;
11384                                 ctl_enqueue_rtr(pending_io);
11385                         }
11386 #if 0
11387                         else
11388                         {
11389                                 printf("Tag 0x%04x is running\n",
11390                                       pending_io->scsiio.tag_num);
11391                         }
11392 #endif
11393
11394                         next_io = (union ctl_io *)TAILQ_NEXT(
11395                             &pending_io->io_hdr, ooa_links);
11396                         for (pending_io=next_io; pending_io != NULL;
11397                              pending_io = next_io) {
11398                                 pending_io->io_hdr.flags &=
11399                                     ~CTL_FLAG_SENT_2OTHER_SC;
11400                                 next_io = (union ctl_io *)TAILQ_NEXT(
11401                                         &pending_io->io_hdr, ooa_links);
11402                                 if (pending_io->io_hdr.flags &
11403                                     CTL_FLAG_IS_WAS_ON_RTR) {
11404 #if 0
11405                                         printf("Tag 0x%04x is running\n",
11406                                                 pending_io->scsiio.tag_num);
11407 #endif
11408                                         continue;
11409                                 }
11410
11411                                 switch (ctl_check_ooa(lun, pending_io,
11412                                     (union ctl_io *)TAILQ_PREV(
11413                                     &pending_io->io_hdr, ctl_ooaq,
11414                                     ooa_links))) {
11415
11416                                 case CTL_ACTION_BLOCK:
11417                                         TAILQ_INSERT_TAIL(&lun->blocked_queue,
11418                                                           &pending_io->io_hdr,
11419                                                           blocked_links);
11420                                         pending_io->io_hdr.flags |=
11421                                             CTL_FLAG_BLOCKED;
11422                                         break;
11423                                 case CTL_ACTION_PASS:
11424                                 case CTL_ACTION_SKIP:
11425                                         pending_io->io_hdr.flags |=
11426                                             CTL_FLAG_IS_WAS_ON_RTR;
11427                                         ctl_enqueue_rtr(pending_io);
11428                                         break;
11429                                 case CTL_ACTION_OVERLAP:
11430                                         ctl_set_overlapped_cmd(
11431                                             (struct ctl_scsiio *)pending_io);
11432                                         ctl_done(pending_io);
11433                                         break;
11434                                 case CTL_ACTION_OVERLAP_TAG:
11435                                         ctl_set_overlapped_tag(
11436                                             (struct ctl_scsiio *)pending_io,
11437                                             pending_io->scsiio.tag_num & 0xff);
11438                                         ctl_done(pending_io);
11439                                         break;
11440                                 case CTL_ACTION_ERROR:
11441                                 default:
11442                                         ctl_set_internal_failure(
11443                                                 (struct ctl_scsiio *)pending_io,
11444                                                 0,  // sks_valid
11445                                                 0); //retry count
11446                                         ctl_done(pending_io);
11447                                         break;
11448                                 }
11449                         }
11450
11451                         ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11452                 } else {
11453                         panic("Unhandled HA mode failover, LUN flags = %#x, "
11454                               "ha_mode = #%x", lun->flags, softc->ha_mode);
11455                 }
11456         }
11457         ctl_pause_rtr = 0;
11458         mtx_unlock(&softc->ctl_lock);
11459 }
11460
11461 static int
11462 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11463 {
11464         struct ctl_lun *lun;
11465         const struct ctl_cmd_entry *entry;
11466         uint32_t initidx, targ_lun;
11467         int retval;
11468
11469         retval = 0;
11470
11471         lun = NULL;
11472
11473         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11474         if ((targ_lun < CTL_MAX_LUNS)
11475          && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11476                 /*
11477                  * If the LUN is invalid, pretend that it doesn't exist.
11478                  * It will go away as soon as all pending I/O has been
11479                  * completed.
11480                  */
11481                 mtx_lock(&lun->lun_lock);
11482                 if (lun->flags & CTL_LUN_DISABLED) {
11483                         mtx_unlock(&lun->lun_lock);
11484                         lun = NULL;
11485                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11486                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11487                 } else {
11488                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11489                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11490                                 lun->be_lun;
11491                         if (lun->be_lun->lun_type == T_PROCESSOR) {
11492                                 ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11493                         }
11494
11495                         /*
11496                          * Every I/O goes into the OOA queue for a
11497                          * particular LUN, and stays there until completion.
11498                          */
11499                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11500                             ooa_links);
11501                 }
11502         } else {
11503                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11504                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11505         }
11506
11507         /* Get command entry and return error if it is unsuppotyed. */
11508         entry = ctl_validate_command(ctsio);
11509         if (entry == NULL) {
11510                 if (lun)
11511                         mtx_unlock(&lun->lun_lock);
11512                 return (retval);
11513         }
11514
11515         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11516         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11517
11518         /*
11519          * Check to see whether we can send this command to LUNs that don't
11520          * exist.  This should pretty much only be the case for inquiry
11521          * and request sense.  Further checks, below, really require having
11522          * a LUN, so we can't really check the command anymore.  Just put
11523          * it on the rtr queue.
11524          */
11525         if (lun == NULL) {
11526                 if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11527                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11528                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11529                         return (retval);
11530                 }
11531
11532                 ctl_set_unsupported_lun(ctsio);
11533                 ctl_done((union ctl_io *)ctsio);
11534                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11535                 return (retval);
11536         } else {
11537                 /*
11538                  * Make sure we support this particular command on this LUN.
11539                  * e.g., we don't support writes to the control LUN.
11540                  */
11541                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11542                         mtx_unlock(&lun->lun_lock);
11543                         ctl_set_invalid_opcode(ctsio);
11544                         ctl_done((union ctl_io *)ctsio);
11545                         return (retval);
11546                 }
11547         }
11548
11549         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11550
11551 #ifdef CTL_WITH_CA
11552         /*
11553          * If we've got a request sense, it'll clear the contingent
11554          * allegiance condition.  Otherwise, if we have a CA condition for
11555          * this initiator, clear it, because it sent down a command other
11556          * than request sense.
11557          */
11558         if ((ctsio->cdb[0] != REQUEST_SENSE)
11559          && (ctl_is_set(lun->have_ca, initidx)))
11560                 ctl_clear_mask(lun->have_ca, initidx);
11561 #endif
11562
11563         /*
11564          * If the command has this flag set, it handles its own unit
11565          * attention reporting, we shouldn't do anything.  Otherwise we
11566          * check for any pending unit attentions, and send them back to the
11567          * initiator.  We only do this when a command initially comes in,
11568          * not when we pull it off the blocked queue.
11569          *
11570          * According to SAM-3, section 5.3.2, the order that things get
11571          * presented back to the host is basically unit attentions caused
11572          * by some sort of reset event, busy status, reservation conflicts
11573          * or task set full, and finally any other status.
11574          *
11575          * One issue here is that some of the unit attentions we report
11576          * don't fall into the "reset" category (e.g. "reported luns data
11577          * has changed").  So reporting it here, before the reservation
11578          * check, may be technically wrong.  I guess the only thing to do
11579          * would be to check for and report the reset events here, and then
11580          * check for the other unit attention types after we check for a
11581          * reservation conflict.
11582          *
11583          * XXX KDM need to fix this
11584          */
11585         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11586                 ctl_ua_type ua_type;
11587                 scsi_sense_data_type sense_format;
11588
11589                 if (lun->flags & CTL_LUN_SENSE_DESC)
11590                         sense_format = SSD_TYPE_DESC;
11591                 else
11592                         sense_format = SSD_TYPE_FIXED;
11593
11594                 ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11595                     sense_format);
11596                 if (ua_type != CTL_UA_NONE) {
11597                         mtx_unlock(&lun->lun_lock);
11598                         ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11599                         ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11600                         ctsio->sense_len = SSD_FULL_SIZE;
11601                         ctl_done((union ctl_io *)ctsio);
11602                         return (retval);
11603                 }
11604         }
11605
11606
11607         if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11608                 mtx_unlock(&lun->lun_lock);
11609                 ctl_done((union ctl_io *)ctsio);
11610                 return (retval);
11611         }
11612
11613         /*
11614          * XXX CHD this is where we want to send IO to other side if
11615          * this LUN is secondary on this SC. We will need to make a copy
11616          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11617          * the copy we send as FROM_OTHER.
11618          * We also need to stuff the address of the original IO so we can
11619          * find it easily. Something similar will need be done on the other
11620          * side so when we are done we can find the copy.
11621          */
11622         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11623                 union ctl_ha_msg msg_info;
11624                 int isc_retval;
11625
11626                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11627
11628                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11629                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11630 #if 0
11631                 printf("1. ctsio %p\n", ctsio);
11632 #endif
11633                 msg_info.hdr.serializing_sc = NULL;
11634                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11635                 msg_info.scsi.tag_num = ctsio->tag_num;
11636                 msg_info.scsi.tag_type = ctsio->tag_type;
11637                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11638
11639                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11640
11641                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11642                     (void *)&msg_info, sizeof(msg_info), 0)) >
11643                     CTL_HA_STATUS_SUCCESS) {
11644                         printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11645                                isc_retval);
11646                         printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11647                 } else {
11648 #if 0
11649                         printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11650 #endif
11651                 }
11652
11653                 /*
11654                  * XXX KDM this I/O is off the incoming queue, but hasn't
11655                  * been inserted on any other queue.  We may need to come
11656                  * up with a holding queue while we wait for serialization
11657                  * so that we have an idea of what we're waiting for from
11658                  * the other side.
11659                  */
11660                 mtx_unlock(&lun->lun_lock);
11661                 return (retval);
11662         }
11663
11664         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11665                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11666                               ctl_ooaq, ooa_links))) {
11667         case CTL_ACTION_BLOCK:
11668                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11669                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11670                                   blocked_links);
11671                 mtx_unlock(&lun->lun_lock);
11672                 return (retval);
11673         case CTL_ACTION_PASS:
11674         case CTL_ACTION_SKIP:
11675                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11676                 mtx_unlock(&lun->lun_lock);
11677                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11678                 break;
11679         case CTL_ACTION_OVERLAP:
11680                 mtx_unlock(&lun->lun_lock);
11681                 ctl_set_overlapped_cmd(ctsio);
11682                 ctl_done((union ctl_io *)ctsio);
11683                 break;
11684         case CTL_ACTION_OVERLAP_TAG:
11685                 mtx_unlock(&lun->lun_lock);
11686                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11687                 ctl_done((union ctl_io *)ctsio);
11688                 break;
11689         case CTL_ACTION_ERROR:
11690         default:
11691                 mtx_unlock(&lun->lun_lock);
11692                 ctl_set_internal_failure(ctsio,
11693                                          /*sks_valid*/ 0,
11694                                          /*retry_count*/ 0);
11695                 ctl_done((union ctl_io *)ctsio);
11696                 break;
11697         }
11698         return (retval);
11699 }
11700
11701 const struct ctl_cmd_entry *
11702 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11703 {
11704         const struct ctl_cmd_entry *entry;
11705         int service_action;
11706
11707         entry = &ctl_cmd_table[ctsio->cdb[0]];
11708         if (sa)
11709                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11710         if (entry->flags & CTL_CMD_FLAG_SA5) {
11711                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11712                 entry = &((const struct ctl_cmd_entry *)
11713                     entry->execute)[service_action];
11714         }
11715         return (entry);
11716 }
11717
11718 const struct ctl_cmd_entry *
11719 ctl_validate_command(struct ctl_scsiio *ctsio)
11720 {
11721         const struct ctl_cmd_entry *entry;
11722         int i, sa;
11723         uint8_t diff;
11724
11725         entry = ctl_get_cmd_entry(ctsio, &sa);
11726         if (entry->execute == NULL) {
11727                 if (sa)
11728                         ctl_set_invalid_field(ctsio,
11729                                               /*sks_valid*/ 1,
11730                                               /*command*/ 1,
11731                                               /*field*/ 1,
11732                                               /*bit_valid*/ 1,
11733                                               /*bit*/ 4);
11734                 else
11735                         ctl_set_invalid_opcode(ctsio);
11736                 ctl_done((union ctl_io *)ctsio);
11737                 return (NULL);
11738         }
11739         KASSERT(entry->length > 0,
11740             ("Not defined length for command 0x%02x/0x%02x",
11741              ctsio->cdb[0], ctsio->cdb[1]));
11742         for (i = 1; i < entry->length; i++) {
11743                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11744                 if (diff == 0)
11745                         continue;
11746                 ctl_set_invalid_field(ctsio,
11747                                       /*sks_valid*/ 1,
11748                                       /*command*/ 1,
11749                                       /*field*/ i,
11750                                       /*bit_valid*/ 1,
11751                                       /*bit*/ fls(diff) - 1);
11752                 ctl_done((union ctl_io *)ctsio);
11753                 return (NULL);
11754         }
11755         return (entry);
11756 }
11757
11758 static int
11759 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11760 {
11761
11762         switch (lun_type) {
11763         case T_PROCESSOR:
11764                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11765                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11766                         return (0);
11767                 break;
11768         case T_DIRECT:
11769                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11770                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11771                         return (0);
11772                 break;
11773         default:
11774                 return (0);
11775         }
11776         return (1);
11777 }
11778
11779 static int
11780 ctl_scsiio(struct ctl_scsiio *ctsio)
11781 {
11782         int retval;
11783         const struct ctl_cmd_entry *entry;
11784
11785         retval = CTL_RETVAL_COMPLETE;
11786
11787         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11788
11789         entry = ctl_get_cmd_entry(ctsio, NULL);
11790
11791         /*
11792          * If this I/O has been aborted, just send it straight to
11793          * ctl_done() without executing it.
11794          */
11795         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11796                 ctl_done((union ctl_io *)ctsio);
11797                 goto bailout;
11798         }
11799
11800         /*
11801          * All the checks should have been handled by ctl_scsiio_precheck().
11802          * We should be clear now to just execute the I/O.
11803          */
11804         retval = entry->execute(ctsio);
11805
11806 bailout:
11807         return (retval);
11808 }
11809
11810 /*
11811  * Since we only implement one target right now, a bus reset simply resets
11812  * our single target.
11813  */
11814 static int
11815 ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11816 {
11817         return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11818 }
11819
11820 static int
11821 ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11822                  ctl_ua_type ua_type)
11823 {
11824         struct ctl_lun *lun;
11825         int retval;
11826
11827         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11828                 union ctl_ha_msg msg_info;
11829
11830                 io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11831                 msg_info.hdr.nexus = io->io_hdr.nexus;
11832                 if (ua_type==CTL_UA_TARG_RESET)
11833                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11834                 else
11835                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
11836                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11837                 msg_info.hdr.original_sc = NULL;
11838                 msg_info.hdr.serializing_sc = NULL;
11839                 if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11840                     (void *)&msg_info, sizeof(msg_info), 0)) {
11841                 }
11842         }
11843         retval = 0;
11844
11845         mtx_lock(&softc->ctl_lock);
11846         STAILQ_FOREACH(lun, &softc->lun_list, links)
11847                 retval += ctl_lun_reset(lun, io, ua_type);
11848         mtx_unlock(&softc->ctl_lock);
11849
11850         return (retval);
11851 }
11852
11853 /*
11854  * The LUN should always be set.  The I/O is optional, and is used to
11855  * distinguish between I/Os sent by this initiator, and by other
11856  * initiators.  We set unit attention for initiators other than this one.
11857  * SAM-3 is vague on this point.  It does say that a unit attention should
11858  * be established for other initiators when a LUN is reset (see section
11859  * 5.7.3), but it doesn't specifically say that the unit attention should
11860  * be established for this particular initiator when a LUN is reset.  Here
11861  * is the relevant text, from SAM-3 rev 8:
11862  *
11863  * 5.7.2 When a SCSI initiator port aborts its own tasks
11864  *
11865  * When a SCSI initiator port causes its own task(s) to be aborted, no
11866  * notification that the task(s) have been aborted shall be returned to
11867  * the SCSI initiator port other than the completion response for the
11868  * command or task management function action that caused the task(s) to
11869  * be aborted and notification(s) associated with related effects of the
11870  * action (e.g., a reset unit attention condition).
11871  *
11872  * XXX KDM for now, we're setting unit attention for all initiators.
11873  */
11874 static int
11875 ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11876 {
11877         union ctl_io *xio;
11878 #if 0
11879         uint32_t initidx;
11880 #endif
11881 #ifdef CTL_WITH_CA
11882         int i;
11883 #endif
11884
11885         mtx_lock(&lun->lun_lock);
11886         /*
11887          * Run through the OOA queue and abort each I/O.
11888          */
11889 #if 0
11890         TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11891 #endif
11892         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11893              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11894                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11895         }
11896
11897         /*
11898          * This version sets unit attention for every
11899          */
11900 #if 0
11901         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11902         ctl_est_ua_all(lun, initidx, ua_type);
11903 #else
11904         ctl_est_ua_all(lun, -1, ua_type);
11905 #endif
11906
11907         /*
11908          * A reset (any kind, really) clears reservations established with
11909          * RESERVE/RELEASE.  It does not clear reservations established
11910          * with PERSISTENT RESERVE OUT, but we don't support that at the
11911          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11912          * reservations made with the RESERVE/RELEASE commands, because
11913          * those commands are obsolete in SPC-3.
11914          */
11915         lun->flags &= ~CTL_LUN_RESERVED;
11916
11917 #ifdef CTL_WITH_CA
11918         for (i = 0; i < CTL_MAX_INITIATORS; i++)
11919                 ctl_clear_mask(lun->have_ca, i);
11920 #endif
11921         mtx_unlock(&lun->lun_lock);
11922
11923         return (0);
11924 }
11925
11926 static void
11927 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11928     int other_sc)
11929 {
11930         union ctl_io *xio;
11931
11932         mtx_assert(&lun->lun_lock, MA_OWNED);
11933
11934         /*
11935          * Run through the OOA queue and attempt to find the given I/O.
11936          * The target port, initiator ID, tag type and tag number have to
11937          * match the values that we got from the initiator.  If we have an
11938          * untagged command to abort, simply abort the first untagged command
11939          * we come to.  We only allow one untagged command at a time of course.
11940          */
11941         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11942              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11943
11944                 if ((targ_port == UINT32_MAX ||
11945                      targ_port == xio->io_hdr.nexus.targ_port) &&
11946                     (init_id == UINT32_MAX ||
11947                      init_id == xio->io_hdr.nexus.initid.id)) {
11948                         if (targ_port != xio->io_hdr.nexus.targ_port ||
11949                             init_id != xio->io_hdr.nexus.initid.id)
11950                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11951                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
11952                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11953                                 union ctl_ha_msg msg_info;
11954
11955                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
11956                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11957                                 msg_info.task.tag_num = xio->scsiio.tag_num;
11958                                 msg_info.task.tag_type = xio->scsiio.tag_type;
11959                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11960                                 msg_info.hdr.original_sc = NULL;
11961                                 msg_info.hdr.serializing_sc = NULL;
11962                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11963                                     (void *)&msg_info, sizeof(msg_info), 0);
11964                         }
11965                 }
11966         }
11967 }
11968
11969 static int
11970 ctl_abort_task_set(union ctl_io *io)
11971 {
11972         struct ctl_softc *softc = control_softc;
11973         struct ctl_lun *lun;
11974         uint32_t targ_lun;
11975
11976         /*
11977          * Look up the LUN.
11978          */
11979         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11980         mtx_lock(&softc->ctl_lock);
11981         if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
11982                 lun = softc->ctl_luns[targ_lun];
11983         else {
11984                 mtx_unlock(&softc->ctl_lock);
11985                 return (1);
11986         }
11987
11988         mtx_lock(&lun->lun_lock);
11989         mtx_unlock(&softc->ctl_lock);
11990         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11991                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11992                     io->io_hdr.nexus.initid.id,
11993                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11994         } else { /* CTL_TASK_CLEAR_TASK_SET */
11995                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11996                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11997         }
11998         mtx_unlock(&lun->lun_lock);
11999         return (0);
12000 }
12001
12002 static int
12003 ctl_i_t_nexus_reset(union ctl_io *io)
12004 {
12005         struct ctl_softc *softc = control_softc;
12006         struct ctl_lun *lun;
12007         uint32_t initidx, residx;
12008
12009         initidx = ctl_get_initindex(&io->io_hdr.nexus);
12010         residx = ctl_get_resindex(&io->io_hdr.nexus);
12011         mtx_lock(&softc->ctl_lock);
12012         STAILQ_FOREACH(lun, &softc->lun_list, links) {
12013                 mtx_lock(&lun->lun_lock);
12014                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12015                     io->io_hdr.nexus.initid.id,
12016                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12017 #ifdef CTL_WITH_CA
12018                 ctl_clear_mask(lun->have_ca, initidx);
12019 #endif
12020                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
12021                         lun->flags &= ~CTL_LUN_RESERVED;
12022                 ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12023                 mtx_unlock(&lun->lun_lock);
12024         }
12025         mtx_unlock(&softc->ctl_lock);
12026         return (0);
12027 }
12028
12029 static int
12030 ctl_abort_task(union ctl_io *io)
12031 {
12032         union ctl_io *xio;
12033         struct ctl_lun *lun;
12034         struct ctl_softc *softc;
12035 #if 0
12036         struct sbuf sb;
12037         char printbuf[128];
12038 #endif
12039         int found;
12040         uint32_t targ_lun;
12041
12042         softc = control_softc;
12043         found = 0;
12044
12045         /*
12046          * Look up the LUN.
12047          */
12048         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12049         mtx_lock(&softc->ctl_lock);
12050         if ((targ_lun < CTL_MAX_LUNS)
12051          && (softc->ctl_luns[targ_lun] != NULL))
12052                 lun = softc->ctl_luns[targ_lun];
12053         else {
12054                 mtx_unlock(&softc->ctl_lock);
12055                 return (1);
12056         }
12057
12058 #if 0
12059         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12060                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12061 #endif
12062
12063         mtx_lock(&lun->lun_lock);
12064         mtx_unlock(&softc->ctl_lock);
12065         /*
12066          * Run through the OOA queue and attempt to find the given I/O.
12067          * The target port, initiator ID, tag type and tag number have to
12068          * match the values that we got from the initiator.  If we have an
12069          * untagged command to abort, simply abort the first untagged command
12070          * we come to.  We only allow one untagged command at a time of course.
12071          */
12072 #if 0
12073         TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12074 #endif
12075         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12076              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12077 #if 0
12078                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12079
12080                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12081                             lun->lun, xio->scsiio.tag_num,
12082                             xio->scsiio.tag_type,
12083                             (xio->io_hdr.blocked_links.tqe_prev
12084                             == NULL) ? "" : " BLOCKED",
12085                             (xio->io_hdr.flags &
12086                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12087                             (xio->io_hdr.flags &
12088                             CTL_FLAG_ABORT) ? " ABORT" : "",
12089                             (xio->io_hdr.flags &
12090                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12091                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12092                 sbuf_finish(&sb);
12093                 printf("%s\n", sbuf_data(&sb));
12094 #endif
12095
12096                 if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12097                  && (xio->io_hdr.nexus.initid.id ==
12098                      io->io_hdr.nexus.initid.id)) {
12099                         /*
12100                          * If the abort says that the task is untagged, the
12101                          * task in the queue must be untagged.  Otherwise,
12102                          * we just check to see whether the tag numbers
12103                          * match.  This is because the QLogic firmware
12104                          * doesn't pass back the tag type in an abort
12105                          * request.
12106                          */
12107 #if 0
12108                         if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12109                           && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12110                          || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12111 #endif
12112                         /*
12113                          * XXX KDM we've got problems with FC, because it
12114                          * doesn't send down a tag type with aborts.  So we
12115                          * can only really go by the tag number...
12116                          * This may cause problems with parallel SCSI.
12117                          * Need to figure that out!!
12118                          */
12119                         if (xio->scsiio.tag_num == io->taskio.tag_num) {
12120                                 xio->io_hdr.flags |= CTL_FLAG_ABORT;
12121                                 found = 1;
12122                                 if ((io->io_hdr.flags &
12123                                      CTL_FLAG_FROM_OTHER_SC) == 0 &&
12124                                     !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12125                                         union ctl_ha_msg msg_info;
12126
12127                                         io->io_hdr.flags |=
12128                                                         CTL_FLAG_SENT_2OTHER_SC;
12129                                         msg_info.hdr.nexus = io->io_hdr.nexus;
12130                                         msg_info.task.task_action =
12131                                                 CTL_TASK_ABORT_TASK;
12132                                         msg_info.task.tag_num =
12133                                                 io->taskio.tag_num;
12134                                         msg_info.task.tag_type =
12135                                                 io->taskio.tag_type;
12136                                         msg_info.hdr.msg_type =
12137                                                 CTL_MSG_MANAGE_TASKS;
12138                                         msg_info.hdr.original_sc = NULL;
12139                                         msg_info.hdr.serializing_sc = NULL;
12140 #if 0
12141                                         printf("Sent Abort to other side\n");
12142 #endif
12143                                         if (CTL_HA_STATUS_SUCCESS !=
12144                                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12145                                                 (void *)&msg_info,
12146                                                 sizeof(msg_info), 0)) {
12147                                         }
12148                                 }
12149 #if 0
12150                                 printf("ctl_abort_task: found I/O to abort\n");
12151 #endif
12152                                 break;
12153                         }
12154                 }
12155         }
12156         mtx_unlock(&lun->lun_lock);
12157
12158         if (found == 0) {
12159                 /*
12160                  * This isn't really an error.  It's entirely possible for
12161                  * the abort and command completion to cross on the wire.
12162                  * This is more of an informative/diagnostic error.
12163                  */
12164 #if 0
12165                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12166                        "%d:%d:%d:%d tag %d type %d\n",
12167                        io->io_hdr.nexus.initid.id,
12168                        io->io_hdr.nexus.targ_port,
12169                        io->io_hdr.nexus.targ_target.id,
12170                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12171                        io->taskio.tag_type);
12172 #endif
12173         }
12174         return (0);
12175 }
12176
12177 static void
12178 ctl_run_task(union ctl_io *io)
12179 {
12180         struct ctl_softc *softc = control_softc;
12181         int retval = 1;
12182         const char *task_desc;
12183
12184         CTL_DEBUG_PRINT(("ctl_run_task\n"));
12185
12186         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12187             ("ctl_run_task: Unextected io_type %d\n",
12188              io->io_hdr.io_type));
12189
12190         task_desc = ctl_scsi_task_string(&io->taskio);
12191         if (task_desc != NULL) {
12192 #ifdef NEEDTOPORT
12193                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12194                             CTL_TASK_REPORT,
12195                             csevent_LogType_Trace,
12196                             csevent_Severity_Information,
12197                             csevent_AlertLevel_Green,
12198                             csevent_FRU_Firmware,
12199                             csevent_FRU_Unknown,
12200                             "CTL: received task: %s",task_desc);
12201 #endif
12202         } else {
12203 #ifdef NEEDTOPORT
12204                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12205                             CTL_TASK_REPORT,
12206                             csevent_LogType_Trace,
12207                             csevent_Severity_Information,
12208                             csevent_AlertLevel_Green,
12209                             csevent_FRU_Firmware,
12210                             csevent_FRU_Unknown,
12211                             "CTL: received unknown task "
12212                             "type: %d (%#x)",
12213                             io->taskio.task_action,
12214                             io->taskio.task_action);
12215 #endif
12216         }
12217         switch (io->taskio.task_action) {
12218         case CTL_TASK_ABORT_TASK:
12219                 retval = ctl_abort_task(io);
12220                 break;
12221         case CTL_TASK_ABORT_TASK_SET:
12222         case CTL_TASK_CLEAR_TASK_SET:
12223                 retval = ctl_abort_task_set(io);
12224                 break;
12225         case CTL_TASK_CLEAR_ACA:
12226                 break;
12227         case CTL_TASK_I_T_NEXUS_RESET:
12228                 retval = ctl_i_t_nexus_reset(io);
12229                 break;
12230         case CTL_TASK_LUN_RESET: {
12231                 struct ctl_lun *lun;
12232                 uint32_t targ_lun;
12233
12234                 targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12235                 mtx_lock(&softc->ctl_lock);
12236                 if ((targ_lun < CTL_MAX_LUNS)
12237                  && (softc->ctl_luns[targ_lun] != NULL))
12238                         lun = softc->ctl_luns[targ_lun];
12239                 else {
12240                         mtx_unlock(&softc->ctl_lock);
12241                         retval = 1;
12242                         break;
12243                 }
12244
12245                 if (!(io->io_hdr.flags &
12246                     CTL_FLAG_FROM_OTHER_SC)) {
12247                         union ctl_ha_msg msg_info;
12248
12249                         io->io_hdr.flags |=
12250                                 CTL_FLAG_SENT_2OTHER_SC;
12251                         msg_info.hdr.msg_type =
12252                                 CTL_MSG_MANAGE_TASKS;
12253                         msg_info.hdr.nexus = io->io_hdr.nexus;
12254                         msg_info.task.task_action =
12255                                 CTL_TASK_LUN_RESET;
12256                         msg_info.hdr.original_sc = NULL;
12257                         msg_info.hdr.serializing_sc = NULL;
12258                         if (CTL_HA_STATUS_SUCCESS !=
12259                             ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12260                             (void *)&msg_info,
12261                             sizeof(msg_info), 0)) {
12262                         }
12263                 }
12264
12265                 retval = ctl_lun_reset(lun, io,
12266                                        CTL_UA_LUN_RESET);
12267                 mtx_unlock(&softc->ctl_lock);
12268                 break;
12269         }
12270         case CTL_TASK_TARGET_RESET:
12271                 retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12272                 break;
12273         case CTL_TASK_BUS_RESET:
12274                 retval = ctl_bus_reset(softc, io);
12275                 break;
12276         case CTL_TASK_PORT_LOGIN:
12277                 break;
12278         case CTL_TASK_PORT_LOGOUT:
12279                 break;
12280         default:
12281                 printf("ctl_run_task: got unknown task management event %d\n",
12282                        io->taskio.task_action);
12283                 break;
12284         }
12285         if (retval == 0)
12286                 io->io_hdr.status = CTL_SUCCESS;
12287         else
12288                 io->io_hdr.status = CTL_ERROR;
12289         ctl_done(io);
12290 }
12291
12292 /*
12293  * For HA operation.  Handle commands that come in from the other
12294  * controller.
12295  */
12296 static void
12297 ctl_handle_isc(union ctl_io *io)
12298 {
12299         int free_io;
12300         struct ctl_lun *lun;
12301         struct ctl_softc *softc;
12302         uint32_t targ_lun;
12303
12304         softc = control_softc;
12305
12306         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12307         lun = softc->ctl_luns[targ_lun];
12308
12309         switch (io->io_hdr.msg_type) {
12310         case CTL_MSG_SERIALIZE:
12311                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12312                 break;
12313         case CTL_MSG_R2R: {
12314                 const struct ctl_cmd_entry *entry;
12315
12316                 /*
12317                  * This is only used in SER_ONLY mode.
12318                  */
12319                 free_io = 0;
12320                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12321                 mtx_lock(&lun->lun_lock);
12322                 if (ctl_scsiio_lun_check(lun,
12323                     entry, (struct ctl_scsiio *)io) != 0) {
12324                         mtx_unlock(&lun->lun_lock);
12325                         ctl_done(io);
12326                         break;
12327                 }
12328                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12329                 mtx_unlock(&lun->lun_lock);
12330                 ctl_enqueue_rtr(io);
12331                 break;
12332         }
12333         case CTL_MSG_FINISH_IO:
12334                 if (softc->ha_mode == CTL_HA_MODE_XFER) {
12335                         free_io = 0;
12336                         ctl_done(io);
12337                 } else {
12338                         free_io = 1;
12339                         mtx_lock(&lun->lun_lock);
12340                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12341                                      ooa_links);
12342                         ctl_check_blocked(lun);
12343                         mtx_unlock(&lun->lun_lock);
12344                 }
12345                 break;
12346         case CTL_MSG_PERS_ACTION:
12347                 ctl_hndl_per_res_out_on_other_sc(
12348                         (union ctl_ha_msg *)&io->presio.pr_msg);
12349                 free_io = 1;
12350                 break;
12351         case CTL_MSG_BAD_JUJU:
12352                 free_io = 0;
12353                 ctl_done(io);
12354                 break;
12355         case CTL_MSG_DATAMOVE:
12356                 /* Only used in XFER mode */
12357                 free_io = 0;
12358                 ctl_datamove_remote(io);
12359                 break;
12360         case CTL_MSG_DATAMOVE_DONE:
12361                 /* Only used in XFER mode */
12362                 free_io = 0;
12363                 io->scsiio.be_move_done(io);
12364                 break;
12365         default:
12366                 free_io = 1;
12367                 printf("%s: Invalid message type %d\n",
12368                        __func__, io->io_hdr.msg_type);
12369                 break;
12370         }
12371         if (free_io)
12372                 ctl_free_io(io);
12373
12374 }
12375
12376
12377 /*
12378  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12379  * there is no match.
12380  */
12381 static ctl_lun_error_pattern
12382 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12383 {
12384         const struct ctl_cmd_entry *entry;
12385         ctl_lun_error_pattern filtered_pattern, pattern;
12386
12387         pattern = desc->error_pattern;
12388
12389         /*
12390          * XXX KDM we need more data passed into this function to match a
12391          * custom pattern, and we actually need to implement custom pattern
12392          * matching.
12393          */
12394         if (pattern & CTL_LUN_PAT_CMD)
12395                 return (CTL_LUN_PAT_CMD);
12396
12397         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12398                 return (CTL_LUN_PAT_ANY);
12399
12400         entry = ctl_get_cmd_entry(ctsio, NULL);
12401
12402         filtered_pattern = entry->pattern & pattern;
12403
12404         /*
12405          * If the user requested specific flags in the pattern (e.g.
12406          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12407          * flags.
12408          *
12409          * If the user did not specify any flags, it doesn't matter whether
12410          * or not the command supports the flags.
12411          */
12412         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12413              (pattern & ~CTL_LUN_PAT_MASK))
12414                 return (CTL_LUN_PAT_NONE);
12415
12416         /*
12417          * If the user asked for a range check, see if the requested LBA
12418          * range overlaps with this command's LBA range.
12419          */
12420         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12421                 uint64_t lba1;
12422                 uint64_t len1;
12423                 ctl_action action;
12424                 int retval;
12425
12426                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12427                 if (retval != 0)
12428                         return (CTL_LUN_PAT_NONE);
12429
12430                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12431                                               desc->lba_range.len, FALSE);
12432                 /*
12433                  * A "pass" means that the LBA ranges don't overlap, so
12434                  * this doesn't match the user's range criteria.
12435                  */
12436                 if (action == CTL_ACTION_PASS)
12437                         return (CTL_LUN_PAT_NONE);
12438         }
12439
12440         return (filtered_pattern);
12441 }
12442
12443 static void
12444 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12445 {
12446         struct ctl_error_desc *desc, *desc2;
12447
12448         mtx_assert(&lun->lun_lock, MA_OWNED);
12449
12450         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12451                 ctl_lun_error_pattern pattern;
12452                 /*
12453                  * Check to see whether this particular command matches
12454                  * the pattern in the descriptor.
12455                  */
12456                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12457                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12458                         continue;
12459
12460                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12461                 case CTL_LUN_INJ_ABORTED:
12462                         ctl_set_aborted(&io->scsiio);
12463                         break;
12464                 case CTL_LUN_INJ_MEDIUM_ERR:
12465                         ctl_set_medium_error(&io->scsiio);
12466                         break;
12467                 case CTL_LUN_INJ_UA:
12468                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12469                          * OCCURRED */
12470                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12471                         break;
12472                 case CTL_LUN_INJ_CUSTOM:
12473                         /*
12474                          * We're assuming the user knows what he is doing.
12475                          * Just copy the sense information without doing
12476                          * checks.
12477                          */
12478                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12479                               ctl_min(sizeof(desc->custom_sense),
12480                                       sizeof(io->scsiio.sense_data)));
12481                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12482                         io->scsiio.sense_len = SSD_FULL_SIZE;
12483                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12484                         break;
12485                 case CTL_LUN_INJ_NONE:
12486                 default:
12487                         /*
12488                          * If this is an error injection type we don't know
12489                          * about, clear the continuous flag (if it is set)
12490                          * so it will get deleted below.
12491                          */
12492                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12493                         break;
12494                 }
12495                 /*
12496                  * By default, each error injection action is a one-shot
12497                  */
12498                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12499                         continue;
12500
12501                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12502
12503                 free(desc, M_CTL);
12504         }
12505 }
12506
12507 #ifdef CTL_IO_DELAY
12508 static void
12509 ctl_datamove_timer_wakeup(void *arg)
12510 {
12511         union ctl_io *io;
12512
12513         io = (union ctl_io *)arg;
12514
12515         ctl_datamove(io);
12516 }
12517 #endif /* CTL_IO_DELAY */
12518
12519 void
12520 ctl_datamove(union ctl_io *io)
12521 {
12522         void (*fe_datamove)(union ctl_io *io);
12523
12524         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12525
12526         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12527
12528 #ifdef CTL_TIME_IO
12529         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12530                 char str[256];
12531                 char path_str[64];
12532                 struct sbuf sb;
12533
12534                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12535                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12536
12537                 sbuf_cat(&sb, path_str);
12538                 switch (io->io_hdr.io_type) {
12539                 case CTL_IO_SCSI:
12540                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12541                         sbuf_printf(&sb, "\n");
12542                         sbuf_cat(&sb, path_str);
12543                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12544                                     io->scsiio.tag_num, io->scsiio.tag_type);
12545                         break;
12546                 case CTL_IO_TASK:
12547                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12548                                     "Tag Type: %d\n", io->taskio.task_action,
12549                                     io->taskio.tag_num, io->taskio.tag_type);
12550                         break;
12551                 default:
12552                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12553                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12554                         break;
12555                 }
12556                 sbuf_cat(&sb, path_str);
12557                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12558                             (intmax_t)time_uptime - io->io_hdr.start_time);
12559                 sbuf_finish(&sb);
12560                 printf("%s", sbuf_data(&sb));
12561         }
12562 #endif /* CTL_TIME_IO */
12563
12564 #ifdef CTL_IO_DELAY
12565         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12566                 struct ctl_lun *lun;
12567
12568                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12569
12570                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12571         } else {
12572                 struct ctl_lun *lun;
12573
12574                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12575                 if ((lun != NULL)
12576                  && (lun->delay_info.datamove_delay > 0)) {
12577                         struct callout *callout;
12578
12579                         callout = (struct callout *)&io->io_hdr.timer_bytes;
12580                         callout_init(callout, /*mpsafe*/ 1);
12581                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12582                         callout_reset(callout,
12583                                       lun->delay_info.datamove_delay * hz,
12584                                       ctl_datamove_timer_wakeup, io);
12585                         if (lun->delay_info.datamove_type ==
12586                             CTL_DELAY_TYPE_ONESHOT)
12587                                 lun->delay_info.datamove_delay = 0;
12588                         return;
12589                 }
12590         }
12591 #endif
12592
12593         /*
12594          * This command has been aborted.  Set the port status, so we fail
12595          * the data move.
12596          */
12597         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12598                 printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12599                        io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12600                        io->io_hdr.nexus.targ_port,
12601                        (uintmax_t)io->io_hdr.nexus.targ_target.id,
12602                        io->io_hdr.nexus.targ_lun);
12603                 io->io_hdr.port_status = 31337;
12604                 /*
12605                  * Note that the backend, in this case, will get the
12606                  * callback in its context.  In other cases it may get
12607                  * called in the frontend's interrupt thread context.
12608                  */
12609                 io->scsiio.be_move_done(io);
12610                 return;
12611         }
12612
12613         /* Don't confuse frontend with zero length data move. */
12614         if (io->scsiio.kern_data_len == 0) {
12615                 io->scsiio.be_move_done(io);
12616                 return;
12617         }
12618
12619         /*
12620          * If we're in XFER mode and this I/O is from the other shelf
12621          * controller, we need to send the DMA to the other side to
12622          * actually transfer the data to/from the host.  In serialize only
12623          * mode the transfer happens below CTL and ctl_datamove() is only
12624          * called on the machine that originally received the I/O.
12625          */
12626         if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12627          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12628                 union ctl_ha_msg msg;
12629                 uint32_t sg_entries_sent;
12630                 int do_sg_copy;
12631                 int i;
12632
12633                 memset(&msg, 0, sizeof(msg));
12634                 msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12635                 msg.hdr.original_sc = io->io_hdr.original_sc;
12636                 msg.hdr.serializing_sc = io;
12637                 msg.hdr.nexus = io->io_hdr.nexus;
12638                 msg.dt.flags = io->io_hdr.flags;
12639                 /*
12640                  * We convert everything into a S/G list here.  We can't
12641                  * pass by reference, only by value between controllers.
12642                  * So we can't pass a pointer to the S/G list, only as many
12643                  * S/G entries as we can fit in here.  If it's possible for
12644                  * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12645                  * then we need to break this up into multiple transfers.
12646                  */
12647                 if (io->scsiio.kern_sg_entries == 0) {
12648                         msg.dt.kern_sg_entries = 1;
12649                         /*
12650                          * If this is in cached memory, flush the cache
12651                          * before we send the DMA request to the other
12652                          * controller.  We want to do this in either the
12653                          * read or the write case.  The read case is
12654                          * straightforward.  In the write case, we want to
12655                          * make sure nothing is in the local cache that
12656                          * could overwrite the DMAed data.
12657                          */
12658                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12659                                 /*
12660                                  * XXX KDM use bus_dmamap_sync() here.
12661                                  */
12662                         }
12663
12664                         /*
12665                          * Convert to a physical address if this is a
12666                          * virtual address.
12667                          */
12668                         if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12669                                 msg.dt.sg_list[0].addr =
12670                                         io->scsiio.kern_data_ptr;
12671                         } else {
12672                                 /*
12673                                  * XXX KDM use busdma here!
12674                                  */
12675 #if 0
12676                                 msg.dt.sg_list[0].addr = (void *)
12677                                         vtophys(io->scsiio.kern_data_ptr);
12678 #endif
12679                         }
12680
12681                         msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12682                         do_sg_copy = 0;
12683                 } else {
12684                         struct ctl_sg_entry *sgl;
12685
12686                         do_sg_copy = 1;
12687                         msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12688                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12689                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12690                                 /*
12691                                  * XXX KDM use bus_dmamap_sync() here.
12692                                  */
12693                         }
12694                 }
12695
12696                 msg.dt.kern_data_len = io->scsiio.kern_data_len;
12697                 msg.dt.kern_total_len = io->scsiio.kern_total_len;
12698                 msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12699                 msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12700                 msg.dt.sg_sequence = 0;
12701
12702                 /*
12703                  * Loop until we've sent all of the S/G entries.  On the
12704                  * other end, we'll recompose these S/G entries into one
12705                  * contiguous list before passing it to the
12706                  */
12707                 for (sg_entries_sent = 0; sg_entries_sent <
12708                      msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12709                         msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12710                                 sizeof(msg.dt.sg_list[0])),
12711                                 msg.dt.kern_sg_entries - sg_entries_sent);
12712
12713                         if (do_sg_copy != 0) {
12714                                 struct ctl_sg_entry *sgl;
12715                                 int j;
12716
12717                                 sgl = (struct ctl_sg_entry *)
12718                                         io->scsiio.kern_data_ptr;
12719                                 /*
12720                                  * If this is in cached memory, flush the cache
12721                                  * before we send the DMA request to the other
12722                                  * controller.  We want to do this in either
12723                                  * the * read or the write case.  The read
12724                                  * case is straightforward.  In the write
12725                                  * case, we want to make sure nothing is
12726                                  * in the local cache that could overwrite
12727                                  * the DMAed data.
12728                                  */
12729
12730                                 for (i = sg_entries_sent, j = 0;
12731                                      i < msg.dt.cur_sg_entries; i++, j++) {
12732                                         if ((io->io_hdr.flags &
12733                                              CTL_FLAG_NO_DATASYNC) == 0) {
12734                                                 /*
12735                                                  * XXX KDM use bus_dmamap_sync()
12736                                                  */
12737                                         }
12738                                         if ((io->io_hdr.flags &
12739                                              CTL_FLAG_BUS_ADDR) == 0) {
12740                                                 /*
12741                                                  * XXX KDM use busdma.
12742                                                  */
12743 #if 0
12744                                                 msg.dt.sg_list[j].addr =(void *)
12745                                                        vtophys(sgl[i].addr);
12746 #endif
12747                                         } else {
12748                                                 msg.dt.sg_list[j].addr =
12749                                                         sgl[i].addr;
12750                                         }
12751                                         msg.dt.sg_list[j].len = sgl[i].len;
12752                                 }
12753                         }
12754
12755                         sg_entries_sent += msg.dt.cur_sg_entries;
12756                         if (sg_entries_sent >= msg.dt.kern_sg_entries)
12757                                 msg.dt.sg_last = 1;
12758                         else
12759                                 msg.dt.sg_last = 0;
12760
12761                         /*
12762                          * XXX KDM drop and reacquire the lock here?
12763                          */
12764                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12765                             sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12766                                 /*
12767                                  * XXX do something here.
12768                                  */
12769                         }
12770
12771                         msg.dt.sent_sg_entries = sg_entries_sent;
12772                 }
12773                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12774                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12775                         ctl_failover_io(io, /*have_lock*/ 0);
12776
12777         } else {
12778
12779                 /*
12780                  * Lookup the fe_datamove() function for this particular
12781                  * front end.
12782                  */
12783                 fe_datamove =
12784                     control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12785
12786                 fe_datamove(io);
12787         }
12788 }
12789
12790 static void
12791 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12792 {
12793         union ctl_ha_msg msg;
12794         int isc_status;
12795
12796         memset(&msg, 0, sizeof(msg));
12797
12798         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12799         msg.hdr.original_sc = io;
12800         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12801         msg.hdr.nexus = io->io_hdr.nexus;
12802         msg.hdr.status = io->io_hdr.status;
12803         msg.scsi.tag_num = io->scsiio.tag_num;
12804         msg.scsi.tag_type = io->scsiio.tag_type;
12805         msg.scsi.scsi_status = io->scsiio.scsi_status;
12806         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12807                sizeof(io->scsiio.sense_data));
12808         msg.scsi.sense_len = io->scsiio.sense_len;
12809         msg.scsi.sense_residual = io->scsiio.sense_residual;
12810         msg.scsi.fetd_status = io->io_hdr.port_status;
12811         msg.scsi.residual = io->scsiio.residual;
12812         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12813
12814         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12815                 ctl_failover_io(io, /*have_lock*/ have_lock);
12816                 return;
12817         }
12818
12819         isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12820         if (isc_status > CTL_HA_STATUS_SUCCESS) {
12821                 /* XXX do something if this fails */
12822         }
12823
12824 }
12825
12826 /*
12827  * The DMA to the remote side is done, now we need to tell the other side
12828  * we're done so it can continue with its data movement.
12829  */
12830 static void
12831 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12832 {
12833         union ctl_io *io;
12834
12835         io = rq->context;
12836
12837         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12838                 printf("%s: ISC DMA write failed with error %d", __func__,
12839                        rq->ret);
12840                 ctl_set_internal_failure(&io->scsiio,
12841                                          /*sks_valid*/ 1,
12842                                          /*retry_count*/ rq->ret);
12843         }
12844
12845         ctl_dt_req_free(rq);
12846
12847         /*
12848          * In this case, we had to malloc the memory locally.  Free it.
12849          */
12850         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12851                 int i;
12852                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12853                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
12854         }
12855         /*
12856          * The data is in local and remote memory, so now we need to send
12857          * status (good or back) back to the other side.
12858          */
12859         ctl_send_datamove_done(io, /*have_lock*/ 0);
12860 }
12861
12862 /*
12863  * We've moved the data from the host/controller into local memory.  Now we
12864  * need to push it over to the remote controller's memory.
12865  */
12866 static int
12867 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12868 {
12869         int retval;
12870
12871         retval = 0;
12872
12873         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12874                                           ctl_datamove_remote_write_cb);
12875
12876         return (retval);
12877 }
12878
12879 static void
12880 ctl_datamove_remote_write(union ctl_io *io)
12881 {
12882         int retval;
12883         void (*fe_datamove)(union ctl_io *io);
12884
12885         /*
12886          * - Get the data from the host/HBA into local memory.
12887          * - DMA memory from the local controller to the remote controller.
12888          * - Send status back to the remote controller.
12889          */
12890
12891         retval = ctl_datamove_remote_sgl_setup(io);
12892         if (retval != 0)
12893                 return;
12894
12895         /* Switch the pointer over so the FETD knows what to do */
12896         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12897
12898         /*
12899          * Use a custom move done callback, since we need to send completion
12900          * back to the other controller, not to the backend on this side.
12901          */
12902         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12903
12904         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12905
12906         fe_datamove(io);
12907
12908         return;
12909
12910 }
12911
12912 static int
12913 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12914 {
12915 #if 0
12916         char str[256];
12917         char path_str[64];
12918         struct sbuf sb;
12919 #endif
12920
12921         /*
12922          * In this case, we had to malloc the memory locally.  Free it.
12923          */
12924         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12925                 int i;
12926                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12927                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
12928         }
12929
12930 #if 0
12931         scsi_path_string(io, path_str, sizeof(path_str));
12932         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12933         sbuf_cat(&sb, path_str);
12934         scsi_command_string(&io->scsiio, NULL, &sb);
12935         sbuf_printf(&sb, "\n");
12936         sbuf_cat(&sb, path_str);
12937         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12938                     io->scsiio.tag_num, io->scsiio.tag_type);
12939         sbuf_cat(&sb, path_str);
12940         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12941                     io->io_hdr.flags, io->io_hdr.status);
12942         sbuf_finish(&sb);
12943         printk("%s", sbuf_data(&sb));
12944 #endif
12945
12946
12947         /*
12948          * The read is done, now we need to send status (good or bad) back
12949          * to the other side.
12950          */
12951         ctl_send_datamove_done(io, /*have_lock*/ 0);
12952
12953         return (0);
12954 }
12955
12956 static void
12957 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12958 {
12959         union ctl_io *io;
12960         void (*fe_datamove)(union ctl_io *io);
12961
12962         io = rq->context;
12963
12964         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12965                 printf("%s: ISC DMA read failed with error %d", __func__,
12966                        rq->ret);
12967                 ctl_set_internal_failure(&io->scsiio,
12968                                          /*sks_valid*/ 1,
12969                                          /*retry_count*/ rq->ret);
12970         }
12971
12972         ctl_dt_req_free(rq);
12973
12974         /* Switch the pointer over so the FETD knows what to do */
12975         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12976
12977         /*
12978          * Use a custom move done callback, since we need to send completion
12979          * back to the other controller, not to the backend on this side.
12980          */
12981         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12982
12983         /* XXX KDM add checks like the ones in ctl_datamove? */
12984
12985         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12986
12987         fe_datamove(io);
12988 }
12989
12990 static int
12991 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12992 {
12993         struct ctl_sg_entry *local_sglist, *remote_sglist;
12994         struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
12995         struct ctl_softc *softc;
12996         int retval;
12997         int i;
12998
12999         retval = 0;
13000         softc = control_softc;
13001
13002         local_sglist = io->io_hdr.local_sglist;
13003         local_dma_sglist = io->io_hdr.local_dma_sglist;
13004         remote_sglist = io->io_hdr.remote_sglist;
13005         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13006
13007         if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13008                 for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13009                         local_sglist[i].len = remote_sglist[i].len;
13010
13011                         /*
13012                          * XXX Detect the situation where the RS-level I/O
13013                          * redirector on the other side has already read the
13014                          * data off of the AOR RS on this side, and
13015                          * transferred it to remote (mirror) memory on the
13016                          * other side.  Since we already have the data in
13017                          * memory here, we just need to use it.
13018                          *
13019                          * XXX KDM this can probably be removed once we
13020                          * get the cache device code in and take the
13021                          * current AOR implementation out.
13022                          */
13023 #ifdef NEEDTOPORT
13024                         if ((remote_sglist[i].addr >=
13025                              (void *)vtophys(softc->mirr->addr))
13026                          && (remote_sglist[i].addr <
13027                              ((void *)vtophys(softc->mirr->addr) +
13028                              CacheMirrorOffset))) {
13029                                 local_sglist[i].addr = remote_sglist[i].addr -
13030                                         CacheMirrorOffset;
13031                                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13032                                      CTL_FLAG_DATA_IN)
13033                                         io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13034                         } else {
13035                                 local_sglist[i].addr = remote_sglist[i].addr +
13036                                         CacheMirrorOffset;
13037                         }
13038 #endif
13039 #if 0
13040                         printf("%s: local %p, remote %p, len %d\n",
13041                                __func__, local_sglist[i].addr,
13042                                remote_sglist[i].addr, local_sglist[i].len);
13043 #endif
13044                 }
13045         } else {
13046                 uint32_t len_to_go;
13047
13048                 /*
13049                  * In this case, we don't have automatically allocated
13050                  * memory for this I/O on this controller.  This typically
13051                  * happens with internal CTL I/O -- e.g. inquiry, mode
13052                  * sense, etc.  Anything coming from RAIDCore will have
13053                  * a mirror area available.
13054                  */
13055                 len_to_go = io->scsiio.kern_data_len;
13056
13057                 /*
13058                  * Clear the no datasync flag, we have to use malloced
13059                  * buffers.
13060                  */
13061                 io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13062
13063                 /*
13064                  * The difficult thing here is that the size of the various
13065                  * S/G segments may be different than the size from the
13066                  * remote controller.  That'll make it harder when DMAing
13067                  * the data back to the other side.
13068                  */
13069                 for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13070                      sizeof(io->io_hdr.remote_sglist[0])) &&
13071                      (len_to_go > 0); i++) {
13072                         local_sglist[i].len = ctl_min(len_to_go, 131072);
13073                         CTL_SIZE_8B(local_dma_sglist[i].len,
13074                                     local_sglist[i].len);
13075                         local_sglist[i].addr =
13076                                 malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13077
13078                         local_dma_sglist[i].addr = local_sglist[i].addr;
13079
13080                         if (local_sglist[i].addr == NULL) {
13081                                 int j;
13082
13083                                 printf("malloc failed for %zd bytes!",
13084                                        local_dma_sglist[i].len);
13085                                 for (j = 0; j < i; j++) {
13086                                         free(local_sglist[j].addr, M_CTL);
13087                                 }
13088                                 ctl_set_internal_failure(&io->scsiio,
13089                                                          /*sks_valid*/ 1,
13090                                                          /*retry_count*/ 4857);
13091                                 retval = 1;
13092                                 goto bailout_error;
13093                                 
13094                         }
13095                         /* XXX KDM do we need a sync here? */
13096
13097                         len_to_go -= local_sglist[i].len;
13098                 }
13099                 /*
13100                  * Reset the number of S/G entries accordingly.  The
13101                  * original number of S/G entries is available in
13102                  * rem_sg_entries.
13103                  */
13104                 io->scsiio.kern_sg_entries = i;
13105
13106 #if 0
13107                 printf("%s: kern_sg_entries = %d\n", __func__,
13108                        io->scsiio.kern_sg_entries);
13109                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13110                         printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13111                                local_sglist[i].addr, local_sglist[i].len,
13112                                local_dma_sglist[i].len);
13113 #endif
13114         }
13115
13116
13117         return (retval);
13118
13119 bailout_error:
13120
13121         ctl_send_datamove_done(io, /*have_lock*/ 0);
13122
13123         return (retval);
13124 }
13125
13126 static int
13127 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13128                          ctl_ha_dt_cb callback)
13129 {
13130         struct ctl_ha_dt_req *rq;
13131         struct ctl_sg_entry *remote_sglist, *local_sglist;
13132         struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13133         uint32_t local_used, remote_used, total_used;
13134         int retval;
13135         int i, j;
13136
13137         retval = 0;
13138
13139         rq = ctl_dt_req_alloc();
13140
13141         /*
13142          * If we failed to allocate the request, and if the DMA didn't fail
13143          * anyway, set busy status.  This is just a resource allocation
13144          * failure.
13145          */
13146         if ((rq == NULL)
13147          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13148                 ctl_set_busy(&io->scsiio);
13149
13150         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13151
13152                 if (rq != NULL)
13153                         ctl_dt_req_free(rq);
13154
13155                 /*
13156                  * The data move failed.  We need to return status back
13157                  * to the other controller.  No point in trying to DMA
13158                  * data to the remote controller.
13159                  */
13160
13161                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13162
13163                 retval = 1;
13164
13165                 goto bailout;
13166         }
13167
13168         local_sglist = io->io_hdr.local_sglist;
13169         local_dma_sglist = io->io_hdr.local_dma_sglist;
13170         remote_sglist = io->io_hdr.remote_sglist;
13171         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13172         local_used = 0;
13173         remote_used = 0;
13174         total_used = 0;
13175
13176         if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13177                 rq->ret = CTL_HA_STATUS_SUCCESS;
13178                 rq->context = io;
13179                 callback(rq);
13180                 goto bailout;
13181         }
13182
13183         /*
13184          * Pull/push the data over the wire from/to the other controller.
13185          * This takes into account the possibility that the local and
13186          * remote sglists may not be identical in terms of the size of
13187          * the elements and the number of elements.
13188          *
13189          * One fundamental assumption here is that the length allocated for
13190          * both the local and remote sglists is identical.  Otherwise, we've
13191          * essentially got a coding error of some sort.
13192          */
13193         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13194                 int isc_ret;
13195                 uint32_t cur_len, dma_length;
13196                 uint8_t *tmp_ptr;
13197
13198                 rq->id = CTL_HA_DATA_CTL;
13199                 rq->command = command;
13200                 rq->context = io;
13201
13202                 /*
13203                  * Both pointers should be aligned.  But it is possible
13204                  * that the allocation length is not.  They should both
13205                  * also have enough slack left over at the end, though,
13206                  * to round up to the next 8 byte boundary.
13207                  */
13208                 cur_len = ctl_min(local_sglist[i].len - local_used,
13209                                   remote_sglist[j].len - remote_used);
13210
13211                 /*
13212                  * In this case, we have a size issue and need to decrease
13213                  * the size, except in the case where we actually have less
13214                  * than 8 bytes left.  In that case, we need to increase
13215                  * the DMA length to get the last bit.
13216                  */
13217                 if ((cur_len & 0x7) != 0) {
13218                         if (cur_len > 0x7) {
13219                                 cur_len = cur_len - (cur_len & 0x7);
13220                                 dma_length = cur_len;
13221                         } else {
13222                                 CTL_SIZE_8B(dma_length, cur_len);
13223                         }
13224
13225                 } else
13226                         dma_length = cur_len;
13227
13228                 /*
13229                  * If we had to allocate memory for this I/O, instead of using
13230                  * the non-cached mirror memory, we'll need to flush the cache
13231                  * before trying to DMA to the other controller.
13232                  *
13233                  * We could end up doing this multiple times for the same
13234                  * segment if we have a larger local segment than remote
13235                  * segment.  That shouldn't be an issue.
13236                  */
13237                 if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13238                         /*
13239                          * XXX KDM use bus_dmamap_sync() here.
13240                          */
13241                 }
13242
13243                 rq->size = dma_length;
13244
13245                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
13246                 tmp_ptr += local_used;
13247
13248                 /* Use physical addresses when talking to ISC hardware */
13249                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13250                         /* XXX KDM use busdma */
13251 #if 0
13252                         rq->local = vtophys(tmp_ptr);
13253 #endif
13254                 } else
13255                         rq->local = tmp_ptr;
13256
13257                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13258                 tmp_ptr += remote_used;
13259                 rq->remote = tmp_ptr;
13260
13261                 rq->callback = NULL;
13262
13263                 local_used += cur_len;
13264                 if (local_used >= local_sglist[i].len) {
13265                         i++;
13266                         local_used = 0;
13267                 }
13268
13269                 remote_used += cur_len;
13270                 if (remote_used >= remote_sglist[j].len) {
13271                         j++;
13272                         remote_used = 0;
13273                 }
13274                 total_used += cur_len;
13275
13276                 if (total_used >= io->scsiio.kern_data_len)
13277                         rq->callback = callback;
13278
13279                 if ((rq->size & 0x7) != 0) {
13280                         printf("%s: warning: size %d is not on 8b boundary\n",
13281                                __func__, rq->size);
13282                 }
13283                 if (((uintptr_t)rq->local & 0x7) != 0) {
13284                         printf("%s: warning: local %p not on 8b boundary\n",
13285                                __func__, rq->local);
13286                 }
13287                 if (((uintptr_t)rq->remote & 0x7) != 0) {
13288                         printf("%s: warning: remote %p not on 8b boundary\n",
13289                                __func__, rq->local);
13290                 }
13291 #if 0
13292                 printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13293                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13294                        rq->local, rq->remote, rq->size);
13295 #endif
13296
13297                 isc_ret = ctl_dt_single(rq);
13298                 if (isc_ret == CTL_HA_STATUS_WAIT)
13299                         continue;
13300
13301                 if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13302                         rq->ret = CTL_HA_STATUS_SUCCESS;
13303                 } else {
13304                         rq->ret = isc_ret;
13305                 }
13306                 callback(rq);
13307                 goto bailout;
13308         }
13309
13310 bailout:
13311         return (retval);
13312
13313 }
13314
13315 static void
13316 ctl_datamove_remote_read(union ctl_io *io)
13317 {
13318         int retval;
13319         int i;
13320
13321         /*
13322          * This will send an error to the other controller in the case of a
13323          * failure.
13324          */
13325         retval = ctl_datamove_remote_sgl_setup(io);
13326         if (retval != 0)
13327                 return;
13328
13329         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13330                                           ctl_datamove_remote_read_cb);
13331         if ((retval != 0)
13332          && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13333                 /*
13334                  * Make sure we free memory if there was an error..  The
13335                  * ctl_datamove_remote_xfer() function will send the
13336                  * datamove done message, or call the callback with an
13337                  * error if there is a problem.
13338                  */
13339                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13340                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13341         }
13342
13343         return;
13344 }
13345
13346 /*
13347  * Process a datamove request from the other controller.  This is used for
13348  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13349  * first.  Once that is complete, the data gets DMAed into the remote
13350  * controller's memory.  For reads, we DMA from the remote controller's
13351  * memory into our memory first, and then move it out to the FETD.
13352  */
13353 static void
13354 ctl_datamove_remote(union ctl_io *io)
13355 {
13356         struct ctl_softc *softc;
13357
13358         softc = control_softc;
13359
13360         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13361
13362         /*
13363          * Note that we look for an aborted I/O here, but don't do some of
13364          * the other checks that ctl_datamove() normally does.
13365          * We don't need to run the datamove delay code, since that should
13366          * have been done if need be on the other controller.
13367          */
13368         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13369                 printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13370                        io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13371                        io->io_hdr.nexus.targ_port,
13372                        io->io_hdr.nexus.targ_target.id,
13373                        io->io_hdr.nexus.targ_lun);
13374                 io->io_hdr.port_status = 31338;
13375                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13376                 return;
13377         }
13378
13379         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13380                 ctl_datamove_remote_write(io);
13381         } else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13382                 ctl_datamove_remote_read(io);
13383         } else {
13384                 union ctl_ha_msg msg;
13385                 struct scsi_sense_data *sense;
13386                 uint8_t sks[3];
13387                 int retry_count;
13388
13389                 memset(&msg, 0, sizeof(msg));
13390
13391                 msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13392                 msg.hdr.status = CTL_SCSI_ERROR;
13393                 msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13394
13395                 retry_count = 4243;
13396
13397                 sense = &msg.scsi.sense_data;
13398                 sks[0] = SSD_SCS_VALID;
13399                 sks[1] = (retry_count >> 8) & 0xff;
13400                 sks[2] = retry_count & 0xff;
13401
13402                 /* "Internal target failure" */
13403                 scsi_set_sense_data(sense,
13404                                     /*sense_format*/ SSD_TYPE_NONE,
13405                                     /*current_error*/ 1,
13406                                     /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13407                                     /*asc*/ 0x44,
13408                                     /*ascq*/ 0x00,
13409                                     /*type*/ SSD_ELEM_SKS,
13410                                     /*size*/ sizeof(sks),
13411                                     /*data*/ sks,
13412                                     SSD_ELEM_NONE);
13413
13414                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13415                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13416                         ctl_failover_io(io, /*have_lock*/ 1);
13417                         return;
13418                 }
13419
13420                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13421                     CTL_HA_STATUS_SUCCESS) {
13422                         /* XXX KDM what to do if this fails? */
13423                 }
13424                 return;
13425         }
13426         
13427 }
13428
13429 static int
13430 ctl_process_done(union ctl_io *io)
13431 {
13432         struct ctl_lun *lun;
13433         struct ctl_softc *softc = control_softc;
13434         void (*fe_done)(union ctl_io *io);
13435         uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13436
13437         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13438
13439         fe_done = softc->ctl_ports[targ_port]->fe_done;
13440
13441 #ifdef CTL_TIME_IO
13442         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13443                 char str[256];
13444                 char path_str[64];
13445                 struct sbuf sb;
13446
13447                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13448                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13449
13450                 sbuf_cat(&sb, path_str);
13451                 switch (io->io_hdr.io_type) {
13452                 case CTL_IO_SCSI:
13453                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13454                         sbuf_printf(&sb, "\n");
13455                         sbuf_cat(&sb, path_str);
13456                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13457                                     io->scsiio.tag_num, io->scsiio.tag_type);
13458                         break;
13459                 case CTL_IO_TASK:
13460                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13461                                     "Tag Type: %d\n", io->taskio.task_action,
13462                                     io->taskio.tag_num, io->taskio.tag_type);
13463                         break;
13464                 default:
13465                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13466                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13467                         break;
13468                 }
13469                 sbuf_cat(&sb, path_str);
13470                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13471                             (intmax_t)time_uptime - io->io_hdr.start_time);
13472                 sbuf_finish(&sb);
13473                 printf("%s", sbuf_data(&sb));
13474         }
13475 #endif /* CTL_TIME_IO */
13476
13477         switch (io->io_hdr.io_type) {
13478         case CTL_IO_SCSI:
13479                 break;
13480         case CTL_IO_TASK:
13481                 if (bootverbose || (ctl_debug & CTL_DEBUG_INFO))
13482                         ctl_io_error_print(io, NULL);
13483                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13484                         ctl_free_io(io);
13485                 else
13486                         fe_done(io);
13487                 return (CTL_RETVAL_COMPLETE);
13488         default:
13489                 panic("ctl_process_done: invalid io type %d\n",
13490                       io->io_hdr.io_type);
13491                 break; /* NOTREACHED */
13492         }
13493
13494         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13495         if (lun == NULL) {
13496                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13497                                  io->io_hdr.nexus.targ_mapped_lun));
13498                 goto bailout;
13499         }
13500
13501         mtx_lock(&lun->lun_lock);
13502
13503         /*
13504          * Check to see if we have any errors to inject here.  We only
13505          * inject errors for commands that don't already have errors set.
13506          */
13507         if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13508             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13509             ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13510                 ctl_inject_error(lun, io);
13511
13512         /*
13513          * XXX KDM how do we treat commands that aren't completed
13514          * successfully?
13515          *
13516          * XXX KDM should we also track I/O latency?
13517          */
13518         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13519             io->io_hdr.io_type == CTL_IO_SCSI) {
13520 #ifdef CTL_TIME_IO
13521                 struct bintime cur_bt;
13522 #endif
13523                 int type;
13524
13525                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13526                     CTL_FLAG_DATA_IN)
13527                         type = CTL_STATS_READ;
13528                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13529                     CTL_FLAG_DATA_OUT)
13530                         type = CTL_STATS_WRITE;
13531                 else
13532                         type = CTL_STATS_NO_IO;
13533
13534                 lun->stats.ports[targ_port].bytes[type] +=
13535                     io->scsiio.kern_total_len;
13536                 lun->stats.ports[targ_port].operations[type]++;
13537 #ifdef CTL_TIME_IO
13538                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13539                    &io->io_hdr.dma_bt);
13540                 lun->stats.ports[targ_port].num_dmas[type] +=
13541                     io->io_hdr.num_dmas;
13542                 getbintime(&cur_bt);
13543                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13544                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13545 #endif
13546         }
13547
13548         /*
13549          * Remove this from the OOA queue.
13550          */
13551         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13552
13553         /*
13554          * Run through the blocked queue on this LUN and see if anything
13555          * has become unblocked, now that this transaction is done.
13556          */
13557         ctl_check_blocked(lun);
13558
13559         /*
13560          * If the LUN has been invalidated, free it if there is nothing
13561          * left on its OOA queue.
13562          */
13563         if ((lun->flags & CTL_LUN_INVALID)
13564          && TAILQ_EMPTY(&lun->ooa_queue)) {
13565                 mtx_unlock(&lun->lun_lock);
13566                 mtx_lock(&softc->ctl_lock);
13567                 ctl_free_lun(lun);
13568                 mtx_unlock(&softc->ctl_lock);
13569         } else
13570                 mtx_unlock(&lun->lun_lock);
13571
13572 bailout:
13573
13574         /*
13575          * If this command has been aborted, make sure we set the status
13576          * properly.  The FETD is responsible for freeing the I/O and doing
13577          * whatever it needs to do to clean up its state.
13578          */
13579         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13580                 ctl_set_task_aborted(&io->scsiio);
13581
13582         /*
13583          * If enabled, print command error status.
13584          * We don't print UAs unless debugging was enabled explicitly.
13585          */
13586         do {
13587                 if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)
13588                         break;
13589                 if (!bootverbose && (ctl_debug & CTL_DEBUG_INFO) == 0)
13590                         break;
13591                 if ((ctl_debug & CTL_DEBUG_INFO) == 0 &&
13592                     ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR) &&
13593                      (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13594                         int error_code, sense_key, asc, ascq;
13595
13596                         scsi_extract_sense_len(&io->scsiio.sense_data,
13597                             io->scsiio.sense_len, &error_code, &sense_key,
13598                             &asc, &ascq, /*show_errors*/ 0);
13599                         if (sense_key == SSD_KEY_UNIT_ATTENTION)
13600                                 break;
13601                 }
13602
13603                 ctl_io_error_print(io, NULL);
13604         } while (0);
13605
13606         /*
13607          * Tell the FETD or the other shelf controller we're done with this
13608          * command.  Note that only SCSI commands get to this point.  Task
13609          * management commands are completed above.
13610          *
13611          * We only send status to the other controller if we're in XFER
13612          * mode.  In SER_ONLY mode, the I/O is done on the controller that
13613          * received the I/O (from CTL's perspective), and so the status is
13614          * generated there.
13615          * 
13616          * XXX KDM if we hold the lock here, we could cause a deadlock
13617          * if the frontend comes back in in this context to queue
13618          * something.
13619          */
13620         if ((softc->ha_mode == CTL_HA_MODE_XFER)
13621          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13622                 union ctl_ha_msg msg;
13623
13624                 memset(&msg, 0, sizeof(msg));
13625                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13626                 msg.hdr.original_sc = io->io_hdr.original_sc;
13627                 msg.hdr.nexus = io->io_hdr.nexus;
13628                 msg.hdr.status = io->io_hdr.status;
13629                 msg.scsi.scsi_status = io->scsiio.scsi_status;
13630                 msg.scsi.tag_num = io->scsiio.tag_num;
13631                 msg.scsi.tag_type = io->scsiio.tag_type;
13632                 msg.scsi.sense_len = io->scsiio.sense_len;
13633                 msg.scsi.sense_residual = io->scsiio.sense_residual;
13634                 msg.scsi.residual = io->scsiio.residual;
13635                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13636                        sizeof(io->scsiio.sense_data));
13637                 /*
13638                  * We copy this whether or not this is an I/O-related
13639                  * command.  Otherwise, we'd have to go and check to see
13640                  * whether it's a read/write command, and it really isn't
13641                  * worth it.
13642                  */
13643                 memcpy(&msg.scsi.lbalen,
13644                        &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13645                        sizeof(msg.scsi.lbalen));
13646
13647                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13648                                 sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13649                         /* XXX do something here */
13650                 }
13651
13652                 ctl_free_io(io);
13653         } else 
13654                 fe_done(io);
13655
13656         return (CTL_RETVAL_COMPLETE);
13657 }
13658
13659 #ifdef CTL_WITH_CA
13660 /*
13661  * Front end should call this if it doesn't do autosense.  When the request
13662  * sense comes back in from the initiator, we'll dequeue this and send it.
13663  */
13664 int
13665 ctl_queue_sense(union ctl_io *io)
13666 {
13667         struct ctl_lun *lun;
13668         struct ctl_softc *softc;
13669         uint32_t initidx, targ_lun;
13670
13671         softc = control_softc;
13672
13673         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13674
13675         /*
13676          * LUN lookup will likely move to the ctl_work_thread() once we
13677          * have our new queueing infrastructure (that doesn't put things on
13678          * a per-LUN queue initially).  That is so that we can handle
13679          * things like an INQUIRY to a LUN that we don't have enabled.  We
13680          * can't deal with that right now.
13681          */
13682         mtx_lock(&softc->ctl_lock);
13683
13684         /*
13685          * If we don't have a LUN for this, just toss the sense
13686          * information.
13687          */
13688         targ_lun = io->io_hdr.nexus.targ_lun;
13689         targ_lun = ctl_map_lun(softc, io->io_hdr.nexus.targ_port, targ_lun);
13690         if ((targ_lun < CTL_MAX_LUNS)
13691          && (softc->ctl_luns[targ_lun] != NULL))
13692                 lun = softc->ctl_luns[targ_lun];
13693         else
13694                 goto bailout;
13695
13696         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13697
13698         mtx_lock(&lun->lun_lock);
13699         /*
13700          * Already have CA set for this LUN...toss the sense information.
13701          */
13702         if (ctl_is_set(lun->have_ca, initidx)) {
13703                 mtx_unlock(&lun->lun_lock);
13704                 goto bailout;
13705         }
13706
13707         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13708                ctl_min(sizeof(lun->pending_sense[initidx]),
13709                sizeof(io->scsiio.sense_data)));
13710         ctl_set_mask(lun->have_ca, initidx);
13711         mtx_unlock(&lun->lun_lock);
13712
13713 bailout:
13714         mtx_unlock(&softc->ctl_lock);
13715
13716         ctl_free_io(io);
13717
13718         return (CTL_RETVAL_COMPLETE);
13719 }
13720 #endif
13721
13722 /*
13723  * Primary command inlet from frontend ports.  All SCSI and task I/O
13724  * requests must go through this function.
13725  */
13726 int
13727 ctl_queue(union ctl_io *io)
13728 {
13729
13730         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13731
13732 #ifdef CTL_TIME_IO
13733         io->io_hdr.start_time = time_uptime;
13734         getbintime(&io->io_hdr.start_bt);
13735 #endif /* CTL_TIME_IO */
13736
13737         /* Map FE-specific LUN ID into global one. */
13738         io->io_hdr.nexus.targ_mapped_lun =
13739             ctl_map_lun(control_softc, io->io_hdr.nexus.targ_port,
13740              io->io_hdr.nexus.targ_lun);
13741
13742         switch (io->io_hdr.io_type) {
13743         case CTL_IO_SCSI:
13744         case CTL_IO_TASK:
13745                 if (ctl_debug & CTL_DEBUG_CDB)
13746                         ctl_io_print(io);
13747                 ctl_enqueue_incoming(io);
13748                 break;
13749         default:
13750                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13751                 return (EINVAL);
13752         }
13753
13754         return (CTL_RETVAL_COMPLETE);
13755 }
13756
13757 #ifdef CTL_IO_DELAY
13758 static void
13759 ctl_done_timer_wakeup(void *arg)
13760 {
13761         union ctl_io *io;
13762
13763         io = (union ctl_io *)arg;
13764         ctl_done(io);
13765 }
13766 #endif /* CTL_IO_DELAY */
13767
13768 void
13769 ctl_done(union ctl_io *io)
13770 {
13771
13772         /*
13773          * Enable this to catch duplicate completion issues.
13774          */
13775 #if 0
13776         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13777                 printf("%s: type %d msg %d cdb %x iptl: "
13778                        "%d:%d:%d:%d tag 0x%04x "
13779                        "flag %#x status %x\n",
13780                         __func__,
13781                         io->io_hdr.io_type,
13782                         io->io_hdr.msg_type,
13783                         io->scsiio.cdb[0],
13784                         io->io_hdr.nexus.initid.id,
13785                         io->io_hdr.nexus.targ_port,
13786                         io->io_hdr.nexus.targ_target.id,
13787                         io->io_hdr.nexus.targ_lun,
13788                         (io->io_hdr.io_type ==
13789                         CTL_IO_TASK) ?
13790                         io->taskio.tag_num :
13791                         io->scsiio.tag_num,
13792                         io->io_hdr.flags,
13793                         io->io_hdr.status);
13794         } else
13795                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13796 #endif
13797
13798         /*
13799          * This is an internal copy of an I/O, and should not go through
13800          * the normal done processing logic.
13801          */
13802         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13803                 return;
13804
13805         /*
13806          * We need to send a msg to the serializing shelf to finish the IO
13807          * as well.  We don't send a finish message to the other shelf if
13808          * this is a task management command.  Task management commands
13809          * aren't serialized in the OOA queue, but rather just executed on
13810          * both shelf controllers for commands that originated on that
13811          * controller.
13812          */
13813         if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13814          && (io->io_hdr.io_type != CTL_IO_TASK)) {
13815                 union ctl_ha_msg msg_io;
13816
13817                 msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13818                 msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13819                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13820                     sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13821                 }
13822                 /* continue on to finish IO */
13823         }
13824 #ifdef CTL_IO_DELAY
13825         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13826                 struct ctl_lun *lun;
13827
13828                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13829
13830                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13831         } else {
13832                 struct ctl_lun *lun;
13833
13834                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13835
13836                 if ((lun != NULL)
13837                  && (lun->delay_info.done_delay > 0)) {
13838                         struct callout *callout;
13839
13840                         callout = (struct callout *)&io->io_hdr.timer_bytes;
13841                         callout_init(callout, /*mpsafe*/ 1);
13842                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13843                         callout_reset(callout,
13844                                       lun->delay_info.done_delay * hz,
13845                                       ctl_done_timer_wakeup, io);
13846                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13847                                 lun->delay_info.done_delay = 0;
13848                         return;
13849                 }
13850         }
13851 #endif /* CTL_IO_DELAY */
13852
13853         ctl_enqueue_done(io);
13854 }
13855
13856 int
13857 ctl_isc(struct ctl_scsiio *ctsio)
13858 {
13859         struct ctl_lun *lun;
13860         int retval;
13861
13862         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13863
13864         CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13865
13866         CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13867
13868         retval = lun->backend->data_submit((union ctl_io *)ctsio);
13869
13870         return (retval);
13871 }
13872
13873
13874 static void
13875 ctl_work_thread(void *arg)
13876 {
13877         struct ctl_thread *thr = (struct ctl_thread *)arg;
13878         struct ctl_softc *softc = thr->ctl_softc;
13879         union ctl_io *io;
13880         int retval;
13881
13882         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13883
13884         for (;;) {
13885                 retval = 0;
13886
13887                 /*
13888                  * We handle the queues in this order:
13889                  * - ISC
13890                  * - done queue (to free up resources, unblock other commands)
13891                  * - RtR queue
13892                  * - incoming queue
13893                  *
13894                  * If those queues are empty, we break out of the loop and
13895                  * go to sleep.
13896                  */
13897                 mtx_lock(&thr->queue_lock);
13898                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13899                 if (io != NULL) {
13900                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13901                         mtx_unlock(&thr->queue_lock);
13902                         ctl_handle_isc(io);
13903                         continue;
13904                 }
13905                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13906                 if (io != NULL) {
13907                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13908                         /* clear any blocked commands, call fe_done */
13909                         mtx_unlock(&thr->queue_lock);
13910                         retval = ctl_process_done(io);
13911                         continue;
13912                 }
13913                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13914                 if (io != NULL) {
13915                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13916                         mtx_unlock(&thr->queue_lock);
13917                         if (io->io_hdr.io_type == CTL_IO_TASK)
13918                                 ctl_run_task(io);
13919                         else
13920                                 ctl_scsiio_precheck(softc, &io->scsiio);
13921                         continue;
13922                 }
13923                 if (!ctl_pause_rtr) {
13924                         io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13925                         if (io != NULL) {
13926                                 STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13927                                 mtx_unlock(&thr->queue_lock);
13928                                 retval = ctl_scsiio(&io->scsiio);
13929                                 if (retval != CTL_RETVAL_COMPLETE)
13930                                         CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13931                                 continue;
13932                         }
13933                 }
13934
13935                 /* Sleep until we have something to do. */
13936                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13937         }
13938 }
13939
13940 static void
13941 ctl_lun_thread(void *arg)
13942 {
13943         struct ctl_softc *softc = (struct ctl_softc *)arg;
13944         struct ctl_be_lun *be_lun;
13945         int retval;
13946
13947         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13948
13949         for (;;) {
13950                 retval = 0;
13951                 mtx_lock(&softc->ctl_lock);
13952                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13953                 if (be_lun != NULL) {
13954                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13955                         mtx_unlock(&softc->ctl_lock);
13956                         ctl_create_lun(be_lun);
13957                         continue;
13958                 }
13959
13960                 /* Sleep until we have something to do. */
13961                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13962                     PDROP | PRIBIO, "-", 0);
13963         }
13964 }
13965
13966 static void
13967 ctl_thresh_thread(void *arg)
13968 {
13969         struct ctl_softc *softc = (struct ctl_softc *)arg;
13970         struct ctl_lun *lun;
13971         struct ctl_be_lun *be_lun;
13972         struct scsi_da_rw_recovery_page *rwpage;
13973         struct ctl_logical_block_provisioning_page *page;
13974         const char *attr;
13975         uint64_t thres, val;
13976         int i, e;
13977
13978         CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13979
13980         for (;;) {
13981                 mtx_lock(&softc->ctl_lock);
13982                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
13983                         be_lun = lun->be_lun;
13984                         if ((lun->flags & CTL_LUN_DISABLED) ||
13985                             (lun->flags & CTL_LUN_OFFLINE) ||
13986                             lun->backend->lun_attr == NULL)
13987                                 continue;
13988                         rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13989                         if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13990                                 continue;
13991                         e = 0;
13992                         page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13993                         for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13994                                 if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13995                                         continue;
13996                                 thres = scsi_4btoul(page->descr[i].count);
13997                                 thres <<= CTL_LBP_EXPONENT;
13998                                 switch (page->descr[i].resource) {
13999                                 case 0x01:
14000                                         attr = "blocksavail";
14001                                         break;
14002                                 case 0x02:
14003                                         attr = "blocksused";
14004                                         break;
14005                                 case 0xf1:
14006                                         attr = "poolblocksavail";
14007                                         break;
14008                                 case 0xf2:
14009                                         attr = "poolblocksused";
14010                                         break;
14011                                 default:
14012                                         continue;
14013                                 }
14014                                 mtx_unlock(&softc->ctl_lock); // XXX
14015                                 val = lun->backend->lun_attr(
14016                                     lun->be_lun->be_lun, attr);
14017                                 mtx_lock(&softc->ctl_lock);
14018                                 if (val == UINT64_MAX)
14019                                         continue;
14020                                 if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
14021                                     == SLBPPD_ARMING_INC)
14022                                         e |= (val >= thres);
14023                                 else
14024                                         e |= (val <= thres);
14025                         }
14026                         mtx_lock(&lun->lun_lock);
14027                         if (e) {
14028                                 if (lun->lasttpt == 0 ||
14029                                     time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
14030                                         lun->lasttpt = time_uptime;
14031                                         ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14032                                 }
14033                         } else {
14034                                 lun->lasttpt = 0;
14035                                 ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14036                         }
14037                         mtx_unlock(&lun->lun_lock);
14038                 }
14039                 mtx_unlock(&softc->ctl_lock);
14040                 pause("-", CTL_LBP_PERIOD * hz);
14041         }
14042 }
14043
14044 static void
14045 ctl_enqueue_incoming(union ctl_io *io)
14046 {
14047         struct ctl_softc *softc = control_softc;
14048         struct ctl_thread *thr;
14049         u_int idx;
14050
14051         idx = (io->io_hdr.nexus.targ_port * 127 +
14052                io->io_hdr.nexus.initid.id) % worker_threads;
14053         thr = &softc->threads[idx];
14054         mtx_lock(&thr->queue_lock);
14055         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14056         mtx_unlock(&thr->queue_lock);
14057         wakeup(thr);
14058 }
14059
14060 static void
14061 ctl_enqueue_rtr(union ctl_io *io)
14062 {
14063         struct ctl_softc *softc = control_softc;
14064         struct ctl_thread *thr;
14065
14066         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14067         mtx_lock(&thr->queue_lock);
14068         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14069         mtx_unlock(&thr->queue_lock);
14070         wakeup(thr);
14071 }
14072
14073 static void
14074 ctl_enqueue_done(union ctl_io *io)
14075 {
14076         struct ctl_softc *softc = control_softc;
14077         struct ctl_thread *thr;
14078
14079         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14080         mtx_lock(&thr->queue_lock);
14081         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14082         mtx_unlock(&thr->queue_lock);
14083         wakeup(thr);
14084 }
14085
14086 static void
14087 ctl_enqueue_isc(union ctl_io *io)
14088 {
14089         struct ctl_softc *softc = control_softc;
14090         struct ctl_thread *thr;
14091
14092         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14093         mtx_lock(&thr->queue_lock);
14094         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14095         mtx_unlock(&thr->queue_lock);
14096         wakeup(thr);
14097 }
14098
14099 /* Initialization and failover */
14100
14101 void
14102 ctl_init_isc_msg(void)
14103 {
14104         printf("CTL: Still calling this thing\n");
14105 }
14106
14107 /*
14108  * Init component
14109  *      Initializes component into configuration defined by bootMode
14110  *      (see hasc-sv.c)
14111  *      returns hasc_Status:
14112  *              OK
14113  *              ERROR - fatal error
14114  */
14115 static ctl_ha_comp_status
14116 ctl_isc_init(struct ctl_ha_component *c)
14117 {
14118         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14119
14120         c->status = ret;
14121         return ret;
14122 }
14123
14124 /* Start component
14125  *      Starts component in state requested. If component starts successfully,
14126  *      it must set its own state to the requestrd state
14127  *      When requested state is HASC_STATE_HA, the component may refine it
14128  *      by adding _SLAVE or _MASTER flags.
14129  *      Currently allowed state transitions are:
14130  *      UNKNOWN->HA             - initial startup
14131  *      UNKNOWN->SINGLE - initial startup when no parter detected
14132  *      HA->SINGLE              - failover
14133  * returns ctl_ha_comp_status:
14134  *              OK      - component successfully started in requested state
14135  *              FAILED  - could not start the requested state, failover may
14136  *                        be possible
14137  *              ERROR   - fatal error detected, no future startup possible
14138  */
14139 static ctl_ha_comp_status
14140 ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14141 {
14142         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14143
14144         printf("%s: go\n", __func__);
14145
14146         // UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14147         if (c->state == CTL_HA_STATE_UNKNOWN ) {
14148                 control_softc->is_single = 0;
14149                 if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14150                     != CTL_HA_STATUS_SUCCESS) {
14151                         printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14152                         ret = CTL_HA_COMP_STATUS_ERROR;
14153                 }
14154         } else if (CTL_HA_STATE_IS_HA(c->state)
14155                 && CTL_HA_STATE_IS_SINGLE(state)){
14156                 // HA->SINGLE transition
14157                 ctl_failover();
14158                 control_softc->is_single = 1;
14159         } else {
14160                 printf("ctl_isc_start:Invalid state transition %X->%X\n",
14161                        c->state, state);
14162                 ret = CTL_HA_COMP_STATUS_ERROR;
14163         }
14164         if (CTL_HA_STATE_IS_SINGLE(state))
14165                 control_softc->is_single = 1;
14166
14167         c->state = state;
14168         c->status = ret;
14169         return ret;
14170 }
14171
14172 /*
14173  * Quiesce component
14174  * The component must clear any error conditions (set status to OK) and
14175  * prepare itself to another Start call
14176  * returns ctl_ha_comp_status:
14177  *      OK
14178  *      ERROR
14179  */
14180 static ctl_ha_comp_status
14181 ctl_isc_quiesce(struct ctl_ha_component *c)
14182 {
14183         int ret = CTL_HA_COMP_STATUS_OK;
14184
14185         ctl_pause_rtr = 1;
14186         c->status = ret;
14187         return ret;
14188 }
14189
14190 struct ctl_ha_component ctl_ha_component_ctlisc =
14191 {
14192         .name = "CTL ISC",
14193         .state = CTL_HA_STATE_UNKNOWN,
14194         .init = ctl_isc_init,
14195         .start = ctl_isc_start,
14196         .quiesce = ctl_isc_quiesce
14197 };
14198
14199 /*
14200  *  vim: ts=8
14201  */