]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cam/ctl/ctl.c
MFC r275455: Remove some unused code.
[FreeBSD/stable/10.git] / sys / cam / ctl / ctl.c
1 /*-
2  * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3  * Copyright (c) 2012 The FreeBSD Foundation
4  * All rights reserved.
5  *
6  * Portions of this software were developed by Edward Tomasz Napierala
7  * under sponsorship from the FreeBSD Foundation.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions, and the following disclaimer,
14  *    without modification.
15  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
16  *    substantially similar to the "NO WARRANTY" disclaimer below
17  *    ("Disclaimer") and any redistribution must be conditioned upon
18  *    including a substantially similar Disclaimer requirement for further
19  *    binary redistribution.
20  *
21  * NO WARRANTY
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
25  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
31  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGES.
33  *
34  * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/ctl.c#8 $
35  */
36 /*
37  * CAM Target Layer, a SCSI device emulation subsystem.
38  *
39  * Author: Ken Merry <ken@FreeBSD.org>
40  */
41
42 #define _CTL_C
43
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/ctype.h>
50 #include <sys/kernel.h>
51 #include <sys/types.h>
52 #include <sys/kthread.h>
53 #include <sys/bio.h>
54 #include <sys/fcntl.h>
55 #include <sys/lock.h>
56 #include <sys/module.h>
57 #include <sys/mutex.h>
58 #include <sys/condvar.h>
59 #include <sys/malloc.h>
60 #include <sys/conf.h>
61 #include <sys/ioccom.h>
62 #include <sys/queue.h>
63 #include <sys/sbuf.h>
64 #include <sys/smp.h>
65 #include <sys/endian.h>
66 #include <sys/sysctl.h>
67 #include <vm/uma.h>
68
69 #include <cam/cam.h>
70 #include <cam/scsi/scsi_all.h>
71 #include <cam/scsi/scsi_da.h>
72 #include <cam/ctl/ctl_io.h>
73 #include <cam/ctl/ctl.h>
74 #include <cam/ctl/ctl_frontend.h>
75 #include <cam/ctl/ctl_frontend_internal.h>
76 #include <cam/ctl/ctl_util.h>
77 #include <cam/ctl/ctl_backend.h>
78 #include <cam/ctl/ctl_ioctl.h>
79 #include <cam/ctl/ctl_ha.h>
80 #include <cam/ctl/ctl_private.h>
81 #include <cam/ctl/ctl_debug.h>
82 #include <cam/ctl/ctl_scsi_all.h>
83 #include <cam/ctl/ctl_error.h>
84
85 struct ctl_softc *control_softc = NULL;
86
87 /*
88  * Size and alignment macros needed for Copan-specific HA hardware.  These
89  * can go away when the HA code is re-written, and uses busdma for any
90  * hardware.
91  */
92 #define CTL_ALIGN_8B(target, source, type)                              \
93         if (((uint32_t)source & 0x7) != 0)                              \
94                 target = (type)(source + (0x8 - ((uint32_t)source & 0x7)));\
95         else                                                            \
96                 target = (type)source;
97
98 #define CTL_SIZE_8B(target, size)                                       \
99         if ((size & 0x7) != 0)                                          \
100                 target = size + (0x8 - (size & 0x7));                   \
101         else                                                            \
102                 target = size;
103
104 #define CTL_ALIGN_8B_MARGIN     16
105
106 /*
107  * Template mode pages.
108  */
109
110 /*
111  * Note that these are default values only.  The actual values will be
112  * filled in when the user does a mode sense.
113  */
114 static struct copan_debugconf_subpage debugconf_page_default = {
115         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
116         DBGCNF_SUBPAGE_CODE,            /* subpage */
117         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
118          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
119         DBGCNF_VERSION,                 /* page_version */
120         {CTL_TIME_IO_DEFAULT_SECS>>8,
121          CTL_TIME_IO_DEFAULT_SECS>>0},  /* ctl_time_io_secs */
122 };
123
124 static struct copan_debugconf_subpage debugconf_page_changeable = {
125         DBGCNF_PAGE_CODE | SMPH_SPF,    /* page_code */
126         DBGCNF_SUBPAGE_CODE,            /* subpage */
127         {(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
128          (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
129         0,                              /* page_version */
130         {0xff,0xff},                    /* ctl_time_io_secs */
131 };
132
133 static struct scsi_da_rw_recovery_page rw_er_page_default = {
134         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
135         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
136         /*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
137         /*read_retry_count*/0,
138         /*correction_span*/0,
139         /*head_offset_count*/0,
140         /*data_strobe_offset_cnt*/0,
141         /*byte8*/SMS_RWER_LBPERE,
142         /*write_retry_count*/0,
143         /*reserved2*/0,
144         /*recovery_time_limit*/{0, 0},
145 };
146
147 static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
148         /*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
149         /*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
150         /*byte3*/0,
151         /*read_retry_count*/0,
152         /*correction_span*/0,
153         /*head_offset_count*/0,
154         /*data_strobe_offset_cnt*/0,
155         /*byte8*/0,
156         /*write_retry_count*/0,
157         /*reserved2*/0,
158         /*recovery_time_limit*/{0, 0},
159 };
160
161 static struct scsi_format_page format_page_default = {
162         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
163         /*page_length*/sizeof(struct scsi_format_page) - 2,
164         /*tracks_per_zone*/ {0, 0},
165         /*alt_sectors_per_zone*/ {0, 0},
166         /*alt_tracks_per_zone*/ {0, 0},
167         /*alt_tracks_per_lun*/ {0, 0},
168         /*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
169                                 CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
170         /*bytes_per_sector*/ {0, 0},
171         /*interleave*/ {0, 0},
172         /*track_skew*/ {0, 0},
173         /*cylinder_skew*/ {0, 0},
174         /*flags*/ SFP_HSEC,
175         /*reserved*/ {0, 0, 0}
176 };
177
178 static struct scsi_format_page format_page_changeable = {
179         /*page_code*/SMS_FORMAT_DEVICE_PAGE,
180         /*page_length*/sizeof(struct scsi_format_page) - 2,
181         /*tracks_per_zone*/ {0, 0},
182         /*alt_sectors_per_zone*/ {0, 0},
183         /*alt_tracks_per_zone*/ {0, 0},
184         /*alt_tracks_per_lun*/ {0, 0},
185         /*sectors_per_track*/ {0, 0},
186         /*bytes_per_sector*/ {0, 0},
187         /*interleave*/ {0, 0},
188         /*track_skew*/ {0, 0},
189         /*cylinder_skew*/ {0, 0},
190         /*flags*/ 0,
191         /*reserved*/ {0, 0, 0}
192 };
193
194 static struct scsi_rigid_disk_page rigid_disk_page_default = {
195         /*page_code*/SMS_RIGID_DISK_PAGE,
196         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
197         /*cylinders*/ {0, 0, 0},
198         /*heads*/ CTL_DEFAULT_HEADS,
199         /*start_write_precomp*/ {0, 0, 0},
200         /*start_reduced_current*/ {0, 0, 0},
201         /*step_rate*/ {0, 0},
202         /*landing_zone_cylinder*/ {0, 0, 0},
203         /*rpl*/ SRDP_RPL_DISABLED,
204         /*rotational_offset*/ 0,
205         /*reserved1*/ 0,
206         /*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
207                            CTL_DEFAULT_ROTATION_RATE & 0xff},
208         /*reserved2*/ {0, 0}
209 };
210
211 static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
212         /*page_code*/SMS_RIGID_DISK_PAGE,
213         /*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
214         /*cylinders*/ {0, 0, 0},
215         /*heads*/ 0,
216         /*start_write_precomp*/ {0, 0, 0},
217         /*start_reduced_current*/ {0, 0, 0},
218         /*step_rate*/ {0, 0},
219         /*landing_zone_cylinder*/ {0, 0, 0},
220         /*rpl*/ 0,
221         /*rotational_offset*/ 0,
222         /*reserved1*/ 0,
223         /*rotation_rate*/ {0, 0},
224         /*reserved2*/ {0, 0}
225 };
226
227 static struct scsi_caching_page caching_page_default = {
228         /*page_code*/SMS_CACHING_PAGE,
229         /*page_length*/sizeof(struct scsi_caching_page) - 2,
230         /*flags1*/ SCP_DISC | SCP_WCE,
231         /*ret_priority*/ 0,
232         /*disable_pf_transfer_len*/ {0xff, 0xff},
233         /*min_prefetch*/ {0, 0},
234         /*max_prefetch*/ {0xff, 0xff},
235         /*max_pf_ceiling*/ {0xff, 0xff},
236         /*flags2*/ 0,
237         /*cache_segments*/ 0,
238         /*cache_seg_size*/ {0, 0},
239         /*reserved*/ 0,
240         /*non_cache_seg_size*/ {0, 0, 0}
241 };
242
243 static struct scsi_caching_page caching_page_changeable = {
244         /*page_code*/SMS_CACHING_PAGE,
245         /*page_length*/sizeof(struct scsi_caching_page) - 2,
246         /*flags1*/ SCP_WCE | SCP_RCD,
247         /*ret_priority*/ 0,
248         /*disable_pf_transfer_len*/ {0, 0},
249         /*min_prefetch*/ {0, 0},
250         /*max_prefetch*/ {0, 0},
251         /*max_pf_ceiling*/ {0, 0},
252         /*flags2*/ 0,
253         /*cache_segments*/ 0,
254         /*cache_seg_size*/ {0, 0},
255         /*reserved*/ 0,
256         /*non_cache_seg_size*/ {0, 0, 0}
257 };
258
259 static struct scsi_control_page control_page_default = {
260         /*page_code*/SMS_CONTROL_MODE_PAGE,
261         /*page_length*/sizeof(struct scsi_control_page) - 2,
262         /*rlec*/0,
263         /*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
264         /*eca_and_aen*/0,
265         /*flags4*/SCP_TAS,
266         /*aen_holdoff_period*/{0, 0},
267         /*busy_timeout_period*/{0, 0},
268         /*extended_selftest_completion_time*/{0, 0}
269 };
270
271 static struct scsi_control_page control_page_changeable = {
272         /*page_code*/SMS_CONTROL_MODE_PAGE,
273         /*page_length*/sizeof(struct scsi_control_page) - 2,
274         /*rlec*/SCP_DSENSE,
275         /*queue_flags*/SCP_QUEUE_ALG_MASK,
276         /*eca_and_aen*/SCP_SWP,
277         /*flags4*/0,
278         /*aen_holdoff_period*/{0, 0},
279         /*busy_timeout_period*/{0, 0},
280         /*extended_selftest_completion_time*/{0, 0}
281 };
282
283 static struct scsi_info_exceptions_page ie_page_default = {
284         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
285         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
286         /*info_flags*/SIEP_FLAGS_DEXCPT,
287         /*mrie*/0,
288         /*interval_timer*/{0, 0, 0, 0},
289         /*report_count*/{0, 0, 0, 0}
290 };
291
292 static struct scsi_info_exceptions_page ie_page_changeable = {
293         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
294         /*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
295         /*info_flags*/0,
296         /*mrie*/0,
297         /*interval_timer*/{0, 0, 0, 0},
298         /*report_count*/{0, 0, 0, 0}
299 };
300
301 #define CTL_LBPM_LEN    (sizeof(struct ctl_logical_block_provisioning_page) - 4)
302
303 static struct ctl_logical_block_provisioning_page lbp_page_default = {{
304         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
305         /*subpage_code*/0x02,
306         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
307         /*flags*/0,
308         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
309         /*descr*/{}},
310         {{/*flags*/0,
311           /*resource*/0x01,
312           /*reserved*/{0, 0},
313           /*count*/{0, 0, 0, 0}},
314          {/*flags*/0,
315           /*resource*/0x02,
316           /*reserved*/{0, 0},
317           /*count*/{0, 0, 0, 0}},
318          {/*flags*/0,
319           /*resource*/0xf1,
320           /*reserved*/{0, 0},
321           /*count*/{0, 0, 0, 0}},
322          {/*flags*/0,
323           /*resource*/0xf2,
324           /*reserved*/{0, 0},
325           /*count*/{0, 0, 0, 0}}
326         }
327 };
328
329 static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
330         /*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
331         /*subpage_code*/0x02,
332         /*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
333         /*flags*/0,
334         /*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
335         /*descr*/{}},
336         {{/*flags*/0,
337           /*resource*/0,
338           /*reserved*/{0, 0},
339           /*count*/{0, 0, 0, 0}},
340          {/*flags*/0,
341           /*resource*/0,
342           /*reserved*/{0, 0},
343           /*count*/{0, 0, 0, 0}},
344          {/*flags*/0,
345           /*resource*/0,
346           /*reserved*/{0, 0},
347           /*count*/{0, 0, 0, 0}},
348          {/*flags*/0,
349           /*resource*/0,
350           /*reserved*/{0, 0},
351           /*count*/{0, 0, 0, 0}}
352         }
353 };
354
355 /*
356  * XXX KDM move these into the softc.
357  */
358 static int rcv_sync_msg;
359 static uint8_t ctl_pause_rtr;
360
361 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
362 static int worker_threads = -1;
363 TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
364 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
365     &worker_threads, 1, "Number of worker threads");
366 static int ctl_debug = CTL_DEBUG_NONE;
367 TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
368 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
369     &ctl_debug, 0, "Enabled debug flags");
370
371 /*
372  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
373  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
374  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
375  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
376  */
377 #define SCSI_EVPD_NUM_SUPPORTED_PAGES   10
378
379 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
380                                   int param);
381 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
382 static int ctl_init(void);
383 void ctl_shutdown(void);
384 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
385 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
386 static void ctl_ioctl_online(void *arg);
387 static void ctl_ioctl_offline(void *arg);
388 static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
389 static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
390 static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
391 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
392 static int ctl_ioctl_submit_wait(union ctl_io *io);
393 static void ctl_ioctl_datamove(union ctl_io *io);
394 static void ctl_ioctl_done(union ctl_io *io);
395 static void ctl_ioctl_hard_startstop_callback(void *arg,
396                                               struct cfi_metatask *metatask);
397 static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
398 static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
399                               struct ctl_ooa *ooa_hdr,
400                               struct ctl_ooa_entry *kern_entries);
401 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
402                      struct thread *td);
403 static uint32_t ctl_map_lun(int port_num, uint32_t lun);
404 static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
405 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 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
440     union ctl_io *pending_io, union ctl_io *ooa_io);
441 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
442                                 union ctl_io *starting_io);
443 static int ctl_check_blocked(struct ctl_lun *lun);
444 static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
445                                 struct ctl_lun *lun,
446                                 const struct ctl_cmd_entry *entry,
447                                 struct ctl_scsiio *ctsio);
448 //static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
449 static void ctl_failover(void);
450 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
451                                struct ctl_scsiio *ctsio);
452 static int ctl_scsiio(struct ctl_scsiio *ctsio);
453
454 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
455 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
456                             ctl_ua_type ua_type);
457 static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
458                          ctl_ua_type ua_type);
459 static int ctl_abort_task(union ctl_io *io);
460 static int ctl_abort_task_set(union ctl_io *io);
461 static int ctl_i_t_nexus_reset(union ctl_io *io);
462 static void ctl_run_task(union ctl_io *io);
463 #ifdef CTL_IO_DELAY
464 static void ctl_datamove_timer_wakeup(void *arg);
465 static void ctl_done_timer_wakeup(void *arg);
466 #endif /* CTL_IO_DELAY */
467
468 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
469 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
470 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
471 static void ctl_datamove_remote_write(union ctl_io *io);
472 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
473 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
474 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
475 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
476                                     ctl_ha_dt_cb callback);
477 static void ctl_datamove_remote_read(union ctl_io *io);
478 static void ctl_datamove_remote(union ctl_io *io);
479 static int ctl_process_done(union ctl_io *io);
480 static void ctl_lun_thread(void *arg);
481 static void ctl_thresh_thread(void *arg);
482 static void ctl_work_thread(void *arg);
483 static void ctl_enqueue_incoming(union ctl_io *io);
484 static void ctl_enqueue_rtr(union ctl_io *io);
485 static void ctl_enqueue_done(union ctl_io *io);
486 static void ctl_enqueue_isc(union ctl_io *io);
487 static const struct ctl_cmd_entry *
488     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
489 static const struct ctl_cmd_entry *
490     ctl_validate_command(struct ctl_scsiio *ctsio);
491 static int ctl_cmd_applicable(uint8_t lun_type,
492     const struct ctl_cmd_entry *entry);
493
494 /*
495  * Load the serialization table.  This isn't very pretty, but is probably
496  * the easiest way to do it.
497  */
498 #include "ctl_ser_table.c"
499
500 /*
501  * We only need to define open, close and ioctl routines for this driver.
502  */
503 static struct cdevsw ctl_cdevsw = {
504         .d_version =    D_VERSION,
505         .d_flags =      0,
506         .d_open =       ctl_open,
507         .d_close =      ctl_close,
508         .d_ioctl =      ctl_ioctl,
509         .d_name =       "ctl",
510 };
511
512
513 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
514 MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
515
516 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
517
518 static moduledata_t ctl_moduledata = {
519         "ctl",
520         ctl_module_event_handler,
521         NULL
522 };
523
524 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
525 MODULE_VERSION(ctl, 1);
526
527 static struct ctl_frontend ioctl_frontend =
528 {
529         .name = "ioctl",
530 };
531
532 static void
533 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
534                             union ctl_ha_msg *msg_info)
535 {
536         struct ctl_scsiio *ctsio;
537
538         if (msg_info->hdr.original_sc == NULL) {
539                 printf("%s: original_sc == NULL!\n", __func__);
540                 /* XXX KDM now what? */
541                 return;
542         }
543
544         ctsio = &msg_info->hdr.original_sc->scsiio;
545         ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
546         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
547         ctsio->io_hdr.status = msg_info->hdr.status;
548         ctsio->scsi_status = msg_info->scsi.scsi_status;
549         ctsio->sense_len = msg_info->scsi.sense_len;
550         ctsio->sense_residual = msg_info->scsi.sense_residual;
551         ctsio->residual = msg_info->scsi.residual;
552         memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
553                sizeof(ctsio->sense_data));
554         memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
555                &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
556         ctl_enqueue_isc((union ctl_io *)ctsio);
557 }
558
559 static void
560 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
561                                 union ctl_ha_msg *msg_info)
562 {
563         struct ctl_scsiio *ctsio;
564
565         if (msg_info->hdr.serializing_sc == NULL) {
566                 printf("%s: serializing_sc == NULL!\n", __func__);
567                 /* XXX KDM now what? */
568                 return;
569         }
570
571         ctsio = &msg_info->hdr.serializing_sc->scsiio;
572 #if 0
573         /*
574          * Attempt to catch the situation where an I/O has
575          * been freed, and we're using it again.
576          */
577         if (ctsio->io_hdr.io_type == 0xff) {
578                 union ctl_io *tmp_io;
579                 tmp_io = (union ctl_io *)ctsio;
580                 printf("%s: %p use after free!\n", __func__,
581                        ctsio);
582                 printf("%s: type %d msg %d cdb %x iptl: "
583                        "%d:%d:%d:%d tag 0x%04x "
584                        "flag %#x status %x\n",
585                         __func__,
586                         tmp_io->io_hdr.io_type,
587                         tmp_io->io_hdr.msg_type,
588                         tmp_io->scsiio.cdb[0],
589                         tmp_io->io_hdr.nexus.initid.id,
590                         tmp_io->io_hdr.nexus.targ_port,
591                         tmp_io->io_hdr.nexus.targ_target.id,
592                         tmp_io->io_hdr.nexus.targ_lun,
593                         (tmp_io->io_hdr.io_type ==
594                         CTL_IO_TASK) ?
595                         tmp_io->taskio.tag_num :
596                         tmp_io->scsiio.tag_num,
597                         tmp_io->io_hdr.flags,
598                         tmp_io->io_hdr.status);
599         }
600 #endif
601         ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
602         ctl_enqueue_isc((union ctl_io *)ctsio);
603 }
604
605 /*
606  * ISC (Inter Shelf Communication) event handler.  Events from the HA
607  * subsystem come in here.
608  */
609 static void
610 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
611 {
612         struct ctl_softc *ctl_softc;
613         union ctl_io *io;
614         struct ctl_prio *presio;
615         ctl_ha_status isc_status;
616
617         ctl_softc = control_softc;
618         io = NULL;
619
620
621 #if 0
622         printf("CTL: Isc Msg event %d\n", event);
623 #endif
624         if (event == CTL_HA_EVT_MSG_RECV) {
625                 union ctl_ha_msg msg_info;
626
627                 isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
628                                              sizeof(msg_info), /*wait*/ 0);
629 #if 0
630                 printf("CTL: msg_type %d\n", msg_info.msg_type);
631 #endif
632                 if (isc_status != 0) {
633                         printf("Error receiving message, status = %d\n",
634                                isc_status);
635                         return;
636                 }
637
638                 switch (msg_info.hdr.msg_type) {
639                 case CTL_MSG_SERIALIZE:
640 #if 0
641                         printf("Serialize\n");
642 #endif
643                         io = ctl_alloc_io_nowait(ctl_softc->othersc_pool);
644                         if (io == NULL) {
645                                 printf("ctl_isc_event_handler: can't allocate "
646                                        "ctl_io!\n");
647                                 /* Bad Juju */
648                                 /* Need to set busy and send msg back */
649                                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
650                                 msg_info.hdr.status = CTL_SCSI_ERROR;
651                                 msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
652                                 msg_info.scsi.sense_len = 0;
653                                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
654                                     sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
655                                 }
656                                 goto bailout;
657                         }
658                         ctl_zero_io(io);
659                         // populate ctsio from msg_info
660                         io->io_hdr.io_type = CTL_IO_SCSI;
661                         io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
662                         io->io_hdr.original_sc = msg_info.hdr.original_sc;
663 #if 0
664                         printf("pOrig %x\n", (int)msg_info.original_sc);
665 #endif
666                         io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
667                                             CTL_FLAG_IO_ACTIVE;
668                         /*
669                          * If we're in serialization-only mode, we don't
670                          * want to go through full done processing.  Thus
671                          * the COPY flag.
672                          *
673                          * XXX KDM add another flag that is more specific.
674                          */
675                         if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
676                                 io->io_hdr.flags |= CTL_FLAG_INT_COPY;
677                         io->io_hdr.nexus = msg_info.hdr.nexus;
678 #if 0
679                         printf("targ %d, port %d, iid %d, lun %d\n",
680                                io->io_hdr.nexus.targ_target.id,
681                                io->io_hdr.nexus.targ_port,
682                                io->io_hdr.nexus.initid.id,
683                                io->io_hdr.nexus.targ_lun);
684 #endif
685                         io->scsiio.tag_num = msg_info.scsi.tag_num;
686                         io->scsiio.tag_type = msg_info.scsi.tag_type;
687                         memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
688                                CTL_MAX_CDBLEN);
689                         if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
690                                 const struct ctl_cmd_entry *entry;
691
692                                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
693                                 io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
694                                 io->io_hdr.flags |=
695                                         entry->flags & CTL_FLAG_DATA_MASK;
696                         }
697                         ctl_enqueue_isc(io);
698                         break;
699
700                 /* Performed on the Originating SC, XFER mode only */
701                 case CTL_MSG_DATAMOVE: {
702                         struct ctl_sg_entry *sgl;
703                         int i, j;
704
705                         io = msg_info.hdr.original_sc;
706                         if (io == NULL) {
707                                 printf("%s: original_sc == NULL!\n", __func__);
708                                 /* XXX KDM do something here */
709                                 break;
710                         }
711                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
712                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
713                         /*
714                          * Keep track of this, we need to send it back over
715                          * when the datamove is complete.
716                          */
717                         io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
718
719                         if (msg_info.dt.sg_sequence == 0) {
720                                 /*
721                                  * XXX KDM we use the preallocated S/G list
722                                  * here, but we'll need to change this to
723                                  * dynamic allocation if we need larger S/G
724                                  * lists.
725                                  */
726                                 if (msg_info.dt.kern_sg_entries >
727                                     sizeof(io->io_hdr.remote_sglist) /
728                                     sizeof(io->io_hdr.remote_sglist[0])) {
729                                         printf("%s: number of S/G entries "
730                                             "needed %u > allocated num %zd\n",
731                                             __func__,
732                                             msg_info.dt.kern_sg_entries,
733                                             sizeof(io->io_hdr.remote_sglist)/
734                                             sizeof(io->io_hdr.remote_sglist[0]));
735                                 
736                                         /*
737                                          * XXX KDM send a message back to
738                                          * the other side to shut down the
739                                          * DMA.  The error will come back
740                                          * through via the normal channel.
741                                          */
742                                         break;
743                                 }
744                                 sgl = io->io_hdr.remote_sglist;
745                                 memset(sgl, 0,
746                                        sizeof(io->io_hdr.remote_sglist));
747
748                                 io->scsiio.kern_data_ptr = (uint8_t *)sgl;
749
750                                 io->scsiio.kern_sg_entries =
751                                         msg_info.dt.kern_sg_entries;
752                                 io->scsiio.rem_sg_entries =
753                                         msg_info.dt.kern_sg_entries;
754                                 io->scsiio.kern_data_len =
755                                         msg_info.dt.kern_data_len;
756                                 io->scsiio.kern_total_len =
757                                         msg_info.dt.kern_total_len;
758                                 io->scsiio.kern_data_resid =
759                                         msg_info.dt.kern_data_resid;
760                                 io->scsiio.kern_rel_offset =
761                                         msg_info.dt.kern_rel_offset;
762                                 /*
763                                  * Clear out per-DMA flags.
764                                  */
765                                 io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
766                                 /*
767                                  * Add per-DMA flags that are set for this
768                                  * particular DMA request.
769                                  */
770                                 io->io_hdr.flags |= msg_info.dt.flags &
771                                                     CTL_FLAG_RDMA_MASK;
772                         } else
773                                 sgl = (struct ctl_sg_entry *)
774                                         io->scsiio.kern_data_ptr;
775
776                         for (i = msg_info.dt.sent_sg_entries, j = 0;
777                              i < (msg_info.dt.sent_sg_entries +
778                              msg_info.dt.cur_sg_entries); i++, j++) {
779                                 sgl[i].addr = msg_info.dt.sg_list[j].addr;
780                                 sgl[i].len = msg_info.dt.sg_list[j].len;
781
782 #if 0
783                                 printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
784                                        __func__,
785                                        msg_info.dt.sg_list[j].addr,
786                                        msg_info.dt.sg_list[j].len,
787                                        sgl[i].addr, sgl[i].len, j, i);
788 #endif
789                         }
790 #if 0
791                         memcpy(&sgl[msg_info.dt.sent_sg_entries],
792                                msg_info.dt.sg_list,
793                                sizeof(*sgl) * msg_info.dt.cur_sg_entries);
794 #endif
795
796                         /*
797                          * If this is the last piece of the I/O, we've got
798                          * the full S/G list.  Queue processing in the thread.
799                          * Otherwise wait for the next piece.
800                          */
801                         if (msg_info.dt.sg_last != 0)
802                                 ctl_enqueue_isc(io);
803                         break;
804                 }
805                 /* Performed on the Serializing (primary) SC, XFER mode only */
806                 case CTL_MSG_DATAMOVE_DONE: {
807                         if (msg_info.hdr.serializing_sc == NULL) {
808                                 printf("%s: serializing_sc == NULL!\n",
809                                        __func__);
810                                 /* XXX KDM now what? */
811                                 break;
812                         }
813                         /*
814                          * We grab the sense information here in case
815                          * there was a failure, so we can return status
816                          * back to the initiator.
817                          */
818                         io = msg_info.hdr.serializing_sc;
819                         io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
820                         io->io_hdr.status = msg_info.hdr.status;
821                         io->scsiio.scsi_status = msg_info.scsi.scsi_status;
822                         io->scsiio.sense_len = msg_info.scsi.sense_len;
823                         io->scsiio.sense_residual =msg_info.scsi.sense_residual;
824                         io->io_hdr.port_status = msg_info.scsi.fetd_status;
825                         io->scsiio.residual = msg_info.scsi.residual;
826                         memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
827                                sizeof(io->scsiio.sense_data));
828                         ctl_enqueue_isc(io);
829                         break;
830                 }
831
832                 /* Preformed on Originating SC, SER_ONLY mode */
833                 case CTL_MSG_R2R:
834                         io = msg_info.hdr.original_sc;
835                         if (io == NULL) {
836                                 printf("%s: Major Bummer\n", __func__);
837                                 return;
838                         } else {
839 #if 0
840                                 printf("pOrig %x\n",(int) ctsio);
841 #endif
842                         }
843                         io->io_hdr.msg_type = CTL_MSG_R2R;
844                         io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
845                         ctl_enqueue_isc(io);
846                         break;
847
848                 /*
849                  * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
850                  * mode.
851                  * Performed on the Originating (i.e. secondary) SC in XFER
852                  * mode
853                  */
854                 case CTL_MSG_FINISH_IO:
855                         if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
856                                 ctl_isc_handler_finish_xfer(ctl_softc,
857                                                             &msg_info);
858                         else
859                                 ctl_isc_handler_finish_ser_only(ctl_softc,
860                                                                 &msg_info);
861                         break;
862
863                 /* Preformed on Originating SC */
864                 case CTL_MSG_BAD_JUJU:
865                         io = msg_info.hdr.original_sc;
866                         if (io == NULL) {
867                                 printf("%s: Bad JUJU!, original_sc is NULL!\n",
868                                        __func__);
869                                 break;
870                         }
871                         ctl_copy_sense_data(&msg_info, io);
872                         /*
873                          * IO should have already been cleaned up on other
874                          * SC so clear this flag so we won't send a message
875                          * back to finish the IO there.
876                          */
877                         io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
878                         io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
879
880                         /* io = msg_info.hdr.serializing_sc; */
881                         io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
882                         ctl_enqueue_isc(io);
883                         break;
884
885                 /* Handle resets sent from the other side */
886                 case CTL_MSG_MANAGE_TASKS: {
887                         struct ctl_taskio *taskio;
888                         taskio = (struct ctl_taskio *)ctl_alloc_io_nowait(
889                             ctl_softc->othersc_pool);
890                         if (taskio == NULL) {
891                                 printf("ctl_isc_event_handler: can't allocate "
892                                        "ctl_io!\n");
893                                 /* Bad Juju */
894                                 /* should I just call the proper reset func
895                                    here??? */
896                                 goto bailout;
897                         }
898                         ctl_zero_io((union ctl_io *)taskio);
899                         taskio->io_hdr.io_type = CTL_IO_TASK;
900                         taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
901                         taskio->io_hdr.nexus = msg_info.hdr.nexus;
902                         taskio->task_action = msg_info.task.task_action;
903                         taskio->tag_num = msg_info.task.tag_num;
904                         taskio->tag_type = msg_info.task.tag_type;
905 #ifdef CTL_TIME_IO
906                         taskio->io_hdr.start_time = time_uptime;
907                         getbintime(&taskio->io_hdr.start_bt);
908 #if 0
909                         cs_prof_gettime(&taskio->io_hdr.start_ticks);
910 #endif
911 #endif /* CTL_TIME_IO */
912                         ctl_run_task((union ctl_io *)taskio);
913                         break;
914                 }
915                 /* Persistent Reserve action which needs attention */
916                 case CTL_MSG_PERS_ACTION:
917                         presio = (struct ctl_prio *)ctl_alloc_io_nowait(
918                             ctl_softc->othersc_pool);
919                         if (presio == NULL) {
920                                 printf("ctl_isc_event_handler: can't allocate "
921                                        "ctl_io!\n");
922                                 /* Bad Juju */
923                                 /* Need to set busy and send msg back */
924                                 goto bailout;
925                         }
926                         ctl_zero_io((union ctl_io *)presio);
927                         presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
928                         presio->pr_msg = msg_info.pr;
929                         ctl_enqueue_isc((union ctl_io *)presio);
930                         break;
931                 case CTL_MSG_SYNC_FE:
932                         rcv_sync_msg = 1;
933                         break;
934                 default:
935                         printf("How did I get here?\n");
936                 }
937         } else if (event == CTL_HA_EVT_MSG_SENT) {
938                 if (param != CTL_HA_STATUS_SUCCESS) {
939                         printf("Bad status from ctl_ha_msg_send status %d\n",
940                                param);
941                 }
942                 return;
943         } else if (event == CTL_HA_EVT_DISCONNECT) {
944                 printf("CTL: Got a disconnect from Isc\n");
945                 return;
946         } else {
947                 printf("ctl_isc_event_handler: Unknown event %d\n", event);
948                 return;
949         }
950
951 bailout:
952         return;
953 }
954
955 static void
956 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
957 {
958         struct scsi_sense_data *sense;
959
960         sense = &dest->scsiio.sense_data;
961         bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
962         dest->scsiio.scsi_status = src->scsi.scsi_status;
963         dest->scsiio.sense_len = src->scsi.sense_len;
964         dest->io_hdr.status = src->hdr.status;
965 }
966
967 static int
968 ctl_ha_state_sysctl(SYSCTL_HANDLER_ARGS)
969 {
970         struct ctl_softc *softc = (struct ctl_softc *)arg1;
971         struct ctl_lun *lun;
972         int error, value, i;
973
974         if (softc->flags & CTL_FLAG_ACTIVE_SHELF)
975                 value = 0;
976         else
977                 value = 1;
978
979         error = sysctl_handle_int(oidp, &value, 0, req);
980         if ((error != 0) || (req->newptr == NULL))
981                 return (error);
982
983         mtx_lock(&softc->ctl_lock);
984         if (value == 0)
985                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
986         else
987                 softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
988         STAILQ_FOREACH(lun, &softc->lun_list, links) {
989                 mtx_lock(&lun->lun_lock);
990                 for (i = 0; i < CTL_MAX_INITIATORS; i++)
991                         lun->pending_ua[i] |= CTL_UA_ASYM_ACC_CHANGE;
992                 mtx_unlock(&lun->lun_lock);
993         }
994         mtx_unlock(&softc->ctl_lock);
995         return (0);
996 }
997
998 static int
999 ctl_init(void)
1000 {
1001         struct ctl_softc *softc;
1002         void *other_pool;
1003         struct ctl_port *port;
1004         int i, error, retval;
1005         //int isc_retval;
1006
1007         retval = 0;
1008         ctl_pause_rtr = 0;
1009         rcv_sync_msg = 0;
1010
1011         control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1012                                M_WAITOK | M_ZERO);
1013         softc = control_softc;
1014
1015         softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1016                               "cam/ctl");
1017
1018         softc->dev->si_drv1 = softc;
1019
1020         /*
1021          * By default, return a "bad LUN" peripheral qualifier for unknown
1022          * LUNs.  The user can override this default using the tunable or
1023          * sysctl.  See the comment in ctl_inquiry_std() for more details.
1024          */
1025         softc->inquiry_pq_no_lun = 1;
1026         TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
1027                           &softc->inquiry_pq_no_lun);
1028         sysctl_ctx_init(&softc->sysctl_ctx);
1029         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1030                 SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1031                 CTLFLAG_RD, 0, "CAM Target Layer");
1032
1033         if (softc->sysctl_tree == NULL) {
1034                 printf("%s: unable to allocate sysctl tree\n", __func__);
1035                 destroy_dev(softc->dev);
1036                 free(control_softc, M_DEVBUF);
1037                 control_softc = NULL;
1038                 return (ENOMEM);
1039         }
1040
1041         SYSCTL_ADD_INT(&softc->sysctl_ctx,
1042                        SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1043                        "inquiry_pq_no_lun", CTLFLAG_RW,
1044                        &softc->inquiry_pq_no_lun, 0,
1045                        "Report no lun possible for invalid LUNs");
1046
1047         mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1048         softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1049             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1050         softc->open_count = 0;
1051
1052         /*
1053          * Default to actually sending a SYNCHRONIZE CACHE command down to
1054          * the drive.
1055          */
1056         softc->flags = CTL_FLAG_REAL_SYNC;
1057
1058         /*
1059          * In Copan's HA scheme, the "master" and "slave" roles are
1060          * figured out through the slot the controller is in.  Although it
1061          * is an active/active system, someone has to be in charge.
1062          */
1063         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1064             OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1065             "HA head ID (0 - no HA)");
1066         if (softc->ha_id == 0) {
1067                 softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1068                 softc->is_single = 1;
1069                 softc->port_offset = 0;
1070         } else
1071                 softc->port_offset = (softc->ha_id - 1) * CTL_MAX_PORTS;
1072         softc->persis_offset = softc->port_offset * CTL_MAX_INIT_PER_PORT;
1073
1074         /*
1075          * XXX KDM need to figure out where we want to get our target ID
1076          * and WWID.  Is it different on each port?
1077          */
1078         softc->target.id = 0;
1079         softc->target.wwid[0] = 0x12345678;
1080         softc->target.wwid[1] = 0x87654321;
1081         STAILQ_INIT(&softc->lun_list);
1082         STAILQ_INIT(&softc->pending_lun_queue);
1083         STAILQ_INIT(&softc->fe_list);
1084         STAILQ_INIT(&softc->port_list);
1085         STAILQ_INIT(&softc->be_list);
1086         ctl_tpc_init(softc);
1087
1088         if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1089                             &other_pool) != 0)
1090         {
1091                 printf("ctl: can't allocate %d entry other SC pool, "
1092                        "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1093                 return (ENOMEM);
1094         }
1095         softc->othersc_pool = other_pool;
1096
1097         if (worker_threads <= 0)
1098                 worker_threads = max(1, mp_ncpus / 4);
1099         if (worker_threads > CTL_MAX_THREADS)
1100                 worker_threads = CTL_MAX_THREADS;
1101
1102         for (i = 0; i < worker_threads; i++) {
1103                 struct ctl_thread *thr = &softc->threads[i];
1104
1105                 mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1106                 thr->ctl_softc = softc;
1107                 STAILQ_INIT(&thr->incoming_queue);
1108                 STAILQ_INIT(&thr->rtr_queue);
1109                 STAILQ_INIT(&thr->done_queue);
1110                 STAILQ_INIT(&thr->isc_queue);
1111
1112                 error = kproc_kthread_add(ctl_work_thread, thr,
1113                     &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1114                 if (error != 0) {
1115                         printf("error creating CTL work thread!\n");
1116                         ctl_pool_free(other_pool);
1117                         return (error);
1118                 }
1119         }
1120         error = kproc_kthread_add(ctl_lun_thread, softc,
1121             &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1122         if (error != 0) {
1123                 printf("error creating CTL lun thread!\n");
1124                 ctl_pool_free(other_pool);
1125                 return (error);
1126         }
1127         error = kproc_kthread_add(ctl_thresh_thread, softc,
1128             &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1129         if (error != 0) {
1130                 printf("error creating CTL threshold thread!\n");
1131                 ctl_pool_free(other_pool);
1132                 return (error);
1133         }
1134         if (bootverbose)
1135                 printf("ctl: CAM Target Layer loaded\n");
1136
1137         /*
1138          * Initialize the ioctl front end.
1139          */
1140         ctl_frontend_register(&ioctl_frontend);
1141         port = &softc->ioctl_info.port;
1142         port->frontend = &ioctl_frontend;
1143         sprintf(softc->ioctl_info.port_name, "ioctl");
1144         port->port_type = CTL_PORT_IOCTL;
1145         port->num_requested_ctl_io = 100;
1146         port->port_name = softc->ioctl_info.port_name;
1147         port->port_online = ctl_ioctl_online;
1148         port->port_offline = ctl_ioctl_offline;
1149         port->onoff_arg = &softc->ioctl_info;
1150         port->lun_enable = ctl_ioctl_lun_enable;
1151         port->lun_disable = ctl_ioctl_lun_disable;
1152         port->targ_lun_arg = &softc->ioctl_info;
1153         port->fe_datamove = ctl_ioctl_datamove;
1154         port->fe_done = ctl_ioctl_done;
1155         port->max_targets = 15;
1156         port->max_target_id = 15;
1157
1158         if (ctl_port_register(&softc->ioctl_info.port) != 0) {
1159                 printf("ctl: ioctl front end registration failed, will "
1160                        "continue anyway\n");
1161         }
1162
1163         SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1164             OID_AUTO, "ha_state", CTLTYPE_INT | CTLFLAG_RWTUN,
1165             softc, 0, ctl_ha_state_sysctl, "I", "HA state for this head");
1166
1167 #ifdef CTL_IO_DELAY
1168         if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1169                 printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1170                        sizeof(struct callout), CTL_TIMER_BYTES);
1171                 return (EINVAL);
1172         }
1173 #endif /* CTL_IO_DELAY */
1174
1175         return (0);
1176 }
1177
1178 void
1179 ctl_shutdown(void)
1180 {
1181         struct ctl_softc *softc;
1182         struct ctl_lun *lun, *next_lun;
1183
1184         softc = (struct ctl_softc *)control_softc;
1185
1186         if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1187                 printf("ctl: ioctl front end deregistration failed\n");
1188
1189         mtx_lock(&softc->ctl_lock);
1190
1191         /*
1192          * Free up each LUN.
1193          */
1194         for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1195                 next_lun = STAILQ_NEXT(lun, links);
1196                 ctl_free_lun(lun);
1197         }
1198
1199         mtx_unlock(&softc->ctl_lock);
1200
1201         ctl_frontend_deregister(&ioctl_frontend);
1202
1203 #if 0
1204         ctl_shutdown_thread(softc->work_thread);
1205         mtx_destroy(&softc->queue_lock);
1206 #endif
1207
1208         ctl_tpc_shutdown(softc);
1209         uma_zdestroy(softc->io_zone);
1210         mtx_destroy(&softc->ctl_lock);
1211
1212         destroy_dev(softc->dev);
1213
1214         sysctl_ctx_free(&softc->sysctl_ctx);
1215
1216         free(control_softc, M_DEVBUF);
1217         control_softc = NULL;
1218
1219         if (bootverbose)
1220                 printf("ctl: CAM Target Layer unloaded\n");
1221 }
1222
1223 static int
1224 ctl_module_event_handler(module_t mod, int what, void *arg)
1225 {
1226
1227         switch (what) {
1228         case MOD_LOAD:
1229                 return (ctl_init());
1230         case MOD_UNLOAD:
1231                 return (EBUSY);
1232         default:
1233                 return (EOPNOTSUPP);
1234         }
1235 }
1236
1237 /*
1238  * XXX KDM should we do some access checks here?  Bump a reference count to
1239  * prevent a CTL module from being unloaded while someone has it open?
1240  */
1241 static int
1242 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1243 {
1244         return (0);
1245 }
1246
1247 static int
1248 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1249 {
1250         return (0);
1251 }
1252
1253 int
1254 ctl_port_enable(ctl_port_type port_type)
1255 {
1256         struct ctl_softc *softc = control_softc;
1257         struct ctl_port *port;
1258
1259         if (softc->is_single == 0) {
1260                 union ctl_ha_msg msg_info;
1261                 int isc_retval;
1262
1263 #if 0
1264                 printf("%s: HA mode, synchronizing frontend enable\n",
1265                         __func__);
1266 #endif
1267                 msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1268                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1269                         sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1270                         printf("Sync msg send error retval %d\n", isc_retval);
1271                 }
1272                 if (!rcv_sync_msg) {
1273                         isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1274                                 sizeof(msg_info), 1);
1275                 }
1276 #if 0
1277                 printf("CTL:Frontend Enable\n");
1278         } else {
1279                 printf("%s: single mode, skipping frontend synchronization\n",
1280                         __func__);
1281 #endif
1282         }
1283
1284         STAILQ_FOREACH(port, &softc->port_list, links) {
1285                 if (port_type & port->port_type)
1286                 {
1287 #if 0
1288                         printf("port %d\n", port->targ_port);
1289 #endif
1290                         ctl_port_online(port);
1291                 }
1292         }
1293
1294         return (0);
1295 }
1296
1297 int
1298 ctl_port_disable(ctl_port_type port_type)
1299 {
1300         struct ctl_softc *softc;
1301         struct ctl_port *port;
1302
1303         softc = control_softc;
1304
1305         STAILQ_FOREACH(port, &softc->port_list, links) {
1306                 if (port_type & port->port_type)
1307                         ctl_port_offline(port);
1308         }
1309
1310         return (0);
1311 }
1312
1313 /*
1314  * Returns 0 for success, 1 for failure.
1315  * Currently the only failure mode is if there aren't enough entries
1316  * allocated.  So, in case of a failure, look at num_entries_dropped,
1317  * reallocate and try again.
1318  */
1319 int
1320 ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1321               int *num_entries_filled, int *num_entries_dropped,
1322               ctl_port_type port_type, int no_virtual)
1323 {
1324         struct ctl_softc *softc;
1325         struct ctl_port *port;
1326         int entries_dropped, entries_filled;
1327         int retval;
1328         int i;
1329
1330         softc = control_softc;
1331
1332         retval = 0;
1333         entries_filled = 0;
1334         entries_dropped = 0;
1335
1336         i = 0;
1337         mtx_lock(&softc->ctl_lock);
1338         STAILQ_FOREACH(port, &softc->port_list, links) {
1339                 struct ctl_port_entry *entry;
1340
1341                 if ((port->port_type & port_type) == 0)
1342                         continue;
1343
1344                 if ((no_virtual != 0)
1345                  && (port->virtual_port != 0))
1346                         continue;
1347
1348                 if (entries_filled >= num_entries_alloced) {
1349                         entries_dropped++;
1350                         continue;
1351                 }
1352                 entry = &entries[i];
1353
1354                 entry->port_type = port->port_type;
1355                 strlcpy(entry->port_name, port->port_name,
1356                         sizeof(entry->port_name));
1357                 entry->physical_port = port->physical_port;
1358                 entry->virtual_port = port->virtual_port;
1359                 entry->wwnn = port->wwnn;
1360                 entry->wwpn = port->wwpn;
1361
1362                 i++;
1363                 entries_filled++;
1364         }
1365
1366         mtx_unlock(&softc->ctl_lock);
1367
1368         if (entries_dropped > 0)
1369                 retval = 1;
1370
1371         *num_entries_dropped = entries_dropped;
1372         *num_entries_filled = entries_filled;
1373
1374         return (retval);
1375 }
1376
1377 static void
1378 ctl_ioctl_online(void *arg)
1379 {
1380         struct ctl_ioctl_info *ioctl_info;
1381
1382         ioctl_info = (struct ctl_ioctl_info *)arg;
1383
1384         ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1385 }
1386
1387 static void
1388 ctl_ioctl_offline(void *arg)
1389 {
1390         struct ctl_ioctl_info *ioctl_info;
1391
1392         ioctl_info = (struct ctl_ioctl_info *)arg;
1393
1394         ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1395 }
1396
1397 /*
1398  * Remove an initiator by port number and initiator ID.
1399  * Returns 0 for success, -1 for failure.
1400  */
1401 int
1402 ctl_remove_initiator(struct ctl_port *port, int iid)
1403 {
1404         struct ctl_softc *softc = control_softc;
1405
1406         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1407
1408         if (iid > CTL_MAX_INIT_PER_PORT) {
1409                 printf("%s: initiator ID %u > maximun %u!\n",
1410                        __func__, iid, CTL_MAX_INIT_PER_PORT);
1411                 return (-1);
1412         }
1413
1414         mtx_lock(&softc->ctl_lock);
1415         port->wwpn_iid[iid].in_use--;
1416         port->wwpn_iid[iid].last_use = time_uptime;
1417         mtx_unlock(&softc->ctl_lock);
1418
1419         return (0);
1420 }
1421
1422 /*
1423  * Add an initiator to the initiator map.
1424  * Returns iid for success, < 0 for failure.
1425  */
1426 int
1427 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1428 {
1429         struct ctl_softc *softc = control_softc;
1430         time_t best_time;
1431         int i, best;
1432
1433         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1434
1435         if (iid >= CTL_MAX_INIT_PER_PORT) {
1436                 printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1437                        __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1438                 free(name, M_CTL);
1439                 return (-1);
1440         }
1441
1442         mtx_lock(&softc->ctl_lock);
1443
1444         if (iid < 0 && (wwpn != 0 || name != NULL)) {
1445                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1446                         if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1447                                 iid = i;
1448                                 break;
1449                         }
1450                         if (name != NULL && port->wwpn_iid[i].name != NULL &&
1451                             strcmp(name, port->wwpn_iid[i].name) == 0) {
1452                                 iid = i;
1453                                 break;
1454                         }
1455                 }
1456         }
1457
1458         if (iid < 0) {
1459                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1460                         if (port->wwpn_iid[i].in_use == 0 &&
1461                             port->wwpn_iid[i].wwpn == 0 &&
1462                             port->wwpn_iid[i].name == NULL) {
1463                                 iid = i;
1464                                 break;
1465                         }
1466                 }
1467         }
1468
1469         if (iid < 0) {
1470                 best = -1;
1471                 best_time = INT32_MAX;
1472                 for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1473                         if (port->wwpn_iid[i].in_use == 0) {
1474                                 if (port->wwpn_iid[i].last_use < best_time) {
1475                                         best = i;
1476                                         best_time = port->wwpn_iid[i].last_use;
1477                                 }
1478                         }
1479                 }
1480                 iid = best;
1481         }
1482
1483         if (iid < 0) {
1484                 mtx_unlock(&softc->ctl_lock);
1485                 free(name, M_CTL);
1486                 return (-2);
1487         }
1488
1489         if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1490                 /*
1491                  * This is not an error yet.
1492                  */
1493                 if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1494 #if 0
1495                         printf("%s: port %d iid %u WWPN %#jx arrived"
1496                             " again\n", __func__, port->targ_port,
1497                             iid, (uintmax_t)wwpn);
1498 #endif
1499                         goto take;
1500                 }
1501                 if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1502                     strcmp(name, port->wwpn_iid[iid].name) == 0) {
1503 #if 0
1504                         printf("%s: port %d iid %u name '%s' arrived"
1505                             " again\n", __func__, port->targ_port,
1506                             iid, name);
1507 #endif
1508                         goto take;
1509                 }
1510
1511                 /*
1512                  * This is an error, but what do we do about it?  The
1513                  * driver is telling us we have a new WWPN for this
1514                  * initiator ID, so we pretty much need to use it.
1515                  */
1516                 printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1517                     " but WWPN %#jx '%s' is still at that address\n",
1518                     __func__, port->targ_port, iid, wwpn, name,
1519                     (uintmax_t)port->wwpn_iid[iid].wwpn,
1520                     port->wwpn_iid[iid].name);
1521
1522                 /*
1523                  * XXX KDM clear have_ca and ua_pending on each LUN for
1524                  * this initiator.
1525                  */
1526         }
1527 take:
1528         free(port->wwpn_iid[iid].name, M_CTL);
1529         port->wwpn_iid[iid].name = name;
1530         port->wwpn_iid[iid].wwpn = wwpn;
1531         port->wwpn_iid[iid].in_use++;
1532         mtx_unlock(&softc->ctl_lock);
1533
1534         return (iid);
1535 }
1536
1537 static int
1538 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1539 {
1540         int len;
1541
1542         switch (port->port_type) {
1543         case CTL_PORT_FC:
1544         {
1545                 struct scsi_transportid_fcp *id =
1546                     (struct scsi_transportid_fcp *)buf;
1547                 if (port->wwpn_iid[iid].wwpn == 0)
1548                         return (0);
1549                 memset(id, 0, sizeof(*id));
1550                 id->format_protocol = SCSI_PROTO_FC;
1551                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1552                 return (sizeof(*id));
1553         }
1554         case CTL_PORT_ISCSI:
1555         {
1556                 struct scsi_transportid_iscsi_port *id =
1557                     (struct scsi_transportid_iscsi_port *)buf;
1558                 if (port->wwpn_iid[iid].name == NULL)
1559                         return (0);
1560                 memset(id, 0, 256);
1561                 id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1562                     SCSI_PROTO_ISCSI;
1563                 len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1564                 len = roundup2(min(len, 252), 4);
1565                 scsi_ulto2b(len, id->additional_length);
1566                 return (sizeof(*id) + len);
1567         }
1568         case CTL_PORT_SAS:
1569         {
1570                 struct scsi_transportid_sas *id =
1571                     (struct scsi_transportid_sas *)buf;
1572                 if (port->wwpn_iid[iid].wwpn == 0)
1573                         return (0);
1574                 memset(id, 0, sizeof(*id));
1575                 id->format_protocol = SCSI_PROTO_SAS;
1576                 scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1577                 return (sizeof(*id));
1578         }
1579         default:
1580         {
1581                 struct scsi_transportid_spi *id =
1582                     (struct scsi_transportid_spi *)buf;
1583                 memset(id, 0, sizeof(*id));
1584                 id->format_protocol = SCSI_PROTO_SPI;
1585                 scsi_ulto2b(iid, id->scsi_addr);
1586                 scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1587                 return (sizeof(*id));
1588         }
1589         }
1590 }
1591
1592 static int
1593 ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1594 {
1595         return (0);
1596 }
1597
1598 static int
1599 ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1600 {
1601         return (0);
1602 }
1603
1604 /*
1605  * Data movement routine for the CTL ioctl frontend port.
1606  */
1607 static int
1608 ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1609 {
1610         struct ctl_sg_entry *ext_sglist, *kern_sglist;
1611         struct ctl_sg_entry ext_entry, kern_entry;
1612         int ext_sglen, ext_sg_entries, kern_sg_entries;
1613         int ext_sg_start, ext_offset;
1614         int len_to_copy, len_copied;
1615         int kern_watermark, ext_watermark;
1616         int ext_sglist_malloced;
1617         int i, j;
1618
1619         ext_sglist_malloced = 0;
1620         ext_sg_start = 0;
1621         ext_offset = 0;
1622
1623         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1624
1625         /*
1626          * If this flag is set, fake the data transfer.
1627          */
1628         if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1629                 ctsio->ext_data_filled = ctsio->ext_data_len;
1630                 goto bailout;
1631         }
1632
1633         /*
1634          * To simplify things here, if we have a single buffer, stick it in
1635          * a S/G entry and just make it a single entry S/G list.
1636          */
1637         if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1638                 int len_seen;
1639
1640                 ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1641
1642                 ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1643                                                            M_WAITOK);
1644                 ext_sglist_malloced = 1;
1645                 if (copyin(ctsio->ext_data_ptr, ext_sglist,
1646                                    ext_sglen) != 0) {
1647                         ctl_set_internal_failure(ctsio,
1648                                                  /*sks_valid*/ 0,
1649                                                  /*retry_count*/ 0);
1650                         goto bailout;
1651                 }
1652                 ext_sg_entries = ctsio->ext_sg_entries;
1653                 len_seen = 0;
1654                 for (i = 0; i < ext_sg_entries; i++) {
1655                         if ((len_seen + ext_sglist[i].len) >=
1656                              ctsio->ext_data_filled) {
1657                                 ext_sg_start = i;
1658                                 ext_offset = ctsio->ext_data_filled - len_seen;
1659                                 break;
1660                         }
1661                         len_seen += ext_sglist[i].len;
1662                 }
1663         } else {
1664                 ext_sglist = &ext_entry;
1665                 ext_sglist->addr = ctsio->ext_data_ptr;
1666                 ext_sglist->len = ctsio->ext_data_len;
1667                 ext_sg_entries = 1;
1668                 ext_sg_start = 0;
1669                 ext_offset = ctsio->ext_data_filled;
1670         }
1671
1672         if (ctsio->kern_sg_entries > 0) {
1673                 kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1674                 kern_sg_entries = ctsio->kern_sg_entries;
1675         } else {
1676                 kern_sglist = &kern_entry;
1677                 kern_sglist->addr = ctsio->kern_data_ptr;
1678                 kern_sglist->len = ctsio->kern_data_len;
1679                 kern_sg_entries = 1;
1680         }
1681
1682
1683         kern_watermark = 0;
1684         ext_watermark = ext_offset;
1685         len_copied = 0;
1686         for (i = ext_sg_start, j = 0;
1687              i < ext_sg_entries && j < kern_sg_entries;) {
1688                 uint8_t *ext_ptr, *kern_ptr;
1689
1690                 len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1691                                       kern_sglist[j].len - kern_watermark);
1692
1693                 ext_ptr = (uint8_t *)ext_sglist[i].addr;
1694                 ext_ptr = ext_ptr + ext_watermark;
1695                 if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1696                         /*
1697                          * XXX KDM fix this!
1698                          */
1699                         panic("need to implement bus address support");
1700 #if 0
1701                         kern_ptr = bus_to_virt(kern_sglist[j].addr);
1702 #endif
1703                 } else
1704                         kern_ptr = (uint8_t *)kern_sglist[j].addr;
1705                 kern_ptr = kern_ptr + kern_watermark;
1706
1707                 kern_watermark += len_to_copy;
1708                 ext_watermark += len_to_copy;
1709
1710                 if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1711                      CTL_FLAG_DATA_IN) {
1712                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1713                                          "bytes to user\n", len_to_copy));
1714                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1715                                          "to %p\n", kern_ptr, ext_ptr));
1716                         if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1717                                 ctl_set_internal_failure(ctsio,
1718                                                          /*sks_valid*/ 0,
1719                                                          /*retry_count*/ 0);
1720                                 goto bailout;
1721                         }
1722                 } else {
1723                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1724                                          "bytes from user\n", len_to_copy));
1725                         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1726                                          "to %p\n", ext_ptr, kern_ptr));
1727                         if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1728                                 ctl_set_internal_failure(ctsio,
1729                                                          /*sks_valid*/ 0,
1730                                                          /*retry_count*/0);
1731                                 goto bailout;
1732                         }
1733                 }
1734
1735                 len_copied += len_to_copy;
1736
1737                 if (ext_sglist[i].len == ext_watermark) {
1738                         i++;
1739                         ext_watermark = 0;
1740                 }
1741
1742                 if (kern_sglist[j].len == kern_watermark) {
1743                         j++;
1744                         kern_watermark = 0;
1745                 }
1746         }
1747
1748         ctsio->ext_data_filled += len_copied;
1749
1750         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1751                          "kern_sg_entries: %d\n", ext_sg_entries,
1752                          kern_sg_entries));
1753         CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1754                          "kern_data_len = %d\n", ctsio->ext_data_len,
1755                          ctsio->kern_data_len));
1756
1757
1758         /* XXX KDM set residual?? */
1759 bailout:
1760
1761         if (ext_sglist_malloced != 0)
1762                 free(ext_sglist, M_CTL);
1763
1764         return (CTL_RETVAL_COMPLETE);
1765 }
1766
1767 /*
1768  * Serialize a command that went down the "wrong" side, and so was sent to
1769  * this controller for execution.  The logic is a little different than the
1770  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1771  * sent back to the other side, but in the success case, we execute the
1772  * command on this side (XFER mode) or tell the other side to execute it
1773  * (SER_ONLY mode).
1774  */
1775 static int
1776 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1777 {
1778         struct ctl_softc *ctl_softc;
1779         union ctl_ha_msg msg_info;
1780         struct ctl_lun *lun;
1781         int retval = 0;
1782         uint32_t targ_lun;
1783
1784         ctl_softc = control_softc;
1785
1786         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1787         lun = ctl_softc->ctl_luns[targ_lun];
1788         if (lun==NULL)
1789         {
1790                 /*
1791                  * Why isn't LUN defined? The other side wouldn't
1792                  * send a cmd if the LUN is undefined.
1793                  */
1794                 printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1795
1796                 /* "Logical unit not supported" */
1797                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1798                                    lun,
1799                                    /*sense_format*/SSD_TYPE_NONE,
1800                                    /*current_error*/ 1,
1801                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1802                                    /*asc*/ 0x25,
1803                                    /*ascq*/ 0x00,
1804                                    SSD_ELEM_NONE);
1805
1806                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1807                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1808                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1809                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1810                 msg_info.hdr.serializing_sc = NULL;
1811                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1812                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1813                                 sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1814                 }
1815                 return(1);
1816
1817         }
1818
1819         mtx_lock(&lun->lun_lock);
1820         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1821
1822         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1823                 (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1824                  ooa_links))) {
1825         case CTL_ACTION_BLOCK:
1826                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1827                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1828                                   blocked_links);
1829                 break;
1830         case CTL_ACTION_PASS:
1831         case CTL_ACTION_SKIP:
1832                 if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1833                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1834                         ctl_enqueue_rtr((union ctl_io *)ctsio);
1835                 } else {
1836
1837                         /* send msg back to other side */
1838                         msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1839                         msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1840                         msg_info.hdr.msg_type = CTL_MSG_R2R;
1841 #if 0
1842                         printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1843 #endif
1844                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1845                             sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1846                         }
1847                 }
1848                 break;
1849         case CTL_ACTION_OVERLAP:
1850                 /* OVERLAPPED COMMANDS ATTEMPTED */
1851                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1852                                    lun,
1853                                    /*sense_format*/SSD_TYPE_NONE,
1854                                    /*current_error*/ 1,
1855                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1856                                    /*asc*/ 0x4E,
1857                                    /*ascq*/ 0x00,
1858                                    SSD_ELEM_NONE);
1859
1860                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1861                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1862                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1863                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1864                 msg_info.hdr.serializing_sc = NULL;
1865                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1866 #if 0
1867                 printf("BAD JUJU:Major Bummer Overlap\n");
1868 #endif
1869                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1870                 retval = 1;
1871                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1872                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1873                 }
1874                 break;
1875         case CTL_ACTION_OVERLAP_TAG:
1876                 /* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1877                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1878                                    lun,
1879                                    /*sense_format*/SSD_TYPE_NONE,
1880                                    /*current_error*/ 1,
1881                                    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1882                                    /*asc*/ 0x4D,
1883                                    /*ascq*/ ctsio->tag_num & 0xff,
1884                                    SSD_ELEM_NONE);
1885
1886                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1887                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1888                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1889                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1890                 msg_info.hdr.serializing_sc = NULL;
1891                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1892 #if 0
1893                 printf("BAD JUJU:Major Bummer Overlap Tag\n");
1894 #endif
1895                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1896                 retval = 1;
1897                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1898                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1899                 }
1900                 break;
1901         case CTL_ACTION_ERROR:
1902         default:
1903                 /* "Internal target failure" */
1904                 ctl_set_sense_data(&msg_info.scsi.sense_data,
1905                                    lun,
1906                                    /*sense_format*/SSD_TYPE_NONE,
1907                                    /*current_error*/ 1,
1908                                    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1909                                    /*asc*/ 0x44,
1910                                    /*ascq*/ 0x00,
1911                                    SSD_ELEM_NONE);
1912
1913                 msg_info.scsi.sense_len = SSD_FULL_SIZE;
1914                 msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1915                 msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1916                 msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1917                 msg_info.hdr.serializing_sc = NULL;
1918                 msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1919 #if 0
1920                 printf("BAD JUJU:Major Bummer HW Error\n");
1921 #endif
1922                 TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1923                 retval = 1;
1924                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1925                     sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1926                 }
1927                 break;
1928         }
1929         mtx_unlock(&lun->lun_lock);
1930         return (retval);
1931 }
1932
1933 static int
1934 ctl_ioctl_submit_wait(union ctl_io *io)
1935 {
1936         struct ctl_fe_ioctl_params params;
1937         ctl_fe_ioctl_state last_state;
1938         int done, retval;
1939
1940         retval = 0;
1941
1942         bzero(&params, sizeof(params));
1943
1944         mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1945         cv_init(&params.sem, "ctlioccv");
1946         params.state = CTL_IOCTL_INPROG;
1947         last_state = params.state;
1948
1949         io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1950
1951         CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1952
1953         /* This shouldn't happen */
1954         if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1955                 return (retval);
1956
1957         done = 0;
1958
1959         do {
1960                 mtx_lock(&params.ioctl_mtx);
1961                 /*
1962                  * Check the state here, and don't sleep if the state has
1963                  * already changed (i.e. wakeup has already occured, but we
1964                  * weren't waiting yet).
1965                  */
1966                 if (params.state == last_state) {
1967                         /* XXX KDM cv_wait_sig instead? */
1968                         cv_wait(&params.sem, &params.ioctl_mtx);
1969                 }
1970                 last_state = params.state;
1971
1972                 switch (params.state) {
1973                 case CTL_IOCTL_INPROG:
1974                         /* Why did we wake up? */
1975                         /* XXX KDM error here? */
1976                         mtx_unlock(&params.ioctl_mtx);
1977                         break;
1978                 case CTL_IOCTL_DATAMOVE:
1979                         CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1980
1981                         /*
1982                          * change last_state back to INPROG to avoid
1983                          * deadlock on subsequent data moves.
1984                          */
1985                         params.state = last_state = CTL_IOCTL_INPROG;
1986
1987                         mtx_unlock(&params.ioctl_mtx);
1988                         ctl_ioctl_do_datamove(&io->scsiio);
1989                         /*
1990                          * Note that in some cases, most notably writes,
1991                          * this will queue the I/O and call us back later.
1992                          * In other cases, generally reads, this routine
1993                          * will immediately call back and wake us up,
1994                          * probably using our own context.
1995                          */
1996                         io->scsiio.be_move_done(io);
1997                         break;
1998                 case CTL_IOCTL_DONE:
1999                         mtx_unlock(&params.ioctl_mtx);
2000                         CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
2001                         done = 1;
2002                         break;
2003                 default:
2004                         mtx_unlock(&params.ioctl_mtx);
2005                         /* XXX KDM error here? */
2006                         break;
2007                 }
2008         } while (done == 0);
2009
2010         mtx_destroy(&params.ioctl_mtx);
2011         cv_destroy(&params.sem);
2012
2013         return (CTL_RETVAL_COMPLETE);
2014 }
2015
2016 static void
2017 ctl_ioctl_datamove(union ctl_io *io)
2018 {
2019         struct ctl_fe_ioctl_params *params;
2020
2021         params = (struct ctl_fe_ioctl_params *)
2022                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2023
2024         mtx_lock(&params->ioctl_mtx);
2025         params->state = CTL_IOCTL_DATAMOVE;
2026         cv_broadcast(&params->sem);
2027         mtx_unlock(&params->ioctl_mtx);
2028 }
2029
2030 static void
2031 ctl_ioctl_done(union ctl_io *io)
2032 {
2033         struct ctl_fe_ioctl_params *params;
2034
2035         params = (struct ctl_fe_ioctl_params *)
2036                 io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2037
2038         mtx_lock(&params->ioctl_mtx);
2039         params->state = CTL_IOCTL_DONE;
2040         cv_broadcast(&params->sem);
2041         mtx_unlock(&params->ioctl_mtx);
2042 }
2043
2044 static void
2045 ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2046 {
2047         struct ctl_fe_ioctl_startstop_info *sd_info;
2048
2049         sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2050
2051         sd_info->hs_info.status = metatask->status;
2052         sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2053         sd_info->hs_info.luns_complete =
2054                 metatask->taskinfo.startstop.luns_complete;
2055         sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2056
2057         cv_broadcast(&sd_info->sem);
2058 }
2059
2060 static void
2061 ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2062 {
2063         struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2064
2065         fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2066
2067         mtx_lock(fe_bbr_info->lock);
2068         fe_bbr_info->bbr_info->status = metatask->status;
2069         fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2070         fe_bbr_info->wakeup_done = 1;
2071         mtx_unlock(fe_bbr_info->lock);
2072
2073         cv_broadcast(&fe_bbr_info->sem);
2074 }
2075
2076 /*
2077  * Returns 0 for success, errno for failure.
2078  */
2079 static int
2080 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2081                    struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2082 {
2083         union ctl_io *io;
2084         int retval;
2085
2086         retval = 0;
2087
2088         mtx_lock(&lun->lun_lock);
2089         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2090              (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2091              ooa_links)) {
2092                 struct ctl_ooa_entry *entry;
2093
2094                 /*
2095                  * If we've got more than we can fit, just count the
2096                  * remaining entries.
2097                  */
2098                 if (*cur_fill_num >= ooa_hdr->alloc_num)
2099                         continue;
2100
2101                 entry = &kern_entries[*cur_fill_num];
2102
2103                 entry->tag_num = io->scsiio.tag_num;
2104                 entry->lun_num = lun->lun;
2105 #ifdef CTL_TIME_IO
2106                 entry->start_bt = io->io_hdr.start_bt;
2107 #endif
2108                 bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2109                 entry->cdb_len = io->scsiio.cdb_len;
2110                 if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2111                         entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2112
2113                 if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2114                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2115
2116                 if (io->io_hdr.flags & CTL_FLAG_ABORT)
2117                         entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2118
2119                 if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2120                         entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2121
2122                 if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2123                         entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2124         }
2125         mtx_unlock(&lun->lun_lock);
2126
2127         return (retval);
2128 }
2129
2130 static void *
2131 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2132                  size_t error_str_len)
2133 {
2134         void *kptr;
2135
2136         kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2137
2138         if (copyin(user_addr, kptr, len) != 0) {
2139                 snprintf(error_str, error_str_len, "Error copying %d bytes "
2140                          "from user address %p to kernel address %p", len,
2141                          user_addr, kptr);
2142                 free(kptr, M_CTL);
2143                 return (NULL);
2144         }
2145
2146         return (kptr);
2147 }
2148
2149 static void
2150 ctl_free_args(int num_args, struct ctl_be_arg *args)
2151 {
2152         int i;
2153
2154         if (args == NULL)
2155                 return;
2156
2157         for (i = 0; i < num_args; i++) {
2158                 free(args[i].kname, M_CTL);
2159                 free(args[i].kvalue, M_CTL);
2160         }
2161
2162         free(args, M_CTL);
2163 }
2164
2165 static struct ctl_be_arg *
2166 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2167                 char *error_str, size_t error_str_len)
2168 {
2169         struct ctl_be_arg *args;
2170         int i;
2171
2172         args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2173                                 error_str, error_str_len);
2174
2175         if (args == NULL)
2176                 goto bailout;
2177
2178         for (i = 0; i < num_args; i++) {
2179                 args[i].kname = NULL;
2180                 args[i].kvalue = NULL;
2181         }
2182
2183         for (i = 0; i < num_args; i++) {
2184                 uint8_t *tmpptr;
2185
2186                 args[i].kname = ctl_copyin_alloc(args[i].name,
2187                         args[i].namelen, error_str, error_str_len);
2188                 if (args[i].kname == NULL)
2189                         goto bailout;
2190
2191                 if (args[i].kname[args[i].namelen - 1] != '\0') {
2192                         snprintf(error_str, error_str_len, "Argument %d "
2193                                  "name is not NUL-terminated", i);
2194                         goto bailout;
2195                 }
2196
2197                 if (args[i].flags & CTL_BEARG_RD) {
2198                         tmpptr = ctl_copyin_alloc(args[i].value,
2199                                 args[i].vallen, error_str, error_str_len);
2200                         if (tmpptr == NULL)
2201                                 goto bailout;
2202                         if ((args[i].flags & CTL_BEARG_ASCII)
2203                          && (tmpptr[args[i].vallen - 1] != '\0')) {
2204                                 snprintf(error_str, error_str_len, "Argument "
2205                                     "%d value is not NUL-terminated", i);
2206                                 goto bailout;
2207                         }
2208                         args[i].kvalue = tmpptr;
2209                 } else {
2210                         args[i].kvalue = malloc(args[i].vallen,
2211                             M_CTL, M_WAITOK | M_ZERO);
2212                 }
2213         }
2214
2215         return (args);
2216 bailout:
2217
2218         ctl_free_args(num_args, args);
2219
2220         return (NULL);
2221 }
2222
2223 static void
2224 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2225 {
2226         int i;
2227
2228         for (i = 0; i < num_args; i++) {
2229                 if (args[i].flags & CTL_BEARG_WR)
2230                         copyout(args[i].kvalue, args[i].value, args[i].vallen);
2231         }
2232 }
2233
2234 /*
2235  * Escape characters that are illegal or not recommended in XML.
2236  */
2237 int
2238 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2239 {
2240         char *end = str + size;
2241         int retval;
2242
2243         retval = 0;
2244
2245         for (; *str && str < end; str++) {
2246                 switch (*str) {
2247                 case '&':
2248                         retval = sbuf_printf(sb, "&amp;");
2249                         break;
2250                 case '>':
2251                         retval = sbuf_printf(sb, "&gt;");
2252                         break;
2253                 case '<':
2254                         retval = sbuf_printf(sb, "&lt;");
2255                         break;
2256                 default:
2257                         retval = sbuf_putc(sb, *str);
2258                         break;
2259                 }
2260
2261                 if (retval != 0)
2262                         break;
2263
2264         }
2265
2266         return (retval);
2267 }
2268
2269 static void
2270 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2271 {
2272         struct scsi_vpd_id_descriptor *desc;
2273         int i;
2274
2275         if (id == NULL || id->len < 4)
2276                 return;
2277         desc = (struct scsi_vpd_id_descriptor *)id->data;
2278         switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2279         case SVPD_ID_TYPE_T10:
2280                 sbuf_printf(sb, "t10.");
2281                 break;
2282         case SVPD_ID_TYPE_EUI64:
2283                 sbuf_printf(sb, "eui.");
2284                 break;
2285         case SVPD_ID_TYPE_NAA:
2286                 sbuf_printf(sb, "naa.");
2287                 break;
2288         case SVPD_ID_TYPE_SCSI_NAME:
2289                 break;
2290         }
2291         switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2292         case SVPD_ID_CODESET_BINARY:
2293                 for (i = 0; i < desc->length; i++)
2294                         sbuf_printf(sb, "%02x", desc->identifier[i]);
2295                 break;
2296         case SVPD_ID_CODESET_ASCII:
2297                 sbuf_printf(sb, "%.*s", (int)desc->length,
2298                     (char *)desc->identifier);
2299                 break;
2300         case SVPD_ID_CODESET_UTF8:
2301                 sbuf_printf(sb, "%s", (char *)desc->identifier);
2302                 break;
2303         }
2304 }
2305
2306 static int
2307 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2308           struct thread *td)
2309 {
2310         struct ctl_softc *softc;
2311         int retval;
2312
2313         softc = control_softc;
2314
2315         retval = 0;
2316
2317         switch (cmd) {
2318         case CTL_IO: {
2319                 union ctl_io *io;
2320                 void *pool_tmp;
2321
2322                 /*
2323                  * If we haven't been "enabled", don't allow any SCSI I/O
2324                  * to this FETD.
2325                  */
2326                 if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2327                         retval = EPERM;
2328                         break;
2329                 }
2330
2331                 io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2332
2333                 /*
2334                  * Need to save the pool reference so it doesn't get
2335                  * spammed by the user's ctl_io.
2336                  */
2337                 pool_tmp = io->io_hdr.pool;
2338                 memcpy(io, (void *)addr, sizeof(*io));
2339                 io->io_hdr.pool = pool_tmp;
2340
2341                 /*
2342                  * No status yet, so make sure the status is set properly.
2343                  */
2344                 io->io_hdr.status = CTL_STATUS_NONE;
2345
2346                 /*
2347                  * The user sets the initiator ID, target and LUN IDs.
2348                  */
2349                 io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2350                 io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2351                 if ((io->io_hdr.io_type == CTL_IO_SCSI)
2352                  && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2353                         io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2354
2355                 retval = ctl_ioctl_submit_wait(io);
2356
2357                 if (retval != 0) {
2358                         ctl_free_io(io);
2359                         break;
2360                 }
2361
2362                 memcpy((void *)addr, io, sizeof(*io));
2363
2364                 /* return this to our pool */
2365                 ctl_free_io(io);
2366
2367                 break;
2368         }
2369         case CTL_ENABLE_PORT:
2370         case CTL_DISABLE_PORT:
2371         case CTL_SET_PORT_WWNS: {
2372                 struct ctl_port *port;
2373                 struct ctl_port_entry *entry;
2374
2375                 entry = (struct ctl_port_entry *)addr;
2376                 
2377                 mtx_lock(&softc->ctl_lock);
2378                 STAILQ_FOREACH(port, &softc->port_list, links) {
2379                         int action, done;
2380
2381                         action = 0;
2382                         done = 0;
2383
2384                         if ((entry->port_type == CTL_PORT_NONE)
2385                          && (entry->targ_port == port->targ_port)) {
2386                                 /*
2387                                  * If the user only wants to enable or
2388                                  * disable or set WWNs on a specific port,
2389                                  * do the operation and we're done.
2390                                  */
2391                                 action = 1;
2392                                 done = 1;
2393                         } else if (entry->port_type & port->port_type) {
2394                                 /*
2395                                  * Compare the user's type mask with the
2396                                  * particular frontend type to see if we
2397                                  * have a match.
2398                                  */
2399                                 action = 1;
2400                                 done = 0;
2401
2402                                 /*
2403                                  * Make sure the user isn't trying to set
2404                                  * WWNs on multiple ports at the same time.
2405                                  */
2406                                 if (cmd == CTL_SET_PORT_WWNS) {
2407                                         printf("%s: Can't set WWNs on "
2408                                                "multiple ports\n", __func__);
2409                                         retval = EINVAL;
2410                                         break;
2411                                 }
2412                         }
2413                         if (action != 0) {
2414                                 /*
2415                                  * XXX KDM we have to drop the lock here,
2416                                  * because the online/offline operations
2417                                  * can potentially block.  We need to
2418                                  * reference count the frontends so they
2419                                  * can't go away,
2420                                  */
2421                                 mtx_unlock(&softc->ctl_lock);
2422
2423                                 if (cmd == CTL_ENABLE_PORT) {
2424                                         struct ctl_lun *lun;
2425
2426                                         STAILQ_FOREACH(lun, &softc->lun_list,
2427                                                        links) {
2428                                                 port->lun_enable(port->targ_lun_arg,
2429                                                     lun->target,
2430                                                     lun->lun);
2431                                         }
2432
2433                                         ctl_port_online(port);
2434                                 } else if (cmd == CTL_DISABLE_PORT) {
2435                                         struct ctl_lun *lun;
2436
2437                                         ctl_port_offline(port);
2438
2439                                         STAILQ_FOREACH(lun, &softc->lun_list,
2440                                                        links) {
2441                                                 port->lun_disable(
2442                                                     port->targ_lun_arg,
2443                                                     lun->target,
2444                                                     lun->lun);
2445                                         }
2446                                 }
2447
2448                                 mtx_lock(&softc->ctl_lock);
2449
2450                                 if (cmd == CTL_SET_PORT_WWNS)
2451                                         ctl_port_set_wwns(port,
2452                                             (entry->flags & CTL_PORT_WWNN_VALID) ?
2453                                             1 : 0, entry->wwnn,
2454                                             (entry->flags & CTL_PORT_WWPN_VALID) ?
2455                                             1 : 0, entry->wwpn);
2456                         }
2457                         if (done != 0)
2458                                 break;
2459                 }
2460                 mtx_unlock(&softc->ctl_lock);
2461                 break;
2462         }
2463         case CTL_GET_PORT_LIST: {
2464                 struct ctl_port *port;
2465                 struct ctl_port_list *list;
2466                 int i;
2467
2468                 list = (struct ctl_port_list *)addr;
2469
2470                 if (list->alloc_len != (list->alloc_num *
2471                     sizeof(struct ctl_port_entry))) {
2472                         printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2473                                "alloc_num %u * sizeof(struct ctl_port_entry) "
2474                                "%zu\n", __func__, list->alloc_len,
2475                                list->alloc_num, sizeof(struct ctl_port_entry));
2476                         retval = EINVAL;
2477                         break;
2478                 }
2479                 list->fill_len = 0;
2480                 list->fill_num = 0;
2481                 list->dropped_num = 0;
2482                 i = 0;
2483                 mtx_lock(&softc->ctl_lock);
2484                 STAILQ_FOREACH(port, &softc->port_list, links) {
2485                         struct ctl_port_entry entry, *list_entry;
2486
2487                         if (list->fill_num >= list->alloc_num) {
2488                                 list->dropped_num++;
2489                                 continue;
2490                         }
2491
2492                         entry.port_type = port->port_type;
2493                         strlcpy(entry.port_name, port->port_name,
2494                                 sizeof(entry.port_name));
2495                         entry.targ_port = port->targ_port;
2496                         entry.physical_port = port->physical_port;
2497                         entry.virtual_port = port->virtual_port;
2498                         entry.wwnn = port->wwnn;
2499                         entry.wwpn = port->wwpn;
2500                         if (port->status & CTL_PORT_STATUS_ONLINE)
2501                                 entry.online = 1;
2502                         else
2503                                 entry.online = 0;
2504
2505                         list_entry = &list->entries[i];
2506
2507                         retval = copyout(&entry, list_entry, sizeof(entry));
2508                         if (retval != 0) {
2509                                 printf("%s: CTL_GET_PORT_LIST: copyout "
2510                                        "returned %d\n", __func__, retval);
2511                                 break;
2512                         }
2513                         i++;
2514                         list->fill_num++;
2515                         list->fill_len += sizeof(entry);
2516                 }
2517                 mtx_unlock(&softc->ctl_lock);
2518
2519                 /*
2520                  * If this is non-zero, we had a copyout fault, so there's
2521                  * probably no point in attempting to set the status inside
2522                  * the structure.
2523                  */
2524                 if (retval != 0)
2525                         break;
2526
2527                 if (list->dropped_num > 0)
2528                         list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2529                 else
2530                         list->status = CTL_PORT_LIST_OK;
2531                 break;
2532         }
2533         case CTL_DUMP_OOA: {
2534                 struct ctl_lun *lun;
2535                 union ctl_io *io;
2536                 char printbuf[128];
2537                 struct sbuf sb;
2538
2539                 mtx_lock(&softc->ctl_lock);
2540                 printf("Dumping OOA queues:\n");
2541                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
2542                         mtx_lock(&lun->lun_lock);
2543                         for (io = (union ctl_io *)TAILQ_FIRST(
2544                              &lun->ooa_queue); io != NULL;
2545                              io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2546                              ooa_links)) {
2547                                 sbuf_new(&sb, printbuf, sizeof(printbuf),
2548                                          SBUF_FIXEDLEN);
2549                                 sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2550                                             (intmax_t)lun->lun,
2551                                             io->scsiio.tag_num,
2552                                             (io->io_hdr.flags &
2553                                             CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2554                                             (io->io_hdr.flags &
2555                                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2556                                             (io->io_hdr.flags &
2557                                             CTL_FLAG_ABORT) ? " ABORT" : "",
2558                                             (io->io_hdr.flags &
2559                                         CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2560                                 ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2561                                 sbuf_finish(&sb);
2562                                 printf("%s\n", sbuf_data(&sb));
2563                         }
2564                         mtx_unlock(&lun->lun_lock);
2565                 }
2566                 printf("OOA queues dump done\n");
2567                 mtx_unlock(&softc->ctl_lock);
2568                 break;
2569         }
2570         case CTL_GET_OOA: {
2571                 struct ctl_lun *lun;
2572                 struct ctl_ooa *ooa_hdr;
2573                 struct ctl_ooa_entry *entries;
2574                 uint32_t cur_fill_num;
2575
2576                 ooa_hdr = (struct ctl_ooa *)addr;
2577
2578                 if ((ooa_hdr->alloc_len == 0)
2579                  || (ooa_hdr->alloc_num == 0)) {
2580                         printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2581                                "must be non-zero\n", __func__,
2582                                ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2583                         retval = EINVAL;
2584                         break;
2585                 }
2586
2587                 if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2588                     sizeof(struct ctl_ooa_entry))) {
2589                         printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2590                                "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2591                                __func__, ooa_hdr->alloc_len,
2592                                ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2593                         retval = EINVAL;
2594                         break;
2595                 }
2596
2597                 entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2598                 if (entries == NULL) {
2599                         printf("%s: could not allocate %d bytes for OOA "
2600                                "dump\n", __func__, ooa_hdr->alloc_len);
2601                         retval = ENOMEM;
2602                         break;
2603                 }
2604
2605                 mtx_lock(&softc->ctl_lock);
2606                 if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2607                  && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2608                   || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2609                         mtx_unlock(&softc->ctl_lock);
2610                         free(entries, M_CTL);
2611                         printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2612                                __func__, (uintmax_t)ooa_hdr->lun_num);
2613                         retval = EINVAL;
2614                         break;
2615                 }
2616
2617                 cur_fill_num = 0;
2618
2619                 if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2620                         STAILQ_FOREACH(lun, &softc->lun_list, links) {
2621                                 retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2622                                         ooa_hdr, entries);
2623                                 if (retval != 0)
2624                                         break;
2625                         }
2626                         if (retval != 0) {
2627                                 mtx_unlock(&softc->ctl_lock);
2628                                 free(entries, M_CTL);
2629                                 break;
2630                         }
2631                 } else {
2632                         lun = softc->ctl_luns[ooa_hdr->lun_num];
2633
2634                         retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2635                                                     entries);
2636                 }
2637                 mtx_unlock(&softc->ctl_lock);
2638
2639                 ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2640                 ooa_hdr->fill_len = ooa_hdr->fill_num *
2641                         sizeof(struct ctl_ooa_entry);
2642                 retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2643                 if (retval != 0) {
2644                         printf("%s: error copying out %d bytes for OOA dump\n", 
2645                                __func__, ooa_hdr->fill_len);
2646                 }
2647
2648                 getbintime(&ooa_hdr->cur_bt);
2649
2650                 if (cur_fill_num > ooa_hdr->alloc_num) {
2651                         ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2652                         ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2653                 } else {
2654                         ooa_hdr->dropped_num = 0;
2655                         ooa_hdr->status = CTL_OOA_OK;
2656                 }
2657
2658                 free(entries, M_CTL);
2659                 break;
2660         }
2661         case CTL_CHECK_OOA: {
2662                 union ctl_io *io;
2663                 struct ctl_lun *lun;
2664                 struct ctl_ooa_info *ooa_info;
2665
2666
2667                 ooa_info = (struct ctl_ooa_info *)addr;
2668
2669                 if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2670                         ooa_info->status = CTL_OOA_INVALID_LUN;
2671                         break;
2672                 }
2673                 mtx_lock(&softc->ctl_lock);
2674                 lun = softc->ctl_luns[ooa_info->lun_id];
2675                 if (lun == NULL) {
2676                         mtx_unlock(&softc->ctl_lock);
2677                         ooa_info->status = CTL_OOA_INVALID_LUN;
2678                         break;
2679                 }
2680                 mtx_lock(&lun->lun_lock);
2681                 mtx_unlock(&softc->ctl_lock);
2682                 ooa_info->num_entries = 0;
2683                 for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2684                      io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2685                      &io->io_hdr, ooa_links)) {
2686                         ooa_info->num_entries++;
2687                 }
2688                 mtx_unlock(&lun->lun_lock);
2689
2690                 ooa_info->status = CTL_OOA_SUCCESS;
2691
2692                 break;
2693         }
2694         case CTL_HARD_START:
2695         case CTL_HARD_STOP: {
2696                 struct ctl_fe_ioctl_startstop_info ss_info;
2697                 struct cfi_metatask *metatask;
2698                 struct mtx hs_mtx;
2699
2700                 mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2701
2702                 cv_init(&ss_info.sem, "hard start/stop cv" );
2703
2704                 metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2705                 if (metatask == NULL) {
2706                         retval = ENOMEM;
2707                         mtx_destroy(&hs_mtx);
2708                         break;
2709                 }
2710
2711                 if (cmd == CTL_HARD_START)
2712                         metatask->tasktype = CFI_TASK_STARTUP;
2713                 else
2714                         metatask->tasktype = CFI_TASK_SHUTDOWN;
2715
2716                 metatask->callback = ctl_ioctl_hard_startstop_callback;
2717                 metatask->callback_arg = &ss_info;
2718
2719                 cfi_action(metatask);
2720
2721                 /* Wait for the callback */
2722                 mtx_lock(&hs_mtx);
2723                 cv_wait_sig(&ss_info.sem, &hs_mtx);
2724                 mtx_unlock(&hs_mtx);
2725
2726                 /*
2727                  * All information has been copied from the metatask by the
2728                  * time cv_broadcast() is called, so we free the metatask here.
2729                  */
2730                 cfi_free_metatask(metatask);
2731
2732                 memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2733
2734                 mtx_destroy(&hs_mtx);
2735                 break;
2736         }
2737         case CTL_BBRREAD: {
2738                 struct ctl_bbrread_info *bbr_info;
2739                 struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2740                 struct mtx bbr_mtx;
2741                 struct cfi_metatask *metatask;
2742
2743                 bbr_info = (struct ctl_bbrread_info *)addr;
2744
2745                 bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2746
2747                 bzero(&bbr_mtx, sizeof(bbr_mtx));
2748                 mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2749
2750                 fe_bbr_info.bbr_info = bbr_info;
2751                 fe_bbr_info.lock = &bbr_mtx;
2752
2753                 cv_init(&fe_bbr_info.sem, "BBR read cv");
2754                 metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2755
2756                 if (metatask == NULL) {
2757                         mtx_destroy(&bbr_mtx);
2758                         cv_destroy(&fe_bbr_info.sem);
2759                         retval = ENOMEM;
2760                         break;
2761                 }
2762                 metatask->tasktype = CFI_TASK_BBRREAD;
2763                 metatask->callback = ctl_ioctl_bbrread_callback;
2764                 metatask->callback_arg = &fe_bbr_info;
2765                 metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2766                 metatask->taskinfo.bbrread.lba = bbr_info->lba;
2767                 metatask->taskinfo.bbrread.len = bbr_info->len;
2768
2769                 cfi_action(metatask);
2770
2771                 mtx_lock(&bbr_mtx);
2772                 while (fe_bbr_info.wakeup_done == 0)
2773                         cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2774                 mtx_unlock(&bbr_mtx);
2775
2776                 bbr_info->status = metatask->status;
2777                 bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2778                 bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2779                 memcpy(&bbr_info->sense_data,
2780                        &metatask->taskinfo.bbrread.sense_data,
2781                        ctl_min(sizeof(bbr_info->sense_data),
2782                                sizeof(metatask->taskinfo.bbrread.sense_data)));
2783
2784                 cfi_free_metatask(metatask);
2785
2786                 mtx_destroy(&bbr_mtx);
2787                 cv_destroy(&fe_bbr_info.sem);
2788
2789                 break;
2790         }
2791         case CTL_DELAY_IO: {
2792                 struct ctl_io_delay_info *delay_info;
2793 #ifdef CTL_IO_DELAY
2794                 struct ctl_lun *lun;
2795 #endif /* CTL_IO_DELAY */
2796
2797                 delay_info = (struct ctl_io_delay_info *)addr;
2798
2799 #ifdef CTL_IO_DELAY
2800                 mtx_lock(&softc->ctl_lock);
2801
2802                 if ((delay_info->lun_id >= CTL_MAX_LUNS)
2803                  || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2804                         delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2805                 } else {
2806                         lun = softc->ctl_luns[delay_info->lun_id];
2807                         mtx_lock(&lun->lun_lock);
2808
2809                         delay_info->status = CTL_DELAY_STATUS_OK;
2810
2811                         switch (delay_info->delay_type) {
2812                         case CTL_DELAY_TYPE_CONT:
2813                                 break;
2814                         case CTL_DELAY_TYPE_ONESHOT:
2815                                 break;
2816                         default:
2817                                 delay_info->status =
2818                                         CTL_DELAY_STATUS_INVALID_TYPE;
2819                                 break;
2820                         }
2821
2822                         switch (delay_info->delay_loc) {
2823                         case CTL_DELAY_LOC_DATAMOVE:
2824                                 lun->delay_info.datamove_type =
2825                                         delay_info->delay_type;
2826                                 lun->delay_info.datamove_delay =
2827                                         delay_info->delay_secs;
2828                                 break;
2829                         case CTL_DELAY_LOC_DONE:
2830                                 lun->delay_info.done_type =
2831                                         delay_info->delay_type;
2832                                 lun->delay_info.done_delay =
2833                                         delay_info->delay_secs;
2834                                 break;
2835                         default:
2836                                 delay_info->status =
2837                                         CTL_DELAY_STATUS_INVALID_LOC;
2838                                 break;
2839                         }
2840                         mtx_unlock(&lun->lun_lock);
2841                 }
2842
2843                 mtx_unlock(&softc->ctl_lock);
2844 #else
2845                 delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2846 #endif /* CTL_IO_DELAY */
2847                 break;
2848         }
2849         case CTL_REALSYNC_SET: {
2850                 int *syncstate;
2851
2852                 syncstate = (int *)addr;
2853
2854                 mtx_lock(&softc->ctl_lock);
2855                 switch (*syncstate) {
2856                 case 0:
2857                         softc->flags &= ~CTL_FLAG_REAL_SYNC;
2858                         break;
2859                 case 1:
2860                         softc->flags |= CTL_FLAG_REAL_SYNC;
2861                         break;
2862                 default:
2863                         retval = EINVAL;
2864                         break;
2865                 }
2866                 mtx_unlock(&softc->ctl_lock);
2867                 break;
2868         }
2869         case CTL_REALSYNC_GET: {
2870                 int *syncstate;
2871
2872                 syncstate = (int*)addr;
2873
2874                 mtx_lock(&softc->ctl_lock);
2875                 if (softc->flags & CTL_FLAG_REAL_SYNC)
2876                         *syncstate = 1;
2877                 else
2878                         *syncstate = 0;
2879                 mtx_unlock(&softc->ctl_lock);
2880
2881                 break;
2882         }
2883         case CTL_SETSYNC:
2884         case CTL_GETSYNC: {
2885                 struct ctl_sync_info *sync_info;
2886                 struct ctl_lun *lun;
2887
2888                 sync_info = (struct ctl_sync_info *)addr;
2889
2890                 mtx_lock(&softc->ctl_lock);
2891                 lun = softc->ctl_luns[sync_info->lun_id];
2892                 if (lun == NULL) {
2893                         mtx_unlock(&softc->ctl_lock);
2894                         sync_info->status = CTL_GS_SYNC_NO_LUN;
2895                 }
2896                 /*
2897                  * Get or set the sync interval.  We're not bounds checking
2898                  * in the set case, hopefully the user won't do something
2899                  * silly.
2900                  */
2901                 mtx_lock(&lun->lun_lock);
2902                 mtx_unlock(&softc->ctl_lock);
2903                 if (cmd == CTL_GETSYNC)
2904                         sync_info->sync_interval = lun->sync_interval;
2905                 else
2906                         lun->sync_interval = sync_info->sync_interval;
2907                 mtx_unlock(&lun->lun_lock);
2908
2909                 sync_info->status = CTL_GS_SYNC_OK;
2910
2911                 break;
2912         }
2913         case CTL_GETSTATS: {
2914                 struct ctl_stats *stats;
2915                 struct ctl_lun *lun;
2916                 int i;
2917
2918                 stats = (struct ctl_stats *)addr;
2919
2920                 if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2921                      stats->alloc_len) {
2922                         stats->status = CTL_SS_NEED_MORE_SPACE;
2923                         stats->num_luns = softc->num_luns;
2924                         break;
2925                 }
2926                 /*
2927                  * XXX KDM no locking here.  If the LUN list changes,
2928                  * things can blow up.
2929                  */
2930                 for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2931                      i++, lun = STAILQ_NEXT(lun, links)) {
2932                         retval = copyout(&lun->stats, &stats->lun_stats[i],
2933                                          sizeof(lun->stats));
2934                         if (retval != 0)
2935                                 break;
2936                 }
2937                 stats->num_luns = softc->num_luns;
2938                 stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2939                                  softc->num_luns;
2940                 stats->status = CTL_SS_OK;
2941 #ifdef CTL_TIME_IO
2942                 stats->flags = CTL_STATS_FLAG_TIME_VALID;
2943 #else
2944                 stats->flags = CTL_STATS_FLAG_NONE;
2945 #endif
2946                 getnanouptime(&stats->timestamp);
2947                 break;
2948         }
2949         case CTL_ERROR_INJECT: {
2950                 struct ctl_error_desc *err_desc, *new_err_desc;
2951                 struct ctl_lun *lun;
2952
2953                 err_desc = (struct ctl_error_desc *)addr;
2954
2955                 new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2956                                       M_WAITOK | M_ZERO);
2957                 bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2958
2959                 mtx_lock(&softc->ctl_lock);
2960                 lun = softc->ctl_luns[err_desc->lun_id];
2961                 if (lun == NULL) {
2962                         mtx_unlock(&softc->ctl_lock);
2963                         free(new_err_desc, M_CTL);
2964                         printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2965                                __func__, (uintmax_t)err_desc->lun_id);
2966                         retval = EINVAL;
2967                         break;
2968                 }
2969                 mtx_lock(&lun->lun_lock);
2970                 mtx_unlock(&softc->ctl_lock);
2971
2972                 /*
2973                  * We could do some checking here to verify the validity
2974                  * of the request, but given the complexity of error
2975                  * injection requests, the checking logic would be fairly
2976                  * complex.
2977                  *
2978                  * For now, if the request is invalid, it just won't get
2979                  * executed and might get deleted.
2980                  */
2981                 STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2982
2983                 /*
2984                  * XXX KDM check to make sure the serial number is unique,
2985                  * in case we somehow manage to wrap.  That shouldn't
2986                  * happen for a very long time, but it's the right thing to
2987                  * do.
2988                  */
2989                 new_err_desc->serial = lun->error_serial;
2990                 err_desc->serial = lun->error_serial;
2991                 lun->error_serial++;
2992
2993                 mtx_unlock(&lun->lun_lock);
2994                 break;
2995         }
2996         case CTL_ERROR_INJECT_DELETE: {
2997                 struct ctl_error_desc *delete_desc, *desc, *desc2;
2998                 struct ctl_lun *lun;
2999                 int delete_done;
3000
3001                 delete_desc = (struct ctl_error_desc *)addr;
3002                 delete_done = 0;
3003
3004                 mtx_lock(&softc->ctl_lock);
3005                 lun = softc->ctl_luns[delete_desc->lun_id];
3006                 if (lun == NULL) {
3007                         mtx_unlock(&softc->ctl_lock);
3008                         printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
3009                                __func__, (uintmax_t)delete_desc->lun_id);
3010                         retval = EINVAL;
3011                         break;
3012                 }
3013                 mtx_lock(&lun->lun_lock);
3014                 mtx_unlock(&softc->ctl_lock);
3015                 STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
3016                         if (desc->serial != delete_desc->serial)
3017                                 continue;
3018
3019                         STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
3020                                       links);
3021                         free(desc, M_CTL);
3022                         delete_done = 1;
3023                 }
3024                 mtx_unlock(&lun->lun_lock);
3025                 if (delete_done == 0) {
3026                         printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
3027                                "error serial %ju on LUN %u\n", __func__, 
3028                                delete_desc->serial, delete_desc->lun_id);
3029                         retval = EINVAL;
3030                         break;
3031                 }
3032                 break;
3033         }
3034         case CTL_DUMP_STRUCTS: {
3035                 int i, j, k;
3036                 struct ctl_port *port;
3037                 struct ctl_frontend *fe;
3038
3039                 mtx_lock(&softc->ctl_lock);
3040                 printf("CTL Persistent Reservation information start:\n");
3041                 for (i = 0; i < CTL_MAX_LUNS; i++) {
3042                         struct ctl_lun *lun;
3043
3044                         lun = softc->ctl_luns[i];
3045
3046                         if ((lun == NULL)
3047                          || ((lun->flags & CTL_LUN_DISABLED) != 0))
3048                                 continue;
3049
3050                         for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
3051                                 if (lun->pr_keys[j] == NULL)
3052                                         continue;
3053                                 for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3054                                         if (lun->pr_keys[j][k] == 0)
3055                                                 continue;
3056                                         printf("  LUN %d port %d iid %d key "
3057                                                "%#jx\n", i, j, k,
3058                                                (uintmax_t)lun->pr_keys[j][k]);
3059                                 }
3060                         }
3061                 }
3062                 printf("CTL Persistent Reservation information end\n");
3063                 printf("CTL Ports:\n");
3064                 STAILQ_FOREACH(port, &softc->port_list, links) {
3065                         printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3066                                "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3067                                port->frontend->name, port->port_type,
3068                                port->physical_port, port->virtual_port,
3069                                (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3070                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3071                                 if (port->wwpn_iid[j].in_use == 0 &&
3072                                     port->wwpn_iid[j].wwpn == 0 &&
3073                                     port->wwpn_iid[j].name == NULL)
3074                                         continue;
3075
3076                                 printf("    iid %u use %d WWPN %#jx '%s'\n",
3077                                     j, port->wwpn_iid[j].in_use,
3078                                     (uintmax_t)port->wwpn_iid[j].wwpn,
3079                                     port->wwpn_iid[j].name);
3080                         }
3081                 }
3082                 printf("CTL Port information end\n");
3083                 mtx_unlock(&softc->ctl_lock);
3084                 /*
3085                  * XXX KDM calling this without a lock.  We'd likely want
3086                  * to drop the lock before calling the frontend's dump
3087                  * routine anyway.
3088                  */
3089                 printf("CTL Frontends:\n");
3090                 STAILQ_FOREACH(fe, &softc->fe_list, links) {
3091                         printf("  Frontend '%s'\n", fe->name);
3092                         if (fe->fe_dump != NULL)
3093                                 fe->fe_dump();
3094                 }
3095                 printf("CTL Frontend information end\n");
3096                 break;
3097         }
3098         case CTL_LUN_REQ: {
3099                 struct ctl_lun_req *lun_req;
3100                 struct ctl_backend_driver *backend;
3101
3102                 lun_req = (struct ctl_lun_req *)addr;
3103
3104                 backend = ctl_backend_find(lun_req->backend);
3105                 if (backend == NULL) {
3106                         lun_req->status = CTL_LUN_ERROR;
3107                         snprintf(lun_req->error_str,
3108                                  sizeof(lun_req->error_str),
3109                                  "Backend \"%s\" not found.",
3110                                  lun_req->backend);
3111                         break;
3112                 }
3113                 if (lun_req->num_be_args > 0) {
3114                         lun_req->kern_be_args = ctl_copyin_args(
3115                                 lun_req->num_be_args,
3116                                 lun_req->be_args,
3117                                 lun_req->error_str,
3118                                 sizeof(lun_req->error_str));
3119                         if (lun_req->kern_be_args == NULL) {
3120                                 lun_req->status = CTL_LUN_ERROR;
3121                                 break;
3122                         }
3123                 }
3124
3125                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3126
3127                 if (lun_req->num_be_args > 0) {
3128                         ctl_copyout_args(lun_req->num_be_args,
3129                                       lun_req->kern_be_args);
3130                         ctl_free_args(lun_req->num_be_args,
3131                                       lun_req->kern_be_args);
3132                 }
3133                 break;
3134         }
3135         case CTL_LUN_LIST: {
3136                 struct sbuf *sb;
3137                 struct ctl_lun *lun;
3138                 struct ctl_lun_list *list;
3139                 struct ctl_option *opt;
3140
3141                 list = (struct ctl_lun_list *)addr;
3142
3143                 /*
3144                  * Allocate a fixed length sbuf here, based on the length
3145                  * of the user's buffer.  We could allocate an auto-extending
3146                  * buffer, and then tell the user how much larger our
3147                  * amount of data is than his buffer, but that presents
3148                  * some problems:
3149                  *
3150                  * 1.  The sbuf(9) routines use a blocking malloc, and so
3151                  *     we can't hold a lock while calling them with an
3152                  *     auto-extending buffer.
3153                  *
3154                  * 2.  There is not currently a LUN reference counting
3155                  *     mechanism, outside of outstanding transactions on
3156                  *     the LUN's OOA queue.  So a LUN could go away on us
3157                  *     while we're getting the LUN number, backend-specific
3158                  *     information, etc.  Thus, given the way things
3159                  *     currently work, we need to hold the CTL lock while
3160                  *     grabbing LUN information.
3161                  *
3162                  * So, from the user's standpoint, the best thing to do is
3163                  * allocate what he thinks is a reasonable buffer length,
3164                  * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3165                  * double the buffer length and try again.  (And repeat
3166                  * that until he succeeds.)
3167                  */
3168                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3169                 if (sb == NULL) {
3170                         list->status = CTL_LUN_LIST_ERROR;
3171                         snprintf(list->error_str, sizeof(list->error_str),
3172                                  "Unable to allocate %d bytes for LUN list",
3173                                  list->alloc_len);
3174                         break;
3175                 }
3176
3177                 sbuf_printf(sb, "<ctllunlist>\n");
3178
3179                 mtx_lock(&softc->ctl_lock);
3180                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
3181                         mtx_lock(&lun->lun_lock);
3182                         retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3183                                              (uintmax_t)lun->lun);
3184
3185                         /*
3186                          * Bail out as soon as we see that we've overfilled
3187                          * the buffer.
3188                          */
3189                         if (retval != 0)
3190                                 break;
3191
3192                         retval = sbuf_printf(sb, "\t<backend_type>%s"
3193                                              "</backend_type>\n",
3194                                              (lun->backend == NULL) ?  "none" :
3195                                              lun->backend->name);
3196
3197                         if (retval != 0)
3198                                 break;
3199
3200                         retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3201                                              lun->be_lun->lun_type);
3202
3203                         if (retval != 0)
3204                                 break;
3205
3206                         if (lun->backend == NULL) {
3207                                 retval = sbuf_printf(sb, "</lun>\n");
3208                                 if (retval != 0)
3209                                         break;
3210                                 continue;
3211                         }
3212
3213                         retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3214                                              (lun->be_lun->maxlba > 0) ?
3215                                              lun->be_lun->maxlba + 1 : 0);
3216
3217                         if (retval != 0)
3218                                 break;
3219
3220                         retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3221                                              lun->be_lun->blocksize);
3222
3223                         if (retval != 0)
3224                                 break;
3225
3226                         retval = sbuf_printf(sb, "\t<serial_number>");
3227
3228                         if (retval != 0)
3229                                 break;
3230
3231                         retval = ctl_sbuf_printf_esc(sb,
3232                             lun->be_lun->serial_num,
3233                             sizeof(lun->be_lun->serial_num));
3234
3235                         if (retval != 0)
3236                                 break;
3237
3238                         retval = sbuf_printf(sb, "</serial_number>\n");
3239                 
3240                         if (retval != 0)
3241                                 break;
3242
3243                         retval = sbuf_printf(sb, "\t<device_id>");
3244
3245                         if (retval != 0)
3246                                 break;
3247
3248                         retval = ctl_sbuf_printf_esc(sb,
3249                             lun->be_lun->device_id,
3250                             sizeof(lun->be_lun->device_id));
3251
3252                         if (retval != 0)
3253                                 break;
3254
3255                         retval = sbuf_printf(sb, "</device_id>\n");
3256
3257                         if (retval != 0)
3258                                 break;
3259
3260                         if (lun->backend->lun_info != NULL) {
3261                                 retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3262                                 if (retval != 0)
3263                                         break;
3264                         }
3265                         STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3266                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3267                                     opt->name, opt->value, opt->name);
3268                                 if (retval != 0)
3269                                         break;
3270                         }
3271
3272                         retval = sbuf_printf(sb, "</lun>\n");
3273
3274                         if (retval != 0)
3275                                 break;
3276                         mtx_unlock(&lun->lun_lock);
3277                 }
3278                 if (lun != NULL)
3279                         mtx_unlock(&lun->lun_lock);
3280                 mtx_unlock(&softc->ctl_lock);
3281
3282                 if ((retval != 0)
3283                  || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3284                         retval = 0;
3285                         sbuf_delete(sb);
3286                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3287                         snprintf(list->error_str, sizeof(list->error_str),
3288                                  "Out of space, %d bytes is too small",
3289                                  list->alloc_len);
3290                         break;
3291                 }
3292
3293                 sbuf_finish(sb);
3294
3295                 retval = copyout(sbuf_data(sb), list->lun_xml,
3296                                  sbuf_len(sb) + 1);
3297
3298                 list->fill_len = sbuf_len(sb) + 1;
3299                 list->status = CTL_LUN_LIST_OK;
3300                 sbuf_delete(sb);
3301                 break;
3302         }
3303         case CTL_ISCSI: {
3304                 struct ctl_iscsi *ci;
3305                 struct ctl_frontend *fe;
3306
3307                 ci = (struct ctl_iscsi *)addr;
3308
3309                 fe = ctl_frontend_find("iscsi");
3310                 if (fe == NULL) {
3311                         ci->status = CTL_ISCSI_ERROR;
3312                         snprintf(ci->error_str, sizeof(ci->error_str),
3313                             "Frontend \"iscsi\" not found.");
3314                         break;
3315                 }
3316
3317                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3318                 break;
3319         }
3320         case CTL_PORT_REQ: {
3321                 struct ctl_req *req;
3322                 struct ctl_frontend *fe;
3323
3324                 req = (struct ctl_req *)addr;
3325
3326                 fe = ctl_frontend_find(req->driver);
3327                 if (fe == NULL) {
3328                         req->status = CTL_LUN_ERROR;
3329                         snprintf(req->error_str, sizeof(req->error_str),
3330                             "Frontend \"%s\" not found.", req->driver);
3331                         break;
3332                 }
3333                 if (req->num_args > 0) {
3334                         req->kern_args = ctl_copyin_args(req->num_args,
3335                             req->args, req->error_str, sizeof(req->error_str));
3336                         if (req->kern_args == NULL) {
3337                                 req->status = CTL_LUN_ERROR;
3338                                 break;
3339                         }
3340                 }
3341
3342                 retval = fe->ioctl(dev, cmd, addr, flag, td);
3343
3344                 if (req->num_args > 0) {
3345                         ctl_copyout_args(req->num_args, req->kern_args);
3346                         ctl_free_args(req->num_args, req->kern_args);
3347                 }
3348                 break;
3349         }
3350         case CTL_PORT_LIST: {
3351                 struct sbuf *sb;
3352                 struct ctl_port *port;
3353                 struct ctl_lun_list *list;
3354                 struct ctl_option *opt;
3355                 int j;
3356
3357                 list = (struct ctl_lun_list *)addr;
3358
3359                 sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3360                 if (sb == NULL) {
3361                         list->status = CTL_LUN_LIST_ERROR;
3362                         snprintf(list->error_str, sizeof(list->error_str),
3363                                  "Unable to allocate %d bytes for LUN list",
3364                                  list->alloc_len);
3365                         break;
3366                 }
3367
3368                 sbuf_printf(sb, "<ctlportlist>\n");
3369
3370                 mtx_lock(&softc->ctl_lock);
3371                 STAILQ_FOREACH(port, &softc->port_list, links) {
3372                         retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3373                                              (uintmax_t)port->targ_port);
3374
3375                         /*
3376                          * Bail out as soon as we see that we've overfilled
3377                          * the buffer.
3378                          */
3379                         if (retval != 0)
3380                                 break;
3381
3382                         retval = sbuf_printf(sb, "\t<frontend_type>%s"
3383                             "</frontend_type>\n", port->frontend->name);
3384                         if (retval != 0)
3385                                 break;
3386
3387                         retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3388                                              port->port_type);
3389                         if (retval != 0)
3390                                 break;
3391
3392                         retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3393                             (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3394                         if (retval != 0)
3395                                 break;
3396
3397                         retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3398                             port->port_name);
3399                         if (retval != 0)
3400                                 break;
3401
3402                         retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3403                             port->physical_port);
3404                         if (retval != 0)
3405                                 break;
3406
3407                         retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3408                             port->virtual_port);
3409                         if (retval != 0)
3410                                 break;
3411
3412                         if (port->target_devid != NULL) {
3413                                 sbuf_printf(sb, "\t<target>");
3414                                 ctl_id_sbuf(port->target_devid, sb);
3415                                 sbuf_printf(sb, "</target>\n");
3416                         }
3417
3418                         if (port->port_devid != NULL) {
3419                                 sbuf_printf(sb, "\t<port>");
3420                                 ctl_id_sbuf(port->port_devid, sb);
3421                                 sbuf_printf(sb, "</port>\n");
3422                         }
3423
3424                         if (port->port_info != NULL) {
3425                                 retval = port->port_info(port->onoff_arg, sb);
3426                                 if (retval != 0)
3427                                         break;
3428                         }
3429                         STAILQ_FOREACH(opt, &port->options, links) {
3430                                 retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3431                                     opt->name, opt->value, opt->name);
3432                                 if (retval != 0)
3433                                         break;
3434                         }
3435
3436                         for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3437                                 if (port->wwpn_iid[j].in_use == 0 ||
3438                                     (port->wwpn_iid[j].wwpn == 0 &&
3439                                      port->wwpn_iid[j].name == NULL))
3440                                         continue;
3441
3442                                 if (port->wwpn_iid[j].name != NULL)
3443                                         retval = sbuf_printf(sb,
3444                                             "\t<initiator>%u %s</initiator>\n",
3445                                             j, port->wwpn_iid[j].name);
3446                                 else
3447                                         retval = sbuf_printf(sb,
3448                                             "\t<initiator>%u naa.%08jx</initiator>\n",
3449                                             j, port->wwpn_iid[j].wwpn);
3450                                 if (retval != 0)
3451                                         break;
3452                         }
3453                         if (retval != 0)
3454                                 break;
3455
3456                         retval = sbuf_printf(sb, "</targ_port>\n");
3457                         if (retval != 0)
3458                                 break;
3459                 }
3460                 mtx_unlock(&softc->ctl_lock);
3461
3462                 if ((retval != 0)
3463                  || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3464                         retval = 0;
3465                         sbuf_delete(sb);
3466                         list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3467                         snprintf(list->error_str, sizeof(list->error_str),
3468                                  "Out of space, %d bytes is too small",
3469                                  list->alloc_len);
3470                         break;
3471                 }
3472
3473                 sbuf_finish(sb);
3474
3475                 retval = copyout(sbuf_data(sb), list->lun_xml,
3476                                  sbuf_len(sb) + 1);
3477
3478                 list->fill_len = sbuf_len(sb) + 1;
3479                 list->status = CTL_LUN_LIST_OK;
3480                 sbuf_delete(sb);
3481                 break;
3482         }
3483         default: {
3484                 /* XXX KDM should we fix this? */
3485 #if 0
3486                 struct ctl_backend_driver *backend;
3487                 unsigned int type;
3488                 int found;
3489
3490                 found = 0;
3491
3492                 /*
3493                  * We encode the backend type as the ioctl type for backend
3494                  * ioctls.  So parse it out here, and then search for a
3495                  * backend of this type.
3496                  */
3497                 type = _IOC_TYPE(cmd);
3498
3499                 STAILQ_FOREACH(backend, &softc->be_list, links) {
3500                         if (backend->type == type) {
3501                                 found = 1;
3502                                 break;
3503                         }
3504                 }
3505                 if (found == 0) {
3506                         printf("ctl: unknown ioctl command %#lx or backend "
3507                                "%d\n", cmd, type);
3508                         retval = EINVAL;
3509                         break;
3510                 }
3511                 retval = backend->ioctl(dev, cmd, addr, flag, td);
3512 #endif
3513                 retval = ENOTTY;
3514                 break;
3515         }
3516         }
3517         return (retval);
3518 }
3519
3520 uint32_t
3521 ctl_get_initindex(struct ctl_nexus *nexus)
3522 {
3523         if (nexus->targ_port < CTL_MAX_PORTS)
3524                 return (nexus->initid.id +
3525                         (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3526         else
3527                 return (nexus->initid.id +
3528                        ((nexus->targ_port - CTL_MAX_PORTS) *
3529                         CTL_MAX_INIT_PER_PORT));
3530 }
3531
3532 uint32_t
3533 ctl_get_resindex(struct ctl_nexus *nexus)
3534 {
3535         return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3536 }
3537
3538 uint32_t
3539 ctl_port_idx(int port_num)
3540 {
3541         if (port_num < CTL_MAX_PORTS)
3542                 return(port_num);
3543         else
3544                 return(port_num - CTL_MAX_PORTS);
3545 }
3546
3547 static uint32_t
3548 ctl_map_lun(int port_num, uint32_t lun_id)
3549 {
3550         struct ctl_port *port;
3551
3552         port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3553         if (port == NULL)
3554                 return (UINT32_MAX);
3555         if (port->lun_map == NULL)
3556                 return (lun_id);
3557         return (port->lun_map(port->targ_lun_arg, lun_id));
3558 }
3559
3560 static uint32_t
3561 ctl_map_lun_back(int port_num, uint32_t lun_id)
3562 {
3563         struct ctl_port *port;
3564         uint32_t i;
3565
3566         port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3567         if (port->lun_map == NULL)
3568                 return (lun_id);
3569         for (i = 0; i < CTL_MAX_LUNS; i++) {
3570                 if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3571                         return (i);
3572         }
3573         return (UINT32_MAX);
3574 }
3575
3576 /*
3577  * Note:  This only works for bitmask sizes that are at least 32 bits, and
3578  * that are a power of 2.
3579  */
3580 int
3581 ctl_ffz(uint32_t *mask, uint32_t size)
3582 {
3583         uint32_t num_chunks, num_pieces;
3584         int i, j;
3585
3586         num_chunks = (size >> 5);
3587         if (num_chunks == 0)
3588                 num_chunks++;
3589         num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3590
3591         for (i = 0; i < num_chunks; i++) {
3592                 for (j = 0; j < num_pieces; j++) {
3593                         if ((mask[i] & (1 << j)) == 0)
3594                                 return ((i << 5) + j);
3595                 }
3596         }
3597
3598         return (-1);
3599 }
3600
3601 int
3602 ctl_set_mask(uint32_t *mask, uint32_t bit)
3603 {
3604         uint32_t chunk, piece;
3605
3606         chunk = bit >> 5;
3607         piece = bit % (sizeof(uint32_t) * 8);
3608
3609         if ((mask[chunk] & (1 << piece)) != 0)
3610                 return (-1);
3611         else
3612                 mask[chunk] |= (1 << piece);
3613
3614         return (0);
3615 }
3616
3617 int
3618 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3619 {
3620         uint32_t chunk, piece;
3621
3622         chunk = bit >> 5;
3623         piece = bit % (sizeof(uint32_t) * 8);
3624
3625         if ((mask[chunk] & (1 << piece)) == 0)
3626                 return (-1);
3627         else
3628                 mask[chunk] &= ~(1 << piece);
3629
3630         return (0);
3631 }
3632
3633 int
3634 ctl_is_set(uint32_t *mask, uint32_t bit)
3635 {
3636         uint32_t chunk, piece;
3637
3638         chunk = bit >> 5;
3639         piece = bit % (sizeof(uint32_t) * 8);
3640
3641         if ((mask[chunk] & (1 << piece)) == 0)
3642                 return (0);
3643         else
3644                 return (1);
3645 }
3646
3647 static uint64_t
3648 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3649 {
3650         uint64_t *t;
3651
3652         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3653         if (t == NULL)
3654                 return (0);
3655         return (t[residx % CTL_MAX_INIT_PER_PORT]);
3656 }
3657
3658 static void
3659 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3660 {
3661         uint64_t *t;
3662
3663         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3664         if (t == NULL)
3665                 return;
3666         t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3667 }
3668
3669 static void
3670 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3671 {
3672         uint64_t *p;
3673         u_int i;
3674
3675         i = residx/CTL_MAX_INIT_PER_PORT;
3676         if (lun->pr_keys[i] != NULL)
3677                 return;
3678         mtx_unlock(&lun->lun_lock);
3679         p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3680             M_WAITOK | M_ZERO);
3681         mtx_lock(&lun->lun_lock);
3682         if (lun->pr_keys[i] == NULL)
3683                 lun->pr_keys[i] = p;
3684         else
3685                 free(p, M_CTL);
3686 }
3687
3688 static void
3689 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3690 {
3691         uint64_t *t;
3692
3693         t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3694         KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3695         t[residx % CTL_MAX_INIT_PER_PORT] = key;
3696 }
3697
3698 /*
3699  * ctl_softc, pool_name, total_ctl_io are passed in.
3700  * npool is passed out.
3701  */
3702 int
3703 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3704                 uint32_t total_ctl_io, void **npool)
3705 {
3706 #ifdef IO_POOLS
3707         struct ctl_io_pool *pool;
3708
3709         pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3710                                             M_NOWAIT | M_ZERO);
3711         if (pool == NULL)
3712                 return (ENOMEM);
3713
3714         snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3715         pool->ctl_softc = ctl_softc;
3716         pool->zone = uma_zsecond_create(pool->name, NULL,
3717             NULL, NULL, NULL, ctl_softc->io_zone);
3718         /* uma_prealloc(pool->zone, total_ctl_io); */
3719
3720         *npool = pool;
3721 #else
3722         *npool = ctl_softc->io_zone;
3723 #endif
3724         return (0);
3725 }
3726
3727 void
3728 ctl_pool_free(struct ctl_io_pool *pool)
3729 {
3730
3731         if (pool == NULL)
3732                 return;
3733
3734 #ifdef IO_POOLS
3735         uma_zdestroy(pool->zone);
3736         free(pool, M_CTL);
3737 #endif
3738 }
3739
3740 union ctl_io *
3741 ctl_alloc_io(void *pool_ref)
3742 {
3743         union ctl_io *io;
3744 #ifdef IO_POOLS
3745         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3746
3747         io = uma_zalloc(pool->zone, M_WAITOK);
3748 #else
3749         io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3750 #endif
3751         if (io != NULL)
3752                 io->io_hdr.pool = pool_ref;
3753         return (io);
3754 }
3755
3756 union ctl_io *
3757 ctl_alloc_io_nowait(void *pool_ref)
3758 {
3759         union ctl_io *io;
3760 #ifdef IO_POOLS
3761         struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3762
3763         io = uma_zalloc(pool->zone, M_NOWAIT);
3764 #else
3765         io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3766 #endif
3767         if (io != NULL)
3768                 io->io_hdr.pool = pool_ref;
3769         return (io);
3770 }
3771
3772 void
3773 ctl_free_io(union ctl_io *io)
3774 {
3775 #ifdef IO_POOLS
3776         struct ctl_io_pool *pool;
3777 #endif
3778
3779         if (io == NULL)
3780                 return;
3781
3782 #ifdef IO_POOLS
3783         pool = (struct ctl_io_pool *)io->io_hdr.pool;
3784         uma_zfree(pool->zone, io);
3785 #else
3786         uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3787 #endif
3788 }
3789
3790 void
3791 ctl_zero_io(union ctl_io *io)
3792 {
3793         void *pool_ref;
3794
3795         if (io == NULL)
3796                 return;
3797
3798         /*
3799          * May need to preserve linked list pointers at some point too.
3800          */
3801         pool_ref = io->io_hdr.pool;
3802         memset(io, 0, sizeof(*io));
3803         io->io_hdr.pool = pool_ref;
3804 }
3805
3806 /*
3807  * This routine is currently used for internal copies of ctl_ios that need
3808  * to persist for some reason after we've already returned status to the
3809  * FETD.  (Thus the flag set.)
3810  *
3811  * XXX XXX
3812  * Note that this makes a blind copy of all fields in the ctl_io, except
3813  * for the pool reference.  This includes any memory that has been
3814  * allocated!  That memory will no longer be valid after done has been
3815  * called, so this would be VERY DANGEROUS for command that actually does
3816  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3817  * start and stop commands, which don't transfer any data, so this is not a
3818  * problem.  If it is used for anything else, the caller would also need to
3819  * allocate data buffer space and this routine would need to be modified to
3820  * copy the data buffer(s) as well.
3821  */
3822 void
3823 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3824 {
3825         void *pool_ref;
3826
3827         if ((src == NULL)
3828          || (dest == NULL))
3829                 return;
3830
3831         /*
3832          * May need to preserve linked list pointers at some point too.
3833          */
3834         pool_ref = dest->io_hdr.pool;
3835
3836         memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3837
3838         dest->io_hdr.pool = pool_ref;
3839         /*
3840          * We need to know that this is an internal copy, and doesn't need
3841          * to get passed back to the FETD that allocated it.
3842          */
3843         dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3844 }
3845
3846 static int
3847 ctl_expand_number(const char *buf, uint64_t *num)
3848 {
3849         char *endptr;
3850         uint64_t number;
3851         unsigned shift;
3852
3853         number = strtoq(buf, &endptr, 0);
3854
3855         switch (tolower((unsigned char)*endptr)) {
3856         case 'e':
3857                 shift = 60;
3858                 break;
3859         case 'p':
3860                 shift = 50;
3861                 break;
3862         case 't':
3863                 shift = 40;
3864                 break;
3865         case 'g':
3866                 shift = 30;
3867                 break;
3868         case 'm':
3869                 shift = 20;
3870                 break;
3871         case 'k':
3872                 shift = 10;
3873                 break;
3874         case 'b':
3875         case '\0': /* No unit. */
3876                 *num = number;
3877                 return (0);
3878         default:
3879                 /* Unrecognized unit. */
3880                 return (-1);
3881         }
3882
3883         if ((number << shift) >> shift != number) {
3884                 /* Overflow */
3885                 return (-1);
3886         }
3887         *num = number << shift;
3888         return (0);
3889 }
3890
3891
3892 /*
3893  * This routine could be used in the future to load default and/or saved
3894  * mode page parameters for a particuar lun.
3895  */
3896 static int
3897 ctl_init_page_index(struct ctl_lun *lun)
3898 {
3899         int i;
3900         struct ctl_page_index *page_index;
3901         const char *value;
3902         uint64_t ival;
3903
3904         memcpy(&lun->mode_pages.index, page_index_template,
3905                sizeof(page_index_template));
3906
3907         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3908
3909                 page_index = &lun->mode_pages.index[i];
3910                 /*
3911                  * If this is a disk-only mode page, there's no point in
3912                  * setting it up.  For some pages, we have to have some
3913                  * basic information about the disk in order to calculate the
3914                  * mode page data.
3915                  */
3916                 if ((lun->be_lun->lun_type != T_DIRECT)
3917                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3918                         continue;
3919
3920                 switch (page_index->page_code & SMPH_PC_MASK) {
3921                 case SMS_RW_ERROR_RECOVERY_PAGE: {
3922                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3923                                 panic("subpage is incorrect!");
3924                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3925                                &rw_er_page_default,
3926                                sizeof(rw_er_page_default));
3927                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3928                                &rw_er_page_changeable,
3929                                sizeof(rw_er_page_changeable));
3930                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3931                                &rw_er_page_default,
3932                                sizeof(rw_er_page_default));
3933                         memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3934                                &rw_er_page_default,
3935                                sizeof(rw_er_page_default));
3936                         page_index->page_data =
3937                                 (uint8_t *)lun->mode_pages.rw_er_page;
3938                         break;
3939                 }
3940                 case SMS_FORMAT_DEVICE_PAGE: {
3941                         struct scsi_format_page *format_page;
3942
3943                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3944                                 panic("subpage is incorrect!");
3945
3946                         /*
3947                          * Sectors per track are set above.  Bytes per
3948                          * sector need to be set here on a per-LUN basis.
3949                          */
3950                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3951                                &format_page_default,
3952                                sizeof(format_page_default));
3953                         memcpy(&lun->mode_pages.format_page[
3954                                CTL_PAGE_CHANGEABLE], &format_page_changeable,
3955                                sizeof(format_page_changeable));
3956                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3957                                &format_page_default,
3958                                sizeof(format_page_default));
3959                         memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3960                                &format_page_default,
3961                                sizeof(format_page_default));
3962
3963                         format_page = &lun->mode_pages.format_page[
3964                                 CTL_PAGE_CURRENT];
3965                         scsi_ulto2b(lun->be_lun->blocksize,
3966                                     format_page->bytes_per_sector);
3967
3968                         format_page = &lun->mode_pages.format_page[
3969                                 CTL_PAGE_DEFAULT];
3970                         scsi_ulto2b(lun->be_lun->blocksize,
3971                                     format_page->bytes_per_sector);
3972
3973                         format_page = &lun->mode_pages.format_page[
3974                                 CTL_PAGE_SAVED];
3975                         scsi_ulto2b(lun->be_lun->blocksize,
3976                                     format_page->bytes_per_sector);
3977
3978                         page_index->page_data =
3979                                 (uint8_t *)lun->mode_pages.format_page;
3980                         break;
3981                 }
3982                 case SMS_RIGID_DISK_PAGE: {
3983                         struct scsi_rigid_disk_page *rigid_disk_page;
3984                         uint32_t sectors_per_cylinder;
3985                         uint64_t cylinders;
3986 #ifndef __XSCALE__
3987                         int shift;
3988 #endif /* !__XSCALE__ */
3989
3990                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3991                                 panic("invalid subpage value %d",
3992                                       page_index->subpage);
3993
3994                         /*
3995                          * Rotation rate and sectors per track are set
3996                          * above.  We calculate the cylinders here based on
3997                          * capacity.  Due to the number of heads and
3998                          * sectors per track we're using, smaller arrays
3999                          * may turn out to have 0 cylinders.  Linux and
4000                          * FreeBSD don't pay attention to these mode pages
4001                          * to figure out capacity, but Solaris does.  It
4002                          * seems to deal with 0 cylinders just fine, and
4003                          * works out a fake geometry based on the capacity.
4004                          */
4005                         memcpy(&lun->mode_pages.rigid_disk_page[
4006                                CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4007                                sizeof(rigid_disk_page_default));
4008                         memcpy(&lun->mode_pages.rigid_disk_page[
4009                                CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4010                                sizeof(rigid_disk_page_changeable));
4011
4012                         sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4013                                 CTL_DEFAULT_HEADS;
4014
4015                         /*
4016                          * The divide method here will be more accurate,
4017                          * probably, but results in floating point being
4018                          * used in the kernel on i386 (__udivdi3()).  On the
4019                          * XScale, though, __udivdi3() is implemented in
4020                          * software.
4021                          *
4022                          * The shift method for cylinder calculation is
4023                          * accurate if sectors_per_cylinder is a power of
4024                          * 2.  Otherwise it might be slightly off -- you
4025                          * might have a bit of a truncation problem.
4026                          */
4027 #ifdef  __XSCALE__
4028                         cylinders = (lun->be_lun->maxlba + 1) /
4029                                 sectors_per_cylinder;
4030 #else
4031                         for (shift = 31; shift > 0; shift--) {
4032                                 if (sectors_per_cylinder & (1 << shift))
4033                                         break;
4034                         }
4035                         cylinders = (lun->be_lun->maxlba + 1) >> shift;
4036 #endif
4037
4038                         /*
4039                          * We've basically got 3 bytes, or 24 bits for the
4040                          * cylinder size in the mode page.  If we're over,
4041                          * just round down to 2^24.
4042                          */
4043                         if (cylinders > 0xffffff)
4044                                 cylinders = 0xffffff;
4045
4046                         rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4047                                 CTL_PAGE_DEFAULT];
4048                         scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4049
4050                         if ((value = ctl_get_opt(&lun->be_lun->options,
4051                             "rpm")) != NULL) {
4052                                 scsi_ulto2b(strtol(value, NULL, 0),
4053                                      rigid_disk_page->rotation_rate);
4054                         }
4055
4056                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4057                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4058                                sizeof(rigid_disk_page_default));
4059                         memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4060                                &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4061                                sizeof(rigid_disk_page_default));
4062
4063                         page_index->page_data =
4064                                 (uint8_t *)lun->mode_pages.rigid_disk_page;
4065                         break;
4066                 }
4067                 case SMS_CACHING_PAGE: {
4068                         struct scsi_caching_page *caching_page;
4069
4070                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4071                                 panic("invalid subpage value %d",
4072                                       page_index->subpage);
4073                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4074                                &caching_page_default,
4075                                sizeof(caching_page_default));
4076                         memcpy(&lun->mode_pages.caching_page[
4077                                CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4078                                sizeof(caching_page_changeable));
4079                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4080                                &caching_page_default,
4081                                sizeof(caching_page_default));
4082                         caching_page = &lun->mode_pages.caching_page[
4083                             CTL_PAGE_SAVED];
4084                         value = ctl_get_opt(&lun->be_lun->options, "writecache");
4085                         if (value != NULL && strcmp(value, "off") == 0)
4086                                 caching_page->flags1 &= ~SCP_WCE;
4087                         value = ctl_get_opt(&lun->be_lun->options, "readcache");
4088                         if (value != NULL && strcmp(value, "off") == 0)
4089                                 caching_page->flags1 |= SCP_RCD;
4090                         memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4091                                &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4092                                sizeof(caching_page_default));
4093                         page_index->page_data =
4094                                 (uint8_t *)lun->mode_pages.caching_page;
4095                         break;
4096                 }
4097                 case SMS_CONTROL_MODE_PAGE: {
4098                         struct scsi_control_page *control_page;
4099
4100                         if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4101                                 panic("invalid subpage value %d",
4102                                       page_index->subpage);
4103
4104                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4105                                &control_page_default,
4106                                sizeof(control_page_default));
4107                         memcpy(&lun->mode_pages.control_page[
4108                                CTL_PAGE_CHANGEABLE], &control_page_changeable,
4109                                sizeof(control_page_changeable));
4110                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4111                                &control_page_default,
4112                                sizeof(control_page_default));
4113                         control_page = &lun->mode_pages.control_page[
4114                             CTL_PAGE_SAVED];
4115                         value = ctl_get_opt(&lun->be_lun->options, "reordering");
4116                         if (value != NULL && strcmp(value, "unrestricted") == 0) {
4117                                 control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4118                                 control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4119                         }
4120                         memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4121                                &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4122                                sizeof(control_page_default));
4123                         page_index->page_data =
4124                                 (uint8_t *)lun->mode_pages.control_page;
4125                         break;
4126
4127                 }
4128                 case SMS_INFO_EXCEPTIONS_PAGE: {
4129                         switch (page_index->subpage) {
4130                         case SMS_SUBPAGE_PAGE_0:
4131                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4132                                        &ie_page_default,
4133                                        sizeof(ie_page_default));
4134                                 memcpy(&lun->mode_pages.ie_page[
4135                                        CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4136                                        sizeof(ie_page_changeable));
4137                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4138                                        &ie_page_default,
4139                                        sizeof(ie_page_default));
4140                                 memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4141                                        &ie_page_default,
4142                                        sizeof(ie_page_default));
4143                                 page_index->page_data =
4144                                         (uint8_t *)lun->mode_pages.ie_page;
4145                                 break;
4146                         case 0x02: {
4147                                 struct ctl_logical_block_provisioning_page *page;
4148
4149                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4150                                        &lbp_page_default,
4151                                        sizeof(lbp_page_default));
4152                                 memcpy(&lun->mode_pages.lbp_page[
4153                                        CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4154                                        sizeof(lbp_page_changeable));
4155                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4156                                        &lbp_page_default,
4157                                        sizeof(lbp_page_default));
4158                                 page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4159                                 value = ctl_get_opt(&lun->be_lun->options,
4160                                     "avail-threshold");
4161                                 if (value != NULL &&
4162                                     ctl_expand_number(value, &ival) == 0) {
4163                                         page->descr[0].flags |= SLBPPD_ENABLED |
4164                                             SLBPPD_ARMING_DEC;
4165                                         if (lun->be_lun->blocksize)
4166                                                 ival /= lun->be_lun->blocksize;
4167                                         else
4168                                                 ival /= 512;
4169                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4170                                             page->descr[0].count);
4171                                 }
4172                                 value = ctl_get_opt(&lun->be_lun->options,
4173                                     "used-threshold");
4174                                 if (value != NULL &&
4175                                     ctl_expand_number(value, &ival) == 0) {
4176                                         page->descr[1].flags |= SLBPPD_ENABLED |
4177                                             SLBPPD_ARMING_INC;
4178                                         if (lun->be_lun->blocksize)
4179                                                 ival /= lun->be_lun->blocksize;
4180                                         else
4181                                                 ival /= 512;
4182                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4183                                             page->descr[1].count);
4184                                 }
4185                                 value = ctl_get_opt(&lun->be_lun->options,
4186                                     "pool-avail-threshold");
4187                                 if (value != NULL &&
4188                                     ctl_expand_number(value, &ival) == 0) {
4189                                         page->descr[2].flags |= SLBPPD_ENABLED |
4190                                             SLBPPD_ARMING_DEC;
4191                                         if (lun->be_lun->blocksize)
4192                                                 ival /= lun->be_lun->blocksize;
4193                                         else
4194                                                 ival /= 512;
4195                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4196                                             page->descr[2].count);
4197                                 }
4198                                 value = ctl_get_opt(&lun->be_lun->options,
4199                                     "pool-used-threshold");
4200                                 if (value != NULL &&
4201                                     ctl_expand_number(value, &ival) == 0) {
4202                                         page->descr[3].flags |= SLBPPD_ENABLED |
4203                                             SLBPPD_ARMING_INC;
4204                                         if (lun->be_lun->blocksize)
4205                                                 ival /= lun->be_lun->blocksize;
4206                                         else
4207                                                 ival /= 512;
4208                                         scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4209                                             page->descr[3].count);
4210                                 }
4211                                 memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4212                                        &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4213                                        sizeof(lbp_page_default));
4214                                 page_index->page_data =
4215                                         (uint8_t *)lun->mode_pages.lbp_page;
4216                         }}
4217                         break;
4218                 }
4219                 case SMS_VENDOR_SPECIFIC_PAGE:{
4220                         switch (page_index->subpage) {
4221                         case DBGCNF_SUBPAGE_CODE: {
4222                                 struct copan_debugconf_subpage *current_page,
4223                                                                *saved_page;
4224
4225                                 memcpy(&lun->mode_pages.debugconf_subpage[
4226                                        CTL_PAGE_CURRENT],
4227                                        &debugconf_page_default,
4228                                        sizeof(debugconf_page_default));
4229                                 memcpy(&lun->mode_pages.debugconf_subpage[
4230                                        CTL_PAGE_CHANGEABLE],
4231                                        &debugconf_page_changeable,
4232                                        sizeof(debugconf_page_changeable));
4233                                 memcpy(&lun->mode_pages.debugconf_subpage[
4234                                        CTL_PAGE_DEFAULT],
4235                                        &debugconf_page_default,
4236                                        sizeof(debugconf_page_default));
4237                                 memcpy(&lun->mode_pages.debugconf_subpage[
4238                                        CTL_PAGE_SAVED],
4239                                        &debugconf_page_default,
4240                                        sizeof(debugconf_page_default));
4241                                 page_index->page_data =
4242                                         (uint8_t *)lun->mode_pages.debugconf_subpage;
4243
4244                                 current_page = (struct copan_debugconf_subpage *)
4245                                         (page_index->page_data +
4246                                          (page_index->page_len *
4247                                           CTL_PAGE_CURRENT));
4248                                 saved_page = (struct copan_debugconf_subpage *)
4249                                         (page_index->page_data +
4250                                          (page_index->page_len *
4251                                           CTL_PAGE_SAVED));
4252                                 break;
4253                         }
4254                         default:
4255                                 panic("invalid subpage value %d",
4256                                       page_index->subpage);
4257                                 break;
4258                         }
4259                         break;
4260                 }
4261                 default:
4262                         panic("invalid page value %d",
4263                               page_index->page_code & SMPH_PC_MASK);
4264                         break;
4265         }
4266         }
4267
4268         return (CTL_RETVAL_COMPLETE);
4269 }
4270
4271 static int
4272 ctl_init_log_page_index(struct ctl_lun *lun)
4273 {
4274         struct ctl_page_index *page_index;
4275         int i, j, k, prev;
4276
4277         memcpy(&lun->log_pages.index, log_page_index_template,
4278                sizeof(log_page_index_template));
4279
4280         prev = -1;
4281         for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4282
4283                 page_index = &lun->log_pages.index[i];
4284                 /*
4285                  * If this is a disk-only mode page, there's no point in
4286                  * setting it up.  For some pages, we have to have some
4287                  * basic information about the disk in order to calculate the
4288                  * mode page data.
4289                  */
4290                 if ((lun->be_lun->lun_type != T_DIRECT)
4291                  && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4292                         continue;
4293
4294                 if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4295                     ((lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) == 0 ||
4296                      lun->backend->lun_attr == NULL))
4297                         continue;
4298
4299                 if (page_index->page_code != prev) {
4300                         lun->log_pages.pages_page[j] = page_index->page_code;
4301                         prev = page_index->page_code;
4302                         j++;
4303                 }
4304                 lun->log_pages.subpages_page[k*2] = page_index->page_code;
4305                 lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4306                 k++;
4307         }
4308         lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4309         lun->log_pages.index[0].page_len = j;
4310         lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4311         lun->log_pages.index[1].page_len = k * 2;
4312         lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4313         lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4314
4315         return (CTL_RETVAL_COMPLETE);
4316 }
4317
4318 static int
4319 hex2bin(const char *str, uint8_t *buf, int buf_size)
4320 {
4321         int i;
4322         u_char c;
4323
4324         memset(buf, 0, buf_size);
4325         while (isspace(str[0]))
4326                 str++;
4327         if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4328                 str += 2;
4329         buf_size *= 2;
4330         for (i = 0; str[i] != 0 && i < buf_size; i++) {
4331                 c = str[i];
4332                 if (isdigit(c))
4333                         c -= '0';
4334                 else if (isalpha(c))
4335                         c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4336                 else
4337                         break;
4338                 if (c >= 16)
4339                         break;
4340                 if ((i & 1) == 0)
4341                         buf[i / 2] |= (c << 4);
4342                 else
4343                         buf[i / 2] |= c;
4344         }
4345         return ((i + 1) / 2);
4346 }
4347
4348 /*
4349  * LUN allocation.
4350  *
4351  * Requirements:
4352  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4353  *   wants us to allocate the LUN and he can block.
4354  * - ctl_softc is always set
4355  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4356  *
4357  * Returns 0 for success, non-zero (errno) for failure.
4358  */
4359 static int
4360 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4361               struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4362 {
4363         struct ctl_lun *nlun, *lun;
4364         struct ctl_port *port;
4365         struct scsi_vpd_id_descriptor *desc;
4366         struct scsi_vpd_id_t10 *t10id;
4367         const char *eui, *naa, *scsiname, *vendor, *value;
4368         int lun_number, i, lun_malloced;
4369         int devidlen, idlen1, idlen2 = 0, len;
4370
4371         if (be_lun == NULL)
4372                 return (EINVAL);
4373
4374         /*
4375          * We currently only support Direct Access or Processor LUN types.
4376          */
4377         switch (be_lun->lun_type) {
4378         case T_DIRECT:
4379                 break;
4380         case T_PROCESSOR:
4381                 break;
4382         case T_SEQUENTIAL:
4383         case T_CHANGER:
4384         default:
4385                 be_lun->lun_config_status(be_lun->be_lun,
4386                                           CTL_LUN_CONFIG_FAILURE);
4387                 break;
4388         }
4389         if (ctl_lun == NULL) {
4390                 lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4391                 lun_malloced = 1;
4392         } else {
4393                 lun_malloced = 0;
4394                 lun = ctl_lun;
4395         }
4396
4397         memset(lun, 0, sizeof(*lun));
4398         if (lun_malloced)
4399                 lun->flags = CTL_LUN_MALLOCED;
4400
4401         /* Generate LUN ID. */
4402         devidlen = max(CTL_DEVID_MIN_LEN,
4403             strnlen(be_lun->device_id, CTL_DEVID_LEN));
4404         idlen1 = sizeof(*t10id) + devidlen;
4405         len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4406         scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4407         if (scsiname != NULL) {
4408                 idlen2 = roundup2(strlen(scsiname) + 1, 4);
4409                 len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4410         }
4411         eui = ctl_get_opt(&be_lun->options, "eui");
4412         if (eui != NULL) {
4413                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4414         }
4415         naa = ctl_get_opt(&be_lun->options, "naa");
4416         if (naa != NULL) {
4417                 len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4418         }
4419         lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4420             M_CTL, M_WAITOK | M_ZERO);
4421         desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4422         desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4423         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4424         desc->length = idlen1;
4425         t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4426         memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4427         if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4428                 strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4429         } else {
4430                 strncpy(t10id->vendor, vendor,
4431                     min(sizeof(t10id->vendor), strlen(vendor)));
4432         }
4433         strncpy((char *)t10id->vendor_spec_id,
4434             (char *)be_lun->device_id, devidlen);
4435         if (scsiname != NULL) {
4436                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4437                     desc->length);
4438                 desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4439                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4440                     SVPD_ID_TYPE_SCSI_NAME;
4441                 desc->length = idlen2;
4442                 strlcpy(desc->identifier, scsiname, idlen2);
4443         }
4444         if (eui != NULL) {
4445                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4446                     desc->length);
4447                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4448                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4449                     SVPD_ID_TYPE_EUI64;
4450                 desc->length = hex2bin(eui, desc->identifier, 16);
4451                 desc->length = desc->length > 12 ? 16 :
4452                     (desc->length > 8 ? 12 : 8);
4453                 len -= 16 - desc->length;
4454         }
4455         if (naa != NULL) {
4456                 desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4457                     desc->length);
4458                 desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4459                 desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4460                     SVPD_ID_TYPE_NAA;
4461                 desc->length = hex2bin(naa, desc->identifier, 16);
4462                 desc->length = desc->length > 8 ? 16 : 8;
4463                 len -= 16 - desc->length;
4464         }
4465         lun->lun_devid->len = len;
4466
4467         mtx_lock(&ctl_softc->ctl_lock);
4468         /*
4469          * See if the caller requested a particular LUN number.  If so, see
4470          * if it is available.  Otherwise, allocate the first available LUN.
4471          */
4472         if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4473                 if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4474                  || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4475                         mtx_unlock(&ctl_softc->ctl_lock);
4476                         if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4477                                 printf("ctl: requested LUN ID %d is higher "
4478                                        "than CTL_MAX_LUNS - 1 (%d)\n",
4479                                        be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4480                         } else {
4481                                 /*
4482                                  * XXX KDM return an error, or just assign
4483                                  * another LUN ID in this case??
4484                                  */
4485                                 printf("ctl: requested LUN ID %d is already "
4486                                        "in use\n", be_lun->req_lun_id);
4487                         }
4488                         if (lun->flags & CTL_LUN_MALLOCED)
4489                                 free(lun, M_CTL);
4490                         be_lun->lun_config_status(be_lun->be_lun,
4491                                                   CTL_LUN_CONFIG_FAILURE);
4492                         return (ENOSPC);
4493                 }
4494                 lun_number = be_lun->req_lun_id;
4495         } else {
4496                 lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4497                 if (lun_number == -1) {
4498                         mtx_unlock(&ctl_softc->ctl_lock);
4499                         printf("ctl: can't allocate LUN on target %ju, out of "
4500                                "LUNs\n", (uintmax_t)target_id.id);
4501                         if (lun->flags & CTL_LUN_MALLOCED)
4502                                 free(lun, M_CTL);
4503                         be_lun->lun_config_status(be_lun->be_lun,
4504                                                   CTL_LUN_CONFIG_FAILURE);
4505                         return (ENOSPC);
4506                 }
4507         }
4508         ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4509
4510         mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4511         lun->target = target_id;
4512         lun->lun = lun_number;
4513         lun->be_lun = be_lun;
4514         /*
4515          * The processor LUN is always enabled.  Disk LUNs come on line
4516          * disabled, and must be enabled by the backend.
4517          */
4518         lun->flags |= CTL_LUN_DISABLED;
4519         lun->backend = be_lun->be;
4520         be_lun->ctl_lun = lun;
4521         be_lun->lun_id = lun_number;
4522         atomic_add_int(&be_lun->be->num_luns, 1);
4523         if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4524                 lun->flags |= CTL_LUN_OFFLINE;
4525
4526         if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4527                 lun->flags |= CTL_LUN_STOPPED;
4528
4529         if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4530                 lun->flags |= CTL_LUN_INOPERABLE;
4531
4532         if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4533                 lun->flags |= CTL_LUN_PRIMARY_SC;
4534
4535         value = ctl_get_opt(&be_lun->options, "readonly");
4536         if (value != NULL && strcmp(value, "on") == 0)
4537                 lun->flags |= CTL_LUN_READONLY;
4538
4539         lun->ctl_softc = ctl_softc;
4540         TAILQ_INIT(&lun->ooa_queue);
4541         TAILQ_INIT(&lun->blocked_queue);
4542         STAILQ_INIT(&lun->error_list);
4543         ctl_tpc_lun_init(lun);
4544
4545         /*
4546          * Initialize the mode and log page index.
4547          */
4548         ctl_init_page_index(lun);
4549         ctl_init_log_page_index(lun);
4550
4551         /*
4552          * Set the poweron UA for all initiators on this LUN only.
4553          */
4554         for (i = 0; i < CTL_MAX_INITIATORS; i++)
4555                 lun->pending_ua[i] = CTL_UA_POWERON;
4556
4557         /*
4558          * Now, before we insert this lun on the lun list, set the lun
4559          * inventory changed UA for all other luns.
4560          */
4561         STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4562                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4563                         nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4564                 }
4565         }
4566
4567         STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4568
4569         ctl_softc->ctl_luns[lun_number] = lun;
4570
4571         ctl_softc->num_luns++;
4572
4573         /* Setup statistics gathering */
4574         lun->stats.device_type = be_lun->lun_type;
4575         lun->stats.lun_number = lun_number;
4576         if (lun->stats.device_type == T_DIRECT)
4577                 lun->stats.blocksize = be_lun->blocksize;
4578         else
4579                 lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4580         for (i = 0;i < CTL_MAX_PORTS;i++)
4581                 lun->stats.ports[i].targ_port = i;
4582
4583         mtx_unlock(&ctl_softc->ctl_lock);
4584
4585         lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4586
4587         /*
4588          * Run through each registered FETD and bring it online if it isn't
4589          * already.  Enable the target ID if it hasn't been enabled, and
4590          * enable this particular LUN.
4591          */
4592         STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4593                 int retval;
4594
4595                 retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4596                 if (retval != 0) {
4597                         printf("ctl_alloc_lun: FETD %s port %d returned error "
4598                                "%d for lun_enable on target %ju lun %d\n",
4599                                port->port_name, port->targ_port, retval,
4600                                (uintmax_t)target_id.id, lun_number);
4601                 } else
4602                         port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4603         }
4604         return (0);
4605 }
4606
4607 /*
4608  * Delete a LUN.
4609  * Assumptions:
4610  * - LUN has already been marked invalid and any pending I/O has been taken
4611  *   care of.
4612  */
4613 static int
4614 ctl_free_lun(struct ctl_lun *lun)
4615 {
4616         struct ctl_softc *softc;
4617 #if 0
4618         struct ctl_port *port;
4619 #endif
4620         struct ctl_lun *nlun;
4621         int i;
4622
4623         softc = lun->ctl_softc;
4624
4625         mtx_assert(&softc->ctl_lock, MA_OWNED);
4626
4627         STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4628
4629         ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4630
4631         softc->ctl_luns[lun->lun] = NULL;
4632
4633         if (!TAILQ_EMPTY(&lun->ooa_queue))
4634                 panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4635
4636         softc->num_luns--;
4637
4638         /*
4639          * XXX KDM this scheme only works for a single target/multiple LUN
4640          * setup.  It needs to be revamped for a multiple target scheme.
4641          *
4642          * XXX KDM this results in port->lun_disable() getting called twice,
4643          * once when ctl_disable_lun() is called, and a second time here.
4644          * We really need to re-think the LUN disable semantics.  There
4645          * should probably be several steps/levels to LUN removal:
4646          *  - disable
4647          *  - invalidate
4648          *  - free
4649          *
4650          * Right now we only have a disable method when communicating to
4651          * the front end ports, at least for individual LUNs.
4652          */
4653 #if 0
4654         STAILQ_FOREACH(port, &softc->port_list, links) {
4655                 int retval;
4656
4657                 retval = port->lun_disable(port->targ_lun_arg, lun->target,
4658                                          lun->lun);
4659                 if (retval != 0) {
4660                         printf("ctl_free_lun: FETD %s port %d returned error "
4661                                "%d for lun_disable on target %ju lun %jd\n",
4662                                port->port_name, port->targ_port, retval,
4663                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4664                 }
4665
4666                 if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4667                         port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4668
4669                         retval = port->targ_disable(port->targ_lun_arg,lun->target);
4670                         if (retval != 0) {
4671                                 printf("ctl_free_lun: FETD %s port %d "
4672                                        "returned error %d for targ_disable on "
4673                                        "target %ju\n", port->port_name,
4674                                        port->targ_port, retval,
4675                                        (uintmax_t)lun->target.id);
4676                         } else
4677                                 port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4678
4679                         if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4680                                 continue;
4681
4682 #if 0
4683                         port->port_offline(port->onoff_arg);
4684                         port->status &= ~CTL_PORT_STATUS_ONLINE;
4685 #endif
4686                 }
4687         }
4688 #endif
4689
4690         /*
4691          * Tell the backend to free resources, if this LUN has a backend.
4692          */
4693         atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4694         lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4695
4696         ctl_tpc_lun_shutdown(lun);
4697         mtx_destroy(&lun->lun_lock);
4698         free(lun->lun_devid, M_CTL);
4699         for (i = 0; i < 2 * CTL_MAX_PORTS; i++) {
4700                 if (lun->pr_keys[i] != NULL)
4701                         free(lun->pr_keys[i], M_CTL);
4702         }
4703         free(lun->write_buffer, M_CTL);
4704         if (lun->flags & CTL_LUN_MALLOCED)
4705                 free(lun, M_CTL);
4706
4707         STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4708                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4709                         nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4710                 }
4711         }
4712
4713         return (0);
4714 }
4715
4716 static void
4717 ctl_create_lun(struct ctl_be_lun *be_lun)
4718 {
4719         struct ctl_softc *ctl_softc;
4720
4721         ctl_softc = control_softc;
4722
4723         /*
4724          * ctl_alloc_lun() should handle all potential failure cases.
4725          */
4726         ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4727 }
4728
4729 int
4730 ctl_add_lun(struct ctl_be_lun *be_lun)
4731 {
4732         struct ctl_softc *ctl_softc = control_softc;
4733
4734         mtx_lock(&ctl_softc->ctl_lock);
4735         STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4736         mtx_unlock(&ctl_softc->ctl_lock);
4737         wakeup(&ctl_softc->pending_lun_queue);
4738
4739         return (0);
4740 }
4741
4742 int
4743 ctl_enable_lun(struct ctl_be_lun *be_lun)
4744 {
4745         struct ctl_softc *ctl_softc;
4746         struct ctl_port *port, *nport;
4747         struct ctl_lun *lun;
4748         int retval;
4749
4750         ctl_softc = control_softc;
4751
4752         lun = (struct ctl_lun *)be_lun->ctl_lun;
4753
4754         mtx_lock(&ctl_softc->ctl_lock);
4755         mtx_lock(&lun->lun_lock);
4756         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4757                 /*
4758                  * eh?  Why did we get called if the LUN is already
4759                  * enabled?
4760                  */
4761                 mtx_unlock(&lun->lun_lock);
4762                 mtx_unlock(&ctl_softc->ctl_lock);
4763                 return (0);
4764         }
4765         lun->flags &= ~CTL_LUN_DISABLED;
4766         mtx_unlock(&lun->lun_lock);
4767
4768         for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4769                 nport = STAILQ_NEXT(port, links);
4770
4771                 /*
4772                  * Drop the lock while we call the FETD's enable routine.
4773                  * This can lead to a callback into CTL (at least in the
4774                  * case of the internal initiator frontend.
4775                  */
4776                 mtx_unlock(&ctl_softc->ctl_lock);
4777                 retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4778                 mtx_lock(&ctl_softc->ctl_lock);
4779                 if (retval != 0) {
4780                         printf("%s: FETD %s port %d returned error "
4781                                "%d for lun_enable on target %ju lun %jd\n",
4782                                __func__, port->port_name, port->targ_port, retval,
4783                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4784                 }
4785 #if 0
4786                  else {
4787             /* NOTE:  TODO:  why does lun enable affect port status? */
4788                         port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4789                 }
4790 #endif
4791         }
4792
4793         mtx_unlock(&ctl_softc->ctl_lock);
4794
4795         return (0);
4796 }
4797
4798 int
4799 ctl_disable_lun(struct ctl_be_lun *be_lun)
4800 {
4801         struct ctl_softc *ctl_softc;
4802         struct ctl_port *port;
4803         struct ctl_lun *lun;
4804         int retval;
4805
4806         ctl_softc = control_softc;
4807
4808         lun = (struct ctl_lun *)be_lun->ctl_lun;
4809
4810         mtx_lock(&ctl_softc->ctl_lock);
4811         mtx_lock(&lun->lun_lock);
4812         if (lun->flags & CTL_LUN_DISABLED) {
4813                 mtx_unlock(&lun->lun_lock);
4814                 mtx_unlock(&ctl_softc->ctl_lock);
4815                 return (0);
4816         }
4817         lun->flags |= CTL_LUN_DISABLED;
4818         mtx_unlock(&lun->lun_lock);
4819
4820         STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4821                 mtx_unlock(&ctl_softc->ctl_lock);
4822                 /*
4823                  * Drop the lock before we call the frontend's disable
4824                  * routine, to avoid lock order reversals.
4825                  *
4826                  * XXX KDM what happens if the frontend list changes while
4827                  * we're traversing it?  It's unlikely, but should be handled.
4828                  */
4829                 retval = port->lun_disable(port->targ_lun_arg, lun->target,
4830                                          lun->lun);
4831                 mtx_lock(&ctl_softc->ctl_lock);
4832                 if (retval != 0) {
4833                         printf("ctl_alloc_lun: FETD %s port %d returned error "
4834                                "%d for lun_disable on target %ju lun %jd\n",
4835                                port->port_name, port->targ_port, retval,
4836                                (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4837                 }
4838         }
4839
4840         mtx_unlock(&ctl_softc->ctl_lock);
4841
4842         return (0);
4843 }
4844
4845 int
4846 ctl_start_lun(struct ctl_be_lun *be_lun)
4847 {
4848         struct ctl_softc *ctl_softc;
4849         struct ctl_lun *lun;
4850
4851         ctl_softc = control_softc;
4852
4853         lun = (struct ctl_lun *)be_lun->ctl_lun;
4854
4855         mtx_lock(&lun->lun_lock);
4856         lun->flags &= ~CTL_LUN_STOPPED;
4857         mtx_unlock(&lun->lun_lock);
4858
4859         return (0);
4860 }
4861
4862 int
4863 ctl_stop_lun(struct ctl_be_lun *be_lun)
4864 {
4865         struct ctl_softc *ctl_softc;
4866         struct ctl_lun *lun;
4867
4868         ctl_softc = control_softc;
4869
4870         lun = (struct ctl_lun *)be_lun->ctl_lun;
4871
4872         mtx_lock(&lun->lun_lock);
4873         lun->flags |= CTL_LUN_STOPPED;
4874         mtx_unlock(&lun->lun_lock);
4875
4876         return (0);
4877 }
4878
4879 int
4880 ctl_lun_offline(struct ctl_be_lun *be_lun)
4881 {
4882         struct ctl_softc *ctl_softc;
4883         struct ctl_lun *lun;
4884
4885         ctl_softc = control_softc;
4886
4887         lun = (struct ctl_lun *)be_lun->ctl_lun;
4888
4889         mtx_lock(&lun->lun_lock);
4890         lun->flags |= CTL_LUN_OFFLINE;
4891         mtx_unlock(&lun->lun_lock);
4892
4893         return (0);
4894 }
4895
4896 int
4897 ctl_lun_online(struct ctl_be_lun *be_lun)
4898 {
4899         struct ctl_softc *ctl_softc;
4900         struct ctl_lun *lun;
4901
4902         ctl_softc = control_softc;
4903
4904         lun = (struct ctl_lun *)be_lun->ctl_lun;
4905
4906         mtx_lock(&lun->lun_lock);
4907         lun->flags &= ~CTL_LUN_OFFLINE;
4908         mtx_unlock(&lun->lun_lock);
4909
4910         return (0);
4911 }
4912
4913 int
4914 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4915 {
4916         struct ctl_softc *ctl_softc;
4917         struct ctl_lun *lun;
4918
4919         ctl_softc = control_softc;
4920
4921         lun = (struct ctl_lun *)be_lun->ctl_lun;
4922
4923         mtx_lock(&lun->lun_lock);
4924
4925         /*
4926          * The LUN needs to be disabled before it can be marked invalid.
4927          */
4928         if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4929                 mtx_unlock(&lun->lun_lock);
4930                 return (-1);
4931         }
4932         /*
4933          * Mark the LUN invalid.
4934          */
4935         lun->flags |= CTL_LUN_INVALID;
4936
4937         /*
4938          * If there is nothing in the OOA queue, go ahead and free the LUN.
4939          * If we have something in the OOA queue, we'll free it when the
4940          * last I/O completes.
4941          */
4942         if (TAILQ_EMPTY(&lun->ooa_queue)) {
4943                 mtx_unlock(&lun->lun_lock);
4944                 mtx_lock(&ctl_softc->ctl_lock);
4945                 ctl_free_lun(lun);
4946                 mtx_unlock(&ctl_softc->ctl_lock);
4947         } else
4948                 mtx_unlock(&lun->lun_lock);
4949
4950         return (0);
4951 }
4952
4953 int
4954 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4955 {
4956         struct ctl_softc *ctl_softc;
4957         struct ctl_lun *lun;
4958
4959         ctl_softc = control_softc;
4960         lun = (struct ctl_lun *)be_lun->ctl_lun;
4961
4962         mtx_lock(&lun->lun_lock);
4963         lun->flags |= CTL_LUN_INOPERABLE;
4964         mtx_unlock(&lun->lun_lock);
4965
4966         return (0);
4967 }
4968
4969 int
4970 ctl_lun_operable(struct ctl_be_lun *be_lun)
4971 {
4972         struct ctl_softc *ctl_softc;
4973         struct ctl_lun *lun;
4974
4975         ctl_softc = control_softc;
4976         lun = (struct ctl_lun *)be_lun->ctl_lun;
4977
4978         mtx_lock(&lun->lun_lock);
4979         lun->flags &= ~CTL_LUN_INOPERABLE;
4980         mtx_unlock(&lun->lun_lock);
4981
4982         return (0);
4983 }
4984
4985 void
4986 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4987 {
4988         struct ctl_lun *lun;
4989         struct ctl_softc *softc;
4990         int i;
4991
4992         softc = control_softc;
4993
4994         lun = (struct ctl_lun *)be_lun->ctl_lun;
4995
4996         mtx_lock(&lun->lun_lock);
4997
4998         for (i = 0; i < CTL_MAX_INITIATORS; i++) 
4999                 lun->pending_ua[i] |= CTL_UA_CAPACITY_CHANGED;
5000
5001         mtx_unlock(&lun->lun_lock);
5002 }
5003
5004 /*
5005  * Backend "memory move is complete" callback for requests that never
5006  * make it down to say RAIDCore's configuration code.
5007  */
5008 int
5009 ctl_config_move_done(union ctl_io *io)
5010 {
5011         int retval;
5012
5013         CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5014         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5015             ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5016
5017         if ((io->io_hdr.port_status != 0) &&
5018             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5019              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5020                 /*
5021                  * For hardware error sense keys, the sense key
5022                  * specific value is defined to be a retry count,
5023                  * but we use it to pass back an internal FETD
5024                  * error code.  XXX KDM  Hopefully the FETD is only
5025                  * using 16 bits for an error code, since that's
5026                  * all the space we have in the sks field.
5027                  */
5028                 ctl_set_internal_failure(&io->scsiio,
5029                                          /*sks_valid*/ 1,
5030                                          /*retry_count*/
5031                                          io->io_hdr.port_status);
5032         }
5033
5034         if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5035             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5036              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5037             ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5038                 /*
5039                  * XXX KDM just assuming a single pointer here, and not a
5040                  * S/G list.  If we start using S/G lists for config data,
5041                  * we'll need to know how to clean them up here as well.
5042                  */
5043                 if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5044                         free(io->scsiio.kern_data_ptr, M_CTL);
5045                 ctl_done(io);
5046                 retval = CTL_RETVAL_COMPLETE;
5047         } else {
5048                 /*
5049                  * XXX KDM now we need to continue data movement.  Some
5050                  * options:
5051                  * - call ctl_scsiio() again?  We don't do this for data
5052                  *   writes, because for those at least we know ahead of
5053                  *   time where the write will go and how long it is.  For
5054                  *   config writes, though, that information is largely
5055                  *   contained within the write itself, thus we need to
5056                  *   parse out the data again.
5057                  *
5058                  * - Call some other function once the data is in?
5059                  */
5060                 if (ctl_debug & CTL_DEBUG_CDB_DATA)
5061                         ctl_data_print(io);
5062
5063                 /*
5064                  * XXX KDM call ctl_scsiio() again for now, and check flag
5065                  * bits to see whether we're allocated or not.
5066                  */
5067                 retval = ctl_scsiio(&io->scsiio);
5068         }
5069         return (retval);
5070 }
5071
5072 /*
5073  * This gets called by a backend driver when it is done with a
5074  * data_submit method.
5075  */
5076 void
5077 ctl_data_submit_done(union ctl_io *io)
5078 {
5079         /*
5080          * If the IO_CONT flag is set, we need to call the supplied
5081          * function to continue processing the I/O, instead of completing
5082          * the I/O just yet.
5083          *
5084          * If there is an error, though, we don't want to keep processing.
5085          * Instead, just send status back to the initiator.
5086          */
5087         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5088             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5089             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5090              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5091                 io->scsiio.io_cont(io);
5092                 return;
5093         }
5094         ctl_done(io);
5095 }
5096
5097 /*
5098  * This gets called by a backend driver when it is done with a
5099  * configuration write.
5100  */
5101 void
5102 ctl_config_write_done(union ctl_io *io)
5103 {
5104         uint8_t *buf;
5105
5106         /*
5107          * If the IO_CONT flag is set, we need to call the supplied
5108          * function to continue processing the I/O, instead of completing
5109          * the I/O just yet.
5110          *
5111          * If there is an error, though, we don't want to keep processing.
5112          * Instead, just send status back to the initiator.
5113          */
5114         if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5115             (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5116             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5117              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5118                 io->scsiio.io_cont(io);
5119                 return;
5120         }
5121         /*
5122          * Since a configuration write can be done for commands that actually
5123          * have data allocated, like write buffer, and commands that have
5124          * no data, like start/stop unit, we need to check here.
5125          */
5126         if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5127                 buf = io->scsiio.kern_data_ptr;
5128         else
5129                 buf = NULL;
5130         ctl_done(io);
5131         if (buf)
5132                 free(buf, M_CTL);
5133 }
5134
5135 /*
5136  * SCSI release command.
5137  */
5138 int
5139 ctl_scsi_release(struct ctl_scsiio *ctsio)
5140 {
5141         int length, longid, thirdparty_id, resv_id;
5142         struct ctl_softc *ctl_softc;
5143         struct ctl_lun *lun;
5144         uint32_t residx;
5145
5146         length = 0;
5147         resv_id = 0;
5148
5149         CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5150
5151         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5152         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5153         ctl_softc = control_softc;
5154
5155         switch (ctsio->cdb[0]) {
5156         case RELEASE_10: {
5157                 struct scsi_release_10 *cdb;
5158
5159                 cdb = (struct scsi_release_10 *)ctsio->cdb;
5160
5161                 if (cdb->byte2 & SR10_LONGID)
5162                         longid = 1;
5163                 else
5164                         thirdparty_id = cdb->thirdparty_id;
5165
5166                 resv_id = cdb->resv_id;
5167                 length = scsi_2btoul(cdb->length);
5168                 break;
5169         }
5170         }
5171
5172
5173         /*
5174          * XXX KDM right now, we only support LUN reservation.  We don't
5175          * support 3rd party reservations, or extent reservations, which
5176          * might actually need the parameter list.  If we've gotten this
5177          * far, we've got a LUN reservation.  Anything else got kicked out
5178          * above.  So, according to SPC, ignore the length.
5179          */
5180         length = 0;
5181
5182         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5183          && (length > 0)) {
5184                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5185                 ctsio->kern_data_len = length;
5186                 ctsio->kern_total_len = length;
5187                 ctsio->kern_data_resid = 0;
5188                 ctsio->kern_rel_offset = 0;
5189                 ctsio->kern_sg_entries = 0;
5190                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5191                 ctsio->be_move_done = ctl_config_move_done;
5192                 ctl_datamove((union ctl_io *)ctsio);
5193
5194                 return (CTL_RETVAL_COMPLETE);
5195         }
5196
5197         if (length > 0)
5198                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5199
5200         mtx_lock(&lun->lun_lock);
5201
5202         /*
5203          * According to SPC, it is not an error for an intiator to attempt
5204          * to release a reservation on a LUN that isn't reserved, or that
5205          * is reserved by another initiator.  The reservation can only be
5206          * released, though, by the initiator who made it or by one of
5207          * several reset type events.
5208          */
5209         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5210                         lun->flags &= ~CTL_LUN_RESERVED;
5211
5212         mtx_unlock(&lun->lun_lock);
5213
5214         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5215                 free(ctsio->kern_data_ptr, M_CTL);
5216                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5217         }
5218
5219         ctl_set_success(ctsio);
5220         ctl_done((union ctl_io *)ctsio);
5221         return (CTL_RETVAL_COMPLETE);
5222 }
5223
5224 int
5225 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5226 {
5227         int extent, thirdparty, longid;
5228         int resv_id, length;
5229         uint64_t thirdparty_id;
5230         struct ctl_softc *ctl_softc;
5231         struct ctl_lun *lun;
5232         uint32_t residx;
5233
5234         extent = 0;
5235         thirdparty = 0;
5236         longid = 0;
5237         resv_id = 0;
5238         length = 0;
5239         thirdparty_id = 0;
5240
5241         CTL_DEBUG_PRINT(("ctl_reserve\n"));
5242
5243         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5244         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5245         ctl_softc = control_softc;
5246
5247         switch (ctsio->cdb[0]) {
5248         case RESERVE_10: {
5249                 struct scsi_reserve_10 *cdb;
5250
5251                 cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5252
5253                 if (cdb->byte2 & SR10_LONGID)
5254                         longid = 1;
5255                 else
5256                         thirdparty_id = cdb->thirdparty_id;
5257
5258                 resv_id = cdb->resv_id;
5259                 length = scsi_2btoul(cdb->length);
5260                 break;
5261         }
5262         }
5263
5264         /*
5265          * XXX KDM right now, we only support LUN reservation.  We don't
5266          * support 3rd party reservations, or extent reservations, which
5267          * might actually need the parameter list.  If we've gotten this
5268          * far, we've got a LUN reservation.  Anything else got kicked out
5269          * above.  So, according to SPC, ignore the length.
5270          */
5271         length = 0;
5272
5273         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5274          && (length > 0)) {
5275                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5276                 ctsio->kern_data_len = length;
5277                 ctsio->kern_total_len = length;
5278                 ctsio->kern_data_resid = 0;
5279                 ctsio->kern_rel_offset = 0;
5280                 ctsio->kern_sg_entries = 0;
5281                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5282                 ctsio->be_move_done = ctl_config_move_done;
5283                 ctl_datamove((union ctl_io *)ctsio);
5284
5285                 return (CTL_RETVAL_COMPLETE);
5286         }
5287
5288         if (length > 0)
5289                 thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5290
5291         mtx_lock(&lun->lun_lock);
5292         if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5293                 ctl_set_reservation_conflict(ctsio);
5294                 goto bailout;
5295         }
5296
5297         lun->flags |= CTL_LUN_RESERVED;
5298         lun->res_idx = residx;
5299
5300         ctl_set_success(ctsio);
5301
5302 bailout:
5303         mtx_unlock(&lun->lun_lock);
5304
5305         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5306                 free(ctsio->kern_data_ptr, M_CTL);
5307                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5308         }
5309
5310         ctl_done((union ctl_io *)ctsio);
5311         return (CTL_RETVAL_COMPLETE);
5312 }
5313
5314 int
5315 ctl_start_stop(struct ctl_scsiio *ctsio)
5316 {
5317         struct scsi_start_stop_unit *cdb;
5318         struct ctl_lun *lun;
5319         struct ctl_softc *ctl_softc;
5320         int retval;
5321
5322         CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5323
5324         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5325         ctl_softc = control_softc;
5326         retval = 0;
5327
5328         cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5329
5330         /*
5331          * XXX KDM
5332          * We don't support the immediate bit on a stop unit.  In order to
5333          * do that, we would need to code up a way to know that a stop is
5334          * pending, and hold off any new commands until it completes, one
5335          * way or another.  Then we could accept or reject those commands
5336          * depending on its status.  We would almost need to do the reverse
5337          * of what we do below for an immediate start -- return the copy of
5338          * the ctl_io to the FETD with status to send to the host (and to
5339          * free the copy!) and then free the original I/O once the stop
5340          * actually completes.  That way, the OOA queue mechanism can work
5341          * to block commands that shouldn't proceed.  Another alternative
5342          * would be to put the copy in the queue in place of the original,
5343          * and return the original back to the caller.  That could be
5344          * slightly safer..
5345          */
5346         if ((cdb->byte2 & SSS_IMMED)
5347          && ((cdb->how & SSS_START) == 0)) {
5348                 ctl_set_invalid_field(ctsio,
5349                                       /*sks_valid*/ 1,
5350                                       /*command*/ 1,
5351                                       /*field*/ 1,
5352                                       /*bit_valid*/ 1,
5353                                       /*bit*/ 0);
5354                 ctl_done((union ctl_io *)ctsio);
5355                 return (CTL_RETVAL_COMPLETE);
5356         }
5357
5358         if ((lun->flags & CTL_LUN_PR_RESERVED)
5359          && ((cdb->how & SSS_START)==0)) {
5360                 uint32_t residx;
5361
5362                 residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5363                 if (ctl_get_prkey(lun, residx) == 0
5364                  || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5365
5366                         ctl_set_reservation_conflict(ctsio);
5367                         ctl_done((union ctl_io *)ctsio);
5368                         return (CTL_RETVAL_COMPLETE);
5369                 }
5370         }
5371
5372         /*
5373          * If there is no backend on this device, we can't start or stop
5374          * it.  In theory we shouldn't get any start/stop commands in the
5375          * first place at this level if the LUN doesn't have a backend.
5376          * That should get stopped by the command decode code.
5377          */
5378         if (lun->backend == NULL) {
5379                 ctl_set_invalid_opcode(ctsio);
5380                 ctl_done((union ctl_io *)ctsio);
5381                 return (CTL_RETVAL_COMPLETE);
5382         }
5383
5384         /*
5385          * XXX KDM Copan-specific offline behavior.
5386          * Figure out a reasonable way to port this?
5387          */
5388 #ifdef NEEDTOPORT
5389         mtx_lock(&lun->lun_lock);
5390
5391         if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5392          && (lun->flags & CTL_LUN_OFFLINE)) {
5393                 /*
5394                  * If the LUN is offline, and the on/offline bit isn't set,
5395                  * reject the start or stop.  Otherwise, let it through.
5396                  */
5397                 mtx_unlock(&lun->lun_lock);
5398                 ctl_set_lun_not_ready(ctsio);
5399                 ctl_done((union ctl_io *)ctsio);
5400         } else {
5401                 mtx_unlock(&lun->lun_lock);
5402 #endif /* NEEDTOPORT */
5403                 /*
5404                  * This could be a start or a stop when we're online,
5405                  * or a stop/offline or start/online.  A start or stop when
5406                  * we're offline is covered in the case above.
5407                  */
5408                 /*
5409                  * In the non-immediate case, we send the request to
5410                  * the backend and return status to the user when
5411                  * it is done.
5412                  *
5413                  * In the immediate case, we allocate a new ctl_io
5414                  * to hold a copy of the request, and send that to
5415                  * the backend.  We then set good status on the
5416                  * user's request and return it immediately.
5417                  */
5418                 if (cdb->byte2 & SSS_IMMED) {
5419                         union ctl_io *new_io;
5420
5421                         new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5422                         ctl_copy_io((union ctl_io *)ctsio, new_io);
5423                         retval = lun->backend->config_write(new_io);
5424                         ctl_set_success(ctsio);
5425                         ctl_done((union ctl_io *)ctsio);
5426                 } else {
5427                         retval = lun->backend->config_write(
5428                                 (union ctl_io *)ctsio);
5429                 }
5430 #ifdef NEEDTOPORT
5431         }
5432 #endif
5433         return (retval);
5434 }
5435
5436 /*
5437  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5438  * we don't really do anything with the LBA and length fields if the user
5439  * passes them in.  Instead we'll just flush out the cache for the entire
5440  * LUN.
5441  */
5442 int
5443 ctl_sync_cache(struct ctl_scsiio *ctsio)
5444 {
5445         struct ctl_lun *lun;
5446         struct ctl_softc *ctl_softc;
5447         uint64_t starting_lba;
5448         uint32_t block_count;
5449         int retval;
5450
5451         CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5452
5453         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5454         ctl_softc = control_softc;
5455         retval = 0;
5456
5457         switch (ctsio->cdb[0]) {
5458         case SYNCHRONIZE_CACHE: {
5459                 struct scsi_sync_cache *cdb;
5460                 cdb = (struct scsi_sync_cache *)ctsio->cdb;
5461
5462                 starting_lba = scsi_4btoul(cdb->begin_lba);
5463                 block_count = scsi_2btoul(cdb->lb_count);
5464                 break;
5465         }
5466         case SYNCHRONIZE_CACHE_16: {
5467                 struct scsi_sync_cache_16 *cdb;
5468                 cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5469
5470                 starting_lba = scsi_8btou64(cdb->begin_lba);
5471                 block_count = scsi_4btoul(cdb->lb_count);
5472                 break;
5473         }
5474         default:
5475                 ctl_set_invalid_opcode(ctsio);
5476                 ctl_done((union ctl_io *)ctsio);
5477                 goto bailout;
5478                 break; /* NOTREACHED */
5479         }
5480
5481         /*
5482          * We check the LBA and length, but don't do anything with them.
5483          * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5484          * get flushed.  This check will just help satisfy anyone who wants
5485          * to see an error for an out of range LBA.
5486          */
5487         if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5488                 ctl_set_lba_out_of_range(ctsio);
5489                 ctl_done((union ctl_io *)ctsio);
5490                 goto bailout;
5491         }
5492
5493         /*
5494          * If this LUN has no backend, we can't flush the cache anyway.
5495          */
5496         if (lun->backend == NULL) {
5497                 ctl_set_invalid_opcode(ctsio);
5498                 ctl_done((union ctl_io *)ctsio);
5499                 goto bailout;
5500         }
5501
5502         /*
5503          * Check to see whether we're configured to send the SYNCHRONIZE
5504          * CACHE command directly to the back end.
5505          */
5506         mtx_lock(&lun->lun_lock);
5507         if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5508          && (++(lun->sync_count) >= lun->sync_interval)) {
5509                 lun->sync_count = 0;
5510                 mtx_unlock(&lun->lun_lock);
5511                 retval = lun->backend->config_write((union ctl_io *)ctsio);
5512         } else {
5513                 mtx_unlock(&lun->lun_lock);
5514                 ctl_set_success(ctsio);
5515                 ctl_done((union ctl_io *)ctsio);
5516         }
5517
5518 bailout:
5519
5520         return (retval);
5521 }
5522
5523 int
5524 ctl_format(struct ctl_scsiio *ctsio)
5525 {
5526         struct scsi_format *cdb;
5527         struct ctl_lun *lun;
5528         struct ctl_softc *ctl_softc;
5529         int length, defect_list_len;
5530
5531         CTL_DEBUG_PRINT(("ctl_format\n"));
5532
5533         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5534         ctl_softc = control_softc;
5535
5536         cdb = (struct scsi_format *)ctsio->cdb;
5537
5538         length = 0;
5539         if (cdb->byte2 & SF_FMTDATA) {
5540                 if (cdb->byte2 & SF_LONGLIST)
5541                         length = sizeof(struct scsi_format_header_long);
5542                 else
5543                         length = sizeof(struct scsi_format_header_short);
5544         }
5545
5546         if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5547          && (length > 0)) {
5548                 ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5549                 ctsio->kern_data_len = length;
5550                 ctsio->kern_total_len = length;
5551                 ctsio->kern_data_resid = 0;
5552                 ctsio->kern_rel_offset = 0;
5553                 ctsio->kern_sg_entries = 0;
5554                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5555                 ctsio->be_move_done = ctl_config_move_done;
5556                 ctl_datamove((union ctl_io *)ctsio);
5557
5558                 return (CTL_RETVAL_COMPLETE);
5559         }
5560
5561         defect_list_len = 0;
5562
5563         if (cdb->byte2 & SF_FMTDATA) {
5564                 if (cdb->byte2 & SF_LONGLIST) {
5565                         struct scsi_format_header_long *header;
5566
5567                         header = (struct scsi_format_header_long *)
5568                                 ctsio->kern_data_ptr;
5569
5570                         defect_list_len = scsi_4btoul(header->defect_list_len);
5571                         if (defect_list_len != 0) {
5572                                 ctl_set_invalid_field(ctsio,
5573                                                       /*sks_valid*/ 1,
5574                                                       /*command*/ 0,
5575                                                       /*field*/ 2,
5576                                                       /*bit_valid*/ 0,
5577                                                       /*bit*/ 0);
5578                                 goto bailout;
5579                         }
5580                 } else {
5581                         struct scsi_format_header_short *header;
5582
5583                         header = (struct scsi_format_header_short *)
5584                                 ctsio->kern_data_ptr;
5585
5586                         defect_list_len = scsi_2btoul(header->defect_list_len);
5587                         if (defect_list_len != 0) {
5588                                 ctl_set_invalid_field(ctsio,
5589                                                       /*sks_valid*/ 1,
5590                                                       /*command*/ 0,
5591                                                       /*field*/ 2,
5592                                                       /*bit_valid*/ 0,
5593                                                       /*bit*/ 0);
5594                                 goto bailout;
5595                         }
5596                 }
5597         }
5598
5599         /*
5600          * The format command will clear out the "Medium format corrupted"
5601          * status if set by the configuration code.  That status is really
5602          * just a way to notify the host that we have lost the media, and
5603          * get them to issue a command that will basically make them think
5604          * they're blowing away the media.
5605          */
5606         mtx_lock(&lun->lun_lock);
5607         lun->flags &= ~CTL_LUN_INOPERABLE;
5608         mtx_unlock(&lun->lun_lock);
5609
5610         ctl_set_success(ctsio);
5611 bailout:
5612
5613         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5614                 free(ctsio->kern_data_ptr, M_CTL);
5615                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5616         }
5617
5618         ctl_done((union ctl_io *)ctsio);
5619         return (CTL_RETVAL_COMPLETE);
5620 }
5621
5622 int
5623 ctl_read_buffer(struct ctl_scsiio *ctsio)
5624 {
5625         struct scsi_read_buffer *cdb;
5626         struct ctl_lun *lun;
5627         int buffer_offset, len;
5628         static uint8_t descr[4];
5629         static uint8_t echo_descr[4] = { 0 };
5630
5631         CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5632
5633         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5634         cdb = (struct scsi_read_buffer *)ctsio->cdb;
5635
5636         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5637             (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5638             (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5639                 ctl_set_invalid_field(ctsio,
5640                                       /*sks_valid*/ 1,
5641                                       /*command*/ 1,
5642                                       /*field*/ 1,
5643                                       /*bit_valid*/ 1,
5644                                       /*bit*/ 4);
5645                 ctl_done((union ctl_io *)ctsio);
5646                 return (CTL_RETVAL_COMPLETE);
5647         }
5648
5649         len = scsi_3btoul(cdb->length);
5650         buffer_offset = scsi_3btoul(cdb->offset);
5651
5652         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5653                 ctl_set_invalid_field(ctsio,
5654                                       /*sks_valid*/ 1,
5655                                       /*command*/ 1,
5656                                       /*field*/ 6,
5657                                       /*bit_valid*/ 0,
5658                                       /*bit*/ 0);
5659                 ctl_done((union ctl_io *)ctsio);
5660                 return (CTL_RETVAL_COMPLETE);
5661         }
5662
5663         if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5664                 descr[0] = 0;
5665                 scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5666                 ctsio->kern_data_ptr = descr;
5667                 len = min(len, sizeof(descr));
5668         } else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5669                 ctsio->kern_data_ptr = echo_descr;
5670                 len = min(len, sizeof(echo_descr));
5671         } else {
5672                 if (lun->write_buffer == NULL) {
5673                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5674                             M_CTL, M_WAITOK);
5675                 }
5676                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5677         }
5678         ctsio->kern_data_len = len;
5679         ctsio->kern_total_len = len;
5680         ctsio->kern_data_resid = 0;
5681         ctsio->kern_rel_offset = 0;
5682         ctsio->kern_sg_entries = 0;
5683         ctl_set_success(ctsio);
5684         ctsio->be_move_done = ctl_config_move_done;
5685         ctl_datamove((union ctl_io *)ctsio);
5686         return (CTL_RETVAL_COMPLETE);
5687 }
5688
5689 int
5690 ctl_write_buffer(struct ctl_scsiio *ctsio)
5691 {
5692         struct scsi_write_buffer *cdb;
5693         struct ctl_lun *lun;
5694         int buffer_offset, len;
5695
5696         CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5697
5698         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5699         cdb = (struct scsi_write_buffer *)ctsio->cdb;
5700
5701         if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5702                 ctl_set_invalid_field(ctsio,
5703                                       /*sks_valid*/ 1,
5704                                       /*command*/ 1,
5705                                       /*field*/ 1,
5706                                       /*bit_valid*/ 1,
5707                                       /*bit*/ 4);
5708                 ctl_done((union ctl_io *)ctsio);
5709                 return (CTL_RETVAL_COMPLETE);
5710         }
5711
5712         len = scsi_3btoul(cdb->length);
5713         buffer_offset = scsi_3btoul(cdb->offset);
5714
5715         if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5716                 ctl_set_invalid_field(ctsio,
5717                                       /*sks_valid*/ 1,
5718                                       /*command*/ 1,
5719                                       /*field*/ 6,
5720                                       /*bit_valid*/ 0,
5721                                       /*bit*/ 0);
5722                 ctl_done((union ctl_io *)ctsio);
5723                 return (CTL_RETVAL_COMPLETE);
5724         }
5725
5726         /*
5727          * If we've got a kernel request that hasn't been malloced yet,
5728          * malloc it and tell the caller the data buffer is here.
5729          */
5730         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5731                 if (lun->write_buffer == NULL) {
5732                         lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5733                             M_CTL, M_WAITOK);
5734                 }
5735                 ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5736                 ctsio->kern_data_len = len;
5737                 ctsio->kern_total_len = len;
5738                 ctsio->kern_data_resid = 0;
5739                 ctsio->kern_rel_offset = 0;
5740                 ctsio->kern_sg_entries = 0;
5741                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5742                 ctsio->be_move_done = ctl_config_move_done;
5743                 ctl_datamove((union ctl_io *)ctsio);
5744
5745                 return (CTL_RETVAL_COMPLETE);
5746         }
5747
5748         ctl_set_success(ctsio);
5749         ctl_done((union ctl_io *)ctsio);
5750         return (CTL_RETVAL_COMPLETE);
5751 }
5752
5753 int
5754 ctl_write_same(struct ctl_scsiio *ctsio)
5755 {
5756         struct ctl_lun *lun;
5757         struct ctl_lba_len_flags *lbalen;
5758         uint64_t lba;
5759         uint32_t num_blocks;
5760         int len, retval;
5761         uint8_t byte2;
5762
5763         retval = CTL_RETVAL_COMPLETE;
5764
5765         CTL_DEBUG_PRINT(("ctl_write_same\n"));
5766
5767         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5768
5769         switch (ctsio->cdb[0]) {
5770         case WRITE_SAME_10: {
5771                 struct scsi_write_same_10 *cdb;
5772
5773                 cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5774
5775                 lba = scsi_4btoul(cdb->addr);
5776                 num_blocks = scsi_2btoul(cdb->length);
5777                 byte2 = cdb->byte2;
5778                 break;
5779         }
5780         case WRITE_SAME_16: {
5781                 struct scsi_write_same_16 *cdb;
5782
5783                 cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5784
5785                 lba = scsi_8btou64(cdb->addr);
5786                 num_blocks = scsi_4btoul(cdb->length);
5787                 byte2 = cdb->byte2;
5788                 break;
5789         }
5790         default:
5791                 /*
5792                  * We got a command we don't support.  This shouldn't
5793                  * happen, commands should be filtered out above us.
5794                  */
5795                 ctl_set_invalid_opcode(ctsio);
5796                 ctl_done((union ctl_io *)ctsio);
5797
5798                 return (CTL_RETVAL_COMPLETE);
5799                 break; /* NOTREACHED */
5800         }
5801
5802         /* NDOB and ANCHOR flags can be used only together with UNMAP */
5803         if ((byte2 & SWS_UNMAP) == 0 &&
5804             (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5805                 ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5806                     /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5807                 ctl_done((union ctl_io *)ctsio);
5808                 return (CTL_RETVAL_COMPLETE);
5809         }
5810
5811         /*
5812          * The first check is to make sure we're in bounds, the second
5813          * check is to catch wrap-around problems.  If the lba + num blocks
5814          * is less than the lba, then we've wrapped around and the block
5815          * range is invalid anyway.
5816          */
5817         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5818          || ((lba + num_blocks) < lba)) {
5819                 ctl_set_lba_out_of_range(ctsio);
5820                 ctl_done((union ctl_io *)ctsio);
5821                 return (CTL_RETVAL_COMPLETE);
5822         }
5823
5824         /* Zero number of blocks means "to the last logical block" */
5825         if (num_blocks == 0) {
5826                 if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5827                         ctl_set_invalid_field(ctsio,
5828                                               /*sks_valid*/ 0,
5829                                               /*command*/ 1,
5830                                               /*field*/ 0,
5831                                               /*bit_valid*/ 0,
5832                                               /*bit*/ 0);
5833                         ctl_done((union ctl_io *)ctsio);
5834                         return (CTL_RETVAL_COMPLETE);
5835                 }
5836                 num_blocks = (lun->be_lun->maxlba + 1) - lba;
5837         }
5838
5839         len = lun->be_lun->blocksize;
5840
5841         /*
5842          * If we've got a kernel request that hasn't been malloced yet,
5843          * malloc it and tell the caller the data buffer is here.
5844          */
5845         if ((byte2 & SWS_NDOB) == 0 &&
5846             (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5847                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5848                 ctsio->kern_data_len = len;
5849                 ctsio->kern_total_len = len;
5850                 ctsio->kern_data_resid = 0;
5851                 ctsio->kern_rel_offset = 0;
5852                 ctsio->kern_sg_entries = 0;
5853                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5854                 ctsio->be_move_done = ctl_config_move_done;
5855                 ctl_datamove((union ctl_io *)ctsio);
5856
5857                 return (CTL_RETVAL_COMPLETE);
5858         }
5859
5860         lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5861         lbalen->lba = lba;
5862         lbalen->len = num_blocks;
5863         lbalen->flags = byte2;
5864         retval = lun->backend->config_write((union ctl_io *)ctsio);
5865
5866         return (retval);
5867 }
5868
5869 int
5870 ctl_unmap(struct ctl_scsiio *ctsio)
5871 {
5872         struct ctl_lun *lun;
5873         struct scsi_unmap *cdb;
5874         struct ctl_ptr_len_flags *ptrlen;
5875         struct scsi_unmap_header *hdr;
5876         struct scsi_unmap_desc *buf, *end, *endnz, *range;
5877         uint64_t lba;
5878         uint32_t num_blocks;
5879         int len, retval;
5880         uint8_t byte2;
5881
5882         retval = CTL_RETVAL_COMPLETE;
5883
5884         CTL_DEBUG_PRINT(("ctl_unmap\n"));
5885
5886         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5887         cdb = (struct scsi_unmap *)ctsio->cdb;
5888
5889         len = scsi_2btoul(cdb->length);
5890         byte2 = cdb->byte2;
5891
5892         /*
5893          * If we've got a kernel request that hasn't been malloced yet,
5894          * malloc it and tell the caller the data buffer is here.
5895          */
5896         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5897                 ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5898                 ctsio->kern_data_len = len;
5899                 ctsio->kern_total_len = len;
5900                 ctsio->kern_data_resid = 0;
5901                 ctsio->kern_rel_offset = 0;
5902                 ctsio->kern_sg_entries = 0;
5903                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5904                 ctsio->be_move_done = ctl_config_move_done;
5905                 ctl_datamove((union ctl_io *)ctsio);
5906
5907                 return (CTL_RETVAL_COMPLETE);
5908         }
5909
5910         len = ctsio->kern_total_len - ctsio->kern_data_resid;
5911         hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5912         if (len < sizeof (*hdr) ||
5913             len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5914             len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5915             scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5916                 ctl_set_invalid_field(ctsio,
5917                                       /*sks_valid*/ 0,
5918                                       /*command*/ 0,
5919                                       /*field*/ 0,
5920                                       /*bit_valid*/ 0,
5921                                       /*bit*/ 0);
5922                 goto done;
5923         }
5924         len = scsi_2btoul(hdr->desc_length);
5925         buf = (struct scsi_unmap_desc *)(hdr + 1);
5926         end = buf + len / sizeof(*buf);
5927
5928         endnz = buf;
5929         for (range = buf; range < end; range++) {
5930                 lba = scsi_8btou64(range->lba);
5931                 num_blocks = scsi_4btoul(range->length);
5932                 if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5933                  || ((lba + num_blocks) < lba)) {
5934                         ctl_set_lba_out_of_range(ctsio);
5935                         ctl_done((union ctl_io *)ctsio);
5936                         return (CTL_RETVAL_COMPLETE);
5937                 }
5938                 if (num_blocks != 0)
5939                         endnz = range + 1;
5940         }
5941
5942         /*
5943          * Block backend can not handle zero last range.
5944          * Filter it out and return if there is nothing left.
5945          */
5946         len = (uint8_t *)endnz - (uint8_t *)buf;
5947         if (len == 0) {
5948                 ctl_set_success(ctsio);
5949                 goto done;
5950         }
5951
5952         mtx_lock(&lun->lun_lock);
5953         ptrlen = (struct ctl_ptr_len_flags *)
5954             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5955         ptrlen->ptr = (void *)buf;
5956         ptrlen->len = len;
5957         ptrlen->flags = byte2;
5958         ctl_check_blocked(lun);
5959         mtx_unlock(&lun->lun_lock);
5960
5961         retval = lun->backend->config_write((union ctl_io *)ctsio);
5962         return (retval);
5963
5964 done:
5965         if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5966                 free(ctsio->kern_data_ptr, M_CTL);
5967                 ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5968         }
5969         ctl_done((union ctl_io *)ctsio);
5970         return (CTL_RETVAL_COMPLETE);
5971 }
5972
5973 /*
5974  * Note that this function currently doesn't actually do anything inside
5975  * CTL to enforce things if the DQue bit is turned on.
5976  *
5977  * Also note that this function can't be used in the default case, because
5978  * the DQue bit isn't set in the changeable mask for the control mode page
5979  * anyway.  This is just here as an example for how to implement a page
5980  * handler, and a placeholder in case we want to allow the user to turn
5981  * tagged queueing on and off.
5982  *
5983  * The D_SENSE bit handling is functional, however, and will turn
5984  * descriptor sense on and off for a given LUN.
5985  */
5986 int
5987 ctl_control_page_handler(struct ctl_scsiio *ctsio,
5988                          struct ctl_page_index *page_index, uint8_t *page_ptr)
5989 {
5990         struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5991         struct ctl_lun *lun;
5992         struct ctl_softc *softc;
5993         int set_ua;
5994         uint32_t initidx;
5995
5996         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5997         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5998         set_ua = 0;
5999
6000         user_cp = (struct scsi_control_page *)page_ptr;
6001         current_cp = (struct scsi_control_page *)
6002                 (page_index->page_data + (page_index->page_len *
6003                 CTL_PAGE_CURRENT));
6004         saved_cp = (struct scsi_control_page *)
6005                 (page_index->page_data + (page_index->page_len *
6006                 CTL_PAGE_SAVED));
6007
6008         softc = control_softc;
6009
6010         mtx_lock(&lun->lun_lock);
6011         if (((current_cp->rlec & SCP_DSENSE) == 0)
6012          && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6013                 /*
6014                  * Descriptor sense is currently turned off and the user
6015                  * wants to turn it on.
6016                  */
6017                 current_cp->rlec |= SCP_DSENSE;
6018                 saved_cp->rlec |= SCP_DSENSE;
6019                 lun->flags |= CTL_LUN_SENSE_DESC;
6020                 set_ua = 1;
6021         } else if (((current_cp->rlec & SCP_DSENSE) != 0)
6022                 && ((user_cp->rlec & SCP_DSENSE) == 0)) {
6023                 /*
6024                  * Descriptor sense is currently turned on, and the user
6025                  * wants to turn it off.
6026                  */
6027                 current_cp->rlec &= ~SCP_DSENSE;
6028                 saved_cp->rlec &= ~SCP_DSENSE;
6029                 lun->flags &= ~CTL_LUN_SENSE_DESC;
6030                 set_ua = 1;
6031         }
6032         if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6033             (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6034                 current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6035                 current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6036                 saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6037                 saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6038                 set_ua = 1;
6039         }
6040         if ((current_cp->eca_and_aen & SCP_SWP) !=
6041             (user_cp->eca_and_aen & SCP_SWP)) {
6042                 current_cp->eca_and_aen &= ~SCP_SWP;
6043                 current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6044                 saved_cp->eca_and_aen &= ~SCP_SWP;
6045                 saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6046                 set_ua = 1;
6047         }
6048         if (set_ua != 0) {
6049                 int i;
6050                 /*
6051                  * Let other initiators know that the mode
6052                  * parameters for this LUN have changed.
6053                  */
6054                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6055                         if (i == initidx)
6056                                 continue;
6057
6058                         lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6059                 }
6060         }
6061         mtx_unlock(&lun->lun_lock);
6062
6063         return (0);
6064 }
6065
6066 int
6067 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6068                      struct ctl_page_index *page_index, uint8_t *page_ptr)
6069 {
6070         struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6071         struct ctl_lun *lun;
6072         int set_ua;
6073         uint32_t initidx;
6074
6075         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6076         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6077         set_ua = 0;
6078
6079         user_cp = (struct scsi_caching_page *)page_ptr;
6080         current_cp = (struct scsi_caching_page *)
6081                 (page_index->page_data + (page_index->page_len *
6082                 CTL_PAGE_CURRENT));
6083         saved_cp = (struct scsi_caching_page *)
6084                 (page_index->page_data + (page_index->page_len *
6085                 CTL_PAGE_SAVED));
6086
6087         mtx_lock(&lun->lun_lock);
6088         if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6089             (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6090                 current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6091                 current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6092                 saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6093                 saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6094                 set_ua = 1;
6095         }
6096         if (set_ua != 0) {
6097                 int i;
6098                 /*
6099                  * Let other initiators know that the mode
6100                  * parameters for this LUN have changed.
6101                  */
6102                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6103                         if (i == initidx)
6104                                 continue;
6105
6106                         lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6107                 }
6108         }
6109         mtx_unlock(&lun->lun_lock);
6110
6111         return (0);
6112 }
6113
6114 int
6115 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6116                                 struct ctl_page_index *page_index,
6117                                 uint8_t *page_ptr)
6118 {
6119         uint8_t *c;
6120         int i;
6121
6122         c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6123         ctl_time_io_secs =
6124                 (c[0] << 8) |
6125                 (c[1] << 0) |
6126                 0;
6127         CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6128         printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6129         printf("page data:");
6130         for (i=0; i<8; i++)
6131                 printf(" %.2x",page_ptr[i]);
6132         printf("\n");
6133         return (0);
6134 }
6135
6136 int
6137 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6138                                struct ctl_page_index *page_index,
6139                                int pc)
6140 {
6141         struct copan_debugconf_subpage *page;
6142
6143         page = (struct copan_debugconf_subpage *)page_index->page_data +
6144                 (page_index->page_len * pc);
6145
6146         switch (pc) {
6147         case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6148         case SMS_PAGE_CTRL_DEFAULT >> 6:
6149         case SMS_PAGE_CTRL_SAVED >> 6:
6150                 /*
6151                  * We don't update the changable or default bits for this page.
6152                  */
6153                 break;
6154         case SMS_PAGE_CTRL_CURRENT >> 6:
6155                 page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6156                 page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6157                 break;
6158         default:
6159 #ifdef NEEDTOPORT
6160                 EPRINT(0, "Invalid PC %d!!", pc);
6161 #endif /* NEEDTOPORT */
6162                 break;
6163         }
6164         return (0);
6165 }
6166
6167
6168 static int
6169 ctl_do_mode_select(union ctl_io *io)
6170 {
6171         struct scsi_mode_page_header *page_header;
6172         struct ctl_page_index *page_index;
6173         struct ctl_scsiio *ctsio;
6174         int control_dev, page_len;
6175         int page_len_offset, page_len_size;
6176         union ctl_modepage_info *modepage_info;
6177         struct ctl_lun *lun;
6178         int *len_left, *len_used;
6179         int retval, i;
6180
6181         ctsio = &io->scsiio;
6182         page_index = NULL;
6183         page_len = 0;
6184         retval = CTL_RETVAL_COMPLETE;
6185
6186         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6187
6188         if (lun->be_lun->lun_type != T_DIRECT)
6189                 control_dev = 1;
6190         else
6191                 control_dev = 0;
6192
6193         modepage_info = (union ctl_modepage_info *)
6194                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6195         len_left = &modepage_info->header.len_left;
6196         len_used = &modepage_info->header.len_used;
6197
6198 do_next_page:
6199
6200         page_header = (struct scsi_mode_page_header *)
6201                 (ctsio->kern_data_ptr + *len_used);
6202
6203         if (*len_left == 0) {
6204                 free(ctsio->kern_data_ptr, M_CTL);
6205                 ctl_set_success(ctsio);
6206                 ctl_done((union ctl_io *)ctsio);
6207                 return (CTL_RETVAL_COMPLETE);
6208         } else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6209
6210                 free(ctsio->kern_data_ptr, M_CTL);
6211                 ctl_set_param_len_error(ctsio);
6212                 ctl_done((union ctl_io *)ctsio);
6213                 return (CTL_RETVAL_COMPLETE);
6214
6215         } else if ((page_header->page_code & SMPH_SPF)
6216                 && (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6217
6218                 free(ctsio->kern_data_ptr, M_CTL);
6219                 ctl_set_param_len_error(ctsio);
6220                 ctl_done((union ctl_io *)ctsio);
6221                 return (CTL_RETVAL_COMPLETE);
6222         }
6223
6224
6225         /*
6226          * XXX KDM should we do something with the block descriptor?
6227          */
6228         for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6229
6230                 if ((control_dev != 0)
6231                  && (lun->mode_pages.index[i].page_flags &
6232                      CTL_PAGE_FLAG_DISK_ONLY))
6233                         continue;
6234
6235                 if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6236                     (page_header->page_code & SMPH_PC_MASK))
6237                         continue;
6238
6239                 /*
6240                  * If neither page has a subpage code, then we've got a
6241                  * match.
6242                  */
6243                 if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6244                  && ((page_header->page_code & SMPH_SPF) == 0)) {
6245                         page_index = &lun->mode_pages.index[i];
6246                         page_len = page_header->page_length;
6247                         break;
6248                 }
6249
6250                 /*
6251                  * If both pages have subpages, then the subpage numbers
6252                  * have to match.
6253                  */
6254                 if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6255                   && (page_header->page_code & SMPH_SPF)) {
6256                         struct scsi_mode_page_header_sp *sph;
6257
6258                         sph = (struct scsi_mode_page_header_sp *)page_header;
6259
6260                         if (lun->mode_pages.index[i].subpage ==
6261                             sph->subpage) {
6262                                 page_index = &lun->mode_pages.index[i];
6263                                 page_len = scsi_2btoul(sph->page_length);
6264                                 break;
6265                         }
6266                 }
6267         }
6268
6269         /*
6270          * If we couldn't find the page, or if we don't have a mode select
6271          * handler for it, send back an error to the user.
6272          */
6273         if ((page_index == NULL)
6274          || (page_index->select_handler == NULL)) {
6275                 ctl_set_invalid_field(ctsio,
6276                                       /*sks_valid*/ 1,
6277                                       /*command*/ 0,
6278                                       /*field*/ *len_used,
6279                                       /*bit_valid*/ 0,
6280                                       /*bit*/ 0);
6281                 free(ctsio->kern_data_ptr, M_CTL);
6282                 ctl_done((union ctl_io *)ctsio);
6283                 return (CTL_RETVAL_COMPLETE);
6284         }
6285
6286         if (page_index->page_code & SMPH_SPF) {
6287                 page_len_offset = 2;
6288                 page_len_size = 2;
6289         } else {
6290                 page_len_size = 1;
6291                 page_len_offset = 1;
6292         }
6293
6294         /*
6295          * If the length the initiator gives us isn't the one we specify in
6296          * the mode page header, or if they didn't specify enough data in
6297          * the CDB to avoid truncating this page, kick out the request.
6298          */
6299         if ((page_len != (page_index->page_len - page_len_offset -
6300                           page_len_size))
6301          || (*len_left < page_index->page_len)) {
6302
6303
6304                 ctl_set_invalid_field(ctsio,
6305                                       /*sks_valid*/ 1,
6306                                       /*command*/ 0,
6307                                       /*field*/ *len_used + page_len_offset,
6308                                       /*bit_valid*/ 0,
6309                                       /*bit*/ 0);
6310                 free(ctsio->kern_data_ptr, M_CTL);
6311                 ctl_done((union ctl_io *)ctsio);
6312                 return (CTL_RETVAL_COMPLETE);
6313         }
6314
6315         /*
6316          * Run through the mode page, checking to make sure that the bits
6317          * the user changed are actually legal for him to change.
6318          */
6319         for (i = 0; i < page_index->page_len; i++) {
6320                 uint8_t *user_byte, *change_mask, *current_byte;
6321                 int bad_bit;
6322                 int j;
6323
6324                 user_byte = (uint8_t *)page_header + i;
6325                 change_mask = page_index->page_data +
6326                               (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6327                 current_byte = page_index->page_data +
6328                                (page_index->page_len * CTL_PAGE_CURRENT) + i;
6329
6330                 /*
6331                  * Check to see whether the user set any bits in this byte
6332                  * that he is not allowed to set.
6333                  */
6334                 if ((*user_byte & ~(*change_mask)) ==
6335                     (*current_byte & ~(*change_mask)))
6336                         continue;
6337
6338                 /*
6339                  * Go through bit by bit to determine which one is illegal.
6340                  */
6341                 bad_bit = 0;
6342                 for (j = 7; j >= 0; j--) {
6343                         if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6344                             (((1 << i) & ~(*change_mask)) & *current_byte)) {
6345                                 bad_bit = i;
6346                                 break;
6347                         }
6348                 }
6349                 ctl_set_invalid_field(ctsio,
6350                                       /*sks_valid*/ 1,
6351                                       /*command*/ 0,
6352                                       /*field*/ *len_used + i,
6353                                       /*bit_valid*/ 1,
6354                                       /*bit*/ bad_bit);
6355                 free(ctsio->kern_data_ptr, M_CTL);
6356                 ctl_done((union ctl_io *)ctsio);
6357                 return (CTL_RETVAL_COMPLETE);
6358         }
6359
6360         /*
6361          * Decrement these before we call the page handler, since we may
6362          * end up getting called back one way or another before the handler
6363          * returns to this context.
6364          */
6365         *len_left -= page_index->page_len;
6366         *len_used += page_index->page_len;
6367
6368         retval = page_index->select_handler(ctsio, page_index,
6369                                             (uint8_t *)page_header);
6370
6371         /*
6372          * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6373          * wait until this queued command completes to finish processing
6374          * the mode page.  If it returns anything other than
6375          * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6376          * already set the sense information, freed the data pointer, and
6377          * completed the io for us.
6378          */
6379         if (retval != CTL_RETVAL_COMPLETE)
6380                 goto bailout_no_done;
6381
6382         /*
6383          * If the initiator sent us more than one page, parse the next one.
6384          */
6385         if (*len_left > 0)
6386                 goto do_next_page;
6387
6388         ctl_set_success(ctsio);
6389         free(ctsio->kern_data_ptr, M_CTL);
6390         ctl_done((union ctl_io *)ctsio);
6391
6392 bailout_no_done:
6393
6394         return (CTL_RETVAL_COMPLETE);
6395
6396 }
6397
6398 int
6399 ctl_mode_select(struct ctl_scsiio *ctsio)
6400 {
6401         int param_len, pf, sp;
6402         int header_size, bd_len;
6403         int len_left, len_used;
6404         struct ctl_page_index *page_index;
6405         struct ctl_lun *lun;
6406         int control_dev, page_len;
6407         union ctl_modepage_info *modepage_info;
6408         int retval;
6409
6410         pf = 0;
6411         sp = 0;
6412         page_len = 0;
6413         len_used = 0;
6414         len_left = 0;
6415         retval = 0;
6416         bd_len = 0;
6417         page_index = NULL;
6418
6419         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6420
6421         if (lun->be_lun->lun_type != T_DIRECT)
6422                 control_dev = 1;
6423         else
6424                 control_dev = 0;
6425
6426         switch (ctsio->cdb[0]) {
6427         case MODE_SELECT_6: {
6428                 struct scsi_mode_select_6 *cdb;
6429
6430                 cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6431
6432                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6433                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6434
6435                 param_len = cdb->length;
6436                 header_size = sizeof(struct scsi_mode_header_6);
6437                 break;
6438         }
6439         case MODE_SELECT_10: {
6440                 struct scsi_mode_select_10 *cdb;
6441
6442                 cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6443
6444                 pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6445                 sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6446
6447                 param_len = scsi_2btoul(cdb->length);
6448                 header_size = sizeof(struct scsi_mode_header_10);
6449                 break;
6450         }
6451         default:
6452                 ctl_set_invalid_opcode(ctsio);
6453                 ctl_done((union ctl_io *)ctsio);
6454                 return (CTL_RETVAL_COMPLETE);
6455                 break; /* NOTREACHED */
6456         }
6457
6458         /*
6459          * From SPC-3:
6460          * "A parameter list length of zero indicates that the Data-Out Buffer
6461          * shall be empty. This condition shall not be considered as an error."
6462          */
6463         if (param_len == 0) {
6464                 ctl_set_success(ctsio);
6465                 ctl_done((union ctl_io *)ctsio);
6466                 return (CTL_RETVAL_COMPLETE);
6467         }
6468
6469         /*
6470          * Since we'll hit this the first time through, prior to
6471          * allocation, we don't need to free a data buffer here.
6472          */
6473         if (param_len < header_size) {
6474                 ctl_set_param_len_error(ctsio);
6475                 ctl_done((union ctl_io *)ctsio);
6476                 return (CTL_RETVAL_COMPLETE);
6477         }
6478
6479         /*
6480          * Allocate the data buffer and grab the user's data.  In theory,
6481          * we shouldn't have to sanity check the parameter list length here
6482          * because the maximum size is 64K.  We should be able to malloc
6483          * that much without too many problems.
6484          */
6485         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6486                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6487                 ctsio->kern_data_len = param_len;
6488                 ctsio->kern_total_len = param_len;
6489                 ctsio->kern_data_resid = 0;
6490                 ctsio->kern_rel_offset = 0;
6491                 ctsio->kern_sg_entries = 0;
6492                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6493                 ctsio->be_move_done = ctl_config_move_done;
6494                 ctl_datamove((union ctl_io *)ctsio);
6495
6496                 return (CTL_RETVAL_COMPLETE);
6497         }
6498
6499         switch (ctsio->cdb[0]) {
6500         case MODE_SELECT_6: {
6501                 struct scsi_mode_header_6 *mh6;
6502
6503                 mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6504                 bd_len = mh6->blk_desc_len;
6505                 break;
6506         }
6507         case MODE_SELECT_10: {
6508                 struct scsi_mode_header_10 *mh10;
6509
6510                 mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6511                 bd_len = scsi_2btoul(mh10->blk_desc_len);
6512                 break;
6513         }
6514         default:
6515                 panic("Invalid CDB type %#x", ctsio->cdb[0]);
6516                 break;
6517         }
6518
6519         if (param_len < (header_size + bd_len)) {
6520                 free(ctsio->kern_data_ptr, M_CTL);
6521                 ctl_set_param_len_error(ctsio);
6522                 ctl_done((union ctl_io *)ctsio);
6523                 return (CTL_RETVAL_COMPLETE);
6524         }
6525
6526         /*
6527          * Set the IO_CONT flag, so that if this I/O gets passed to
6528          * ctl_config_write_done(), it'll get passed back to
6529          * ctl_do_mode_select() for further processing, or completion if
6530          * we're all done.
6531          */
6532         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6533         ctsio->io_cont = ctl_do_mode_select;
6534
6535         modepage_info = (union ctl_modepage_info *)
6536                 ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6537
6538         memset(modepage_info, 0, sizeof(*modepage_info));
6539
6540         len_left = param_len - header_size - bd_len;
6541         len_used = header_size + bd_len;
6542
6543         modepage_info->header.len_left = len_left;
6544         modepage_info->header.len_used = len_used;
6545
6546         return (ctl_do_mode_select((union ctl_io *)ctsio));
6547 }
6548
6549 int
6550 ctl_mode_sense(struct ctl_scsiio *ctsio)
6551 {
6552         struct ctl_lun *lun;
6553         int pc, page_code, dbd, llba, subpage;
6554         int alloc_len, page_len, header_len, total_len;
6555         struct scsi_mode_block_descr *block_desc;
6556         struct ctl_page_index *page_index;
6557         int control_dev;
6558
6559         dbd = 0;
6560         llba = 0;
6561         block_desc = NULL;
6562         page_index = NULL;
6563
6564         CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6565
6566         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6567
6568         if (lun->be_lun->lun_type != T_DIRECT)
6569                 control_dev = 1;
6570         else
6571                 control_dev = 0;
6572
6573         switch (ctsio->cdb[0]) {
6574         case MODE_SENSE_6: {
6575                 struct scsi_mode_sense_6 *cdb;
6576
6577                 cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6578
6579                 header_len = sizeof(struct scsi_mode_hdr_6);
6580                 if (cdb->byte2 & SMS_DBD)
6581                         dbd = 1;
6582                 else
6583                         header_len += sizeof(struct scsi_mode_block_descr);
6584
6585                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6586                 page_code = cdb->page & SMS_PAGE_CODE;
6587                 subpage = cdb->subpage;
6588                 alloc_len = cdb->length;
6589                 break;
6590         }
6591         case MODE_SENSE_10: {
6592                 struct scsi_mode_sense_10 *cdb;
6593
6594                 cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6595
6596                 header_len = sizeof(struct scsi_mode_hdr_10);
6597
6598                 if (cdb->byte2 & SMS_DBD)
6599                         dbd = 1;
6600                 else
6601                         header_len += sizeof(struct scsi_mode_block_descr);
6602                 if (cdb->byte2 & SMS10_LLBAA)
6603                         llba = 1;
6604                 pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6605                 page_code = cdb->page & SMS_PAGE_CODE;
6606                 subpage = cdb->subpage;
6607                 alloc_len = scsi_2btoul(cdb->length);
6608                 break;
6609         }
6610         default:
6611                 ctl_set_invalid_opcode(ctsio);
6612                 ctl_done((union ctl_io *)ctsio);
6613                 return (CTL_RETVAL_COMPLETE);
6614                 break; /* NOTREACHED */
6615         }
6616
6617         /*
6618          * We have to make a first pass through to calculate the size of
6619          * the pages that match the user's query.  Then we allocate enough
6620          * memory to hold it, and actually copy the data into the buffer.
6621          */
6622         switch (page_code) {
6623         case SMS_ALL_PAGES_PAGE: {
6624                 int i;
6625
6626                 page_len = 0;
6627
6628                 /*
6629                  * At the moment, values other than 0 and 0xff here are
6630                  * reserved according to SPC-3.
6631                  */
6632                 if ((subpage != SMS_SUBPAGE_PAGE_0)
6633                  && (subpage != SMS_SUBPAGE_ALL)) {
6634                         ctl_set_invalid_field(ctsio,
6635                                               /*sks_valid*/ 1,
6636                                               /*command*/ 1,
6637                                               /*field*/ 3,
6638                                               /*bit_valid*/ 0,
6639                                               /*bit*/ 0);
6640                         ctl_done((union ctl_io *)ctsio);
6641                         return (CTL_RETVAL_COMPLETE);
6642                 }
6643
6644                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6645                         if ((control_dev != 0)
6646                          && (lun->mode_pages.index[i].page_flags &
6647                              CTL_PAGE_FLAG_DISK_ONLY))
6648                                 continue;
6649
6650                         /*
6651                          * We don't use this subpage if the user didn't
6652                          * request all subpages.
6653                          */
6654                         if ((lun->mode_pages.index[i].subpage != 0)
6655                          && (subpage == SMS_SUBPAGE_PAGE_0))
6656                                 continue;
6657
6658 #if 0
6659                         printf("found page %#x len %d\n",
6660                                lun->mode_pages.index[i].page_code &
6661                                SMPH_PC_MASK,
6662                                lun->mode_pages.index[i].page_len);
6663 #endif
6664                         page_len += lun->mode_pages.index[i].page_len;
6665                 }
6666                 break;
6667         }
6668         default: {
6669                 int i;
6670
6671                 page_len = 0;
6672
6673                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6674                         /* Look for the right page code */
6675                         if ((lun->mode_pages.index[i].page_code &
6676                              SMPH_PC_MASK) != page_code)
6677                                 continue;
6678
6679                         /* Look for the right subpage or the subpage wildcard*/
6680                         if ((lun->mode_pages.index[i].subpage != subpage)
6681                          && (subpage != SMS_SUBPAGE_ALL))
6682                                 continue;
6683
6684                         /* Make sure the page is supported for this dev type */
6685                         if ((control_dev != 0)
6686                          && (lun->mode_pages.index[i].page_flags &
6687                              CTL_PAGE_FLAG_DISK_ONLY))
6688                                 continue;
6689
6690 #if 0
6691                         printf("found page %#x len %d\n",
6692                                lun->mode_pages.index[i].page_code &
6693                                SMPH_PC_MASK,
6694                                lun->mode_pages.index[i].page_len);
6695 #endif
6696
6697                         page_len += lun->mode_pages.index[i].page_len;
6698                 }
6699
6700                 if (page_len == 0) {
6701                         ctl_set_invalid_field(ctsio,
6702                                               /*sks_valid*/ 1,
6703                                               /*command*/ 1,
6704                                               /*field*/ 2,
6705                                               /*bit_valid*/ 1,
6706                                               /*bit*/ 5);
6707                         ctl_done((union ctl_io *)ctsio);
6708                         return (CTL_RETVAL_COMPLETE);
6709                 }
6710                 break;
6711         }
6712         }
6713
6714         total_len = header_len + page_len;
6715 #if 0
6716         printf("header_len = %d, page_len = %d, total_len = %d\n",
6717                header_len, page_len, total_len);
6718 #endif
6719
6720         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6721         ctsio->kern_sg_entries = 0;
6722         ctsio->kern_data_resid = 0;
6723         ctsio->kern_rel_offset = 0;
6724         if (total_len < alloc_len) {
6725                 ctsio->residual = alloc_len - total_len;
6726                 ctsio->kern_data_len = total_len;
6727                 ctsio->kern_total_len = total_len;
6728         } else {
6729                 ctsio->residual = 0;
6730                 ctsio->kern_data_len = alloc_len;
6731                 ctsio->kern_total_len = alloc_len;
6732         }
6733
6734         switch (ctsio->cdb[0]) {
6735         case MODE_SENSE_6: {
6736                 struct scsi_mode_hdr_6 *header;
6737
6738                 header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6739
6740                 header->datalen = ctl_min(total_len - 1, 254);
6741                 if (control_dev == 0) {
6742                         header->dev_specific = 0x10; /* DPOFUA */
6743                         if ((lun->flags & CTL_LUN_READONLY) ||
6744                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6745                             .eca_and_aen & SCP_SWP) != 0)
6746                                     header->dev_specific |= 0x80; /* WP */
6747                 }
6748                 if (dbd)
6749                         header->block_descr_len = 0;
6750                 else
6751                         header->block_descr_len =
6752                                 sizeof(struct scsi_mode_block_descr);
6753                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6754                 break;
6755         }
6756         case MODE_SENSE_10: {
6757                 struct scsi_mode_hdr_10 *header;
6758                 int datalen;
6759
6760                 header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6761
6762                 datalen = ctl_min(total_len - 2, 65533);
6763                 scsi_ulto2b(datalen, header->datalen);
6764                 if (control_dev == 0) {
6765                         header->dev_specific = 0x10; /* DPOFUA */
6766                         if ((lun->flags & CTL_LUN_READONLY) ||
6767                             (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6768                             .eca_and_aen & SCP_SWP) != 0)
6769                                     header->dev_specific |= 0x80; /* WP */
6770                 }
6771                 if (dbd)
6772                         scsi_ulto2b(0, header->block_descr_len);
6773                 else
6774                         scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6775                                     header->block_descr_len);
6776                 block_desc = (struct scsi_mode_block_descr *)&header[1];
6777                 break;
6778         }
6779         default:
6780                 panic("invalid CDB type %#x", ctsio->cdb[0]);
6781                 break; /* NOTREACHED */
6782         }
6783
6784         /*
6785          * If we've got a disk, use its blocksize in the block
6786          * descriptor.  Otherwise, just set it to 0.
6787          */
6788         if (dbd == 0) {
6789                 if (control_dev == 0)
6790                         scsi_ulto3b(lun->be_lun->blocksize,
6791                                     block_desc->block_len);
6792                 else
6793                         scsi_ulto3b(0, block_desc->block_len);
6794         }
6795
6796         switch (page_code) {
6797         case SMS_ALL_PAGES_PAGE: {
6798                 int i, data_used;
6799
6800                 data_used = header_len;
6801                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6802                         struct ctl_page_index *page_index;
6803
6804                         page_index = &lun->mode_pages.index[i];
6805
6806                         if ((control_dev != 0)
6807                          && (page_index->page_flags &
6808                             CTL_PAGE_FLAG_DISK_ONLY))
6809                                 continue;
6810
6811                         /*
6812                          * We don't use this subpage if the user didn't
6813                          * request all subpages.  We already checked (above)
6814                          * to make sure the user only specified a subpage
6815                          * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6816                          */
6817                         if ((page_index->subpage != 0)
6818                          && (subpage == SMS_SUBPAGE_PAGE_0))
6819                                 continue;
6820
6821                         /*
6822                          * Call the handler, if it exists, to update the
6823                          * page to the latest values.
6824                          */
6825                         if (page_index->sense_handler != NULL)
6826                                 page_index->sense_handler(ctsio, page_index,pc);
6827
6828                         memcpy(ctsio->kern_data_ptr + data_used,
6829                                page_index->page_data +
6830                                (page_index->page_len * pc),
6831                                page_index->page_len);
6832                         data_used += page_index->page_len;
6833                 }
6834                 break;
6835         }
6836         default: {
6837                 int i, data_used;
6838
6839                 data_used = header_len;
6840
6841                 for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6842                         struct ctl_page_index *page_index;
6843
6844                         page_index = &lun->mode_pages.index[i];
6845
6846                         /* Look for the right page code */
6847                         if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6848                                 continue;
6849
6850                         /* Look for the right subpage or the subpage wildcard*/
6851                         if ((page_index->subpage != subpage)
6852                          && (subpage != SMS_SUBPAGE_ALL))
6853                                 continue;
6854
6855                         /* Make sure the page is supported for this dev type */
6856                         if ((control_dev != 0)
6857                          && (page_index->page_flags &
6858                              CTL_PAGE_FLAG_DISK_ONLY))
6859                                 continue;
6860
6861                         /*
6862                          * Call the handler, if it exists, to update the
6863                          * page to the latest values.
6864                          */
6865                         if (page_index->sense_handler != NULL)
6866                                 page_index->sense_handler(ctsio, page_index,pc);
6867
6868                         memcpy(ctsio->kern_data_ptr + data_used,
6869                                page_index->page_data +
6870                                (page_index->page_len * pc),
6871                                page_index->page_len);
6872                         data_used += page_index->page_len;
6873                 }
6874                 break;
6875         }
6876         }
6877
6878         ctl_set_success(ctsio);
6879         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6880         ctsio->be_move_done = ctl_config_move_done;
6881         ctl_datamove((union ctl_io *)ctsio);
6882         return (CTL_RETVAL_COMPLETE);
6883 }
6884
6885 int
6886 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6887                                struct ctl_page_index *page_index,
6888                                int pc)
6889 {
6890         struct ctl_lun *lun;
6891         struct scsi_log_param_header *phdr;
6892         uint8_t *data;
6893         uint64_t val;
6894
6895         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6896         data = page_index->page_data;
6897
6898         if (lun->backend->lun_attr != NULL &&
6899             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6900              != UINT64_MAX) {
6901                 phdr = (struct scsi_log_param_header *)data;
6902                 scsi_ulto2b(0x0001, phdr->param_code);
6903                 phdr->param_control = SLP_LBIN | SLP_LP;
6904                 phdr->param_len = 8;
6905                 data = (uint8_t *)(phdr + 1);
6906                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6907                 data[4] = 0x02; /* per-pool */
6908                 data += phdr->param_len;
6909         }
6910
6911         if (lun->backend->lun_attr != NULL &&
6912             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6913              != UINT64_MAX) {
6914                 phdr = (struct scsi_log_param_header *)data;
6915                 scsi_ulto2b(0x0002, phdr->param_code);
6916                 phdr->param_control = SLP_LBIN | SLP_LP;
6917                 phdr->param_len = 8;
6918                 data = (uint8_t *)(phdr + 1);
6919                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6920                 data[4] = 0x01; /* per-LUN */
6921                 data += phdr->param_len;
6922         }
6923
6924         if (lun->backend->lun_attr != NULL &&
6925             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6926              != UINT64_MAX) {
6927                 phdr = (struct scsi_log_param_header *)data;
6928                 scsi_ulto2b(0x00f1, phdr->param_code);
6929                 phdr->param_control = SLP_LBIN | SLP_LP;
6930                 phdr->param_len = 8;
6931                 data = (uint8_t *)(phdr + 1);
6932                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6933                 data[4] = 0x02; /* per-pool */
6934                 data += phdr->param_len;
6935         }
6936
6937         if (lun->backend->lun_attr != NULL &&
6938             (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6939              != UINT64_MAX) {
6940                 phdr = (struct scsi_log_param_header *)data;
6941                 scsi_ulto2b(0x00f2, phdr->param_code);
6942                 phdr->param_control = SLP_LBIN | SLP_LP;
6943                 phdr->param_len = 8;
6944                 data = (uint8_t *)(phdr + 1);
6945                 scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6946                 data[4] = 0x02; /* per-pool */
6947                 data += phdr->param_len;
6948         }
6949
6950         page_index->page_len = data - page_index->page_data;
6951         return (0);
6952 }
6953
6954 int
6955 ctl_log_sense(struct ctl_scsiio *ctsio)
6956 {
6957         struct ctl_lun *lun;
6958         int i, pc, page_code, subpage;
6959         int alloc_len, total_len;
6960         struct ctl_page_index *page_index;
6961         struct scsi_log_sense *cdb;
6962         struct scsi_log_header *header;
6963
6964         CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6965
6966         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6967         cdb = (struct scsi_log_sense *)ctsio->cdb;
6968         pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6969         page_code = cdb->page & SLS_PAGE_CODE;
6970         subpage = cdb->subpage;
6971         alloc_len = scsi_2btoul(cdb->length);
6972
6973         page_index = NULL;
6974         for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6975                 page_index = &lun->log_pages.index[i];
6976
6977                 /* Look for the right page code */
6978                 if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6979                         continue;
6980
6981                 /* Look for the right subpage or the subpage wildcard*/
6982                 if (page_index->subpage != subpage)
6983                         continue;
6984
6985                 break;
6986         }
6987         if (i >= CTL_NUM_LOG_PAGES) {
6988                 ctl_set_invalid_field(ctsio,
6989                                       /*sks_valid*/ 1,
6990                                       /*command*/ 1,
6991                                       /*field*/ 2,
6992                                       /*bit_valid*/ 0,
6993                                       /*bit*/ 0);
6994                 ctl_done((union ctl_io *)ctsio);
6995                 return (CTL_RETVAL_COMPLETE);
6996         }
6997
6998         total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6999
7000         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7001         ctsio->kern_sg_entries = 0;
7002         ctsio->kern_data_resid = 0;
7003         ctsio->kern_rel_offset = 0;
7004         if (total_len < alloc_len) {
7005                 ctsio->residual = alloc_len - total_len;
7006                 ctsio->kern_data_len = total_len;
7007                 ctsio->kern_total_len = total_len;
7008         } else {
7009                 ctsio->residual = 0;
7010                 ctsio->kern_data_len = alloc_len;
7011                 ctsio->kern_total_len = alloc_len;
7012         }
7013
7014         header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7015         header->page = page_index->page_code;
7016         if (page_index->subpage) {
7017                 header->page |= SL_SPF;
7018                 header->subpage = page_index->subpage;
7019         }
7020         scsi_ulto2b(page_index->page_len, header->datalen);
7021
7022         /*
7023          * Call the handler, if it exists, to update the
7024          * page to the latest values.
7025          */
7026         if (page_index->sense_handler != NULL)
7027                 page_index->sense_handler(ctsio, page_index, pc);
7028
7029         memcpy(header + 1, page_index->page_data, page_index->page_len);
7030
7031         ctl_set_success(ctsio);
7032         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7033         ctsio->be_move_done = ctl_config_move_done;
7034         ctl_datamove((union ctl_io *)ctsio);
7035         return (CTL_RETVAL_COMPLETE);
7036 }
7037
7038 int
7039 ctl_read_capacity(struct ctl_scsiio *ctsio)
7040 {
7041         struct scsi_read_capacity *cdb;
7042         struct scsi_read_capacity_data *data;
7043         struct ctl_lun *lun;
7044         uint32_t lba;
7045
7046         CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7047
7048         cdb = (struct scsi_read_capacity *)ctsio->cdb;
7049
7050         lba = scsi_4btoul(cdb->addr);
7051         if (((cdb->pmi & SRC_PMI) == 0)
7052          && (lba != 0)) {
7053                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7054                                       /*sks_valid*/ 1,
7055                                       /*command*/ 1,
7056                                       /*field*/ 2,
7057                                       /*bit_valid*/ 0,
7058                                       /*bit*/ 0);
7059                 ctl_done((union ctl_io *)ctsio);
7060                 return (CTL_RETVAL_COMPLETE);
7061         }
7062
7063         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7064
7065         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7066         data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7067         ctsio->residual = 0;
7068         ctsio->kern_data_len = sizeof(*data);
7069         ctsio->kern_total_len = sizeof(*data);
7070         ctsio->kern_data_resid = 0;
7071         ctsio->kern_rel_offset = 0;
7072         ctsio->kern_sg_entries = 0;
7073
7074         /*
7075          * If the maximum LBA is greater than 0xfffffffe, the user must
7076          * issue a SERVICE ACTION IN (16) command, with the read capacity
7077          * serivce action set.
7078          */
7079         if (lun->be_lun->maxlba > 0xfffffffe)
7080                 scsi_ulto4b(0xffffffff, data->addr);
7081         else
7082                 scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7083
7084         /*
7085          * XXX KDM this may not be 512 bytes...
7086          */
7087         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7088
7089         ctl_set_success(ctsio);
7090         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7091         ctsio->be_move_done = ctl_config_move_done;
7092         ctl_datamove((union ctl_io *)ctsio);
7093         return (CTL_RETVAL_COMPLETE);
7094 }
7095
7096 int
7097 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7098 {
7099         struct scsi_read_capacity_16 *cdb;
7100         struct scsi_read_capacity_data_long *data;
7101         struct ctl_lun *lun;
7102         uint64_t lba;
7103         uint32_t alloc_len;
7104
7105         CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7106
7107         cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7108
7109         alloc_len = scsi_4btoul(cdb->alloc_len);
7110         lba = scsi_8btou64(cdb->addr);
7111
7112         if ((cdb->reladr & SRC16_PMI)
7113          && (lba != 0)) {
7114                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7115                                       /*sks_valid*/ 1,
7116                                       /*command*/ 1,
7117                                       /*field*/ 2,
7118                                       /*bit_valid*/ 0,
7119                                       /*bit*/ 0);
7120                 ctl_done((union ctl_io *)ctsio);
7121                 return (CTL_RETVAL_COMPLETE);
7122         }
7123
7124         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7125
7126         ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7127         data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7128
7129         if (sizeof(*data) < alloc_len) {
7130                 ctsio->residual = alloc_len - sizeof(*data);
7131                 ctsio->kern_data_len = sizeof(*data);
7132                 ctsio->kern_total_len = sizeof(*data);
7133         } else {
7134                 ctsio->residual = 0;
7135                 ctsio->kern_data_len = alloc_len;
7136                 ctsio->kern_total_len = alloc_len;
7137         }
7138         ctsio->kern_data_resid = 0;
7139         ctsio->kern_rel_offset = 0;
7140         ctsio->kern_sg_entries = 0;
7141
7142         scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7143         /* XXX KDM this may not be 512 bytes... */
7144         scsi_ulto4b(lun->be_lun->blocksize, data->length);
7145         data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7146         scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7147         if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7148                 data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7149
7150         ctl_set_success(ctsio);
7151         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7152         ctsio->be_move_done = ctl_config_move_done;
7153         ctl_datamove((union ctl_io *)ctsio);
7154         return (CTL_RETVAL_COMPLETE);
7155 }
7156
7157 int
7158 ctl_read_defect(struct ctl_scsiio *ctsio)
7159 {
7160         struct scsi_read_defect_data_10 *ccb10;
7161         struct scsi_read_defect_data_12 *ccb12;
7162         struct scsi_read_defect_data_hdr_10 *data10;
7163         struct scsi_read_defect_data_hdr_12 *data12;
7164         uint32_t alloc_len, data_len;
7165         uint8_t format;
7166
7167         CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7168
7169         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7170                 ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7171                 format = ccb10->format;
7172                 alloc_len = scsi_2btoul(ccb10->alloc_length);
7173                 data_len = sizeof(*data10);
7174         } else {
7175                 ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7176                 format = ccb12->format;
7177                 alloc_len = scsi_4btoul(ccb12->alloc_length);
7178                 data_len = sizeof(*data12);
7179         }
7180         if (alloc_len == 0) {
7181                 ctl_set_success(ctsio);
7182                 ctl_done((union ctl_io *)ctsio);
7183                 return (CTL_RETVAL_COMPLETE);
7184         }
7185
7186         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7187         if (data_len < alloc_len) {
7188                 ctsio->residual = alloc_len - data_len;
7189                 ctsio->kern_data_len = data_len;
7190                 ctsio->kern_total_len = data_len;
7191         } else {
7192                 ctsio->residual = 0;
7193                 ctsio->kern_data_len = alloc_len;
7194                 ctsio->kern_total_len = alloc_len;
7195         }
7196         ctsio->kern_data_resid = 0;
7197         ctsio->kern_rel_offset = 0;
7198         ctsio->kern_sg_entries = 0;
7199
7200         if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7201                 data10 = (struct scsi_read_defect_data_hdr_10 *)
7202                     ctsio->kern_data_ptr;
7203                 data10->format = format;
7204                 scsi_ulto2b(0, data10->length);
7205         } else {
7206                 data12 = (struct scsi_read_defect_data_hdr_12 *)
7207                     ctsio->kern_data_ptr;
7208                 data12->format = format;
7209                 scsi_ulto2b(0, data12->generation);
7210                 scsi_ulto4b(0, data12->length);
7211         }
7212
7213         ctl_set_success(ctsio);
7214         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7215         ctsio->be_move_done = ctl_config_move_done;
7216         ctl_datamove((union ctl_io *)ctsio);
7217         return (CTL_RETVAL_COMPLETE);
7218 }
7219
7220 int
7221 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7222 {
7223         struct scsi_maintenance_in *cdb;
7224         int retval;
7225         int alloc_len, ext, total_len = 0, g, p, pc, pg, gs, os;
7226         int num_target_port_groups, num_target_ports;
7227         struct ctl_lun *lun;
7228         struct ctl_softc *softc;
7229         struct ctl_port *port;
7230         struct scsi_target_group_data *rtg_ptr;
7231         struct scsi_target_group_data_extended *rtg_ext_ptr;
7232         struct scsi_target_port_group_descriptor *tpg_desc;
7233
7234         CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7235
7236         cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7237         softc = control_softc;
7238         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7239
7240         retval = CTL_RETVAL_COMPLETE;
7241
7242         switch (cdb->byte2 & STG_PDF_MASK) {
7243         case STG_PDF_LENGTH:
7244                 ext = 0;
7245                 break;
7246         case STG_PDF_EXTENDED:
7247                 ext = 1;
7248                 break;
7249         default:
7250                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7251                                       /*sks_valid*/ 1,
7252                                       /*command*/ 1,
7253                                       /*field*/ 2,
7254                                       /*bit_valid*/ 1,
7255                                       /*bit*/ 5);
7256                 ctl_done((union ctl_io *)ctsio);
7257                 return(retval);
7258         }
7259
7260         if (softc->is_single)
7261                 num_target_port_groups = 1;
7262         else
7263                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7264         num_target_ports = 0;
7265         mtx_lock(&softc->ctl_lock);
7266         STAILQ_FOREACH(port, &softc->port_list, links) {
7267                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7268                         continue;
7269                 if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7270                         continue;
7271                 num_target_ports++;
7272         }
7273         mtx_unlock(&softc->ctl_lock);
7274
7275         if (ext)
7276                 total_len = sizeof(struct scsi_target_group_data_extended);
7277         else
7278                 total_len = sizeof(struct scsi_target_group_data);
7279         total_len += sizeof(struct scsi_target_port_group_descriptor) *
7280                 num_target_port_groups +
7281             sizeof(struct scsi_target_port_descriptor) *
7282                 num_target_ports * num_target_port_groups;
7283
7284         alloc_len = scsi_4btoul(cdb->length);
7285
7286         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7287
7288         ctsio->kern_sg_entries = 0;
7289
7290         if (total_len < alloc_len) {
7291                 ctsio->residual = alloc_len - total_len;
7292                 ctsio->kern_data_len = total_len;
7293                 ctsio->kern_total_len = total_len;
7294         } else {
7295                 ctsio->residual = 0;
7296                 ctsio->kern_data_len = alloc_len;
7297                 ctsio->kern_total_len = alloc_len;
7298         }
7299         ctsio->kern_data_resid = 0;
7300         ctsio->kern_rel_offset = 0;
7301
7302         if (ext) {
7303                 rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7304                     ctsio->kern_data_ptr;
7305                 scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7306                 rtg_ext_ptr->format_type = 0x10;
7307                 rtg_ext_ptr->implicit_transition_time = 0;
7308                 tpg_desc = &rtg_ext_ptr->groups[0];
7309         } else {
7310                 rtg_ptr = (struct scsi_target_group_data *)
7311                     ctsio->kern_data_ptr;
7312                 scsi_ulto4b(total_len - 4, rtg_ptr->length);
7313                 tpg_desc = &rtg_ptr->groups[0];
7314         }
7315
7316         mtx_lock(&softc->ctl_lock);
7317         pg = softc->port_offset / CTL_MAX_PORTS;
7318         if (softc->flags & CTL_FLAG_ACTIVE_SHELF) {
7319                 if (softc->ha_mode == CTL_HA_MODE_ACT_STBY) {
7320                         gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7321                         os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7322                 } else if (lun->flags & CTL_LUN_PRIMARY_SC) {
7323                         gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7324                         os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7325                 } else {
7326                         gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7327                         os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7328                 }
7329         } else {
7330                 gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7331                 os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7332         }
7333         for (g = 0; g < num_target_port_groups; g++) {
7334                 tpg_desc->pref_state = (g == pg) ? gs : os;
7335                 tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP;
7336                 scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7337                 tpg_desc->status = TPG_IMPLICIT;
7338                 pc = 0;
7339                 STAILQ_FOREACH(port, &softc->port_list, links) {
7340                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7341                                 continue;
7342                         if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7343                             CTL_MAX_LUNS)
7344                                 continue;
7345                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7346                         scsi_ulto2b(p, tpg_desc->descriptors[pc].
7347                             relative_target_port_identifier);
7348                         pc++;
7349                 }
7350                 tpg_desc->target_port_count = pc;
7351                 tpg_desc = (struct scsi_target_port_group_descriptor *)
7352                     &tpg_desc->descriptors[pc];
7353         }
7354         mtx_unlock(&softc->ctl_lock);
7355
7356         ctl_set_success(ctsio);
7357         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7358         ctsio->be_move_done = ctl_config_move_done;
7359         ctl_datamove((union ctl_io *)ctsio);
7360         return(retval);
7361 }
7362
7363 int
7364 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7365 {
7366         struct ctl_lun *lun;
7367         struct scsi_report_supported_opcodes *cdb;
7368         const struct ctl_cmd_entry *entry, *sentry;
7369         struct scsi_report_supported_opcodes_all *all;
7370         struct scsi_report_supported_opcodes_descr *descr;
7371         struct scsi_report_supported_opcodes_one *one;
7372         int retval;
7373         int alloc_len, total_len;
7374         int opcode, service_action, i, j, num;
7375
7376         CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7377
7378         cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7379         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7380
7381         retval = CTL_RETVAL_COMPLETE;
7382
7383         opcode = cdb->requested_opcode;
7384         service_action = scsi_2btoul(cdb->requested_service_action);
7385         switch (cdb->options & RSO_OPTIONS_MASK) {
7386         case RSO_OPTIONS_ALL:
7387                 num = 0;
7388                 for (i = 0; i < 256; i++) {
7389                         entry = &ctl_cmd_table[i];
7390                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7391                                 for (j = 0; j < 32; j++) {
7392                                         sentry = &((const struct ctl_cmd_entry *)
7393                                             entry->execute)[j];
7394                                         if (ctl_cmd_applicable(
7395                                             lun->be_lun->lun_type, sentry))
7396                                                 num++;
7397                                 }
7398                         } else {
7399                                 if (ctl_cmd_applicable(lun->be_lun->lun_type,
7400                                     entry))
7401                                         num++;
7402                         }
7403                 }
7404                 total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7405                     num * sizeof(struct scsi_report_supported_opcodes_descr);
7406                 break;
7407         case RSO_OPTIONS_OC:
7408                 if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7409                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7410                                               /*sks_valid*/ 1,
7411                                               /*command*/ 1,
7412                                               /*field*/ 2,
7413                                               /*bit_valid*/ 1,
7414                                               /*bit*/ 2);
7415                         ctl_done((union ctl_io *)ctsio);
7416                         return (CTL_RETVAL_COMPLETE);
7417                 }
7418                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7419                 break;
7420         case RSO_OPTIONS_OC_SA:
7421                 if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7422                     service_action >= 32) {
7423                         ctl_set_invalid_field(/*ctsio*/ ctsio,
7424                                               /*sks_valid*/ 1,
7425                                               /*command*/ 1,
7426                                               /*field*/ 2,
7427                                               /*bit_valid*/ 1,
7428                                               /*bit*/ 2);
7429                         ctl_done((union ctl_io *)ctsio);
7430                         return (CTL_RETVAL_COMPLETE);
7431                 }
7432                 total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7433                 break;
7434         default:
7435                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7436                                       /*sks_valid*/ 1,
7437                                       /*command*/ 1,
7438                                       /*field*/ 2,
7439                                       /*bit_valid*/ 1,
7440                                       /*bit*/ 2);
7441                 ctl_done((union ctl_io *)ctsio);
7442                 return (CTL_RETVAL_COMPLETE);
7443         }
7444
7445         alloc_len = scsi_4btoul(cdb->length);
7446
7447         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7448
7449         ctsio->kern_sg_entries = 0;
7450
7451         if (total_len < alloc_len) {
7452                 ctsio->residual = alloc_len - total_len;
7453                 ctsio->kern_data_len = total_len;
7454                 ctsio->kern_total_len = total_len;
7455         } else {
7456                 ctsio->residual = 0;
7457                 ctsio->kern_data_len = alloc_len;
7458                 ctsio->kern_total_len = alloc_len;
7459         }
7460         ctsio->kern_data_resid = 0;
7461         ctsio->kern_rel_offset = 0;
7462
7463         switch (cdb->options & RSO_OPTIONS_MASK) {
7464         case RSO_OPTIONS_ALL:
7465                 all = (struct scsi_report_supported_opcodes_all *)
7466                     ctsio->kern_data_ptr;
7467                 num = 0;
7468                 for (i = 0; i < 256; i++) {
7469                         entry = &ctl_cmd_table[i];
7470                         if (entry->flags & CTL_CMD_FLAG_SA5) {
7471                                 for (j = 0; j < 32; j++) {
7472                                         sentry = &((const struct ctl_cmd_entry *)
7473                                             entry->execute)[j];
7474                                         if (!ctl_cmd_applicable(
7475                                             lun->be_lun->lun_type, sentry))
7476                                                 continue;
7477                                         descr = &all->descr[num++];
7478                                         descr->opcode = i;
7479                                         scsi_ulto2b(j, descr->service_action);
7480                                         descr->flags = RSO_SERVACTV;
7481                                         scsi_ulto2b(sentry->length,
7482                                             descr->cdb_length);
7483                                 }
7484                         } else {
7485                                 if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7486                                     entry))
7487                                         continue;
7488                                 descr = &all->descr[num++];
7489                                 descr->opcode = i;
7490                                 scsi_ulto2b(0, descr->service_action);
7491                                 descr->flags = 0;
7492                                 scsi_ulto2b(entry->length, descr->cdb_length);
7493                         }
7494                 }
7495                 scsi_ulto4b(
7496                     num * sizeof(struct scsi_report_supported_opcodes_descr),
7497                     all->length);
7498                 break;
7499         case RSO_OPTIONS_OC:
7500                 one = (struct scsi_report_supported_opcodes_one *)
7501                     ctsio->kern_data_ptr;
7502                 entry = &ctl_cmd_table[opcode];
7503                 goto fill_one;
7504         case RSO_OPTIONS_OC_SA:
7505                 one = (struct scsi_report_supported_opcodes_one *)
7506                     ctsio->kern_data_ptr;
7507                 entry = &ctl_cmd_table[opcode];
7508                 entry = &((const struct ctl_cmd_entry *)
7509                     entry->execute)[service_action];
7510 fill_one:
7511                 if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7512                         one->support = 3;
7513                         scsi_ulto2b(entry->length, one->cdb_length);
7514                         one->cdb_usage[0] = opcode;
7515                         memcpy(&one->cdb_usage[1], entry->usage,
7516                             entry->length - 1);
7517                 } else
7518                         one->support = 1;
7519                 break;
7520         }
7521
7522         ctl_set_success(ctsio);
7523         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7524         ctsio->be_move_done = ctl_config_move_done;
7525         ctl_datamove((union ctl_io *)ctsio);
7526         return(retval);
7527 }
7528
7529 int
7530 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7531 {
7532         struct scsi_report_supported_tmf *cdb;
7533         struct scsi_report_supported_tmf_data *data;
7534         int retval;
7535         int alloc_len, total_len;
7536
7537         CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7538
7539         cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7540
7541         retval = CTL_RETVAL_COMPLETE;
7542
7543         total_len = sizeof(struct scsi_report_supported_tmf_data);
7544         alloc_len = scsi_4btoul(cdb->length);
7545
7546         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7547
7548         ctsio->kern_sg_entries = 0;
7549
7550         if (total_len < alloc_len) {
7551                 ctsio->residual = alloc_len - total_len;
7552                 ctsio->kern_data_len = total_len;
7553                 ctsio->kern_total_len = total_len;
7554         } else {
7555                 ctsio->residual = 0;
7556                 ctsio->kern_data_len = alloc_len;
7557                 ctsio->kern_total_len = alloc_len;
7558         }
7559         ctsio->kern_data_resid = 0;
7560         ctsio->kern_rel_offset = 0;
7561
7562         data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7563         data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7564         data->byte2 |= RST_ITNRS;
7565
7566         ctl_set_success(ctsio);
7567         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7568         ctsio->be_move_done = ctl_config_move_done;
7569         ctl_datamove((union ctl_io *)ctsio);
7570         return (retval);
7571 }
7572
7573 int
7574 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7575 {
7576         struct scsi_report_timestamp *cdb;
7577         struct scsi_report_timestamp_data *data;
7578         struct timeval tv;
7579         int64_t timestamp;
7580         int retval;
7581         int alloc_len, total_len;
7582
7583         CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7584
7585         cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7586
7587         retval = CTL_RETVAL_COMPLETE;
7588
7589         total_len = sizeof(struct scsi_report_timestamp_data);
7590         alloc_len = scsi_4btoul(cdb->length);
7591
7592         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7593
7594         ctsio->kern_sg_entries = 0;
7595
7596         if (total_len < alloc_len) {
7597                 ctsio->residual = alloc_len - total_len;
7598                 ctsio->kern_data_len = total_len;
7599                 ctsio->kern_total_len = total_len;
7600         } else {
7601                 ctsio->residual = 0;
7602                 ctsio->kern_data_len = alloc_len;
7603                 ctsio->kern_total_len = alloc_len;
7604         }
7605         ctsio->kern_data_resid = 0;
7606         ctsio->kern_rel_offset = 0;
7607
7608         data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7609         scsi_ulto2b(sizeof(*data) - 2, data->length);
7610         data->origin = RTS_ORIG_OUTSIDE;
7611         getmicrotime(&tv);
7612         timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7613         scsi_ulto4b(timestamp >> 16, data->timestamp);
7614         scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7615
7616         ctl_set_success(ctsio);
7617         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7618         ctsio->be_move_done = ctl_config_move_done;
7619         ctl_datamove((union ctl_io *)ctsio);
7620         return (retval);
7621 }
7622
7623 int
7624 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7625 {
7626         struct scsi_per_res_in *cdb;
7627         int alloc_len, total_len = 0;
7628         /* struct scsi_per_res_in_rsrv in_data; */
7629         struct ctl_lun *lun;
7630         struct ctl_softc *softc;
7631         uint64_t key;
7632
7633         CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7634
7635         softc = control_softc;
7636
7637         cdb = (struct scsi_per_res_in *)ctsio->cdb;
7638
7639         alloc_len = scsi_2btoul(cdb->length);
7640
7641         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7642
7643 retry:
7644         mtx_lock(&lun->lun_lock);
7645         switch (cdb->action) {
7646         case SPRI_RK: /* read keys */
7647                 total_len = sizeof(struct scsi_per_res_in_keys) +
7648                         lun->pr_key_count *
7649                         sizeof(struct scsi_per_res_key);
7650                 break;
7651         case SPRI_RR: /* read reservation */
7652                 if (lun->flags & CTL_LUN_PR_RESERVED)
7653                         total_len = sizeof(struct scsi_per_res_in_rsrv);
7654                 else
7655                         total_len = sizeof(struct scsi_per_res_in_header);
7656                 break;
7657         case SPRI_RC: /* report capabilities */
7658                 total_len = sizeof(struct scsi_per_res_cap);
7659                 break;
7660         case SPRI_RS: /* read full status */
7661                 total_len = sizeof(struct scsi_per_res_in_header) +
7662                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7663                     lun->pr_key_count;
7664                 break;
7665         default:
7666                 panic("Invalid PR type %x", cdb->action);
7667         }
7668         mtx_unlock(&lun->lun_lock);
7669
7670         ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7671
7672         if (total_len < alloc_len) {
7673                 ctsio->residual = alloc_len - total_len;
7674                 ctsio->kern_data_len = total_len;
7675                 ctsio->kern_total_len = total_len;
7676         } else {
7677                 ctsio->residual = 0;
7678                 ctsio->kern_data_len = alloc_len;
7679                 ctsio->kern_total_len = alloc_len;
7680         }
7681
7682         ctsio->kern_data_resid = 0;
7683         ctsio->kern_rel_offset = 0;
7684         ctsio->kern_sg_entries = 0;
7685
7686         mtx_lock(&lun->lun_lock);
7687         switch (cdb->action) {
7688         case SPRI_RK: { // read keys
7689         struct scsi_per_res_in_keys *res_keys;
7690                 int i, key_count;
7691
7692                 res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7693
7694                 /*
7695                  * We had to drop the lock to allocate our buffer, which
7696                  * leaves time for someone to come in with another
7697                  * persistent reservation.  (That is unlikely, though,
7698                  * since this should be the only persistent reservation
7699                  * command active right now.)
7700                  */
7701                 if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7702                     (lun->pr_key_count *
7703                      sizeof(struct scsi_per_res_key)))){
7704                         mtx_unlock(&lun->lun_lock);
7705                         free(ctsio->kern_data_ptr, M_CTL);
7706                         printf("%s: reservation length changed, retrying\n",
7707                                __func__);
7708                         goto retry;
7709                 }
7710
7711                 scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7712
7713                 scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7714                              lun->pr_key_count, res_keys->header.length);
7715
7716                 for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7717                         if ((key = ctl_get_prkey(lun, i)) == 0)
7718                                 continue;
7719
7720                         /*
7721                          * We used lun->pr_key_count to calculate the
7722                          * size to allocate.  If it turns out the number of
7723                          * initiators with the registered flag set is
7724                          * larger than that (i.e. they haven't been kept in
7725                          * sync), we've got a problem.
7726                          */
7727                         if (key_count >= lun->pr_key_count) {
7728 #ifdef NEEDTOPORT
7729                                 csevent_log(CSC_CTL | CSC_SHELF_SW |
7730                                             CTL_PR_ERROR,
7731                                             csevent_LogType_Fault,
7732                                             csevent_AlertLevel_Yellow,
7733                                             csevent_FRU_ShelfController,
7734                                             csevent_FRU_Firmware,
7735                                         csevent_FRU_Unknown,
7736                                             "registered keys %d >= key "
7737                                             "count %d", key_count,
7738                                             lun->pr_key_count);
7739 #endif
7740                                 key_count++;
7741                                 continue;
7742                         }
7743                         scsi_u64to8b(key, res_keys->keys[key_count].key);
7744                         key_count++;
7745                 }
7746                 break;
7747         }
7748         case SPRI_RR: { // read reservation
7749                 struct scsi_per_res_in_rsrv *res;
7750                 int tmp_len, header_only;
7751
7752                 res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7753
7754                 scsi_ulto4b(lun->PRGeneration, res->header.generation);
7755
7756                 if (lun->flags & CTL_LUN_PR_RESERVED)
7757                 {
7758                         tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7759                         scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7760                                     res->header.length);
7761                         header_only = 0;
7762                 } else {
7763                         tmp_len = sizeof(struct scsi_per_res_in_header);
7764                         scsi_ulto4b(0, res->header.length);
7765                         header_only = 1;
7766                 }
7767
7768                 /*
7769                  * We had to drop the lock to allocate our buffer, which
7770                  * leaves time for someone to come in with another
7771                  * persistent reservation.  (That is unlikely, though,
7772                  * since this should be the only persistent reservation
7773                  * command active right now.)
7774                  */
7775                 if (tmp_len != total_len) {
7776                         mtx_unlock(&lun->lun_lock);
7777                         free(ctsio->kern_data_ptr, M_CTL);
7778                         printf("%s: reservation status changed, retrying\n",
7779                                __func__);
7780                         goto retry;
7781                 }
7782
7783                 /*
7784                  * No reservation held, so we're done.
7785                  */
7786                 if (header_only != 0)
7787                         break;
7788
7789                 /*
7790                  * If the registration is an All Registrants type, the key
7791                  * is 0, since it doesn't really matter.
7792                  */
7793                 if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7794                         scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7795                             res->data.reservation);
7796                 }
7797                 res->data.scopetype = lun->res_type;
7798                 break;
7799         }
7800         case SPRI_RC:     //report capabilities
7801         {
7802                 struct scsi_per_res_cap *res_cap;
7803                 uint16_t type_mask;
7804
7805                 res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7806                 scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7807                 res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7808                 type_mask = SPRI_TM_WR_EX_AR |
7809                             SPRI_TM_EX_AC_RO |
7810                             SPRI_TM_WR_EX_RO |
7811                             SPRI_TM_EX_AC |
7812                             SPRI_TM_WR_EX |
7813                             SPRI_TM_EX_AC_AR;
7814                 scsi_ulto2b(type_mask, res_cap->type_mask);
7815                 break;
7816         }
7817         case SPRI_RS: { // read full status
7818                 struct scsi_per_res_in_full *res_status;
7819                 struct scsi_per_res_in_full_desc *res_desc;
7820                 struct ctl_port *port;
7821                 int i, len;
7822
7823                 res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7824
7825                 /*
7826                  * We had to drop the lock to allocate our buffer, which
7827                  * leaves time for someone to come in with another
7828                  * persistent reservation.  (That is unlikely, though,
7829                  * since this should be the only persistent reservation
7830                  * command active right now.)
7831                  */
7832                 if (total_len < (sizeof(struct scsi_per_res_in_header) +
7833                     (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7834                      lun->pr_key_count)){
7835                         mtx_unlock(&lun->lun_lock);
7836                         free(ctsio->kern_data_ptr, M_CTL);
7837                         printf("%s: reservation length changed, retrying\n",
7838                                __func__);
7839                         goto retry;
7840                 }
7841
7842                 scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7843
7844                 res_desc = &res_status->desc[0];
7845                 for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7846                         if ((key = ctl_get_prkey(lun, i)) == 0)
7847                                 continue;
7848
7849                         scsi_u64to8b(key, res_desc->res_key.key);
7850                         if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7851                             (lun->pr_res_idx == i ||
7852                              lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7853                                 res_desc->flags = SPRI_FULL_R_HOLDER;
7854                                 res_desc->scopetype = lun->res_type;
7855                         }
7856                         scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7857                             res_desc->rel_trgt_port_id);
7858                         len = 0;
7859                         port = softc->ctl_ports[
7860                             ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
7861                         if (port != NULL)
7862                                 len = ctl_create_iid(port,
7863                                     i % CTL_MAX_INIT_PER_PORT,
7864                                     res_desc->transport_id);
7865                         scsi_ulto4b(len, res_desc->additional_length);
7866                         res_desc = (struct scsi_per_res_in_full_desc *)
7867                             &res_desc->transport_id[len];
7868                 }
7869                 scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7870                     res_status->header.length);
7871                 break;
7872         }
7873         default:
7874                 /*
7875                  * This is a bug, because we just checked for this above,
7876                  * and should have returned an error.
7877                  */
7878                 panic("Invalid PR type %x", cdb->action);
7879                 break; /* NOTREACHED */
7880         }
7881         mtx_unlock(&lun->lun_lock);
7882
7883         ctl_set_success(ctsio);
7884         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7885         ctsio->be_move_done = ctl_config_move_done;
7886         ctl_datamove((union ctl_io *)ctsio);
7887         return (CTL_RETVAL_COMPLETE);
7888 }
7889
7890 static void
7891 ctl_set_res_ua(struct ctl_lun *lun, uint32_t residx, ctl_ua_type ua)
7892 {
7893         int off = lun->ctl_softc->persis_offset;
7894
7895         if (residx >= off && residx < off + CTL_MAX_INITIATORS)
7896                 lun->pending_ua[residx - off] |= ua;
7897 }
7898
7899 /*
7900  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7901  * it should return.
7902  */
7903 static int
7904 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7905                 uint64_t sa_res_key, uint8_t type, uint32_t residx,
7906                 struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7907                 struct scsi_per_res_out_parms* param)
7908 {
7909         union ctl_ha_msg persis_io;
7910         int retval, i;
7911         int isc_retval;
7912
7913         retval = 0;
7914
7915         mtx_lock(&lun->lun_lock);
7916         if (sa_res_key == 0) {
7917                 if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7918                         /* validate scope and type */
7919                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7920                              SPR_LU_SCOPE) {
7921                                 mtx_unlock(&lun->lun_lock);
7922                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7923                                                       /*sks_valid*/ 1,
7924                                                       /*command*/ 1,
7925                                                       /*field*/ 2,
7926                                                       /*bit_valid*/ 1,
7927                                                       /*bit*/ 4);
7928                                 ctl_done((union ctl_io *)ctsio);
7929                                 return (1);
7930                         }
7931
7932                         if (type>8 || type==2 || type==4 || type==0) {
7933                                 mtx_unlock(&lun->lun_lock);
7934                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
7935                                                       /*sks_valid*/ 1,
7936                                                       /*command*/ 1,
7937                                                       /*field*/ 2,
7938                                                       /*bit_valid*/ 1,
7939                                                       /*bit*/ 0);
7940                                 ctl_done((union ctl_io *)ctsio);
7941                                 return (1);
7942                         }
7943
7944                         /*
7945                          * Unregister everybody else and build UA for
7946                          * them
7947                          */
7948                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7949                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
7950                                         continue;
7951
7952                                 ctl_clr_prkey(lun, i);
7953                                 ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
7954                         }
7955                         lun->pr_key_count = 1;
7956                         lun->res_type = type;
7957                         if (lun->res_type != SPR_TYPE_WR_EX_AR
7958                          && lun->res_type != SPR_TYPE_EX_AC_AR)
7959                                 lun->pr_res_idx = residx;
7960
7961                         /* send msg to other side */
7962                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7963                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7964                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7965                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
7966                         persis_io.pr.pr_info.res_type = type;
7967                         memcpy(persis_io.pr.pr_info.sa_res_key,
7968                                param->serv_act_res_key,
7969                                sizeof(param->serv_act_res_key));
7970                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7971                              &persis_io, sizeof(persis_io), 0)) >
7972                              CTL_HA_STATUS_SUCCESS) {
7973                                 printf("CTL:Persis Out error returned "
7974                                        "from ctl_ha_msg_send %d\n",
7975                                        isc_retval);
7976                         }
7977                 } else {
7978                         /* not all registrants */
7979                         mtx_unlock(&lun->lun_lock);
7980                         free(ctsio->kern_data_ptr, M_CTL);
7981                         ctl_set_invalid_field(ctsio,
7982                                               /*sks_valid*/ 1,
7983                                               /*command*/ 0,
7984                                               /*field*/ 8,
7985                                               /*bit_valid*/ 0,
7986                                               /*bit*/ 0);
7987                         ctl_done((union ctl_io *)ctsio);
7988                         return (1);
7989                 }
7990         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7991                 || !(lun->flags & CTL_LUN_PR_RESERVED)) {
7992                 int found = 0;
7993
7994                 if (res_key == sa_res_key) {
7995                         /* special case */
7996                         /*
7997                          * The spec implies this is not good but doesn't
7998                          * say what to do. There are two choices either
7999                          * generate a res conflict or check condition
8000                          * with illegal field in parameter data. Since
8001                          * that is what is done when the sa_res_key is
8002                          * zero I'll take that approach since this has
8003                          * to do with the sa_res_key.
8004                          */
8005                         mtx_unlock(&lun->lun_lock);
8006                         free(ctsio->kern_data_ptr, M_CTL);
8007                         ctl_set_invalid_field(ctsio,
8008                                               /*sks_valid*/ 1,
8009                                               /*command*/ 0,
8010                                               /*field*/ 8,
8011                                               /*bit_valid*/ 0,
8012                                               /*bit*/ 0);
8013                         ctl_done((union ctl_io *)ctsio);
8014                         return (1);
8015                 }
8016
8017                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8018                         if (ctl_get_prkey(lun, i) != sa_res_key)
8019                                 continue;
8020
8021                         found = 1;
8022                         ctl_clr_prkey(lun, i);
8023                         lun->pr_key_count--;
8024                         ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8025                 }
8026                 if (!found) {
8027                         mtx_unlock(&lun->lun_lock);
8028                         free(ctsio->kern_data_ptr, M_CTL);
8029                         ctl_set_reservation_conflict(ctsio);
8030                         ctl_done((union ctl_io *)ctsio);
8031                         return (CTL_RETVAL_COMPLETE);
8032                 }
8033                 /* send msg to other side */
8034                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8035                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8036                 persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8037                 persis_io.pr.pr_info.residx = lun->pr_res_idx;
8038                 persis_io.pr.pr_info.res_type = type;
8039                 memcpy(persis_io.pr.pr_info.sa_res_key,
8040                        param->serv_act_res_key,
8041                        sizeof(param->serv_act_res_key));
8042                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8043                      &persis_io, sizeof(persis_io), 0)) >
8044                      CTL_HA_STATUS_SUCCESS) {
8045                         printf("CTL:Persis Out error returned from "
8046                                "ctl_ha_msg_send %d\n", isc_retval);
8047                 }
8048         } else {
8049                 /* Reserved but not all registrants */
8050                 /* sa_res_key is res holder */
8051                 if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8052                         /* validate scope and type */
8053                         if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8054                              SPR_LU_SCOPE) {
8055                                 mtx_unlock(&lun->lun_lock);
8056                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8057                                                       /*sks_valid*/ 1,
8058                                                       /*command*/ 1,
8059                                                       /*field*/ 2,
8060                                                       /*bit_valid*/ 1,
8061                                                       /*bit*/ 4);
8062                                 ctl_done((union ctl_io *)ctsio);
8063                                 return (1);
8064                         }
8065
8066                         if (type>8 || type==2 || type==4 || type==0) {
8067                                 mtx_unlock(&lun->lun_lock);
8068                                 ctl_set_invalid_field(/*ctsio*/ ctsio,
8069                                                       /*sks_valid*/ 1,
8070                                                       /*command*/ 1,
8071                                                       /*field*/ 2,
8072                                                       /*bit_valid*/ 1,
8073                                                       /*bit*/ 0);
8074                                 ctl_done((union ctl_io *)ctsio);
8075                                 return (1);
8076                         }
8077
8078                         /*
8079                          * Do the following:
8080                          * if sa_res_key != res_key remove all
8081                          * registrants w/sa_res_key and generate UA
8082                          * for these registrants(Registrations
8083                          * Preempted) if it wasn't an exclusive
8084                          * reservation generate UA(Reservations
8085                          * Preempted) for all other registered nexuses
8086                          * if the type has changed. Establish the new
8087                          * reservation and holder. If res_key and
8088                          * sa_res_key are the same do the above
8089                          * except don't unregister the res holder.
8090                          */
8091
8092                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8093                                 if (i == residx || ctl_get_prkey(lun, i) == 0)
8094                                         continue;
8095
8096                                 if (sa_res_key == ctl_get_prkey(lun, i)) {
8097                                         ctl_clr_prkey(lun, i);
8098                                         lun->pr_key_count--;
8099                                         ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8100                                 } else if (type != lun->res_type
8101                                         && (lun->res_type == SPR_TYPE_WR_EX_RO
8102                                          || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8103                                         ctl_set_res_ua(lun, i, CTL_UA_RES_RELEASE);
8104                                 }
8105                         }
8106                         lun->res_type = type;
8107                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8108                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8109                                 lun->pr_res_idx = residx;
8110                         else
8111                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8112
8113                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8114                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8115                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8116                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8117                         persis_io.pr.pr_info.res_type = type;
8118                         memcpy(persis_io.pr.pr_info.sa_res_key,
8119                                param->serv_act_res_key,
8120                                sizeof(param->serv_act_res_key));
8121                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8122                              &persis_io, sizeof(persis_io), 0)) >
8123                              CTL_HA_STATUS_SUCCESS) {
8124                                 printf("CTL:Persis Out error returned "
8125                                        "from ctl_ha_msg_send %d\n",
8126                                        isc_retval);
8127                         }
8128                 } else {
8129                         /*
8130                          * sa_res_key is not the res holder just
8131                          * remove registrants
8132                          */
8133                         int found=0;
8134
8135                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8136                                 if (sa_res_key != ctl_get_prkey(lun, i))
8137                                         continue;
8138
8139                                 found = 1;
8140                                 ctl_clr_prkey(lun, i);
8141                                 lun->pr_key_count--;
8142                                 ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8143                         }
8144
8145                         if (!found) {
8146                                 mtx_unlock(&lun->lun_lock);
8147                                 free(ctsio->kern_data_ptr, M_CTL);
8148                                 ctl_set_reservation_conflict(ctsio);
8149                                 ctl_done((union ctl_io *)ctsio);
8150                                 return (1);
8151                         }
8152                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8153                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8154                         persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8155                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8156                         persis_io.pr.pr_info.res_type = type;
8157                         memcpy(persis_io.pr.pr_info.sa_res_key,
8158                                param->serv_act_res_key,
8159                                sizeof(param->serv_act_res_key));
8160                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8161                              &persis_io, sizeof(persis_io), 0)) >
8162                              CTL_HA_STATUS_SUCCESS) {
8163                                 printf("CTL:Persis Out error returned "
8164                                        "from ctl_ha_msg_send %d\n",
8165                                 isc_retval);
8166                         }
8167                 }
8168         }
8169
8170         lun->PRGeneration++;
8171         mtx_unlock(&lun->lun_lock);
8172
8173         return (retval);
8174 }
8175
8176 static void
8177 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8178 {
8179         uint64_t sa_res_key;
8180         int i;
8181
8182         sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8183
8184         if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8185          || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8186          || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8187                 if (sa_res_key == 0) {
8188                         /*
8189                          * Unregister everybody else and build UA for
8190                          * them
8191                          */
8192                         for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8193                                 if (i == msg->pr.pr_info.residx ||
8194                                     ctl_get_prkey(lun, i) == 0)
8195                                         continue;
8196
8197                                 ctl_clr_prkey(lun, i);
8198                                 ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8199                         }
8200
8201                         lun->pr_key_count = 1;
8202                         lun->res_type = msg->pr.pr_info.res_type;
8203                         if (lun->res_type != SPR_TYPE_WR_EX_AR
8204                          && lun->res_type != SPR_TYPE_EX_AC_AR)
8205                                 lun->pr_res_idx = msg->pr.pr_info.residx;
8206                 } else {
8207                         for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8208                                 if (sa_res_key == ctl_get_prkey(lun, i))
8209                                         continue;
8210
8211                                 ctl_clr_prkey(lun, i);
8212                                 lun->pr_key_count--;
8213                                 ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8214                         }
8215                 }
8216         } else {
8217                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8218                         if (i == msg->pr.pr_info.residx ||
8219                             ctl_get_prkey(lun, i) == 0)
8220                                 continue;
8221
8222                         if (sa_res_key == ctl_get_prkey(lun, i)) {
8223                                 ctl_clr_prkey(lun, i);
8224                                 lun->pr_key_count--;
8225                                 ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8226                         } else if (msg->pr.pr_info.res_type != lun->res_type
8227                                 && (lun->res_type == SPR_TYPE_WR_EX_RO
8228                                  || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8229                                 ctl_set_res_ua(lun, i, CTL_UA_RES_RELEASE);
8230                         }
8231                 }
8232                 lun->res_type = msg->pr.pr_info.res_type;
8233                 if (lun->res_type != SPR_TYPE_WR_EX_AR
8234                  && lun->res_type != SPR_TYPE_EX_AC_AR)
8235                         lun->pr_res_idx = msg->pr.pr_info.residx;
8236                 else
8237                         lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8238         }
8239         lun->PRGeneration++;
8240
8241 }
8242
8243
8244 int
8245 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8246 {
8247         int retval;
8248         int isc_retval;
8249         u_int32_t param_len;
8250         struct scsi_per_res_out *cdb;
8251         struct ctl_lun *lun;
8252         struct scsi_per_res_out_parms* param;
8253         struct ctl_softc *softc;
8254         uint32_t residx;
8255         uint64_t res_key, sa_res_key, key;
8256         uint8_t type;
8257         union ctl_ha_msg persis_io;
8258         int    i;
8259
8260         CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8261
8262         retval = CTL_RETVAL_COMPLETE;
8263
8264         softc = control_softc;
8265
8266         cdb = (struct scsi_per_res_out *)ctsio->cdb;
8267         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8268
8269         /*
8270          * We only support whole-LUN scope.  The scope & type are ignored for
8271          * register, register and ignore existing key and clear.
8272          * We sometimes ignore scope and type on preempts too!!
8273          * Verify reservation type here as well.
8274          */
8275         type = cdb->scope_type & SPR_TYPE_MASK;
8276         if ((cdb->action == SPRO_RESERVE)
8277          || (cdb->action == SPRO_RELEASE)) {
8278                 if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8279                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8280                                               /*sks_valid*/ 1,
8281                                               /*command*/ 1,
8282                                               /*field*/ 2,
8283                                               /*bit_valid*/ 1,
8284                                               /*bit*/ 4);
8285                         ctl_done((union ctl_io *)ctsio);
8286                         return (CTL_RETVAL_COMPLETE);
8287                 }
8288
8289                 if (type>8 || type==2 || type==4 || type==0) {
8290                         ctl_set_invalid_field(/*ctsio*/ ctsio,
8291                                               /*sks_valid*/ 1,
8292                                               /*command*/ 1,
8293                                               /*field*/ 2,
8294                                               /*bit_valid*/ 1,
8295                                               /*bit*/ 0);
8296                         ctl_done((union ctl_io *)ctsio);
8297                         return (CTL_RETVAL_COMPLETE);
8298                 }
8299         }
8300
8301         param_len = scsi_4btoul(cdb->length);
8302
8303         if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8304                 ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8305                 ctsio->kern_data_len = param_len;
8306                 ctsio->kern_total_len = param_len;
8307                 ctsio->kern_data_resid = 0;
8308                 ctsio->kern_rel_offset = 0;
8309                 ctsio->kern_sg_entries = 0;
8310                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8311                 ctsio->be_move_done = ctl_config_move_done;
8312                 ctl_datamove((union ctl_io *)ctsio);
8313
8314                 return (CTL_RETVAL_COMPLETE);
8315         }
8316
8317         param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8318
8319         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8320         res_key = scsi_8btou64(param->res_key.key);
8321         sa_res_key = scsi_8btou64(param->serv_act_res_key);
8322
8323         /*
8324          * Validate the reservation key here except for SPRO_REG_IGNO
8325          * This must be done for all other service actions
8326          */
8327         if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8328                 mtx_lock(&lun->lun_lock);
8329                 if ((key = ctl_get_prkey(lun, residx)) != 0) {
8330                         if (res_key != key) {
8331                                 /*
8332                                  * The current key passed in doesn't match
8333                                  * the one the initiator previously
8334                                  * registered.
8335                                  */
8336                                 mtx_unlock(&lun->lun_lock);
8337                                 free(ctsio->kern_data_ptr, M_CTL);
8338                                 ctl_set_reservation_conflict(ctsio);
8339                                 ctl_done((union ctl_io *)ctsio);
8340                                 return (CTL_RETVAL_COMPLETE);
8341                         }
8342                 } else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8343                         /*
8344                          * We are not registered
8345                          */
8346                         mtx_unlock(&lun->lun_lock);
8347                         free(ctsio->kern_data_ptr, M_CTL);
8348                         ctl_set_reservation_conflict(ctsio);
8349                         ctl_done((union ctl_io *)ctsio);
8350                         return (CTL_RETVAL_COMPLETE);
8351                 } else if (res_key != 0) {
8352                         /*
8353                          * We are not registered and trying to register but
8354                          * the register key isn't zero.
8355                          */
8356                         mtx_unlock(&lun->lun_lock);
8357                         free(ctsio->kern_data_ptr, M_CTL);
8358                         ctl_set_reservation_conflict(ctsio);
8359                         ctl_done((union ctl_io *)ctsio);
8360                         return (CTL_RETVAL_COMPLETE);
8361                 }
8362                 mtx_unlock(&lun->lun_lock);
8363         }
8364
8365         switch (cdb->action & SPRO_ACTION_MASK) {
8366         case SPRO_REGISTER:
8367         case SPRO_REG_IGNO: {
8368
8369 #if 0
8370                 printf("Registration received\n");
8371 #endif
8372
8373                 /*
8374                  * We don't support any of these options, as we report in
8375                  * the read capabilities request (see
8376                  * ctl_persistent_reserve_in(), above).
8377                  */
8378                 if ((param->flags & SPR_SPEC_I_PT)
8379                  || (param->flags & SPR_ALL_TG_PT)
8380                  || (param->flags & SPR_APTPL)) {
8381                         int bit_ptr;
8382
8383                         if (param->flags & SPR_APTPL)
8384                                 bit_ptr = 0;
8385                         else if (param->flags & SPR_ALL_TG_PT)
8386                                 bit_ptr = 2;
8387                         else /* SPR_SPEC_I_PT */
8388                                 bit_ptr = 3;
8389
8390                         free(ctsio->kern_data_ptr, M_CTL);
8391                         ctl_set_invalid_field(ctsio,
8392                                               /*sks_valid*/ 1,
8393                                               /*command*/ 0,
8394                                               /*field*/ 20,
8395                                               /*bit_valid*/ 1,
8396                                               /*bit*/ bit_ptr);
8397                         ctl_done((union ctl_io *)ctsio);
8398                         return (CTL_RETVAL_COMPLETE);
8399                 }
8400
8401                 mtx_lock(&lun->lun_lock);
8402
8403                 /*
8404                  * The initiator wants to clear the
8405                  * key/unregister.
8406                  */
8407                 if (sa_res_key == 0) {
8408                         if ((res_key == 0
8409                           && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8410                          || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8411                           && ctl_get_prkey(lun, residx) == 0)) {
8412                                 mtx_unlock(&lun->lun_lock);
8413                                 goto done;
8414                         }
8415
8416                         ctl_clr_prkey(lun, residx);
8417                         lun->pr_key_count--;
8418
8419                         if (residx == lun->pr_res_idx) {
8420                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8421                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8422
8423                                 if ((lun->res_type == SPR_TYPE_WR_EX_RO
8424                                   || lun->res_type == SPR_TYPE_EX_AC_RO)
8425                                  && lun->pr_key_count) {
8426                                         /*
8427                                          * If the reservation is a registrants
8428                                          * only type we need to generate a UA
8429                                          * for other registered inits.  The
8430                                          * sense code should be RESERVATIONS
8431                                          * RELEASED
8432                                          */
8433
8434                                         for (i = 0; i < CTL_MAX_INITIATORS;i++){
8435                                                 if (ctl_get_prkey(lun, i +
8436                                                     softc->persis_offset) == 0)
8437                                                         continue;
8438                                                 lun->pending_ua[i] |=
8439                                                         CTL_UA_RES_RELEASE;
8440                                         }
8441                                 }
8442                                 lun->res_type = 0;
8443                         } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8444                                 if (lun->pr_key_count==0) {
8445                                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8446                                         lun->res_type = 0;
8447                                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8448                                 }
8449                         }
8450                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8451                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8452                         persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8453                         persis_io.pr.pr_info.residx = residx;
8454                         if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8455                              &persis_io, sizeof(persis_io), 0 )) >
8456                              CTL_HA_STATUS_SUCCESS) {
8457                                 printf("CTL:Persis Out error returned from "
8458                                        "ctl_ha_msg_send %d\n", isc_retval);
8459                         }
8460                 } else /* sa_res_key != 0 */ {
8461
8462                         /*
8463                          * If we aren't registered currently then increment
8464                          * the key count and set the registered flag.
8465                          */
8466                         ctl_alloc_prkey(lun, residx);
8467                         if (ctl_get_prkey(lun, residx) == 0)
8468                                 lun->pr_key_count++;
8469                         ctl_set_prkey(lun, residx, sa_res_key);
8470
8471                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8472                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8473                         persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8474                         persis_io.pr.pr_info.residx = residx;
8475                         memcpy(persis_io.pr.pr_info.sa_res_key,
8476                                param->serv_act_res_key,
8477                                sizeof(param->serv_act_res_key));
8478                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8479                              &persis_io, sizeof(persis_io), 0)) >
8480                              CTL_HA_STATUS_SUCCESS) {
8481                                 printf("CTL:Persis Out error returned from "
8482                                        "ctl_ha_msg_send %d\n", isc_retval);
8483                         }
8484                 }
8485                 lun->PRGeneration++;
8486                 mtx_unlock(&lun->lun_lock);
8487
8488                 break;
8489         }
8490         case SPRO_RESERVE:
8491 #if 0
8492                 printf("Reserve executed type %d\n", type);
8493 #endif
8494                 mtx_lock(&lun->lun_lock);
8495                 if (lun->flags & CTL_LUN_PR_RESERVED) {
8496                         /*
8497                          * if this isn't the reservation holder and it's
8498                          * not a "all registrants" type or if the type is
8499                          * different then we have a conflict
8500                          */
8501                         if ((lun->pr_res_idx != residx
8502                           && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8503                          || lun->res_type != type) {
8504                                 mtx_unlock(&lun->lun_lock);
8505                                 free(ctsio->kern_data_ptr, M_CTL);
8506                                 ctl_set_reservation_conflict(ctsio);
8507                                 ctl_done((union ctl_io *)ctsio);
8508                                 return (CTL_RETVAL_COMPLETE);
8509                         }
8510                         mtx_unlock(&lun->lun_lock);
8511                 } else /* create a reservation */ {
8512                         /*
8513                          * If it's not an "all registrants" type record
8514                          * reservation holder
8515                          */
8516                         if (type != SPR_TYPE_WR_EX_AR
8517                          && type != SPR_TYPE_EX_AC_AR)
8518                                 lun->pr_res_idx = residx; /* Res holder */
8519                         else
8520                                 lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8521
8522                         lun->flags |= CTL_LUN_PR_RESERVED;
8523                         lun->res_type = type;
8524
8525                         mtx_unlock(&lun->lun_lock);
8526
8527                         /* send msg to other side */
8528                         persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8529                         persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8530                         persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8531                         persis_io.pr.pr_info.residx = lun->pr_res_idx;
8532                         persis_io.pr.pr_info.res_type = type;
8533                         if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8534                              &persis_io, sizeof(persis_io), 0)) >
8535                              CTL_HA_STATUS_SUCCESS) {
8536                                 printf("CTL:Persis Out error returned from "
8537                                        "ctl_ha_msg_send %d\n", isc_retval);
8538                         }
8539                 }
8540                 break;
8541
8542         case SPRO_RELEASE:
8543                 mtx_lock(&lun->lun_lock);
8544                 if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8545                         /* No reservation exists return good status */
8546                         mtx_unlock(&lun->lun_lock);
8547                         goto done;
8548                 }
8549                 /*
8550                  * Is this nexus a reservation holder?
8551                  */
8552                 if (lun->pr_res_idx != residx
8553                  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8554                         /*
8555                          * not a res holder return good status but
8556                          * do nothing
8557                          */
8558                         mtx_unlock(&lun->lun_lock);
8559                         goto done;
8560                 }
8561
8562                 if (lun->res_type != type) {
8563                         mtx_unlock(&lun->lun_lock);
8564                         free(ctsio->kern_data_ptr, M_CTL);
8565                         ctl_set_illegal_pr_release(ctsio);
8566                         ctl_done((union ctl_io *)ctsio);
8567                         return (CTL_RETVAL_COMPLETE);
8568                 }
8569
8570                 /* okay to release */
8571                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8572                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8573                 lun->res_type = 0;
8574
8575                 /*
8576                  * if this isn't an exclusive access
8577                  * res generate UA for all other
8578                  * registrants.
8579                  */
8580                 if (type != SPR_TYPE_EX_AC
8581                  && type != SPR_TYPE_WR_EX) {
8582                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8583                                 if (i == residx ||
8584                                     ctl_get_prkey(lun,
8585                                      i + softc->persis_offset) == 0)
8586                                         continue;
8587                                 lun->pending_ua[i] |= CTL_UA_RES_RELEASE;
8588                         }
8589                 }
8590                 mtx_unlock(&lun->lun_lock);
8591                 /* Send msg to other side */
8592                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8593                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8594                 persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8595                 if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8596                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8597                         printf("CTL:Persis Out error returned from "
8598                                "ctl_ha_msg_send %d\n", isc_retval);
8599                 }
8600                 break;
8601
8602         case SPRO_CLEAR:
8603                 /* send msg to other side */
8604
8605                 mtx_lock(&lun->lun_lock);
8606                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8607                 lun->res_type = 0;
8608                 lun->pr_key_count = 0;
8609                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8610
8611                 ctl_clr_prkey(lun, residx);
8612                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8613                         if (ctl_get_prkey(lun, i) != 0) {
8614                                 ctl_clr_prkey(lun, i);
8615                                 ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8616                         }
8617                 lun->PRGeneration++;
8618                 mtx_unlock(&lun->lun_lock);
8619                 persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8620                 persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8621                 persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8622                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8623                      sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8624                         printf("CTL:Persis Out error returned from "
8625                                "ctl_ha_msg_send %d\n", isc_retval);
8626                 }
8627                 break;
8628
8629         case SPRO_PREEMPT:
8630         case SPRO_PRE_ABO: {
8631                 int nretval;
8632
8633                 nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8634                                           residx, ctsio, cdb, param);
8635                 if (nretval != 0)
8636                         return (CTL_RETVAL_COMPLETE);
8637                 break;
8638         }
8639         default:
8640                 panic("Invalid PR type %x", cdb->action);
8641         }
8642
8643 done:
8644         free(ctsio->kern_data_ptr, M_CTL);
8645         ctl_set_success(ctsio);
8646         ctl_done((union ctl_io *)ctsio);
8647
8648         return (retval);
8649 }
8650
8651 /*
8652  * This routine is for handling a message from the other SC pertaining to
8653  * persistent reserve out. All the error checking will have been done
8654  * so only perorming the action need be done here to keep the two
8655  * in sync.
8656  */
8657 static void
8658 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8659 {
8660         struct ctl_lun *lun;
8661         struct ctl_softc *softc;
8662         int i;
8663         uint32_t targ_lun;
8664
8665         softc = control_softc;
8666
8667         targ_lun = msg->hdr.nexus.targ_mapped_lun;
8668         lun = softc->ctl_luns[targ_lun];
8669         mtx_lock(&lun->lun_lock);
8670         switch(msg->pr.pr_info.action) {
8671         case CTL_PR_REG_KEY:
8672                 ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8673                 if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8674                         lun->pr_key_count++;
8675                 ctl_set_prkey(lun, msg->pr.pr_info.residx,
8676                     scsi_8btou64(msg->pr.pr_info.sa_res_key));
8677                 lun->PRGeneration++;
8678                 break;
8679
8680         case CTL_PR_UNREG_KEY:
8681                 ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8682                 lun->pr_key_count--;
8683
8684                 /* XXX Need to see if the reservation has been released */
8685                 /* if so do we need to generate UA? */
8686                 if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8687                         lun->flags &= ~CTL_LUN_PR_RESERVED;
8688                         lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8689
8690                         if ((lun->res_type == SPR_TYPE_WR_EX_RO
8691                           || lun->res_type == SPR_TYPE_EX_AC_RO)
8692                          && lun->pr_key_count) {
8693                                 /*
8694                                  * If the reservation is a registrants
8695                                  * only type we need to generate a UA
8696                                  * for other registered inits.  The
8697                                  * sense code should be RESERVATIONS
8698                                  * RELEASED
8699                                  */
8700
8701                                 for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8702                                         if (ctl_get_prkey(lun, i +
8703                                             softc->persis_offset) == 0)
8704                                                 continue;
8705
8706                                         lun->pending_ua[i] |=
8707                                                 CTL_UA_RES_RELEASE;
8708                                 }
8709                         }
8710                         lun->res_type = 0;
8711                 } else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8712                         if (lun->pr_key_count==0) {
8713                                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8714                                 lun->res_type = 0;
8715                                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8716                         }
8717                 }
8718                 lun->PRGeneration++;
8719                 break;
8720
8721         case CTL_PR_RESERVE:
8722                 lun->flags |= CTL_LUN_PR_RESERVED;
8723                 lun->res_type = msg->pr.pr_info.res_type;
8724                 lun->pr_res_idx = msg->pr.pr_info.residx;
8725
8726                 break;
8727
8728         case CTL_PR_RELEASE:
8729                 /*
8730                  * if this isn't an exclusive access res generate UA for all
8731                  * other registrants.
8732                  */
8733                 if (lun->res_type != SPR_TYPE_EX_AC
8734                  && lun->res_type != SPR_TYPE_WR_EX) {
8735                         for (i = 0; i < CTL_MAX_INITIATORS; i++)
8736                                 if (ctl_get_prkey(lun, i + softc->persis_offset) != 0)
8737                                         lun->pending_ua[i] |=
8738                                                 CTL_UA_RES_RELEASE;
8739                 }
8740
8741                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8742                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8743                 lun->res_type = 0;
8744                 break;
8745
8746         case CTL_PR_PREEMPT:
8747                 ctl_pro_preempt_other(lun, msg);
8748                 break;
8749         case CTL_PR_CLEAR:
8750                 lun->flags &= ~CTL_LUN_PR_RESERVED;
8751                 lun->res_type = 0;
8752                 lun->pr_key_count = 0;
8753                 lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8754
8755                 for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8756                         if (ctl_get_prkey(lun, i) == 0)
8757                                 continue;
8758                         ctl_clr_prkey(lun, i);
8759                         ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8760                 }
8761                 lun->PRGeneration++;
8762                 break;
8763         }
8764
8765         mtx_unlock(&lun->lun_lock);
8766 }
8767
8768 int
8769 ctl_read_write(struct ctl_scsiio *ctsio)
8770 {
8771         struct ctl_lun *lun;
8772         struct ctl_lba_len_flags *lbalen;
8773         uint64_t lba;
8774         uint32_t num_blocks;
8775         int flags, retval;
8776         int isread;
8777
8778         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8779
8780         CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8781
8782         flags = 0;
8783         retval = CTL_RETVAL_COMPLETE;
8784
8785         isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8786               || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8787         switch (ctsio->cdb[0]) {
8788         case READ_6:
8789         case WRITE_6: {
8790                 struct scsi_rw_6 *cdb;
8791
8792                 cdb = (struct scsi_rw_6 *)ctsio->cdb;
8793
8794                 lba = scsi_3btoul(cdb->addr);
8795                 /* only 5 bits are valid in the most significant address byte */
8796                 lba &= 0x1fffff;
8797                 num_blocks = cdb->length;
8798                 /*
8799                  * This is correct according to SBC-2.
8800                  */
8801                 if (num_blocks == 0)
8802                         num_blocks = 256;
8803                 break;
8804         }
8805         case READ_10:
8806         case WRITE_10: {
8807                 struct scsi_rw_10 *cdb;
8808
8809                 cdb = (struct scsi_rw_10 *)ctsio->cdb;
8810                 if (cdb->byte2 & SRW10_FUA)
8811                         flags |= CTL_LLF_FUA;
8812                 if (cdb->byte2 & SRW10_DPO)
8813                         flags |= CTL_LLF_DPO;
8814                 lba = scsi_4btoul(cdb->addr);
8815                 num_blocks = scsi_2btoul(cdb->length);
8816                 break;
8817         }
8818         case WRITE_VERIFY_10: {
8819                 struct scsi_write_verify_10 *cdb;
8820
8821                 cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8822                 flags |= CTL_LLF_FUA;
8823                 if (cdb->byte2 & SWV_DPO)
8824                         flags |= CTL_LLF_DPO;
8825                 lba = scsi_4btoul(cdb->addr);
8826                 num_blocks = scsi_2btoul(cdb->length);
8827                 break;
8828         }
8829         case READ_12:
8830         case WRITE_12: {
8831                 struct scsi_rw_12 *cdb;
8832
8833                 cdb = (struct scsi_rw_12 *)ctsio->cdb;
8834                 if (cdb->byte2 & SRW12_FUA)
8835                         flags |= CTL_LLF_FUA;
8836                 if (cdb->byte2 & SRW12_DPO)
8837                         flags |= CTL_LLF_DPO;
8838                 lba = scsi_4btoul(cdb->addr);
8839                 num_blocks = scsi_4btoul(cdb->length);
8840                 break;
8841         }
8842         case WRITE_VERIFY_12: {
8843                 struct scsi_write_verify_12 *cdb;
8844
8845                 cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8846                 flags |= CTL_LLF_FUA;
8847                 if (cdb->byte2 & SWV_DPO)
8848                         flags |= CTL_LLF_DPO;
8849                 lba = scsi_4btoul(cdb->addr);
8850                 num_blocks = scsi_4btoul(cdb->length);
8851                 break;
8852         }
8853         case READ_16:
8854         case WRITE_16: {
8855                 struct scsi_rw_16 *cdb;
8856
8857                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8858                 if (cdb->byte2 & SRW12_FUA)
8859                         flags |= CTL_LLF_FUA;
8860                 if (cdb->byte2 & SRW12_DPO)
8861                         flags |= CTL_LLF_DPO;
8862                 lba = scsi_8btou64(cdb->addr);
8863                 num_blocks = scsi_4btoul(cdb->length);
8864                 break;
8865         }
8866         case WRITE_ATOMIC_16: {
8867                 struct scsi_rw_16 *cdb;
8868
8869                 if (lun->be_lun->atomicblock == 0) {
8870                         ctl_set_invalid_opcode(ctsio);
8871                         ctl_done((union ctl_io *)ctsio);
8872                         return (CTL_RETVAL_COMPLETE);
8873                 }
8874
8875                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
8876                 if (cdb->byte2 & SRW12_FUA)
8877                         flags |= CTL_LLF_FUA;
8878                 if (cdb->byte2 & SRW12_DPO)
8879                         flags |= CTL_LLF_DPO;
8880                 lba = scsi_8btou64(cdb->addr);
8881                 num_blocks = scsi_4btoul(cdb->length);
8882                 if (num_blocks > lun->be_lun->atomicblock) {
8883                         ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8884                             /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8885                             /*bit*/ 0);
8886                         ctl_done((union ctl_io *)ctsio);
8887                         return (CTL_RETVAL_COMPLETE);
8888                 }
8889                 break;
8890         }
8891         case WRITE_VERIFY_16: {
8892                 struct scsi_write_verify_16 *cdb;
8893
8894                 cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8895                 flags |= CTL_LLF_FUA;
8896                 if (cdb->byte2 & SWV_DPO)
8897                         flags |= CTL_LLF_DPO;
8898                 lba = scsi_8btou64(cdb->addr);
8899                 num_blocks = scsi_4btoul(cdb->length);
8900                 break;
8901         }
8902         default:
8903                 /*
8904                  * We got a command we don't support.  This shouldn't
8905                  * happen, commands should be filtered out above us.
8906                  */
8907                 ctl_set_invalid_opcode(ctsio);
8908                 ctl_done((union ctl_io *)ctsio);
8909
8910                 return (CTL_RETVAL_COMPLETE);
8911                 break; /* NOTREACHED */
8912         }
8913
8914         /*
8915          * The first check is to make sure we're in bounds, the second
8916          * check is to catch wrap-around problems.  If the lba + num blocks
8917          * is less than the lba, then we've wrapped around and the block
8918          * range is invalid anyway.
8919          */
8920         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8921          || ((lba + num_blocks) < lba)) {
8922                 ctl_set_lba_out_of_range(ctsio);
8923                 ctl_done((union ctl_io *)ctsio);
8924                 return (CTL_RETVAL_COMPLETE);
8925         }
8926
8927         /*
8928          * According to SBC-3, a transfer length of 0 is not an error.
8929          * Note that this cannot happen with WRITE(6) or READ(6), since 0
8930          * translates to 256 blocks for those commands.
8931          */
8932         if (num_blocks == 0) {
8933                 ctl_set_success(ctsio);
8934                 ctl_done((union ctl_io *)ctsio);
8935                 return (CTL_RETVAL_COMPLETE);
8936         }
8937
8938         /* Set FUA and/or DPO if caches are disabled. */
8939         if (isread) {
8940                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8941                     SCP_RCD) != 0)
8942                         flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8943         } else {
8944                 if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8945                     SCP_WCE) == 0)
8946                         flags |= CTL_LLF_FUA;
8947         }
8948
8949         lbalen = (struct ctl_lba_len_flags *)
8950             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8951         lbalen->lba = lba;
8952         lbalen->len = num_blocks;
8953         lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8954
8955         ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8956         ctsio->kern_rel_offset = 0;
8957
8958         CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8959
8960         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8961
8962         return (retval);
8963 }
8964
8965 static int
8966 ctl_cnw_cont(union ctl_io *io)
8967 {
8968         struct ctl_scsiio *ctsio;
8969         struct ctl_lun *lun;
8970         struct ctl_lba_len_flags *lbalen;
8971         int retval;
8972
8973         ctsio = &io->scsiio;
8974         ctsio->io_hdr.status = CTL_STATUS_NONE;
8975         ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8976         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8977         lbalen = (struct ctl_lba_len_flags *)
8978             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8979         lbalen->flags &= ~CTL_LLF_COMPARE;
8980         lbalen->flags |= CTL_LLF_WRITE;
8981
8982         CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8983         retval = lun->backend->data_submit((union ctl_io *)ctsio);
8984         return (retval);
8985 }
8986
8987 int
8988 ctl_cnw(struct ctl_scsiio *ctsio)
8989 {
8990         struct ctl_lun *lun;
8991         struct ctl_lba_len_flags *lbalen;
8992         uint64_t lba;
8993         uint32_t num_blocks;
8994         int flags, retval;
8995
8996         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8997
8998         CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8999
9000         flags = 0;
9001         retval = CTL_RETVAL_COMPLETE;
9002
9003         switch (ctsio->cdb[0]) {
9004         case COMPARE_AND_WRITE: {
9005                 struct scsi_compare_and_write *cdb;
9006
9007                 cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9008                 if (cdb->byte2 & SRW10_FUA)
9009                         flags |= CTL_LLF_FUA;
9010                 if (cdb->byte2 & SRW10_DPO)
9011                         flags |= CTL_LLF_DPO;
9012                 lba = scsi_8btou64(cdb->addr);
9013                 num_blocks = cdb->length;
9014                 break;
9015         }
9016         default:
9017                 /*
9018                  * We got a command we don't support.  This shouldn't
9019                  * happen, commands should be filtered out above us.
9020                  */
9021                 ctl_set_invalid_opcode(ctsio);
9022                 ctl_done((union ctl_io *)ctsio);
9023
9024                 return (CTL_RETVAL_COMPLETE);
9025                 break; /* NOTREACHED */
9026         }
9027
9028         /*
9029          * The first check is to make sure we're in bounds, the second
9030          * check is to catch wrap-around problems.  If the lba + num blocks
9031          * is less than the lba, then we've wrapped around and the block
9032          * range is invalid anyway.
9033          */
9034         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9035          || ((lba + num_blocks) < lba)) {
9036                 ctl_set_lba_out_of_range(ctsio);
9037                 ctl_done((union ctl_io *)ctsio);
9038                 return (CTL_RETVAL_COMPLETE);
9039         }
9040
9041         /*
9042          * According to SBC-3, a transfer length of 0 is not an error.
9043          */
9044         if (num_blocks == 0) {
9045                 ctl_set_success(ctsio);
9046                 ctl_done((union ctl_io *)ctsio);
9047                 return (CTL_RETVAL_COMPLETE);
9048         }
9049
9050         /* Set FUA if write cache is disabled. */
9051         if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9052             SCP_WCE) == 0)
9053                 flags |= CTL_LLF_FUA;
9054
9055         ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9056         ctsio->kern_rel_offset = 0;
9057
9058         /*
9059          * Set the IO_CONT flag, so that if this I/O gets passed to
9060          * ctl_data_submit_done(), it'll get passed back to
9061          * ctl_ctl_cnw_cont() for further processing.
9062          */
9063         ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9064         ctsio->io_cont = ctl_cnw_cont;
9065
9066         lbalen = (struct ctl_lba_len_flags *)
9067             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9068         lbalen->lba = lba;
9069         lbalen->len = num_blocks;
9070         lbalen->flags = CTL_LLF_COMPARE | flags;
9071
9072         CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9073         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9074         return (retval);
9075 }
9076
9077 int
9078 ctl_verify(struct ctl_scsiio *ctsio)
9079 {
9080         struct ctl_lun *lun;
9081         struct ctl_lba_len_flags *lbalen;
9082         uint64_t lba;
9083         uint32_t num_blocks;
9084         int bytchk, flags;
9085         int retval;
9086
9087         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9088
9089         CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9090
9091         bytchk = 0;
9092         flags = CTL_LLF_FUA;
9093         retval = CTL_RETVAL_COMPLETE;
9094
9095         switch (ctsio->cdb[0]) {
9096         case VERIFY_10: {
9097                 struct scsi_verify_10 *cdb;
9098
9099                 cdb = (struct scsi_verify_10 *)ctsio->cdb;
9100                 if (cdb->byte2 & SVFY_BYTCHK)
9101                         bytchk = 1;
9102                 if (cdb->byte2 & SVFY_DPO)
9103                         flags |= CTL_LLF_DPO;
9104                 lba = scsi_4btoul(cdb->addr);
9105                 num_blocks = scsi_2btoul(cdb->length);
9106                 break;
9107         }
9108         case VERIFY_12: {
9109                 struct scsi_verify_12 *cdb;
9110
9111                 cdb = (struct scsi_verify_12 *)ctsio->cdb;
9112                 if (cdb->byte2 & SVFY_BYTCHK)
9113                         bytchk = 1;
9114                 if (cdb->byte2 & SVFY_DPO)
9115                         flags |= CTL_LLF_DPO;
9116                 lba = scsi_4btoul(cdb->addr);
9117                 num_blocks = scsi_4btoul(cdb->length);
9118                 break;
9119         }
9120         case VERIFY_16: {
9121                 struct scsi_rw_16 *cdb;
9122
9123                 cdb = (struct scsi_rw_16 *)ctsio->cdb;
9124                 if (cdb->byte2 & SVFY_BYTCHK)
9125                         bytchk = 1;
9126                 if (cdb->byte2 & SVFY_DPO)
9127                         flags |= CTL_LLF_DPO;
9128                 lba = scsi_8btou64(cdb->addr);
9129                 num_blocks = scsi_4btoul(cdb->length);
9130                 break;
9131         }
9132         default:
9133                 /*
9134                  * We got a command we don't support.  This shouldn't
9135                  * happen, commands should be filtered out above us.
9136                  */
9137                 ctl_set_invalid_opcode(ctsio);
9138                 ctl_done((union ctl_io *)ctsio);
9139                 return (CTL_RETVAL_COMPLETE);
9140         }
9141
9142         /*
9143          * The first check is to make sure we're in bounds, the second
9144          * check is to catch wrap-around problems.  If the lba + num blocks
9145          * is less than the lba, then we've wrapped around and the block
9146          * range is invalid anyway.
9147          */
9148         if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9149          || ((lba + num_blocks) < lba)) {
9150                 ctl_set_lba_out_of_range(ctsio);
9151                 ctl_done((union ctl_io *)ctsio);
9152                 return (CTL_RETVAL_COMPLETE);
9153         }
9154
9155         /*
9156          * According to SBC-3, a transfer length of 0 is not an error.
9157          */
9158         if (num_blocks == 0) {
9159                 ctl_set_success(ctsio);
9160                 ctl_done((union ctl_io *)ctsio);
9161                 return (CTL_RETVAL_COMPLETE);
9162         }
9163
9164         lbalen = (struct ctl_lba_len_flags *)
9165             &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9166         lbalen->lba = lba;
9167         lbalen->len = num_blocks;
9168         if (bytchk) {
9169                 lbalen->flags = CTL_LLF_COMPARE | flags;
9170                 ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9171         } else {
9172                 lbalen->flags = CTL_LLF_VERIFY | flags;
9173                 ctsio->kern_total_len = 0;
9174         }
9175         ctsio->kern_rel_offset = 0;
9176
9177         CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9178         retval = lun->backend->data_submit((union ctl_io *)ctsio);
9179         return (retval);
9180 }
9181
9182 int
9183 ctl_report_luns(struct ctl_scsiio *ctsio)
9184 {
9185         struct scsi_report_luns *cdb;
9186         struct scsi_report_luns_data *lun_data;
9187         struct ctl_lun *lun, *request_lun;
9188         int num_luns, retval;
9189         uint32_t alloc_len, lun_datalen;
9190         int num_filled, well_known;
9191         uint32_t initidx, targ_lun_id, lun_id;
9192
9193         retval = CTL_RETVAL_COMPLETE;
9194         well_known = 0;
9195
9196         cdb = (struct scsi_report_luns *)ctsio->cdb;
9197
9198         CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9199
9200         mtx_lock(&control_softc->ctl_lock);
9201         num_luns = control_softc->num_luns;
9202         mtx_unlock(&control_softc->ctl_lock);
9203
9204         switch (cdb->select_report) {
9205         case RPL_REPORT_DEFAULT:
9206         case RPL_REPORT_ALL:
9207                 break;
9208         case RPL_REPORT_WELLKNOWN:
9209                 well_known = 1;
9210                 num_luns = 0;
9211                 break;
9212         default:
9213                 ctl_set_invalid_field(ctsio,
9214                                       /*sks_valid*/ 1,
9215                                       /*command*/ 1,
9216                                       /*field*/ 2,
9217                                       /*bit_valid*/ 0,
9218                                       /*bit*/ 0);
9219                 ctl_done((union ctl_io *)ctsio);
9220                 return (retval);
9221                 break; /* NOTREACHED */
9222         }
9223
9224         alloc_len = scsi_4btoul(cdb->length);
9225         /*
9226          * The initiator has to allocate at least 16 bytes for this request,
9227          * so he can at least get the header and the first LUN.  Otherwise
9228          * we reject the request (per SPC-3 rev 14, section 6.21).
9229          */
9230         if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9231             sizeof(struct scsi_report_luns_lundata))) {
9232                 ctl_set_invalid_field(ctsio,
9233                                       /*sks_valid*/ 1,
9234                                       /*command*/ 1,
9235                                       /*field*/ 6,
9236                                       /*bit_valid*/ 0,
9237                                       /*bit*/ 0);
9238                 ctl_done((union ctl_io *)ctsio);
9239                 return (retval);
9240         }
9241
9242         request_lun = (struct ctl_lun *)
9243                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9244
9245         lun_datalen = sizeof(*lun_data) +
9246                 (num_luns * sizeof(struct scsi_report_luns_lundata));
9247
9248         ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9249         lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9250         ctsio->kern_sg_entries = 0;
9251
9252         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9253
9254         mtx_lock(&control_softc->ctl_lock);
9255         for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9256                 lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9257                 if (lun_id >= CTL_MAX_LUNS)
9258                         continue;
9259                 lun = control_softc->ctl_luns[lun_id];
9260                 if (lun == NULL)
9261                         continue;
9262
9263                 if (targ_lun_id <= 0xff) {
9264                         /*
9265                          * Peripheral addressing method, bus number 0.
9266                          */
9267                         lun_data->luns[num_filled].lundata[0] =
9268                                 RPL_LUNDATA_ATYP_PERIPH;
9269                         lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9270                         num_filled++;
9271                 } else if (targ_lun_id <= 0x3fff) {
9272                         /*
9273                          * Flat addressing method.
9274                          */
9275                         lun_data->luns[num_filled].lundata[0] =
9276                                 RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9277                         lun_data->luns[num_filled].lundata[1] =
9278                                 (targ_lun_id & 0xff);
9279                         num_filled++;
9280                 } else if (targ_lun_id <= 0xffffff) {
9281                         /*
9282                          * Extended flat addressing method.
9283                          */
9284                         lun_data->luns[num_filled].lundata[0] =
9285                             RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9286                         scsi_ulto3b(targ_lun_id,
9287                             &lun_data->luns[num_filled].lundata[1]);
9288                         num_filled++;
9289                 } else {
9290                         printf("ctl_report_luns: bogus LUN number %jd, "
9291                                "skipping\n", (intmax_t)targ_lun_id);
9292                 }
9293                 /*
9294                  * According to SPC-3, rev 14 section 6.21:
9295                  *
9296                  * "The execution of a REPORT LUNS command to any valid and
9297                  * installed logical unit shall clear the REPORTED LUNS DATA
9298                  * HAS CHANGED unit attention condition for all logical
9299                  * units of that target with respect to the requesting
9300                  * initiator. A valid and installed logical unit is one
9301                  * having a PERIPHERAL QUALIFIER of 000b in the standard
9302                  * INQUIRY data (see 6.4.2)."
9303                  *
9304                  * If request_lun is NULL, the LUN this report luns command
9305                  * was issued to is either disabled or doesn't exist. In that
9306                  * case, we shouldn't clear any pending lun change unit
9307                  * attention.
9308                  */
9309                 if (request_lun != NULL) {
9310                         mtx_lock(&lun->lun_lock);
9311                         lun->pending_ua[initidx] &= ~CTL_UA_LUN_CHANGE;
9312                         mtx_unlock(&lun->lun_lock);
9313                 }
9314         }
9315         mtx_unlock(&control_softc->ctl_lock);
9316
9317         /*
9318          * It's quite possible that we've returned fewer LUNs than we allocated
9319          * space for.  Trim it.
9320          */
9321         lun_datalen = sizeof(*lun_data) +
9322                 (num_filled * sizeof(struct scsi_report_luns_lundata));
9323
9324         if (lun_datalen < alloc_len) {
9325                 ctsio->residual = alloc_len - lun_datalen;
9326                 ctsio->kern_data_len = lun_datalen;
9327                 ctsio->kern_total_len = lun_datalen;
9328         } else {
9329                 ctsio->residual = 0;
9330                 ctsio->kern_data_len = alloc_len;
9331                 ctsio->kern_total_len = alloc_len;
9332         }
9333         ctsio->kern_data_resid = 0;
9334         ctsio->kern_rel_offset = 0;
9335         ctsio->kern_sg_entries = 0;
9336
9337         /*
9338          * We set this to the actual data length, regardless of how much
9339          * space we actually have to return results.  If the user looks at
9340          * this value, he'll know whether or not he allocated enough space
9341          * and reissue the command if necessary.  We don't support well
9342          * known logical units, so if the user asks for that, return none.
9343          */
9344         scsi_ulto4b(lun_datalen - 8, lun_data->length);
9345
9346         /*
9347          * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9348          * this request.
9349          */
9350         ctl_set_success(ctsio);
9351         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9352         ctsio->be_move_done = ctl_config_move_done;
9353         ctl_datamove((union ctl_io *)ctsio);
9354         return (retval);
9355 }
9356
9357 int
9358 ctl_request_sense(struct ctl_scsiio *ctsio)
9359 {
9360         struct scsi_request_sense *cdb;
9361         struct scsi_sense_data *sense_ptr;
9362         struct ctl_lun *lun;
9363         uint32_t initidx;
9364         int have_error;
9365         scsi_sense_data_type sense_format;
9366
9367         cdb = (struct scsi_request_sense *)ctsio->cdb;
9368
9369         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9370
9371         CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9372
9373         /*
9374          * Determine which sense format the user wants.
9375          */
9376         if (cdb->byte2 & SRS_DESC)
9377                 sense_format = SSD_TYPE_DESC;
9378         else
9379                 sense_format = SSD_TYPE_FIXED;
9380
9381         ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9382         sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9383         ctsio->kern_sg_entries = 0;
9384
9385         /*
9386          * struct scsi_sense_data, which is currently set to 256 bytes, is
9387          * larger than the largest allowed value for the length field in the
9388          * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9389          */
9390         ctsio->residual = 0;
9391         ctsio->kern_data_len = cdb->length;
9392         ctsio->kern_total_len = cdb->length;
9393
9394         ctsio->kern_data_resid = 0;
9395         ctsio->kern_rel_offset = 0;
9396         ctsio->kern_sg_entries = 0;
9397
9398         /*
9399          * If we don't have a LUN, we don't have any pending sense.
9400          */
9401         if (lun == NULL)
9402                 goto no_sense;
9403
9404         have_error = 0;
9405         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9406         /*
9407          * Check for pending sense, and then for pending unit attentions.
9408          * Pending sense gets returned first, then pending unit attentions.
9409          */
9410         mtx_lock(&lun->lun_lock);
9411 #ifdef CTL_WITH_CA
9412         if (ctl_is_set(lun->have_ca, initidx)) {
9413                 scsi_sense_data_type stored_format;
9414
9415                 /*
9416                  * Check to see which sense format was used for the stored
9417                  * sense data.
9418                  */
9419                 stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9420
9421                 /*
9422                  * If the user requested a different sense format than the
9423                  * one we stored, then we need to convert it to the other
9424                  * format.  If we're going from descriptor to fixed format
9425                  * sense data, we may lose things in translation, depending
9426                  * on what options were used.
9427                  *
9428                  * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9429                  * for some reason we'll just copy it out as-is.
9430                  */
9431                 if ((stored_format == SSD_TYPE_FIXED)
9432                  && (sense_format == SSD_TYPE_DESC))
9433                         ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9434                             &lun->pending_sense[initidx],
9435                             (struct scsi_sense_data_desc *)sense_ptr);
9436                 else if ((stored_format == SSD_TYPE_DESC)
9437                       && (sense_format == SSD_TYPE_FIXED))
9438                         ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9439                             &lun->pending_sense[initidx],
9440                             (struct scsi_sense_data_fixed *)sense_ptr);
9441                 else
9442                         memcpy(sense_ptr, &lun->pending_sense[initidx],
9443                                ctl_min(sizeof(*sense_ptr),
9444                                sizeof(lun->pending_sense[initidx])));
9445
9446                 ctl_clear_mask(lun->have_ca, initidx);
9447                 have_error = 1;
9448         } else
9449 #endif
9450         if (lun->pending_ua[initidx] != CTL_UA_NONE) {
9451                 ctl_ua_type ua_type;
9452
9453                 ua_type = ctl_build_ua(&lun->pending_ua[initidx],
9454                                        sense_ptr, sense_format);
9455                 if (ua_type != CTL_UA_NONE)
9456                         have_error = 1;
9457         }
9458         mtx_unlock(&lun->lun_lock);
9459
9460         /*
9461          * We already have a pending error, return it.
9462          */
9463         if (have_error != 0) {
9464                 /*
9465                  * We report the SCSI status as OK, since the status of the
9466                  * request sense command itself is OK.
9467                  * We report 0 for the sense length, because we aren't doing
9468                  * autosense in this case.  We're reporting sense as
9469                  * parameter data.
9470                  */
9471                 ctl_set_success(ctsio);
9472                 ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9473                 ctsio->be_move_done = ctl_config_move_done;
9474                 ctl_datamove((union ctl_io *)ctsio);
9475                 return (CTL_RETVAL_COMPLETE);
9476         }
9477
9478 no_sense:
9479
9480         /*
9481          * No sense information to report, so we report that everything is
9482          * okay.
9483          */
9484         ctl_set_sense_data(sense_ptr,
9485                            lun,
9486                            sense_format,
9487                            /*current_error*/ 1,
9488                            /*sense_key*/ SSD_KEY_NO_SENSE,
9489                            /*asc*/ 0x00,
9490                            /*ascq*/ 0x00,
9491                            SSD_ELEM_NONE);
9492
9493         /*
9494          * We report 0 for the sense length, because we aren't doing
9495          * autosense in this case.  We're reporting sense as parameter data.
9496          */
9497         ctl_set_success(ctsio);
9498         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9499         ctsio->be_move_done = ctl_config_move_done;
9500         ctl_datamove((union ctl_io *)ctsio);
9501         return (CTL_RETVAL_COMPLETE);
9502 }
9503
9504 int
9505 ctl_tur(struct ctl_scsiio *ctsio)
9506 {
9507
9508         CTL_DEBUG_PRINT(("ctl_tur\n"));
9509
9510         ctl_set_success(ctsio);
9511         ctl_done((union ctl_io *)ctsio);
9512
9513         return (CTL_RETVAL_COMPLETE);
9514 }
9515
9516 #ifdef notyet
9517 static int
9518 ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9519 {
9520
9521 }
9522 #endif
9523
9524 static int
9525 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9526 {
9527         struct scsi_vpd_supported_pages *pages;
9528         int sup_page_size;
9529         struct ctl_lun *lun;
9530
9531         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9532
9533         sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9534             SCSI_EVPD_NUM_SUPPORTED_PAGES;
9535         ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9536         pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9537         ctsio->kern_sg_entries = 0;
9538
9539         if (sup_page_size < alloc_len) {
9540                 ctsio->residual = alloc_len - sup_page_size;
9541                 ctsio->kern_data_len = sup_page_size;
9542                 ctsio->kern_total_len = sup_page_size;
9543         } else {
9544                 ctsio->residual = 0;
9545                 ctsio->kern_data_len = alloc_len;
9546                 ctsio->kern_total_len = alloc_len;
9547         }
9548         ctsio->kern_data_resid = 0;
9549         ctsio->kern_rel_offset = 0;
9550         ctsio->kern_sg_entries = 0;
9551
9552         /*
9553          * The control device is always connected.  The disk device, on the
9554          * other hand, may not be online all the time.  Need to change this
9555          * to figure out whether the disk device is actually online or not.
9556          */
9557         if (lun != NULL)
9558                 pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9559                                 lun->be_lun->lun_type;
9560         else
9561                 pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9562
9563         pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9564         /* Supported VPD pages */
9565         pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9566         /* Serial Number */
9567         pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9568         /* Device Identification */
9569         pages->page_list[2] = SVPD_DEVICE_ID;
9570         /* Extended INQUIRY Data */
9571         pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9572         /* Mode Page Policy */
9573         pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9574         /* SCSI Ports */
9575         pages->page_list[5] = SVPD_SCSI_PORTS;
9576         /* Third-party Copy */
9577         pages->page_list[6] = SVPD_SCSI_TPC;
9578         /* Block limits */
9579         pages->page_list[7] = SVPD_BLOCK_LIMITS;
9580         /* Block Device Characteristics */
9581         pages->page_list[8] = SVPD_BDC;
9582         /* Logical Block Provisioning */
9583         pages->page_list[9] = SVPD_LBP;
9584
9585         ctl_set_success(ctsio);
9586         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9587         ctsio->be_move_done = ctl_config_move_done;
9588         ctl_datamove((union ctl_io *)ctsio);
9589         return (CTL_RETVAL_COMPLETE);
9590 }
9591
9592 static int
9593 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9594 {
9595         struct scsi_vpd_unit_serial_number *sn_ptr;
9596         struct ctl_lun *lun;
9597         int data_len;
9598
9599         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9600
9601         data_len = 4 + CTL_SN_LEN;
9602         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9603         sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9604         if (data_len < alloc_len) {
9605                 ctsio->residual = alloc_len - data_len;
9606                 ctsio->kern_data_len = data_len;
9607                 ctsio->kern_total_len = data_len;
9608         } else {
9609                 ctsio->residual = 0;
9610                 ctsio->kern_data_len = alloc_len;
9611                 ctsio->kern_total_len = alloc_len;
9612         }
9613         ctsio->kern_data_resid = 0;
9614         ctsio->kern_rel_offset = 0;
9615         ctsio->kern_sg_entries = 0;
9616
9617         /*
9618          * The control device is always connected.  The disk device, on the
9619          * other hand, may not be online all the time.  Need to change this
9620          * to figure out whether the disk device is actually online or not.
9621          */
9622         if (lun != NULL)
9623                 sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9624                                   lun->be_lun->lun_type;
9625         else
9626                 sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9627
9628         sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9629         sn_ptr->length = CTL_SN_LEN;
9630         /*
9631          * If we don't have a LUN, we just leave the serial number as
9632          * all spaces.
9633          */
9634         if (lun != NULL) {
9635                 strncpy((char *)sn_ptr->serial_num,
9636                         (char *)lun->be_lun->serial_num, CTL_SN_LEN);
9637         } else
9638                 memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9639
9640         ctl_set_success(ctsio);
9641         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9642         ctsio->be_move_done = ctl_config_move_done;
9643         ctl_datamove((union ctl_io *)ctsio);
9644         return (CTL_RETVAL_COMPLETE);
9645 }
9646
9647
9648 static int
9649 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9650 {
9651         struct scsi_vpd_extended_inquiry_data *eid_ptr;
9652         struct ctl_lun *lun;
9653         int data_len;
9654
9655         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9656
9657         data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9658         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9659         eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9660         ctsio->kern_sg_entries = 0;
9661
9662         if (data_len < alloc_len) {
9663                 ctsio->residual = alloc_len - data_len;
9664                 ctsio->kern_data_len = data_len;
9665                 ctsio->kern_total_len = data_len;
9666         } else {
9667                 ctsio->residual = 0;
9668                 ctsio->kern_data_len = alloc_len;
9669                 ctsio->kern_total_len = alloc_len;
9670         }
9671         ctsio->kern_data_resid = 0;
9672         ctsio->kern_rel_offset = 0;
9673         ctsio->kern_sg_entries = 0;
9674
9675         /*
9676          * The control device is always connected.  The disk device, on the
9677          * other hand, may not be online all the time.
9678          */
9679         if (lun != NULL)
9680                 eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9681                                      lun->be_lun->lun_type;
9682         else
9683                 eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9684         eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9685         eid_ptr->page_length = data_len - 4;
9686         eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9687         eid_ptr->flags3 = SVPD_EID_V_SUP;
9688
9689         ctl_set_success(ctsio);
9690         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9691         ctsio->be_move_done = ctl_config_move_done;
9692         ctl_datamove((union ctl_io *)ctsio);
9693         return (CTL_RETVAL_COMPLETE);
9694 }
9695
9696 static int
9697 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9698 {
9699         struct scsi_vpd_mode_page_policy *mpp_ptr;
9700         struct ctl_lun *lun;
9701         int data_len;
9702
9703         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9704
9705         data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9706             sizeof(struct scsi_vpd_mode_page_policy_descr);
9707
9708         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9709         mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9710         ctsio->kern_sg_entries = 0;
9711
9712         if (data_len < alloc_len) {
9713                 ctsio->residual = alloc_len - data_len;
9714                 ctsio->kern_data_len = data_len;
9715                 ctsio->kern_total_len = data_len;
9716         } else {
9717                 ctsio->residual = 0;
9718                 ctsio->kern_data_len = alloc_len;
9719                 ctsio->kern_total_len = alloc_len;
9720         }
9721         ctsio->kern_data_resid = 0;
9722         ctsio->kern_rel_offset = 0;
9723         ctsio->kern_sg_entries = 0;
9724
9725         /*
9726          * The control device is always connected.  The disk device, on the
9727          * other hand, may not be online all the time.
9728          */
9729         if (lun != NULL)
9730                 mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9731                                      lun->be_lun->lun_type;
9732         else
9733                 mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9734         mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9735         scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9736         mpp_ptr->descr[0].page_code = 0x3f;
9737         mpp_ptr->descr[0].subpage_code = 0xff;
9738         mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9739
9740         ctl_set_success(ctsio);
9741         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9742         ctsio->be_move_done = ctl_config_move_done;
9743         ctl_datamove((union ctl_io *)ctsio);
9744         return (CTL_RETVAL_COMPLETE);
9745 }
9746
9747 static int
9748 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9749 {
9750         struct scsi_vpd_device_id *devid_ptr;
9751         struct scsi_vpd_id_descriptor *desc;
9752         struct ctl_softc *ctl_softc;
9753         struct ctl_lun *lun;
9754         struct ctl_port *port;
9755         int data_len;
9756         uint8_t proto;
9757
9758         ctl_softc = control_softc;
9759
9760         port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9761         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9762
9763         data_len = sizeof(struct scsi_vpd_device_id) +
9764             sizeof(struct scsi_vpd_id_descriptor) +
9765                 sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9766             sizeof(struct scsi_vpd_id_descriptor) +
9767                 sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9768         if (lun && lun->lun_devid)
9769                 data_len += lun->lun_devid->len;
9770         if (port->port_devid)
9771                 data_len += port->port_devid->len;
9772         if (port->target_devid)
9773                 data_len += port->target_devid->len;
9774
9775         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9776         devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9777         ctsio->kern_sg_entries = 0;
9778
9779         if (data_len < alloc_len) {
9780                 ctsio->residual = alloc_len - data_len;
9781                 ctsio->kern_data_len = data_len;
9782                 ctsio->kern_total_len = data_len;
9783         } else {
9784                 ctsio->residual = 0;
9785                 ctsio->kern_data_len = alloc_len;
9786                 ctsio->kern_total_len = alloc_len;
9787         }
9788         ctsio->kern_data_resid = 0;
9789         ctsio->kern_rel_offset = 0;
9790         ctsio->kern_sg_entries = 0;
9791
9792         /*
9793          * The control device is always connected.  The disk device, on the
9794          * other hand, may not be online all the time.
9795          */
9796         if (lun != NULL)
9797                 devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9798                                      lun->be_lun->lun_type;
9799         else
9800                 devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9801         devid_ptr->page_code = SVPD_DEVICE_ID;
9802         scsi_ulto2b(data_len - 4, devid_ptr->length);
9803
9804         if (port->port_type == CTL_PORT_FC)
9805                 proto = SCSI_PROTO_FC << 4;
9806         else if (port->port_type == CTL_PORT_ISCSI)
9807                 proto = SCSI_PROTO_ISCSI << 4;
9808         else
9809                 proto = SCSI_PROTO_SPI << 4;
9810         desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9811
9812         /*
9813          * We're using a LUN association here.  i.e., this device ID is a
9814          * per-LUN identifier.
9815          */
9816         if (lun && lun->lun_devid) {
9817                 memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9818                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9819                     lun->lun_devid->len);
9820         }
9821
9822         /*
9823          * This is for the WWPN which is a port association.
9824          */
9825         if (port->port_devid) {
9826                 memcpy(desc, port->port_devid->data, port->port_devid->len);
9827                 desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9828                     port->port_devid->len);
9829         }
9830
9831         /*
9832          * This is for the Relative Target Port(type 4h) identifier
9833          */
9834         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9835         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9836             SVPD_ID_TYPE_RELTARG;
9837         desc->length = 4;
9838         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9839         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9840             sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9841
9842         /*
9843          * This is for the Target Port Group(type 5h) identifier
9844          */
9845         desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9846         desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9847             SVPD_ID_TYPE_TPORTGRP;
9848         desc->length = 4;
9849         scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
9850             &desc->identifier[2]);
9851         desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9852             sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9853
9854         /*
9855          * This is for the Target identifier
9856          */
9857         if (port->target_devid) {
9858                 memcpy(desc, port->target_devid->data, port->target_devid->len);
9859         }
9860
9861         ctl_set_success(ctsio);
9862         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9863         ctsio->be_move_done = ctl_config_move_done;
9864         ctl_datamove((union ctl_io *)ctsio);
9865         return (CTL_RETVAL_COMPLETE);
9866 }
9867
9868 static int
9869 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9870 {
9871         struct ctl_softc *softc = control_softc;
9872         struct scsi_vpd_scsi_ports *sp;
9873         struct scsi_vpd_port_designation *pd;
9874         struct scsi_vpd_port_designation_cont *pdc;
9875         struct ctl_lun *lun;
9876         struct ctl_port *port;
9877         int data_len, num_target_ports, iid_len, id_len, g, pg, p;
9878         int num_target_port_groups;
9879
9880         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9881
9882         if (softc->is_single)
9883                 num_target_port_groups = 1;
9884         else
9885                 num_target_port_groups = NUM_TARGET_PORT_GROUPS;
9886         num_target_ports = 0;
9887         iid_len = 0;
9888         id_len = 0;
9889         mtx_lock(&softc->ctl_lock);
9890         STAILQ_FOREACH(port, &softc->port_list, links) {
9891                 if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9892                         continue;
9893                 if (lun != NULL &&
9894                     ctl_map_lun_back(port->targ_port, lun->lun) >=
9895                     CTL_MAX_LUNS)
9896                         continue;
9897                 num_target_ports++;
9898                 if (port->init_devid)
9899                         iid_len += port->init_devid->len;
9900                 if (port->port_devid)
9901                         id_len += port->port_devid->len;
9902         }
9903         mtx_unlock(&softc->ctl_lock);
9904
9905         data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
9906             num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9907              sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9908         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9909         sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9910         ctsio->kern_sg_entries = 0;
9911
9912         if (data_len < alloc_len) {
9913                 ctsio->residual = alloc_len - data_len;
9914                 ctsio->kern_data_len = data_len;
9915                 ctsio->kern_total_len = data_len;
9916         } else {
9917                 ctsio->residual = 0;
9918                 ctsio->kern_data_len = alloc_len;
9919                 ctsio->kern_total_len = alloc_len;
9920         }
9921         ctsio->kern_data_resid = 0;
9922         ctsio->kern_rel_offset = 0;
9923         ctsio->kern_sg_entries = 0;
9924
9925         /*
9926          * The control device is always connected.  The disk device, on the
9927          * other hand, may not be online all the time.  Need to change this
9928          * to figure out whether the disk device is actually online or not.
9929          */
9930         if (lun != NULL)
9931                 sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9932                                   lun->be_lun->lun_type;
9933         else
9934                 sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9935
9936         sp->page_code = SVPD_SCSI_PORTS;
9937         scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9938             sp->page_length);
9939         pd = &sp->design[0];
9940
9941         mtx_lock(&softc->ctl_lock);
9942         pg = softc->port_offset / CTL_MAX_PORTS;
9943         for (g = 0; g < num_target_port_groups; g++) {
9944                 STAILQ_FOREACH(port, &softc->port_list, links) {
9945                         if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9946                                 continue;
9947                         if (lun != NULL &&
9948                             ctl_map_lun_back(port->targ_port, lun->lun) >=
9949                             CTL_MAX_LUNS)
9950                                 continue;
9951                         p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
9952                         scsi_ulto2b(p, pd->relative_port_id);
9953                         if (port->init_devid && g == pg) {
9954                                 iid_len = port->init_devid->len;
9955                                 memcpy(pd->initiator_transportid,
9956                                     port->init_devid->data, port->init_devid->len);
9957                         } else
9958                                 iid_len = 0;
9959                         scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9960                         pdc = (struct scsi_vpd_port_designation_cont *)
9961                             (&pd->initiator_transportid[iid_len]);
9962                         if (port->port_devid && g == pg) {
9963                                 id_len = port->port_devid->len;
9964                                 memcpy(pdc->target_port_descriptors,
9965                                     port->port_devid->data, port->port_devid->len);
9966                         } else
9967                                 id_len = 0;
9968                         scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9969                         pd = (struct scsi_vpd_port_designation *)
9970                             ((uint8_t *)pdc->target_port_descriptors + id_len);
9971                 }
9972         }
9973         mtx_unlock(&softc->ctl_lock);
9974
9975         ctl_set_success(ctsio);
9976         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9977         ctsio->be_move_done = ctl_config_move_done;
9978         ctl_datamove((union ctl_io *)ctsio);
9979         return (CTL_RETVAL_COMPLETE);
9980 }
9981
9982 static int
9983 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9984 {
9985         struct scsi_vpd_block_limits *bl_ptr;
9986         struct ctl_lun *lun;
9987         int bs;
9988
9989         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9990
9991         ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9992         bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9993         ctsio->kern_sg_entries = 0;
9994
9995         if (sizeof(*bl_ptr) < alloc_len) {
9996                 ctsio->residual = alloc_len - sizeof(*bl_ptr);
9997                 ctsio->kern_data_len = sizeof(*bl_ptr);
9998                 ctsio->kern_total_len = sizeof(*bl_ptr);
9999         } else {
10000                 ctsio->residual = 0;
10001                 ctsio->kern_data_len = alloc_len;
10002                 ctsio->kern_total_len = alloc_len;
10003         }
10004         ctsio->kern_data_resid = 0;
10005         ctsio->kern_rel_offset = 0;
10006         ctsio->kern_sg_entries = 0;
10007
10008         /*
10009          * The control device is always connected.  The disk device, on the
10010          * other hand, may not be online all the time.  Need to change this
10011          * to figure out whether the disk device is actually online or not.
10012          */
10013         if (lun != NULL)
10014                 bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10015                                   lun->be_lun->lun_type;
10016         else
10017                 bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10018
10019         bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10020         scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10021         bl_ptr->max_cmp_write_len = 0xff;
10022         scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10023         if (lun != NULL) {
10024                 bs = lun->be_lun->blocksize;
10025                 scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10026                 if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10027                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10028                         scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10029                         if (lun->be_lun->pblockexp != 0) {
10030                                 scsi_ulto4b((1 << lun->be_lun->pblockexp),
10031                                     bl_ptr->opt_unmap_grain);
10032                                 scsi_ulto4b(0x80000000 | lun->be_lun->pblockoff,
10033                                     bl_ptr->unmap_grain_align);
10034                         }
10035                 }
10036                 scsi_ulto4b(lun->be_lun->atomicblock,
10037                     bl_ptr->max_atomic_transfer_length);
10038                 scsi_ulto4b(0, bl_ptr->atomic_alignment);
10039                 scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10040         }
10041         scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10042
10043         ctl_set_success(ctsio);
10044         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10045         ctsio->be_move_done = ctl_config_move_done;
10046         ctl_datamove((union ctl_io *)ctsio);
10047         return (CTL_RETVAL_COMPLETE);
10048 }
10049
10050 static int
10051 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10052 {
10053         struct scsi_vpd_block_device_characteristics *bdc_ptr;
10054         struct ctl_lun *lun;
10055         const char *value;
10056         u_int i;
10057
10058         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10059
10060         ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10061         bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10062         ctsio->kern_sg_entries = 0;
10063
10064         if (sizeof(*bdc_ptr) < alloc_len) {
10065                 ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10066                 ctsio->kern_data_len = sizeof(*bdc_ptr);
10067                 ctsio->kern_total_len = sizeof(*bdc_ptr);
10068         } else {
10069                 ctsio->residual = 0;
10070                 ctsio->kern_data_len = alloc_len;
10071                 ctsio->kern_total_len = alloc_len;
10072         }
10073         ctsio->kern_data_resid = 0;
10074         ctsio->kern_rel_offset = 0;
10075         ctsio->kern_sg_entries = 0;
10076
10077         /*
10078          * The control device is always connected.  The disk device, on the
10079          * other hand, may not be online all the time.  Need to change this
10080          * to figure out whether the disk device is actually online or not.
10081          */
10082         if (lun != NULL)
10083                 bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10084                                   lun->be_lun->lun_type;
10085         else
10086                 bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10087         bdc_ptr->page_code = SVPD_BDC;
10088         scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10089         if (lun != NULL &&
10090             (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10091                 i = strtol(value, NULL, 0);
10092         else
10093                 i = CTL_DEFAULT_ROTATION_RATE;
10094         scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10095         if (lun != NULL &&
10096             (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10097                 i = strtol(value, NULL, 0);
10098         else
10099                 i = 0;
10100         bdc_ptr->wab_wac_ff = (i & 0x0f);
10101         bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10102
10103         ctl_set_success(ctsio);
10104         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10105         ctsio->be_move_done = ctl_config_move_done;
10106         ctl_datamove((union ctl_io *)ctsio);
10107         return (CTL_RETVAL_COMPLETE);
10108 }
10109
10110 static int
10111 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10112 {
10113         struct scsi_vpd_logical_block_prov *lbp_ptr;
10114         struct ctl_lun *lun;
10115
10116         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10117
10118         ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10119         lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10120         ctsio->kern_sg_entries = 0;
10121
10122         if (sizeof(*lbp_ptr) < alloc_len) {
10123                 ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10124                 ctsio->kern_data_len = sizeof(*lbp_ptr);
10125                 ctsio->kern_total_len = sizeof(*lbp_ptr);
10126         } else {
10127                 ctsio->residual = 0;
10128                 ctsio->kern_data_len = alloc_len;
10129                 ctsio->kern_total_len = alloc_len;
10130         }
10131         ctsio->kern_data_resid = 0;
10132         ctsio->kern_rel_offset = 0;
10133         ctsio->kern_sg_entries = 0;
10134
10135         /*
10136          * The control device is always connected.  The disk device, on the
10137          * other hand, may not be online all the time.  Need to change this
10138          * to figure out whether the disk device is actually online or not.
10139          */
10140         if (lun != NULL)
10141                 lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10142                                   lun->be_lun->lun_type;
10143         else
10144                 lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10145
10146         lbp_ptr->page_code = SVPD_LBP;
10147         scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10148         if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10149                 lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10150                 lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10151                     SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10152                 lbp_ptr->prov_type = SVPD_LBP_THIN;
10153         }
10154
10155         ctl_set_success(ctsio);
10156         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10157         ctsio->be_move_done = ctl_config_move_done;
10158         ctl_datamove((union ctl_io *)ctsio);
10159         return (CTL_RETVAL_COMPLETE);
10160 }
10161
10162 static int
10163 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10164 {
10165         struct scsi_inquiry *cdb;
10166         int alloc_len, retval;
10167
10168         cdb = (struct scsi_inquiry *)ctsio->cdb;
10169
10170         retval = CTL_RETVAL_COMPLETE;
10171
10172         alloc_len = scsi_2btoul(cdb->length);
10173
10174         switch (cdb->page_code) {
10175         case SVPD_SUPPORTED_PAGES:
10176                 retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10177                 break;
10178         case SVPD_UNIT_SERIAL_NUMBER:
10179                 retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10180                 break;
10181         case SVPD_DEVICE_ID:
10182                 retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10183                 break;
10184         case SVPD_EXTENDED_INQUIRY_DATA:
10185                 retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10186                 break;
10187         case SVPD_MODE_PAGE_POLICY:
10188                 retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10189                 break;
10190         case SVPD_SCSI_PORTS:
10191                 retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10192                 break;
10193         case SVPD_SCSI_TPC:
10194                 retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10195                 break;
10196         case SVPD_BLOCK_LIMITS:
10197                 retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10198                 break;
10199         case SVPD_BDC:
10200                 retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10201                 break;
10202         case SVPD_LBP:
10203                 retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10204                 break;
10205         default:
10206                 ctl_set_invalid_field(ctsio,
10207                                       /*sks_valid*/ 1,
10208                                       /*command*/ 1,
10209                                       /*field*/ 2,
10210                                       /*bit_valid*/ 0,
10211                                       /*bit*/ 0);
10212                 ctl_done((union ctl_io *)ctsio);
10213                 retval = CTL_RETVAL_COMPLETE;
10214                 break;
10215         }
10216
10217         return (retval);
10218 }
10219
10220 static int
10221 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10222 {
10223         struct scsi_inquiry_data *inq_ptr;
10224         struct scsi_inquiry *cdb;
10225         struct ctl_softc *ctl_softc;
10226         struct ctl_lun *lun;
10227         char *val;
10228         uint32_t alloc_len, data_len;
10229         ctl_port_type port_type;
10230
10231         ctl_softc = control_softc;
10232
10233         /*
10234          * Figure out whether we're talking to a Fibre Channel port or not.
10235          * We treat the ioctl front end, and any SCSI adapters, as packetized
10236          * SCSI front ends.
10237          */
10238         port_type = ctl_softc->ctl_ports[
10239             ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10240         if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10241                 port_type = CTL_PORT_SCSI;
10242
10243         lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10244         cdb = (struct scsi_inquiry *)ctsio->cdb;
10245         alloc_len = scsi_2btoul(cdb->length);
10246
10247         /*
10248          * We malloc the full inquiry data size here and fill it
10249          * in.  If the user only asks for less, we'll give him
10250          * that much.
10251          */
10252         data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10253         ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10254         inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10255         ctsio->kern_sg_entries = 0;
10256         ctsio->kern_data_resid = 0;
10257         ctsio->kern_rel_offset = 0;
10258
10259         if (data_len < alloc_len) {
10260                 ctsio->residual = alloc_len - data_len;
10261                 ctsio->kern_data_len = data_len;
10262                 ctsio->kern_total_len = data_len;
10263         } else {
10264                 ctsio->residual = 0;
10265                 ctsio->kern_data_len = alloc_len;
10266                 ctsio->kern_total_len = alloc_len;
10267         }
10268
10269         /*
10270          * If we have a LUN configured, report it as connected.  Otherwise,
10271          * report that it is offline or no device is supported, depending 
10272          * on the value of inquiry_pq_no_lun.
10273          *
10274          * According to the spec (SPC-4 r34), the peripheral qualifier
10275          * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10276          *
10277          * "A peripheral device having the specified peripheral device type 
10278          * is not connected to this logical unit. However, the device
10279          * server is capable of supporting the specified peripheral device
10280          * type on this logical unit."
10281          *
10282          * According to the same spec, the peripheral qualifier
10283          * SID_QUAL_BAD_LU (011b) is used in this scenario:
10284          *
10285          * "The device server is not capable of supporting a peripheral
10286          * device on this logical unit. For this peripheral qualifier the
10287          * peripheral device type shall be set to 1Fh. All other peripheral
10288          * device type values are reserved for this peripheral qualifier."
10289          *
10290          * Given the text, it would seem that we probably want to report that
10291          * the LUN is offline here.  There is no LUN connected, but we can
10292          * support a LUN at the given LUN number.
10293          *
10294          * In the real world, though, it sounds like things are a little
10295          * different:
10296          *
10297          * - Linux, when presented with a LUN with the offline peripheral
10298          *   qualifier, will create an sg driver instance for it.  So when
10299          *   you attach it to CTL, you wind up with a ton of sg driver
10300          *   instances.  (One for every LUN that Linux bothered to probe.)
10301          *   Linux does this despite the fact that it issues a REPORT LUNs
10302          *   to LUN 0 to get the inventory of supported LUNs.
10303          *
10304          * - There is other anecdotal evidence (from Emulex folks) about
10305          *   arrays that use the offline peripheral qualifier for LUNs that
10306          *   are on the "passive" path in an active/passive array.
10307          *
10308          * So the solution is provide a hopefully reasonable default
10309          * (return bad/no LUN) and allow the user to change the behavior
10310          * with a tunable/sysctl variable.
10311          */
10312         if (lun != NULL)
10313                 inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10314                                   lun->be_lun->lun_type;
10315         else if (ctl_softc->inquiry_pq_no_lun == 0)
10316                 inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10317         else
10318                 inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10319
10320         /* RMB in byte 2 is 0 */
10321         inq_ptr->version = SCSI_REV_SPC4;
10322
10323         /*
10324          * According to SAM-3, even if a device only supports a single
10325          * level of LUN addressing, it should still set the HISUP bit:
10326          *
10327          * 4.9.1 Logical unit numbers overview
10328          *
10329          * All logical unit number formats described in this standard are
10330          * hierarchical in structure even when only a single level in that
10331          * hierarchy is used. The HISUP bit shall be set to one in the
10332          * standard INQUIRY data (see SPC-2) when any logical unit number
10333          * format described in this standard is used.  Non-hierarchical
10334          * formats are outside the scope of this standard.
10335          *
10336          * Therefore we set the HiSup bit here.
10337          *
10338          * The reponse format is 2, per SPC-3.
10339          */
10340         inq_ptr->response_format = SID_HiSup | 2;
10341
10342         inq_ptr->additional_length = data_len -
10343             (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10344         CTL_DEBUG_PRINT(("additional_length = %d\n",
10345                          inq_ptr->additional_length));
10346
10347         inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10348         /* 16 bit addressing */
10349         if (port_type == CTL_PORT_SCSI)
10350                 inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10351         /* XXX set the SID_MultiP bit here if we're actually going to
10352            respond on multiple ports */
10353         inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10354
10355         /* 16 bit data bus, synchronous transfers */
10356         if (port_type == CTL_PORT_SCSI)
10357                 inq_ptr->flags = SID_WBus16 | SID_Sync;
10358         /*
10359          * XXX KDM do we want to support tagged queueing on the control
10360          * device at all?
10361          */
10362         if ((lun == NULL)
10363          || (lun->be_lun->lun_type != T_PROCESSOR))
10364                 inq_ptr->flags |= SID_CmdQue;
10365         /*
10366          * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10367          * We have 8 bytes for the vendor name, and 16 bytes for the device
10368          * name and 4 bytes for the revision.
10369          */
10370         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10371             "vendor")) == NULL) {
10372                 strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10373         } else {
10374                 memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10375                 strncpy(inq_ptr->vendor, val,
10376                     min(sizeof(inq_ptr->vendor), strlen(val)));
10377         }
10378         if (lun == NULL) {
10379                 strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10380                     sizeof(inq_ptr->product));
10381         } else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10382                 switch (lun->be_lun->lun_type) {
10383                 case T_DIRECT:
10384                         strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10385                             sizeof(inq_ptr->product));
10386                         break;
10387                 case T_PROCESSOR:
10388                         strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10389                             sizeof(inq_ptr->product));
10390                         break;
10391                 default:
10392                         strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10393                             sizeof(inq_ptr->product));
10394                         break;
10395                 }
10396         } else {
10397                 memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10398                 strncpy(inq_ptr->product, val,
10399                     min(sizeof(inq_ptr->product), strlen(val)));
10400         }
10401
10402         /*
10403          * XXX make this a macro somewhere so it automatically gets
10404          * incremented when we make changes.
10405          */
10406         if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10407             "revision")) == NULL) {
10408                 strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10409         } else {
10410                 memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10411                 strncpy(inq_ptr->revision, val,
10412                     min(sizeof(inq_ptr->revision), strlen(val)));
10413         }
10414
10415         /*
10416          * For parallel SCSI, we support double transition and single
10417          * transition clocking.  We also support QAS (Quick Arbitration
10418          * and Selection) and Information Unit transfers on both the
10419          * control and array devices.
10420          */
10421         if (port_type == CTL_PORT_SCSI)
10422                 inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10423                                     SID_SPI_IUS;
10424
10425         /* SAM-5 (no version claimed) */
10426         scsi_ulto2b(0x00A0, inq_ptr->version1);
10427         /* SPC-4 (no version claimed) */
10428         scsi_ulto2b(0x0460, inq_ptr->version2);
10429         if (port_type == CTL_PORT_FC) {
10430                 /* FCP-2 ANSI INCITS.350:2003 */
10431                 scsi_ulto2b(0x0917, inq_ptr->version3);
10432         } else if (port_type == CTL_PORT_SCSI) {
10433                 /* SPI-4 ANSI INCITS.362:200x */
10434                 scsi_ulto2b(0x0B56, inq_ptr->version3);
10435         } else if (port_type == CTL_PORT_ISCSI) {
10436                 /* iSCSI (no version claimed) */
10437                 scsi_ulto2b(0x0960, inq_ptr->version3);
10438         } else if (port_type == CTL_PORT_SAS) {
10439                 /* SAS (no version claimed) */
10440                 scsi_ulto2b(0x0BE0, inq_ptr->version3);
10441         }
10442
10443         if (lun == NULL) {
10444                 /* SBC-4 (no version claimed) */
10445                 scsi_ulto2b(0x0600, inq_ptr->version4);
10446         } else {
10447                 switch (lun->be_lun->lun_type) {
10448                 case T_DIRECT:
10449                         /* SBC-4 (no version claimed) */
10450                         scsi_ulto2b(0x0600, inq_ptr->version4);
10451                         break;
10452                 case T_PROCESSOR:
10453                 default:
10454                         break;
10455                 }
10456         }
10457
10458         ctl_set_success(ctsio);
10459         ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10460         ctsio->be_move_done = ctl_config_move_done;
10461         ctl_datamove((union ctl_io *)ctsio);
10462         return (CTL_RETVAL_COMPLETE);
10463 }
10464
10465 int
10466 ctl_inquiry(struct ctl_scsiio *ctsio)
10467 {
10468         struct scsi_inquiry *cdb;
10469         int retval;
10470
10471         CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10472
10473         cdb = (struct scsi_inquiry *)ctsio->cdb;
10474         if (cdb->byte2 & SI_EVPD)
10475                 retval = ctl_inquiry_evpd(ctsio);
10476         else if (cdb->page_code == 0)
10477                 retval = ctl_inquiry_std(ctsio);
10478         else {
10479                 ctl_set_invalid_field(ctsio,
10480                                       /*sks_valid*/ 1,
10481                                       /*command*/ 1,
10482                                       /*field*/ 2,
10483                                       /*bit_valid*/ 0,
10484                                       /*bit*/ 0);
10485                 ctl_done((union ctl_io *)ctsio);
10486                 return (CTL_RETVAL_COMPLETE);
10487         }
10488
10489         return (retval);
10490 }
10491
10492 /*
10493  * For known CDB types, parse the LBA and length.
10494  */
10495 static int
10496 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10497 {
10498         if (io->io_hdr.io_type != CTL_IO_SCSI)
10499                 return (1);
10500
10501         switch (io->scsiio.cdb[0]) {
10502         case COMPARE_AND_WRITE: {
10503                 struct scsi_compare_and_write *cdb;
10504
10505                 cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10506
10507                 *lba = scsi_8btou64(cdb->addr);
10508                 *len = cdb->length;
10509                 break;
10510         }
10511         case READ_6:
10512         case WRITE_6: {
10513                 struct scsi_rw_6 *cdb;
10514
10515                 cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10516
10517                 *lba = scsi_3btoul(cdb->addr);
10518                 /* only 5 bits are valid in the most significant address byte */
10519                 *lba &= 0x1fffff;
10520                 *len = cdb->length;
10521                 break;
10522         }
10523         case READ_10:
10524         case WRITE_10: {
10525                 struct scsi_rw_10 *cdb;
10526
10527                 cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10528
10529                 *lba = scsi_4btoul(cdb->addr);
10530                 *len = scsi_2btoul(cdb->length);
10531                 break;
10532         }
10533         case WRITE_VERIFY_10: {
10534                 struct scsi_write_verify_10 *cdb;
10535
10536                 cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10537
10538                 *lba = scsi_4btoul(cdb->addr);
10539                 *len = scsi_2btoul(cdb->length);
10540                 break;
10541         }
10542         case READ_12:
10543         case WRITE_12: {
10544                 struct scsi_rw_12 *cdb;
10545
10546                 cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10547
10548                 *lba = scsi_4btoul(cdb->addr);
10549                 *len = scsi_4btoul(cdb->length);
10550                 break;
10551         }
10552         case WRITE_VERIFY_12: {
10553                 struct scsi_write_verify_12 *cdb;
10554
10555                 cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10556
10557                 *lba = scsi_4btoul(cdb->addr);
10558                 *len = scsi_4btoul(cdb->length);
10559                 break;
10560         }
10561         case READ_16:
10562         case WRITE_16:
10563         case WRITE_ATOMIC_16: {
10564                 struct scsi_rw_16 *cdb;
10565
10566                 cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10567
10568                 *lba = scsi_8btou64(cdb->addr);
10569                 *len = scsi_4btoul(cdb->length);
10570                 break;
10571         }
10572         case WRITE_VERIFY_16: {
10573                 struct scsi_write_verify_16 *cdb;
10574
10575                 cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10576
10577                 *lba = scsi_8btou64(cdb->addr);
10578                 *len = scsi_4btoul(cdb->length);
10579                 break;
10580         }
10581         case WRITE_SAME_10: {
10582                 struct scsi_write_same_10 *cdb;
10583
10584                 cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10585
10586                 *lba = scsi_4btoul(cdb->addr);
10587                 *len = scsi_2btoul(cdb->length);
10588                 break;
10589         }
10590         case WRITE_SAME_16: {
10591                 struct scsi_write_same_16 *cdb;
10592
10593                 cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10594
10595                 *lba = scsi_8btou64(cdb->addr);
10596                 *len = scsi_4btoul(cdb->length);
10597                 break;
10598         }
10599         case VERIFY_10: {
10600                 struct scsi_verify_10 *cdb;
10601
10602                 cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10603
10604                 *lba = scsi_4btoul(cdb->addr);
10605                 *len = scsi_2btoul(cdb->length);
10606                 break;
10607         }
10608         case VERIFY_12: {
10609                 struct scsi_verify_12 *cdb;
10610
10611                 cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10612
10613                 *lba = scsi_4btoul(cdb->addr);
10614                 *len = scsi_4btoul(cdb->length);
10615                 break;
10616         }
10617         case VERIFY_16: {
10618                 struct scsi_verify_16 *cdb;
10619
10620                 cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10621
10622                 *lba = scsi_8btou64(cdb->addr);
10623                 *len = scsi_4btoul(cdb->length);
10624                 break;
10625         }
10626         case UNMAP: {
10627                 *lba = 0;
10628                 *len = UINT64_MAX;
10629                 break;
10630         }
10631         default:
10632                 return (1);
10633                 break; /* NOTREACHED */
10634         }
10635
10636         return (0);
10637 }
10638
10639 static ctl_action
10640 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2)
10641 {
10642         uint64_t endlba1, endlba2;
10643
10644         endlba1 = lba1 + len1 - 1;
10645         endlba2 = lba2 + len2 - 1;
10646
10647         if ((endlba1 < lba2)
10648          || (endlba2 < lba1))
10649                 return (CTL_ACTION_PASS);
10650         else
10651                 return (CTL_ACTION_BLOCK);
10652 }
10653
10654 static int
10655 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10656 {
10657         struct ctl_ptr_len_flags *ptrlen;
10658         struct scsi_unmap_desc *buf, *end, *range;
10659         uint64_t lba;
10660         uint32_t len;
10661
10662         /* If not UNMAP -- go other way. */
10663         if (io->io_hdr.io_type != CTL_IO_SCSI ||
10664             io->scsiio.cdb[0] != UNMAP)
10665                 return (CTL_ACTION_ERROR);
10666
10667         /* If UNMAP without data -- block and wait for data. */
10668         ptrlen = (struct ctl_ptr_len_flags *)
10669             &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10670         if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10671             ptrlen->ptr == NULL)
10672                 return (CTL_ACTION_BLOCK);
10673
10674         /* UNMAP with data -- check for collision. */
10675         buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10676         end = buf + ptrlen->len / sizeof(*buf);
10677         for (range = buf; range < end; range++) {
10678                 lba = scsi_8btou64(range->lba);
10679                 len = scsi_4btoul(range->length);
10680                 if ((lba < lba2 + len2) && (lba + len > lba2))
10681                         return (CTL_ACTION_BLOCK);
10682         }
10683         return (CTL_ACTION_PASS);
10684 }
10685
10686 static ctl_action
10687 ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10688 {
10689         uint64_t lba1, lba2;
10690         uint64_t len1, len2;
10691         int retval;
10692
10693         if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10694                 return (CTL_ACTION_ERROR);
10695
10696         retval = ctl_extent_check_unmap(io2, lba1, len1);
10697         if (retval != CTL_ACTION_ERROR)
10698                 return (retval);
10699
10700         if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10701                 return (CTL_ACTION_ERROR);
10702
10703         return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10704 }
10705
10706 static ctl_action
10707 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10708     union ctl_io *ooa_io)
10709 {
10710         const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10711         ctl_serialize_action *serialize_row;
10712
10713         /*
10714          * The initiator attempted multiple untagged commands at the same
10715          * time.  Can't do that.
10716          */
10717         if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10718          && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10719          && ((pending_io->io_hdr.nexus.targ_port ==
10720               ooa_io->io_hdr.nexus.targ_port)
10721           && (pending_io->io_hdr.nexus.initid.id ==
10722               ooa_io->io_hdr.nexus.initid.id))
10723          && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10724                 return (CTL_ACTION_OVERLAP);
10725
10726         /*
10727          * The initiator attempted to send multiple tagged commands with
10728          * the same ID.  (It's fine if different initiators have the same
10729          * tag ID.)
10730          *
10731          * Even if all of those conditions are true, we don't kill the I/O
10732          * if the command ahead of us has been aborted.  We won't end up
10733          * sending it to the FETD, and it's perfectly legal to resend a
10734          * command with the same tag number as long as the previous
10735          * instance of this tag number has been aborted somehow.
10736          */
10737         if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10738          && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10739          && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10740          && ((pending_io->io_hdr.nexus.targ_port ==
10741               ooa_io->io_hdr.nexus.targ_port)
10742           && (pending_io->io_hdr.nexus.initid.id ==
10743               ooa_io->io_hdr.nexus.initid.id))
10744          && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10745                 return (CTL_ACTION_OVERLAP_TAG);
10746
10747         /*
10748          * If we get a head of queue tag, SAM-3 says that we should
10749          * immediately execute it.
10750          *
10751          * What happens if this command would normally block for some other
10752          * reason?  e.g. a request sense with a head of queue tag
10753          * immediately after a write.  Normally that would block, but this
10754          * will result in its getting executed immediately...
10755          *
10756          * We currently return "pass" instead of "skip", so we'll end up
10757          * going through the rest of the queue to check for overlapped tags.
10758          *
10759          * XXX KDM check for other types of blockage first??
10760          */
10761         if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10762                 return (CTL_ACTION_PASS);
10763
10764         /*
10765          * Ordered tags have to block until all items ahead of them
10766          * have completed.  If we get called with an ordered tag, we always
10767          * block, if something else is ahead of us in the queue.
10768          */
10769         if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10770                 return (CTL_ACTION_BLOCK);
10771
10772         /*
10773          * Simple tags get blocked until all head of queue and ordered tags
10774          * ahead of them have completed.  I'm lumping untagged commands in
10775          * with simple tags here.  XXX KDM is that the right thing to do?
10776          */
10777         if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10778           || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10779          && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10780           || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10781                 return (CTL_ACTION_BLOCK);
10782
10783         pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10784         ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10785
10786         serialize_row = ctl_serialize_table[ooa_entry->seridx];
10787
10788         switch (serialize_row[pending_entry->seridx]) {
10789         case CTL_SER_BLOCK:
10790                 return (CTL_ACTION_BLOCK);
10791         case CTL_SER_EXTENT:
10792                 return (ctl_extent_check(pending_io, ooa_io));
10793         case CTL_SER_EXTENTOPT:
10794                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10795                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10796                         return (ctl_extent_check(pending_io, ooa_io));
10797                 /* FALLTHROUGH */
10798         case CTL_SER_PASS:
10799                 return (CTL_ACTION_PASS);
10800         case CTL_SER_BLOCKOPT:
10801                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10802                     & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10803                         return (CTL_ACTION_BLOCK);
10804                 return (CTL_ACTION_PASS);
10805         case CTL_SER_SKIP:
10806                 return (CTL_ACTION_SKIP);
10807         default:
10808                 panic("invalid serialization value %d",
10809                       serialize_row[pending_entry->seridx]);
10810         }
10811
10812         return (CTL_ACTION_ERROR);
10813 }
10814
10815 /*
10816  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10817  * Assumptions:
10818  * - pending_io is generally either incoming, or on the blocked queue
10819  * - starting I/O is the I/O we want to start the check with.
10820  */
10821 static ctl_action
10822 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10823               union ctl_io *starting_io)
10824 {
10825         union ctl_io *ooa_io;
10826         ctl_action action;
10827
10828         mtx_assert(&lun->lun_lock, MA_OWNED);
10829
10830         /*
10831          * Run back along the OOA queue, starting with the current
10832          * blocked I/O and going through every I/O before it on the
10833          * queue.  If starting_io is NULL, we'll just end up returning
10834          * CTL_ACTION_PASS.
10835          */
10836         for (ooa_io = starting_io; ooa_io != NULL;
10837              ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10838              ooa_links)){
10839
10840                 /*
10841                  * This routine just checks to see whether
10842                  * cur_blocked is blocked by ooa_io, which is ahead
10843                  * of it in the queue.  It doesn't queue/dequeue
10844                  * cur_blocked.
10845                  */
10846                 action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10847                 switch (action) {
10848                 case CTL_ACTION_BLOCK:
10849                 case CTL_ACTION_OVERLAP:
10850                 case CTL_ACTION_OVERLAP_TAG:
10851                 case CTL_ACTION_SKIP:
10852                 case CTL_ACTION_ERROR:
10853                         return (action);
10854                         break; /* NOTREACHED */
10855                 case CTL_ACTION_PASS:
10856                         break;
10857                 default:
10858                         panic("invalid action %d", action);
10859                         break;  /* NOTREACHED */
10860                 }
10861         }
10862
10863         return (CTL_ACTION_PASS);
10864 }
10865
10866 /*
10867  * Assumptions:
10868  * - An I/O has just completed, and has been removed from the per-LUN OOA
10869  *   queue, so some items on the blocked queue may now be unblocked.
10870  */
10871 static int
10872 ctl_check_blocked(struct ctl_lun *lun)
10873 {
10874         union ctl_io *cur_blocked, *next_blocked;
10875
10876         mtx_assert(&lun->lun_lock, MA_OWNED);
10877
10878         /*
10879          * Run forward from the head of the blocked queue, checking each
10880          * entry against the I/Os prior to it on the OOA queue to see if
10881          * there is still any blockage.
10882          *
10883          * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10884          * with our removing a variable on it while it is traversing the
10885          * list.
10886          */
10887         for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10888              cur_blocked != NULL; cur_blocked = next_blocked) {
10889                 union ctl_io *prev_ooa;
10890                 ctl_action action;
10891
10892                 next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10893                                                           blocked_links);
10894
10895                 prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10896                                                       ctl_ooaq, ooa_links);
10897
10898                 /*
10899                  * If cur_blocked happens to be the first item in the OOA
10900                  * queue now, prev_ooa will be NULL, and the action
10901                  * returned will just be CTL_ACTION_PASS.
10902                  */
10903                 action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10904
10905                 switch (action) {
10906                 case CTL_ACTION_BLOCK:
10907                         /* Nothing to do here, still blocked */
10908                         break;
10909                 case CTL_ACTION_OVERLAP:
10910                 case CTL_ACTION_OVERLAP_TAG:
10911                         /*
10912                          * This shouldn't happen!  In theory we've already
10913                          * checked this command for overlap...
10914                          */
10915                         break;
10916                 case CTL_ACTION_PASS:
10917                 case CTL_ACTION_SKIP: {
10918                         struct ctl_softc *softc;
10919                         const struct ctl_cmd_entry *entry;
10920                         int isc_retval;
10921
10922                         /*
10923                          * The skip case shouldn't happen, this transaction
10924                          * should have never made it onto the blocked queue.
10925                          */
10926                         /*
10927                          * This I/O is no longer blocked, we can remove it
10928                          * from the blocked queue.  Since this is a TAILQ
10929                          * (doubly linked list), we can do O(1) removals
10930                          * from any place on the list.
10931                          */
10932                         TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
10933                                      blocked_links);
10934                         cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10935
10936                         if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
10937                                 /*
10938                                  * Need to send IO back to original side to
10939                                  * run
10940                                  */
10941                                 union ctl_ha_msg msg_info;
10942
10943                                 msg_info.hdr.original_sc =
10944                                         cur_blocked->io_hdr.original_sc;
10945                                 msg_info.hdr.serializing_sc = cur_blocked;
10946                                 msg_info.hdr.msg_type = CTL_MSG_R2R;
10947                                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
10948                                      &msg_info, sizeof(msg_info), 0)) >
10949                                      CTL_HA_STATUS_SUCCESS) {
10950                                         printf("CTL:Check Blocked error from "
10951                                                "ctl_ha_msg_send %d\n",
10952                                                isc_retval);
10953                                 }
10954                                 break;
10955                         }
10956                         entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
10957                         softc = control_softc;
10958
10959                         /*
10960                          * Check this I/O for LUN state changes that may
10961                          * have happened while this command was blocked.
10962                          * The LUN state may have been changed by a command
10963                          * ahead of us in the queue, so we need to re-check
10964                          * for any states that can be caused by SCSI
10965                          * commands.
10966                          */
10967                         if (ctl_scsiio_lun_check(softc, lun, entry,
10968                                                  &cur_blocked->scsiio) == 0) {
10969                                 cur_blocked->io_hdr.flags |=
10970                                                       CTL_FLAG_IS_WAS_ON_RTR;
10971                                 ctl_enqueue_rtr(cur_blocked);
10972                         } else
10973                                 ctl_done(cur_blocked);
10974                         break;
10975                 }
10976                 default:
10977                         /*
10978                          * This probably shouldn't happen -- we shouldn't
10979                          * get CTL_ACTION_ERROR, or anything else.
10980                          */
10981                         break;
10982                 }
10983         }
10984
10985         return (CTL_RETVAL_COMPLETE);
10986 }
10987
10988 /*
10989  * This routine (with one exception) checks LUN flags that can be set by
10990  * commands ahead of us in the OOA queue.  These flags have to be checked
10991  * when a command initially comes in, and when we pull a command off the
10992  * blocked queue and are preparing to execute it.  The reason we have to
10993  * check these flags for commands on the blocked queue is that the LUN
10994  * state may have been changed by a command ahead of us while we're on the
10995  * blocked queue.
10996  *
10997  * Ordering is somewhat important with these checks, so please pay
10998  * careful attention to the placement of any new checks.
10999  */
11000 static int
11001 ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11002     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11003 {
11004         int retval;
11005         uint32_t residx;
11006
11007         retval = 0;
11008
11009         mtx_assert(&lun->lun_lock, MA_OWNED);
11010
11011         /*
11012          * If this shelf is a secondary shelf controller, we have to reject
11013          * any media access commands.
11014          */
11015         if ((ctl_softc->flags & CTL_FLAG_ACTIVE_SHELF) == 0 &&
11016             (entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0) {
11017                 ctl_set_lun_standby(ctsio);
11018                 retval = 1;
11019                 goto bailout;
11020         }
11021
11022         if (entry->pattern & CTL_LUN_PAT_WRITE) {
11023                 if (lun->flags & CTL_LUN_READONLY) {
11024                         ctl_set_sense(ctsio, /*current_error*/ 1,
11025                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11026                             /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11027                         retval = 1;
11028                         goto bailout;
11029                 }
11030                 if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11031                     .eca_and_aen & SCP_SWP) != 0) {
11032                         ctl_set_sense(ctsio, /*current_error*/ 1,
11033                             /*sense_key*/ SSD_KEY_DATA_PROTECT,
11034                             /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11035                         retval = 1;
11036                         goto bailout;
11037                 }
11038         }
11039
11040         /*
11041          * Check for a reservation conflict.  If this command isn't allowed
11042          * even on reserved LUNs, and if this initiator isn't the one who
11043          * reserved us, reject the command with a reservation conflict.
11044          */
11045         residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11046         if ((lun->flags & CTL_LUN_RESERVED)
11047          && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11048                 if (lun->res_idx != residx) {
11049                         ctl_set_reservation_conflict(ctsio);
11050                         retval = 1;
11051                         goto bailout;
11052                 }
11053         }
11054
11055         if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11056             (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11057                 /* No reservation or command is allowed. */;
11058         } else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11059             (lun->res_type == SPR_TYPE_WR_EX ||
11060              lun->res_type == SPR_TYPE_WR_EX_RO ||
11061              lun->res_type == SPR_TYPE_WR_EX_AR)) {
11062                 /* The command is allowed for Write Exclusive resv. */;
11063         } else {
11064                 /*
11065                  * if we aren't registered or it's a res holder type
11066                  * reservation and this isn't the res holder then set a
11067                  * conflict.
11068                  */
11069                 if (ctl_get_prkey(lun, residx) == 0
11070                  || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11071                         ctl_set_reservation_conflict(ctsio);
11072                         retval = 1;
11073                         goto bailout;
11074                 }
11075
11076         }
11077
11078         if ((lun->flags & CTL_LUN_OFFLINE)
11079          && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11080                 ctl_set_lun_not_ready(ctsio);
11081                 retval = 1;
11082                 goto bailout;
11083         }
11084
11085         /*
11086          * If the LUN is stopped, see if this particular command is allowed
11087          * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11088          */
11089         if ((lun->flags & CTL_LUN_STOPPED)
11090          && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11091                 /* "Logical unit not ready, initializing cmd. required" */
11092                 ctl_set_lun_stopped(ctsio);
11093                 retval = 1;
11094                 goto bailout;
11095         }
11096
11097         if ((lun->flags & CTL_LUN_INOPERABLE)
11098          && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11099                 /* "Medium format corrupted" */
11100                 ctl_set_medium_format_corrupted(ctsio);
11101                 retval = 1;
11102                 goto bailout;
11103         }
11104
11105 bailout:
11106         return (retval);
11107
11108 }
11109
11110 static void
11111 ctl_failover_io(union ctl_io *io, int have_lock)
11112 {
11113         ctl_set_busy(&io->scsiio);
11114         ctl_done(io);
11115 }
11116
11117 static void
11118 ctl_failover(void)
11119 {
11120         struct ctl_lun *lun;
11121         struct ctl_softc *ctl_softc;
11122         union ctl_io *next_io, *pending_io;
11123         union ctl_io *io;
11124         int lun_idx;
11125         int i;
11126
11127         ctl_softc = control_softc;
11128
11129         mtx_lock(&ctl_softc->ctl_lock);
11130         /*
11131          * Remove any cmds from the other SC from the rtr queue.  These
11132          * will obviously only be for LUNs for which we're the primary.
11133          * We can't send status or get/send data for these commands.
11134          * Since they haven't been executed yet, we can just remove them.
11135          * We'll either abort them or delete them below, depending on
11136          * which HA mode we're in.
11137          */
11138 #ifdef notyet
11139         mtx_lock(&ctl_softc->queue_lock);
11140         for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11141              io != NULL; io = next_io) {
11142                 next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11143                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11144                         STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11145                                       ctl_io_hdr, links);
11146         }
11147         mtx_unlock(&ctl_softc->queue_lock);
11148 #endif
11149
11150         for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11151                 lun = ctl_softc->ctl_luns[lun_idx];
11152                 if (lun==NULL)
11153                         continue;
11154
11155                 /*
11156                  * Processor LUNs are primary on both sides.
11157                  * XXX will this always be true?
11158                  */
11159                 if (lun->be_lun->lun_type == T_PROCESSOR)
11160                         continue;
11161
11162                 if ((lun->flags & CTL_LUN_PRIMARY_SC)
11163                  && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11164                         printf("FAILOVER: primary lun %d\n", lun_idx);
11165                         /*
11166                          * Remove all commands from the other SC. First from the
11167                          * blocked queue then from the ooa queue. Once we have
11168                          * removed them. Call ctl_check_blocked to see if there
11169                          * is anything that can run.
11170                          */
11171                         for (io = (union ctl_io *)TAILQ_FIRST(
11172                              &lun->blocked_queue); io != NULL; io = next_io) {
11173
11174                                 next_io = (union ctl_io *)TAILQ_NEXT(
11175                                     &io->io_hdr, blocked_links);
11176
11177                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11178                                         TAILQ_REMOVE(&lun->blocked_queue,
11179                                                      &io->io_hdr,blocked_links);
11180                                         io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11181                                         TAILQ_REMOVE(&lun->ooa_queue,
11182                                                      &io->io_hdr, ooa_links);
11183
11184                                         ctl_free_io(io);
11185                                 }
11186                         }
11187
11188                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11189                              io != NULL; io = next_io) {
11190
11191                                 next_io = (union ctl_io *)TAILQ_NEXT(
11192                                     &io->io_hdr, ooa_links);
11193
11194                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11195
11196                                         TAILQ_REMOVE(&lun->ooa_queue,
11197                                                 &io->io_hdr,
11198                                                 ooa_links);
11199
11200                                         ctl_free_io(io);
11201                                 }
11202                         }
11203                         ctl_check_blocked(lun);
11204                 } else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11205                         && (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11206
11207                         printf("FAILOVER: primary lun %d\n", lun_idx);
11208                         /*
11209                          * Abort all commands from the other SC.  We can't
11210                          * send status back for them now.  These should get
11211                          * cleaned up when they are completed or come out
11212                          * for a datamove operation.
11213                          */
11214                         for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11215                              io != NULL; io = next_io) {
11216                                 next_io = (union ctl_io *)TAILQ_NEXT(
11217                                         &io->io_hdr, ooa_links);
11218
11219                                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11220                                         io->io_hdr.flags |= CTL_FLAG_ABORT;
11221                         }
11222                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11223                         && (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11224
11225                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11226
11227                         lun->flags |= CTL_LUN_PRIMARY_SC;
11228
11229                         /*
11230                          * We send all I/O that was sent to this controller
11231                          * and redirected to the other side back with
11232                          * busy status, and have the initiator retry it.
11233                          * Figuring out how much data has been transferred,
11234                          * etc. and picking up where we left off would be 
11235                          * very tricky.
11236                          *
11237                          * XXX KDM need to remove I/O from the blocked
11238                          * queue as well!
11239                          */
11240                         for (pending_io = (union ctl_io *)TAILQ_FIRST(
11241                              &lun->ooa_queue); pending_io != NULL;
11242                              pending_io = next_io) {
11243
11244                                 next_io =  (union ctl_io *)TAILQ_NEXT(
11245                                         &pending_io->io_hdr, ooa_links);
11246
11247                                 pending_io->io_hdr.flags &=
11248                                         ~CTL_FLAG_SENT_2OTHER_SC;
11249
11250                                 if (pending_io->io_hdr.flags &
11251                                     CTL_FLAG_IO_ACTIVE) {
11252                                         pending_io->io_hdr.flags |=
11253                                                 CTL_FLAG_FAILOVER;
11254                                 } else {
11255                                         ctl_set_busy(&pending_io->scsiio);
11256                                         ctl_done(pending_io);
11257                                 }
11258                         }
11259
11260                         /*
11261                          * Build Unit Attention
11262                          */
11263                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11264                                 lun->pending_ua[i] |=
11265                                                      CTL_UA_ASYM_ACC_CHANGE;
11266                         }
11267                 } else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11268                         && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11269                         printf("FAILOVER: secondary lun %d\n", lun_idx);
11270                         /*
11271                          * if the first io on the OOA is not on the RtR queue
11272                          * add it.
11273                          */
11274                         lun->flags |= CTL_LUN_PRIMARY_SC;
11275
11276                         pending_io = (union ctl_io *)TAILQ_FIRST(
11277                             &lun->ooa_queue);
11278                         if (pending_io==NULL) {
11279                                 printf("Nothing on OOA queue\n");
11280                                 continue;
11281                         }
11282
11283                         pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11284                         if ((pending_io->io_hdr.flags &
11285                              CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11286                                 pending_io->io_hdr.flags |=
11287                                     CTL_FLAG_IS_WAS_ON_RTR;
11288                                 ctl_enqueue_rtr(pending_io);
11289                         }
11290 #if 0
11291                         else
11292                         {
11293                                 printf("Tag 0x%04x is running\n",
11294                                       pending_io->scsiio.tag_num);
11295                         }
11296 #endif
11297
11298                         next_io = (union ctl_io *)TAILQ_NEXT(
11299                             &pending_io->io_hdr, ooa_links);
11300                         for (pending_io=next_io; pending_io != NULL;
11301                              pending_io = next_io) {
11302                                 pending_io->io_hdr.flags &=
11303                                     ~CTL_FLAG_SENT_2OTHER_SC;
11304                                 next_io = (union ctl_io *)TAILQ_NEXT(
11305                                         &pending_io->io_hdr, ooa_links);
11306                                 if (pending_io->io_hdr.flags &
11307                                     CTL_FLAG_IS_WAS_ON_RTR) {
11308 #if 0
11309                                         printf("Tag 0x%04x is running\n",
11310                                                 pending_io->scsiio.tag_num);
11311 #endif
11312                                         continue;
11313                                 }
11314
11315                                 switch (ctl_check_ooa(lun, pending_io,
11316                                     (union ctl_io *)TAILQ_PREV(
11317                                     &pending_io->io_hdr, ctl_ooaq,
11318                                     ooa_links))) {
11319
11320                                 case CTL_ACTION_BLOCK:
11321                                         TAILQ_INSERT_TAIL(&lun->blocked_queue,
11322                                                           &pending_io->io_hdr,
11323                                                           blocked_links);
11324                                         pending_io->io_hdr.flags |=
11325                                             CTL_FLAG_BLOCKED;
11326                                         break;
11327                                 case CTL_ACTION_PASS:
11328                                 case CTL_ACTION_SKIP:
11329                                         pending_io->io_hdr.flags |=
11330                                             CTL_FLAG_IS_WAS_ON_RTR;
11331                                         ctl_enqueue_rtr(pending_io);
11332                                         break;
11333                                 case CTL_ACTION_OVERLAP:
11334                                         ctl_set_overlapped_cmd(
11335                                             (struct ctl_scsiio *)pending_io);
11336                                         ctl_done(pending_io);
11337                                         break;
11338                                 case CTL_ACTION_OVERLAP_TAG:
11339                                         ctl_set_overlapped_tag(
11340                                             (struct ctl_scsiio *)pending_io,
11341                                             pending_io->scsiio.tag_num & 0xff);
11342                                         ctl_done(pending_io);
11343                                         break;
11344                                 case CTL_ACTION_ERROR:
11345                                 default:
11346                                         ctl_set_internal_failure(
11347                                                 (struct ctl_scsiio *)pending_io,
11348                                                 0,  // sks_valid
11349                                                 0); //retry count
11350                                         ctl_done(pending_io);
11351                                         break;
11352                                 }
11353                         }
11354
11355                         /*
11356                          * Build Unit Attention
11357                          */
11358                         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11359                                 lun->pending_ua[i] |=
11360                                                      CTL_UA_ASYM_ACC_CHANGE;
11361                         }
11362                 } else {
11363                         panic("Unhandled HA mode failover, LUN flags = %#x, "
11364                               "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11365                 }
11366         }
11367         ctl_pause_rtr = 0;
11368         mtx_unlock(&ctl_softc->ctl_lock);
11369 }
11370
11371 static int
11372 ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11373 {
11374         struct ctl_lun *lun;
11375         const struct ctl_cmd_entry *entry;
11376         uint32_t initidx, targ_lun;
11377         int retval;
11378
11379         retval = 0;
11380
11381         lun = NULL;
11382
11383         targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11384         if ((targ_lun < CTL_MAX_LUNS)
11385          && ((lun = ctl_softc->ctl_luns[targ_lun]) != NULL)) {
11386                 /*
11387                  * If the LUN is invalid, pretend that it doesn't exist.
11388                  * It will go away as soon as all pending I/O has been
11389                  * completed.
11390                  */
11391                 mtx_lock(&lun->lun_lock);
11392                 if (lun->flags & CTL_LUN_DISABLED) {
11393                         mtx_unlock(&lun->lun_lock);
11394                         lun = NULL;
11395                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11396                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11397                 } else {
11398                         ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11399                         ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11400                                 lun->be_lun;
11401                         if (lun->be_lun->lun_type == T_PROCESSOR) {
11402                                 ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11403                         }
11404
11405                         /*
11406                          * Every I/O goes into the OOA queue for a
11407                          * particular LUN, and stays there until completion.
11408                          */
11409                         TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11410                             ooa_links);
11411                 }
11412         } else {
11413                 ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11414                 ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11415         }
11416
11417         /* Get command entry and return error if it is unsuppotyed. */
11418         entry = ctl_validate_command(ctsio);
11419         if (entry == NULL) {
11420                 if (lun)
11421                         mtx_unlock(&lun->lun_lock);
11422                 return (retval);
11423         }
11424
11425         ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11426         ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11427
11428         /*
11429          * Check to see whether we can send this command to LUNs that don't
11430          * exist.  This should pretty much only be the case for inquiry
11431          * and request sense.  Further checks, below, really require having
11432          * a LUN, so we can't really check the command anymore.  Just put
11433          * it on the rtr queue.
11434          */
11435         if (lun == NULL) {
11436                 if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11437                         ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11438                         ctl_enqueue_rtr((union ctl_io *)ctsio);
11439                         return (retval);
11440                 }
11441
11442                 ctl_set_unsupported_lun(ctsio);
11443                 ctl_done((union ctl_io *)ctsio);
11444                 CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11445                 return (retval);
11446         } else {
11447                 /*
11448                  * Make sure we support this particular command on this LUN.
11449                  * e.g., we don't support writes to the control LUN.
11450                  */
11451                 if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11452                         mtx_unlock(&lun->lun_lock);
11453                         ctl_set_invalid_opcode(ctsio);
11454                         ctl_done((union ctl_io *)ctsio);
11455                         return (retval);
11456                 }
11457         }
11458
11459         initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11460
11461 #ifdef CTL_WITH_CA
11462         /*
11463          * If we've got a request sense, it'll clear the contingent
11464          * allegiance condition.  Otherwise, if we have a CA condition for
11465          * this initiator, clear it, because it sent down a command other
11466          * than request sense.
11467          */
11468         if ((ctsio->cdb[0] != REQUEST_SENSE)
11469          && (ctl_is_set(lun->have_ca, initidx)))
11470                 ctl_clear_mask(lun->have_ca, initidx);
11471 #endif
11472
11473         /*
11474          * If the command has this flag set, it handles its own unit
11475          * attention reporting, we shouldn't do anything.  Otherwise we
11476          * check for any pending unit attentions, and send them back to the
11477          * initiator.  We only do this when a command initially comes in,
11478          * not when we pull it off the blocked queue.
11479          *
11480          * According to SAM-3, section 5.3.2, the order that things get
11481          * presented back to the host is basically unit attentions caused
11482          * by some sort of reset event, busy status, reservation conflicts
11483          * or task set full, and finally any other status.
11484          *
11485          * One issue here is that some of the unit attentions we report
11486          * don't fall into the "reset" category (e.g. "reported luns data
11487          * has changed").  So reporting it here, before the reservation
11488          * check, may be technically wrong.  I guess the only thing to do
11489          * would be to check for and report the reset events here, and then
11490          * check for the other unit attention types after we check for a
11491          * reservation conflict.
11492          *
11493          * XXX KDM need to fix this
11494          */
11495         if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11496                 ctl_ua_type ua_type;
11497
11498                 if (lun->pending_ua[initidx] != CTL_UA_NONE) {
11499                         scsi_sense_data_type sense_format;
11500
11501                         if (lun != NULL)
11502                                 sense_format = (lun->flags &
11503                                     CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11504                                     SSD_TYPE_FIXED;
11505                         else
11506                                 sense_format = SSD_TYPE_FIXED;
11507
11508                         ua_type = ctl_build_ua(&lun->pending_ua[initidx],
11509                             &ctsio->sense_data, sense_format);
11510                         if (ua_type != CTL_UA_NONE) {
11511                                 ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11512                                 ctsio->io_hdr.status = CTL_SCSI_ERROR |
11513                                                        CTL_AUTOSENSE;
11514                                 ctsio->sense_len = SSD_FULL_SIZE;
11515                                 mtx_unlock(&lun->lun_lock);
11516                                 ctl_done((union ctl_io *)ctsio);
11517                                 return (retval);
11518                         }
11519                 }
11520         }
11521
11522
11523         if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11524                 mtx_unlock(&lun->lun_lock);
11525                 ctl_done((union ctl_io *)ctsio);
11526                 return (retval);
11527         }
11528
11529         /*
11530          * XXX CHD this is where we want to send IO to other side if
11531          * this LUN is secondary on this SC. We will need to make a copy
11532          * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11533          * the copy we send as FROM_OTHER.
11534          * We also need to stuff the address of the original IO so we can
11535          * find it easily. Something similar will need be done on the other
11536          * side so when we are done we can find the copy.
11537          */
11538         if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11539                 union ctl_ha_msg msg_info;
11540                 int isc_retval;
11541
11542                 ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11543
11544                 msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11545                 msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11546 #if 0
11547                 printf("1. ctsio %p\n", ctsio);
11548 #endif
11549                 msg_info.hdr.serializing_sc = NULL;
11550                 msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11551                 msg_info.scsi.tag_num = ctsio->tag_num;
11552                 msg_info.scsi.tag_type = ctsio->tag_type;
11553                 memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11554
11555                 ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11556
11557                 if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11558                     (void *)&msg_info, sizeof(msg_info), 0)) >
11559                     CTL_HA_STATUS_SUCCESS) {
11560                         printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11561                                isc_retval);
11562                         printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11563                 } else {
11564 #if 0
11565                         printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11566 #endif
11567                 }
11568
11569                 /*
11570                  * XXX KDM this I/O is off the incoming queue, but hasn't
11571                  * been inserted on any other queue.  We may need to come
11572                  * up with a holding queue while we wait for serialization
11573                  * so that we have an idea of what we're waiting for from
11574                  * the other side.
11575                  */
11576                 mtx_unlock(&lun->lun_lock);
11577                 return (retval);
11578         }
11579
11580         switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11581                               (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11582                               ctl_ooaq, ooa_links))) {
11583         case CTL_ACTION_BLOCK:
11584                 ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11585                 TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11586                                   blocked_links);
11587                 mtx_unlock(&lun->lun_lock);
11588                 return (retval);
11589         case CTL_ACTION_PASS:
11590         case CTL_ACTION_SKIP:
11591                 ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11592                 mtx_unlock(&lun->lun_lock);
11593                 ctl_enqueue_rtr((union ctl_io *)ctsio);
11594                 break;
11595         case CTL_ACTION_OVERLAP:
11596                 mtx_unlock(&lun->lun_lock);
11597                 ctl_set_overlapped_cmd(ctsio);
11598                 ctl_done((union ctl_io *)ctsio);
11599                 break;
11600         case CTL_ACTION_OVERLAP_TAG:
11601                 mtx_unlock(&lun->lun_lock);
11602                 ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11603                 ctl_done((union ctl_io *)ctsio);
11604                 break;
11605         case CTL_ACTION_ERROR:
11606         default:
11607                 mtx_unlock(&lun->lun_lock);
11608                 ctl_set_internal_failure(ctsio,
11609                                          /*sks_valid*/ 0,
11610                                          /*retry_count*/ 0);
11611                 ctl_done((union ctl_io *)ctsio);
11612                 break;
11613         }
11614         return (retval);
11615 }
11616
11617 const struct ctl_cmd_entry *
11618 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11619 {
11620         const struct ctl_cmd_entry *entry;
11621         int service_action;
11622
11623         entry = &ctl_cmd_table[ctsio->cdb[0]];
11624         if (sa)
11625                 *sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11626         if (entry->flags & CTL_CMD_FLAG_SA5) {
11627                 service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11628                 entry = &((const struct ctl_cmd_entry *)
11629                     entry->execute)[service_action];
11630         }
11631         return (entry);
11632 }
11633
11634 const struct ctl_cmd_entry *
11635 ctl_validate_command(struct ctl_scsiio *ctsio)
11636 {
11637         const struct ctl_cmd_entry *entry;
11638         int i, sa;
11639         uint8_t diff;
11640
11641         entry = ctl_get_cmd_entry(ctsio, &sa);
11642         if (entry->execute == NULL) {
11643                 if (sa)
11644                         ctl_set_invalid_field(ctsio,
11645                                               /*sks_valid*/ 1,
11646                                               /*command*/ 1,
11647                                               /*field*/ 1,
11648                                               /*bit_valid*/ 1,
11649                                               /*bit*/ 4);
11650                 else
11651                         ctl_set_invalid_opcode(ctsio);
11652                 ctl_done((union ctl_io *)ctsio);
11653                 return (NULL);
11654         }
11655         KASSERT(entry->length > 0,
11656             ("Not defined length for command 0x%02x/0x%02x",
11657              ctsio->cdb[0], ctsio->cdb[1]));
11658         for (i = 1; i < entry->length; i++) {
11659                 diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11660                 if (diff == 0)
11661                         continue;
11662                 ctl_set_invalid_field(ctsio,
11663                                       /*sks_valid*/ 1,
11664                                       /*command*/ 1,
11665                                       /*field*/ i,
11666                                       /*bit_valid*/ 1,
11667                                       /*bit*/ fls(diff) - 1);
11668                 ctl_done((union ctl_io *)ctsio);
11669                 return (NULL);
11670         }
11671         return (entry);
11672 }
11673
11674 static int
11675 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11676 {
11677
11678         switch (lun_type) {
11679         case T_PROCESSOR:
11680                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11681                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11682                         return (0);
11683                 break;
11684         case T_DIRECT:
11685                 if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11686                     ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11687                         return (0);
11688                 break;
11689         default:
11690                 return (0);
11691         }
11692         return (1);
11693 }
11694
11695 static int
11696 ctl_scsiio(struct ctl_scsiio *ctsio)
11697 {
11698         int retval;
11699         const struct ctl_cmd_entry *entry;
11700
11701         retval = CTL_RETVAL_COMPLETE;
11702
11703         CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11704
11705         entry = ctl_get_cmd_entry(ctsio, NULL);
11706
11707         /*
11708          * If this I/O has been aborted, just send it straight to
11709          * ctl_done() without executing it.
11710          */
11711         if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11712                 ctl_done((union ctl_io *)ctsio);
11713                 goto bailout;
11714         }
11715
11716         /*
11717          * All the checks should have been handled by ctl_scsiio_precheck().
11718          * We should be clear now to just execute the I/O.
11719          */
11720         retval = entry->execute(ctsio);
11721
11722 bailout:
11723         return (retval);
11724 }
11725
11726 /*
11727  * Since we only implement one target right now, a bus reset simply resets
11728  * our single target.
11729  */
11730 static int
11731 ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11732 {
11733         return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11734 }
11735
11736 static int
11737 ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11738                  ctl_ua_type ua_type)
11739 {
11740         struct ctl_lun *lun;
11741         int retval;
11742
11743         if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11744                 union ctl_ha_msg msg_info;
11745
11746                 io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11747                 msg_info.hdr.nexus = io->io_hdr.nexus;
11748                 if (ua_type==CTL_UA_TARG_RESET)
11749                         msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11750                 else
11751                         msg_info.task.task_action = CTL_TASK_BUS_RESET;
11752                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11753                 msg_info.hdr.original_sc = NULL;
11754                 msg_info.hdr.serializing_sc = NULL;
11755                 if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11756                     (void *)&msg_info, sizeof(msg_info), 0)) {
11757                 }
11758         }
11759         retval = 0;
11760
11761         mtx_lock(&ctl_softc->ctl_lock);
11762         STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11763                 retval += ctl_lun_reset(lun, io, ua_type);
11764         mtx_unlock(&ctl_softc->ctl_lock);
11765
11766         return (retval);
11767 }
11768
11769 /*
11770  * The LUN should always be set.  The I/O is optional, and is used to
11771  * distinguish between I/Os sent by this initiator, and by other
11772  * initiators.  We set unit attention for initiators other than this one.
11773  * SAM-3 is vague on this point.  It does say that a unit attention should
11774  * be established for other initiators when a LUN is reset (see section
11775  * 5.7.3), but it doesn't specifically say that the unit attention should
11776  * be established for this particular initiator when a LUN is reset.  Here
11777  * is the relevant text, from SAM-3 rev 8:
11778  *
11779  * 5.7.2 When a SCSI initiator port aborts its own tasks
11780  *
11781  * When a SCSI initiator port causes its own task(s) to be aborted, no
11782  * notification that the task(s) have been aborted shall be returned to
11783  * the SCSI initiator port other than the completion response for the
11784  * command or task management function action that caused the task(s) to
11785  * be aborted and notification(s) associated with related effects of the
11786  * action (e.g., a reset unit attention condition).
11787  *
11788  * XXX KDM for now, we're setting unit attention for all initiators.
11789  */
11790 static int
11791 ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11792 {
11793         union ctl_io *xio;
11794 #if 0
11795         uint32_t initidx;
11796 #endif
11797         int i;
11798
11799         mtx_lock(&lun->lun_lock);
11800         /*
11801          * Run through the OOA queue and abort each I/O.
11802          */
11803 #if 0
11804         TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11805 #endif
11806         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11807              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11808                 xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11809         }
11810
11811         /*
11812          * This version sets unit attention for every
11813          */
11814 #if 0
11815         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11816         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11817                 if (initidx == i)
11818                         continue;
11819                 lun->pending_ua[i] |= ua_type;
11820         }
11821 #endif
11822
11823         /*
11824          * A reset (any kind, really) clears reservations established with
11825          * RESERVE/RELEASE.  It does not clear reservations established
11826          * with PERSISTENT RESERVE OUT, but we don't support that at the
11827          * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11828          * reservations made with the RESERVE/RELEASE commands, because
11829          * those commands are obsolete in SPC-3.
11830          */
11831         lun->flags &= ~CTL_LUN_RESERVED;
11832
11833         for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11834 #ifdef CTL_WITH_CA
11835                 ctl_clear_mask(lun->have_ca, i);
11836 #endif
11837                 lun->pending_ua[i] |= ua_type;
11838         }
11839         mtx_unlock(&lun->lun_lock);
11840
11841         return (0);
11842 }
11843
11844 static void
11845 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11846     int other_sc)
11847 {
11848         union ctl_io *xio;
11849
11850         mtx_assert(&lun->lun_lock, MA_OWNED);
11851
11852         /*
11853          * Run through the OOA queue and attempt to find the given I/O.
11854          * The target port, initiator ID, tag type and tag number have to
11855          * match the values that we got from the initiator.  If we have an
11856          * untagged command to abort, simply abort the first untagged command
11857          * we come to.  We only allow one untagged command at a time of course.
11858          */
11859         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11860              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11861
11862                 if ((targ_port == UINT32_MAX ||
11863                      targ_port == xio->io_hdr.nexus.targ_port) &&
11864                     (init_id == UINT32_MAX ||
11865                      init_id == xio->io_hdr.nexus.initid.id)) {
11866                         if (targ_port != xio->io_hdr.nexus.targ_port ||
11867                             init_id != xio->io_hdr.nexus.initid.id)
11868                                 xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11869                         xio->io_hdr.flags |= CTL_FLAG_ABORT;
11870                         if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11871                                 union ctl_ha_msg msg_info;
11872
11873                                 msg_info.hdr.nexus = xio->io_hdr.nexus;
11874                                 msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11875                                 msg_info.task.tag_num = xio->scsiio.tag_num;
11876                                 msg_info.task.tag_type = xio->scsiio.tag_type;
11877                                 msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11878                                 msg_info.hdr.original_sc = NULL;
11879                                 msg_info.hdr.serializing_sc = NULL;
11880                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11881                                     (void *)&msg_info, sizeof(msg_info), 0);
11882                         }
11883                 }
11884         }
11885 }
11886
11887 static int
11888 ctl_abort_task_set(union ctl_io *io)
11889 {
11890         struct ctl_softc *softc = control_softc;
11891         struct ctl_lun *lun;
11892         uint32_t targ_lun;
11893
11894         /*
11895          * Look up the LUN.
11896          */
11897         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11898         mtx_lock(&softc->ctl_lock);
11899         if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
11900                 lun = softc->ctl_luns[targ_lun];
11901         else {
11902                 mtx_unlock(&softc->ctl_lock);
11903                 return (1);
11904         }
11905
11906         mtx_lock(&lun->lun_lock);
11907         mtx_unlock(&softc->ctl_lock);
11908         if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11909                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11910                     io->io_hdr.nexus.initid.id,
11911                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11912         } else { /* CTL_TASK_CLEAR_TASK_SET */
11913                 ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11914                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11915         }
11916         mtx_unlock(&lun->lun_lock);
11917         return (0);
11918 }
11919
11920 static int
11921 ctl_i_t_nexus_reset(union ctl_io *io)
11922 {
11923         struct ctl_softc *softc = control_softc;
11924         struct ctl_lun *lun;
11925         uint32_t initidx, residx;
11926
11927         initidx = ctl_get_initindex(&io->io_hdr.nexus);
11928         residx = ctl_get_resindex(&io->io_hdr.nexus);
11929         mtx_lock(&softc->ctl_lock);
11930         STAILQ_FOREACH(lun, &softc->lun_list, links) {
11931                 mtx_lock(&lun->lun_lock);
11932                 ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11933                     io->io_hdr.nexus.initid.id,
11934                     (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11935 #ifdef CTL_WITH_CA
11936                 ctl_clear_mask(lun->have_ca, initidx);
11937 #endif
11938                 if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
11939                         lun->flags &= ~CTL_LUN_RESERVED;
11940                 lun->pending_ua[initidx] |= CTL_UA_I_T_NEXUS_LOSS;
11941                 mtx_unlock(&lun->lun_lock);
11942         }
11943         mtx_unlock(&softc->ctl_lock);
11944         return (0);
11945 }
11946
11947 static int
11948 ctl_abort_task(union ctl_io *io)
11949 {
11950         union ctl_io *xio;
11951         struct ctl_lun *lun;
11952         struct ctl_softc *ctl_softc;
11953 #if 0
11954         struct sbuf sb;
11955         char printbuf[128];
11956 #endif
11957         int found;
11958         uint32_t targ_lun;
11959
11960         ctl_softc = control_softc;
11961         found = 0;
11962
11963         /*
11964          * Look up the LUN.
11965          */
11966         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11967         mtx_lock(&ctl_softc->ctl_lock);
11968         if ((targ_lun < CTL_MAX_LUNS)
11969          && (ctl_softc->ctl_luns[targ_lun] != NULL))
11970                 lun = ctl_softc->ctl_luns[targ_lun];
11971         else {
11972                 mtx_unlock(&ctl_softc->ctl_lock);
11973                 return (1);
11974         }
11975
11976 #if 0
11977         printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11978                lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11979 #endif
11980
11981         mtx_lock(&lun->lun_lock);
11982         mtx_unlock(&ctl_softc->ctl_lock);
11983         /*
11984          * Run through the OOA queue and attempt to find the given I/O.
11985          * The target port, initiator ID, tag type and tag number have to
11986          * match the values that we got from the initiator.  If we have an
11987          * untagged command to abort, simply abort the first untagged command
11988          * we come to.  We only allow one untagged command at a time of course.
11989          */
11990 #if 0
11991         TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11992 #endif
11993         for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11994              xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11995 #if 0
11996                 sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
11997
11998                 sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
11999                             lun->lun, xio->scsiio.tag_num,
12000                             xio->scsiio.tag_type,
12001                             (xio->io_hdr.blocked_links.tqe_prev
12002                             == NULL) ? "" : " BLOCKED",
12003                             (xio->io_hdr.flags &
12004                             CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12005                             (xio->io_hdr.flags &
12006                             CTL_FLAG_ABORT) ? " ABORT" : "",
12007                             (xio->io_hdr.flags &
12008                             CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12009                 ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12010                 sbuf_finish(&sb);
12011                 printf("%s\n", sbuf_data(&sb));
12012 #endif
12013
12014                 if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12015                  && (xio->io_hdr.nexus.initid.id ==
12016                      io->io_hdr.nexus.initid.id)) {
12017                         /*
12018                          * If the abort says that the task is untagged, the
12019                          * task in the queue must be untagged.  Otherwise,
12020                          * we just check to see whether the tag numbers
12021                          * match.  This is because the QLogic firmware
12022                          * doesn't pass back the tag type in an abort
12023                          * request.
12024                          */
12025 #if 0
12026                         if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12027                           && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12028                          || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12029 #endif
12030                         /*
12031                          * XXX KDM we've got problems with FC, because it
12032                          * doesn't send down a tag type with aborts.  So we
12033                          * can only really go by the tag number...
12034                          * This may cause problems with parallel SCSI.
12035                          * Need to figure that out!!
12036                          */
12037                         if (xio->scsiio.tag_num == io->taskio.tag_num) {
12038                                 xio->io_hdr.flags |= CTL_FLAG_ABORT;
12039                                 found = 1;
12040                                 if ((io->io_hdr.flags &
12041                                      CTL_FLAG_FROM_OTHER_SC) == 0 &&
12042                                     !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12043                                         union ctl_ha_msg msg_info;
12044
12045                                         io->io_hdr.flags |=
12046                                                         CTL_FLAG_SENT_2OTHER_SC;
12047                                         msg_info.hdr.nexus = io->io_hdr.nexus;
12048                                         msg_info.task.task_action =
12049                                                 CTL_TASK_ABORT_TASK;
12050                                         msg_info.task.tag_num =
12051                                                 io->taskio.tag_num;
12052                                         msg_info.task.tag_type =
12053                                                 io->taskio.tag_type;
12054                                         msg_info.hdr.msg_type =
12055                                                 CTL_MSG_MANAGE_TASKS;
12056                                         msg_info.hdr.original_sc = NULL;
12057                                         msg_info.hdr.serializing_sc = NULL;
12058 #if 0
12059                                         printf("Sent Abort to other side\n");
12060 #endif
12061                                         if (CTL_HA_STATUS_SUCCESS !=
12062                                                 ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12063                                                 (void *)&msg_info,
12064                                                 sizeof(msg_info), 0)) {
12065                                         }
12066                                 }
12067 #if 0
12068                                 printf("ctl_abort_task: found I/O to abort\n");
12069 #endif
12070                                 break;
12071                         }
12072                 }
12073         }
12074         mtx_unlock(&lun->lun_lock);
12075
12076         if (found == 0) {
12077                 /*
12078                  * This isn't really an error.  It's entirely possible for
12079                  * the abort and command completion to cross on the wire.
12080                  * This is more of an informative/diagnostic error.
12081                  */
12082 #if 0
12083                 printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12084                        "%d:%d:%d:%d tag %d type %d\n",
12085                        io->io_hdr.nexus.initid.id,
12086                        io->io_hdr.nexus.targ_port,
12087                        io->io_hdr.nexus.targ_target.id,
12088                        io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12089                        io->taskio.tag_type);
12090 #endif
12091         }
12092         return (0);
12093 }
12094
12095 static void
12096 ctl_run_task(union ctl_io *io)
12097 {
12098         struct ctl_softc *ctl_softc = control_softc;
12099         int retval = 1;
12100         const char *task_desc;
12101
12102         CTL_DEBUG_PRINT(("ctl_run_task\n"));
12103
12104         KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12105             ("ctl_run_task: Unextected io_type %d\n",
12106              io->io_hdr.io_type));
12107
12108         task_desc = ctl_scsi_task_string(&io->taskio);
12109         if (task_desc != NULL) {
12110 #ifdef NEEDTOPORT
12111                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12112                             CTL_TASK_REPORT,
12113                             csevent_LogType_Trace,
12114                             csevent_Severity_Information,
12115                             csevent_AlertLevel_Green,
12116                             csevent_FRU_Firmware,
12117                             csevent_FRU_Unknown,
12118                             "CTL: received task: %s",task_desc);
12119 #endif
12120         } else {
12121 #ifdef NEEDTOPORT
12122                 csevent_log(CSC_CTL | CSC_SHELF_SW |
12123                             CTL_TASK_REPORT,
12124                             csevent_LogType_Trace,
12125                             csevent_Severity_Information,
12126                             csevent_AlertLevel_Green,
12127                             csevent_FRU_Firmware,
12128                             csevent_FRU_Unknown,
12129                             "CTL: received unknown task "
12130                             "type: %d (%#x)",
12131                             io->taskio.task_action,
12132                             io->taskio.task_action);
12133 #endif
12134         }
12135         switch (io->taskio.task_action) {
12136         case CTL_TASK_ABORT_TASK:
12137                 retval = ctl_abort_task(io);
12138                 break;
12139         case CTL_TASK_ABORT_TASK_SET:
12140         case CTL_TASK_CLEAR_TASK_SET:
12141                 retval = ctl_abort_task_set(io);
12142                 break;
12143         case CTL_TASK_CLEAR_ACA:
12144                 break;
12145         case CTL_TASK_I_T_NEXUS_RESET:
12146                 retval = ctl_i_t_nexus_reset(io);
12147                 break;
12148         case CTL_TASK_LUN_RESET: {
12149                 struct ctl_lun *lun;
12150                 uint32_t targ_lun;
12151
12152                 targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12153                 mtx_lock(&ctl_softc->ctl_lock);
12154                 if ((targ_lun < CTL_MAX_LUNS)
12155                  && (ctl_softc->ctl_luns[targ_lun] != NULL))
12156                         lun = ctl_softc->ctl_luns[targ_lun];
12157                 else {
12158                         mtx_unlock(&ctl_softc->ctl_lock);
12159                         retval = 1;
12160                         break;
12161                 }
12162
12163                 if (!(io->io_hdr.flags &
12164                     CTL_FLAG_FROM_OTHER_SC)) {
12165                         union ctl_ha_msg msg_info;
12166
12167                         io->io_hdr.flags |=
12168                                 CTL_FLAG_SENT_2OTHER_SC;
12169                         msg_info.hdr.msg_type =
12170                                 CTL_MSG_MANAGE_TASKS;
12171                         msg_info.hdr.nexus = io->io_hdr.nexus;
12172                         msg_info.task.task_action =
12173                                 CTL_TASK_LUN_RESET;
12174                         msg_info.hdr.original_sc = NULL;
12175                         msg_info.hdr.serializing_sc = NULL;
12176                         if (CTL_HA_STATUS_SUCCESS !=
12177                             ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12178                             (void *)&msg_info,
12179                             sizeof(msg_info), 0)) {
12180                         }
12181                 }
12182
12183                 retval = ctl_lun_reset(lun, io,
12184                                        CTL_UA_LUN_RESET);
12185                 mtx_unlock(&ctl_softc->ctl_lock);
12186                 break;
12187         }
12188         case CTL_TASK_TARGET_RESET:
12189                 retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12190                 break;
12191         case CTL_TASK_BUS_RESET:
12192                 retval = ctl_bus_reset(ctl_softc, io);
12193                 break;
12194         case CTL_TASK_PORT_LOGIN:
12195                 break;
12196         case CTL_TASK_PORT_LOGOUT:
12197                 break;
12198         default:
12199                 printf("ctl_run_task: got unknown task management event %d\n",
12200                        io->taskio.task_action);
12201                 break;
12202         }
12203         if (retval == 0)
12204                 io->io_hdr.status = CTL_SUCCESS;
12205         else
12206                 io->io_hdr.status = CTL_ERROR;
12207         ctl_done(io);
12208 }
12209
12210 /*
12211  * For HA operation.  Handle commands that come in from the other
12212  * controller.
12213  */
12214 static void
12215 ctl_handle_isc(union ctl_io *io)
12216 {
12217         int free_io;
12218         struct ctl_lun *lun;
12219         struct ctl_softc *ctl_softc;
12220         uint32_t targ_lun;
12221
12222         ctl_softc = control_softc;
12223
12224         targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12225         lun = ctl_softc->ctl_luns[targ_lun];
12226
12227         switch (io->io_hdr.msg_type) {
12228         case CTL_MSG_SERIALIZE:
12229                 free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12230                 break;
12231         case CTL_MSG_R2R: {
12232                 const struct ctl_cmd_entry *entry;
12233
12234                 /*
12235                  * This is only used in SER_ONLY mode.
12236                  */
12237                 free_io = 0;
12238                 entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12239                 mtx_lock(&lun->lun_lock);
12240                 if (ctl_scsiio_lun_check(ctl_softc, lun,
12241                     entry, (struct ctl_scsiio *)io) != 0) {
12242                         mtx_unlock(&lun->lun_lock);
12243                         ctl_done(io);
12244                         break;
12245                 }
12246                 io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12247                 mtx_unlock(&lun->lun_lock);
12248                 ctl_enqueue_rtr(io);
12249                 break;
12250         }
12251         case CTL_MSG_FINISH_IO:
12252                 if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12253                         free_io = 0;
12254                         ctl_done(io);
12255                 } else {
12256                         free_io = 1;
12257                         mtx_lock(&lun->lun_lock);
12258                         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12259                                      ooa_links);
12260                         ctl_check_blocked(lun);
12261                         mtx_unlock(&lun->lun_lock);
12262                 }
12263                 break;
12264         case CTL_MSG_PERS_ACTION:
12265                 ctl_hndl_per_res_out_on_other_sc(
12266                         (union ctl_ha_msg *)&io->presio.pr_msg);
12267                 free_io = 1;
12268                 break;
12269         case CTL_MSG_BAD_JUJU:
12270                 free_io = 0;
12271                 ctl_done(io);
12272                 break;
12273         case CTL_MSG_DATAMOVE:
12274                 /* Only used in XFER mode */
12275                 free_io = 0;
12276                 ctl_datamove_remote(io);
12277                 break;
12278         case CTL_MSG_DATAMOVE_DONE:
12279                 /* Only used in XFER mode */
12280                 free_io = 0;
12281                 io->scsiio.be_move_done(io);
12282                 break;
12283         default:
12284                 free_io = 1;
12285                 printf("%s: Invalid message type %d\n",
12286                        __func__, io->io_hdr.msg_type);
12287                 break;
12288         }
12289         if (free_io)
12290                 ctl_free_io(io);
12291
12292 }
12293
12294
12295 /*
12296  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12297  * there is no match.
12298  */
12299 static ctl_lun_error_pattern
12300 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12301 {
12302         const struct ctl_cmd_entry *entry;
12303         ctl_lun_error_pattern filtered_pattern, pattern;
12304
12305         pattern = desc->error_pattern;
12306
12307         /*
12308          * XXX KDM we need more data passed into this function to match a
12309          * custom pattern, and we actually need to implement custom pattern
12310          * matching.
12311          */
12312         if (pattern & CTL_LUN_PAT_CMD)
12313                 return (CTL_LUN_PAT_CMD);
12314
12315         if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12316                 return (CTL_LUN_PAT_ANY);
12317
12318         entry = ctl_get_cmd_entry(ctsio, NULL);
12319
12320         filtered_pattern = entry->pattern & pattern;
12321
12322         /*
12323          * If the user requested specific flags in the pattern (e.g.
12324          * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12325          * flags.
12326          *
12327          * If the user did not specify any flags, it doesn't matter whether
12328          * or not the command supports the flags.
12329          */
12330         if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12331              (pattern & ~CTL_LUN_PAT_MASK))
12332                 return (CTL_LUN_PAT_NONE);
12333
12334         /*
12335          * If the user asked for a range check, see if the requested LBA
12336          * range overlaps with this command's LBA range.
12337          */
12338         if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12339                 uint64_t lba1;
12340                 uint64_t len1;
12341                 ctl_action action;
12342                 int retval;
12343
12344                 retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12345                 if (retval != 0)
12346                         return (CTL_LUN_PAT_NONE);
12347
12348                 action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12349                                               desc->lba_range.len);
12350                 /*
12351                  * A "pass" means that the LBA ranges don't overlap, so
12352                  * this doesn't match the user's range criteria.
12353                  */
12354                 if (action == CTL_ACTION_PASS)
12355                         return (CTL_LUN_PAT_NONE);
12356         }
12357
12358         return (filtered_pattern);
12359 }
12360
12361 static void
12362 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12363 {
12364         struct ctl_error_desc *desc, *desc2;
12365
12366         mtx_assert(&lun->lun_lock, MA_OWNED);
12367
12368         STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12369                 ctl_lun_error_pattern pattern;
12370                 /*
12371                  * Check to see whether this particular command matches
12372                  * the pattern in the descriptor.
12373                  */
12374                 pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12375                 if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12376                         continue;
12377
12378                 switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12379                 case CTL_LUN_INJ_ABORTED:
12380                         ctl_set_aborted(&io->scsiio);
12381                         break;
12382                 case CTL_LUN_INJ_MEDIUM_ERR:
12383                         ctl_set_medium_error(&io->scsiio);
12384                         break;
12385                 case CTL_LUN_INJ_UA:
12386                         /* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12387                          * OCCURRED */
12388                         ctl_set_ua(&io->scsiio, 0x29, 0x00);
12389                         break;
12390                 case CTL_LUN_INJ_CUSTOM:
12391                         /*
12392                          * We're assuming the user knows what he is doing.
12393                          * Just copy the sense information without doing
12394                          * checks.
12395                          */
12396                         bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12397                               ctl_min(sizeof(desc->custom_sense),
12398                                       sizeof(io->scsiio.sense_data)));
12399                         io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12400                         io->scsiio.sense_len = SSD_FULL_SIZE;
12401                         io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12402                         break;
12403                 case CTL_LUN_INJ_NONE:
12404                 default:
12405                         /*
12406                          * If this is an error injection type we don't know
12407                          * about, clear the continuous flag (if it is set)
12408                          * so it will get deleted below.
12409                          */
12410                         desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12411                         break;
12412                 }
12413                 /*
12414                  * By default, each error injection action is a one-shot
12415                  */
12416                 if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12417                         continue;
12418
12419                 STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12420
12421                 free(desc, M_CTL);
12422         }
12423 }
12424
12425 #ifdef CTL_IO_DELAY
12426 static void
12427 ctl_datamove_timer_wakeup(void *arg)
12428 {
12429         union ctl_io *io;
12430
12431         io = (union ctl_io *)arg;
12432
12433         ctl_datamove(io);
12434 }
12435 #endif /* CTL_IO_DELAY */
12436
12437 void
12438 ctl_datamove(union ctl_io *io)
12439 {
12440         void (*fe_datamove)(union ctl_io *io);
12441
12442         mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12443
12444         CTL_DEBUG_PRINT(("ctl_datamove\n"));
12445
12446 #ifdef CTL_TIME_IO
12447         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12448                 char str[256];
12449                 char path_str[64];
12450                 struct sbuf sb;
12451
12452                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
12453                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12454
12455                 sbuf_cat(&sb, path_str);
12456                 switch (io->io_hdr.io_type) {
12457                 case CTL_IO_SCSI:
12458                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12459                         sbuf_printf(&sb, "\n");
12460                         sbuf_cat(&sb, path_str);
12461                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12462                                     io->scsiio.tag_num, io->scsiio.tag_type);
12463                         break;
12464                 case CTL_IO_TASK:
12465                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12466                                     "Tag Type: %d\n", io->taskio.task_action,
12467                                     io->taskio.tag_num, io->taskio.tag_type);
12468                         break;
12469                 default:
12470                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12471                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12472                         break;
12473                 }
12474                 sbuf_cat(&sb, path_str);
12475                 sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12476                             (intmax_t)time_uptime - io->io_hdr.start_time);
12477                 sbuf_finish(&sb);
12478                 printf("%s", sbuf_data(&sb));
12479         }
12480 #endif /* CTL_TIME_IO */
12481
12482 #ifdef CTL_IO_DELAY
12483         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12484                 struct ctl_lun *lun;
12485
12486                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12487
12488                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12489         } else {
12490                 struct ctl_lun *lun;
12491
12492                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12493                 if ((lun != NULL)
12494                  && (lun->delay_info.datamove_delay > 0)) {
12495                         struct callout *callout;
12496
12497                         callout = (struct callout *)&io->io_hdr.timer_bytes;
12498                         callout_init(callout, /*mpsafe*/ 1);
12499                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12500                         callout_reset(callout,
12501                                       lun->delay_info.datamove_delay * hz,
12502                                       ctl_datamove_timer_wakeup, io);
12503                         if (lun->delay_info.datamove_type ==
12504                             CTL_DELAY_TYPE_ONESHOT)
12505                                 lun->delay_info.datamove_delay = 0;
12506                         return;
12507                 }
12508         }
12509 #endif
12510
12511         /*
12512          * This command has been aborted.  Set the port status, so we fail
12513          * the data move.
12514          */
12515         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12516                 printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12517                        io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12518                        io->io_hdr.nexus.targ_port,
12519                        (uintmax_t)io->io_hdr.nexus.targ_target.id,
12520                        io->io_hdr.nexus.targ_lun);
12521                 io->io_hdr.port_status = 31337;
12522                 /*
12523                  * Note that the backend, in this case, will get the
12524                  * callback in its context.  In other cases it may get
12525                  * called in the frontend's interrupt thread context.
12526                  */
12527                 io->scsiio.be_move_done(io);
12528                 return;
12529         }
12530
12531         /* Don't confuse frontend with zero length data move. */
12532         if (io->scsiio.kern_data_len == 0) {
12533                 io->scsiio.be_move_done(io);
12534                 return;
12535         }
12536
12537         /*
12538          * If we're in XFER mode and this I/O is from the other shelf
12539          * controller, we need to send the DMA to the other side to
12540          * actually transfer the data to/from the host.  In serialize only
12541          * mode the transfer happens below CTL and ctl_datamove() is only
12542          * called on the machine that originally received the I/O.
12543          */
12544         if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12545          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12546                 union ctl_ha_msg msg;
12547                 uint32_t sg_entries_sent;
12548                 int do_sg_copy;
12549                 int i;
12550
12551                 memset(&msg, 0, sizeof(msg));
12552                 msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12553                 msg.hdr.original_sc = io->io_hdr.original_sc;
12554                 msg.hdr.serializing_sc = io;
12555                 msg.hdr.nexus = io->io_hdr.nexus;
12556                 msg.dt.flags = io->io_hdr.flags;
12557                 /*
12558                  * We convert everything into a S/G list here.  We can't
12559                  * pass by reference, only by value between controllers.
12560                  * So we can't pass a pointer to the S/G list, only as many
12561                  * S/G entries as we can fit in here.  If it's possible for
12562                  * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12563                  * then we need to break this up into multiple transfers.
12564                  */
12565                 if (io->scsiio.kern_sg_entries == 0) {
12566                         msg.dt.kern_sg_entries = 1;
12567                         /*
12568                          * If this is in cached memory, flush the cache
12569                          * before we send the DMA request to the other
12570                          * controller.  We want to do this in either the
12571                          * read or the write case.  The read case is
12572                          * straightforward.  In the write case, we want to
12573                          * make sure nothing is in the local cache that
12574                          * could overwrite the DMAed data.
12575                          */
12576                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12577                                 /*
12578                                  * XXX KDM use bus_dmamap_sync() here.
12579                                  */
12580                         }
12581
12582                         /*
12583                          * Convert to a physical address if this is a
12584                          * virtual address.
12585                          */
12586                         if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12587                                 msg.dt.sg_list[0].addr =
12588                                         io->scsiio.kern_data_ptr;
12589                         } else {
12590                                 /*
12591                                  * XXX KDM use busdma here!
12592                                  */
12593 #if 0
12594                                 msg.dt.sg_list[0].addr = (void *)
12595                                         vtophys(io->scsiio.kern_data_ptr);
12596 #endif
12597                         }
12598
12599                         msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12600                         do_sg_copy = 0;
12601                 } else {
12602                         struct ctl_sg_entry *sgl;
12603
12604                         do_sg_copy = 1;
12605                         msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12606                         sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12607                         if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12608                                 /*
12609                                  * XXX KDM use bus_dmamap_sync() here.
12610                                  */
12611                         }
12612                 }
12613
12614                 msg.dt.kern_data_len = io->scsiio.kern_data_len;
12615                 msg.dt.kern_total_len = io->scsiio.kern_total_len;
12616                 msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12617                 msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12618                 msg.dt.sg_sequence = 0;
12619
12620                 /*
12621                  * Loop until we've sent all of the S/G entries.  On the
12622                  * other end, we'll recompose these S/G entries into one
12623                  * contiguous list before passing it to the
12624                  */
12625                 for (sg_entries_sent = 0; sg_entries_sent <
12626                      msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12627                         msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12628                                 sizeof(msg.dt.sg_list[0])),
12629                                 msg.dt.kern_sg_entries - sg_entries_sent);
12630
12631                         if (do_sg_copy != 0) {
12632                                 struct ctl_sg_entry *sgl;
12633                                 int j;
12634
12635                                 sgl = (struct ctl_sg_entry *)
12636                                         io->scsiio.kern_data_ptr;
12637                                 /*
12638                                  * If this is in cached memory, flush the cache
12639                                  * before we send the DMA request to the other
12640                                  * controller.  We want to do this in either
12641                                  * the * read or the write case.  The read
12642                                  * case is straightforward.  In the write
12643                                  * case, we want to make sure nothing is
12644                                  * in the local cache that could overwrite
12645                                  * the DMAed data.
12646                                  */
12647
12648                                 for (i = sg_entries_sent, j = 0;
12649                                      i < msg.dt.cur_sg_entries; i++, j++) {
12650                                         if ((io->io_hdr.flags &
12651                                              CTL_FLAG_NO_DATASYNC) == 0) {
12652                                                 /*
12653                                                  * XXX KDM use bus_dmamap_sync()
12654                                                  */
12655                                         }
12656                                         if ((io->io_hdr.flags &
12657                                              CTL_FLAG_BUS_ADDR) == 0) {
12658                                                 /*
12659                                                  * XXX KDM use busdma.
12660                                                  */
12661 #if 0
12662                                                 msg.dt.sg_list[j].addr =(void *)
12663                                                        vtophys(sgl[i].addr);
12664 #endif
12665                                         } else {
12666                                                 msg.dt.sg_list[j].addr =
12667                                                         sgl[i].addr;
12668                                         }
12669                                         msg.dt.sg_list[j].len = sgl[i].len;
12670                                 }
12671                         }
12672
12673                         sg_entries_sent += msg.dt.cur_sg_entries;
12674                         if (sg_entries_sent >= msg.dt.kern_sg_entries)
12675                                 msg.dt.sg_last = 1;
12676                         else
12677                                 msg.dt.sg_last = 0;
12678
12679                         /*
12680                          * XXX KDM drop and reacquire the lock here?
12681                          */
12682                         if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12683                             sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12684                                 /*
12685                                  * XXX do something here.
12686                                  */
12687                         }
12688
12689                         msg.dt.sent_sg_entries = sg_entries_sent;
12690                 }
12691                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12692                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12693                         ctl_failover_io(io, /*have_lock*/ 0);
12694
12695         } else {
12696
12697                 /*
12698                  * Lookup the fe_datamove() function for this particular
12699                  * front end.
12700                  */
12701                 fe_datamove =
12702                     control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12703
12704                 fe_datamove(io);
12705         }
12706 }
12707
12708 static void
12709 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12710 {
12711         union ctl_ha_msg msg;
12712         int isc_status;
12713
12714         memset(&msg, 0, sizeof(msg));
12715
12716         msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12717         msg.hdr.original_sc = io;
12718         msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12719         msg.hdr.nexus = io->io_hdr.nexus;
12720         msg.hdr.status = io->io_hdr.status;
12721         msg.scsi.tag_num = io->scsiio.tag_num;
12722         msg.scsi.tag_type = io->scsiio.tag_type;
12723         msg.scsi.scsi_status = io->scsiio.scsi_status;
12724         memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12725                sizeof(io->scsiio.sense_data));
12726         msg.scsi.sense_len = io->scsiio.sense_len;
12727         msg.scsi.sense_residual = io->scsiio.sense_residual;
12728         msg.scsi.fetd_status = io->io_hdr.port_status;
12729         msg.scsi.residual = io->scsiio.residual;
12730         io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12731
12732         if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12733                 ctl_failover_io(io, /*have_lock*/ have_lock);
12734                 return;
12735         }
12736
12737         isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12738         if (isc_status > CTL_HA_STATUS_SUCCESS) {
12739                 /* XXX do something if this fails */
12740         }
12741
12742 }
12743
12744 /*
12745  * The DMA to the remote side is done, now we need to tell the other side
12746  * we're done so it can continue with its data movement.
12747  */
12748 static void
12749 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12750 {
12751         union ctl_io *io;
12752
12753         io = rq->context;
12754
12755         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12756                 printf("%s: ISC DMA write failed with error %d", __func__,
12757                        rq->ret);
12758                 ctl_set_internal_failure(&io->scsiio,
12759                                          /*sks_valid*/ 1,
12760                                          /*retry_count*/ rq->ret);
12761         }
12762
12763         ctl_dt_req_free(rq);
12764
12765         /*
12766          * In this case, we had to malloc the memory locally.  Free it.
12767          */
12768         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12769                 int i;
12770                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12771                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
12772         }
12773         /*
12774          * The data is in local and remote memory, so now we need to send
12775          * status (good or back) back to the other side.
12776          */
12777         ctl_send_datamove_done(io, /*have_lock*/ 0);
12778 }
12779
12780 /*
12781  * We've moved the data from the host/controller into local memory.  Now we
12782  * need to push it over to the remote controller's memory.
12783  */
12784 static int
12785 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12786 {
12787         int retval;
12788
12789         retval = 0;
12790
12791         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12792                                           ctl_datamove_remote_write_cb);
12793
12794         return (retval);
12795 }
12796
12797 static void
12798 ctl_datamove_remote_write(union ctl_io *io)
12799 {
12800         int retval;
12801         void (*fe_datamove)(union ctl_io *io);
12802
12803         /*
12804          * - Get the data from the host/HBA into local memory.
12805          * - DMA memory from the local controller to the remote controller.
12806          * - Send status back to the remote controller.
12807          */
12808
12809         retval = ctl_datamove_remote_sgl_setup(io);
12810         if (retval != 0)
12811                 return;
12812
12813         /* Switch the pointer over so the FETD knows what to do */
12814         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12815
12816         /*
12817          * Use a custom move done callback, since we need to send completion
12818          * back to the other controller, not to the backend on this side.
12819          */
12820         io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12821
12822         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12823
12824         fe_datamove(io);
12825
12826         return;
12827
12828 }
12829
12830 static int
12831 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12832 {
12833 #if 0
12834         char str[256];
12835         char path_str[64];
12836         struct sbuf sb;
12837 #endif
12838
12839         /*
12840          * In this case, we had to malloc the memory locally.  Free it.
12841          */
12842         if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12843                 int i;
12844                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12845                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
12846         }
12847
12848 #if 0
12849         scsi_path_string(io, path_str, sizeof(path_str));
12850         sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12851         sbuf_cat(&sb, path_str);
12852         scsi_command_string(&io->scsiio, NULL, &sb);
12853         sbuf_printf(&sb, "\n");
12854         sbuf_cat(&sb, path_str);
12855         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12856                     io->scsiio.tag_num, io->scsiio.tag_type);
12857         sbuf_cat(&sb, path_str);
12858         sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12859                     io->io_hdr.flags, io->io_hdr.status);
12860         sbuf_finish(&sb);
12861         printk("%s", sbuf_data(&sb));
12862 #endif
12863
12864
12865         /*
12866          * The read is done, now we need to send status (good or bad) back
12867          * to the other side.
12868          */
12869         ctl_send_datamove_done(io, /*have_lock*/ 0);
12870
12871         return (0);
12872 }
12873
12874 static void
12875 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12876 {
12877         union ctl_io *io;
12878         void (*fe_datamove)(union ctl_io *io);
12879
12880         io = rq->context;
12881
12882         if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12883                 printf("%s: ISC DMA read failed with error %d", __func__,
12884                        rq->ret);
12885                 ctl_set_internal_failure(&io->scsiio,
12886                                          /*sks_valid*/ 1,
12887                                          /*retry_count*/ rq->ret);
12888         }
12889
12890         ctl_dt_req_free(rq);
12891
12892         /* Switch the pointer over so the FETD knows what to do */
12893         io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12894
12895         /*
12896          * Use a custom move done callback, since we need to send completion
12897          * back to the other controller, not to the backend on this side.
12898          */
12899         io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12900
12901         /* XXX KDM add checks like the ones in ctl_datamove? */
12902
12903         fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12904
12905         fe_datamove(io);
12906 }
12907
12908 static int
12909 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12910 {
12911         struct ctl_sg_entry *local_sglist, *remote_sglist;
12912         struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
12913         struct ctl_softc *softc;
12914         int retval;
12915         int i;
12916
12917         retval = 0;
12918         softc = control_softc;
12919
12920         local_sglist = io->io_hdr.local_sglist;
12921         local_dma_sglist = io->io_hdr.local_dma_sglist;
12922         remote_sglist = io->io_hdr.remote_sglist;
12923         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12924
12925         if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
12926                 for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
12927                         local_sglist[i].len = remote_sglist[i].len;
12928
12929                         /*
12930                          * XXX Detect the situation where the RS-level I/O
12931                          * redirector on the other side has already read the
12932                          * data off of the AOR RS on this side, and
12933                          * transferred it to remote (mirror) memory on the
12934                          * other side.  Since we already have the data in
12935                          * memory here, we just need to use it.
12936                          *
12937                          * XXX KDM this can probably be removed once we
12938                          * get the cache device code in and take the
12939                          * current AOR implementation out.
12940                          */
12941 #ifdef NEEDTOPORT
12942                         if ((remote_sglist[i].addr >=
12943                              (void *)vtophys(softc->mirr->addr))
12944                          && (remote_sglist[i].addr <
12945                              ((void *)vtophys(softc->mirr->addr) +
12946                              CacheMirrorOffset))) {
12947                                 local_sglist[i].addr = remote_sglist[i].addr -
12948                                         CacheMirrorOffset;
12949                                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12950                                      CTL_FLAG_DATA_IN)
12951                                         io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
12952                         } else {
12953                                 local_sglist[i].addr = remote_sglist[i].addr +
12954                                         CacheMirrorOffset;
12955                         }
12956 #endif
12957 #if 0
12958                         printf("%s: local %p, remote %p, len %d\n",
12959                                __func__, local_sglist[i].addr,
12960                                remote_sglist[i].addr, local_sglist[i].len);
12961 #endif
12962                 }
12963         } else {
12964                 uint32_t len_to_go;
12965
12966                 /*
12967                  * In this case, we don't have automatically allocated
12968                  * memory for this I/O on this controller.  This typically
12969                  * happens with internal CTL I/O -- e.g. inquiry, mode
12970                  * sense, etc.  Anything coming from RAIDCore will have
12971                  * a mirror area available.
12972                  */
12973                 len_to_go = io->scsiio.kern_data_len;
12974
12975                 /*
12976                  * Clear the no datasync flag, we have to use malloced
12977                  * buffers.
12978                  */
12979                 io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
12980
12981                 /*
12982                  * The difficult thing here is that the size of the various
12983                  * S/G segments may be different than the size from the
12984                  * remote controller.  That'll make it harder when DMAing
12985                  * the data back to the other side.
12986                  */
12987                 for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
12988                      sizeof(io->io_hdr.remote_sglist[0])) &&
12989                      (len_to_go > 0); i++) {
12990                         local_sglist[i].len = ctl_min(len_to_go, 131072);
12991                         CTL_SIZE_8B(local_dma_sglist[i].len,
12992                                     local_sglist[i].len);
12993                         local_sglist[i].addr =
12994                                 malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
12995
12996                         local_dma_sglist[i].addr = local_sglist[i].addr;
12997
12998                         if (local_sglist[i].addr == NULL) {
12999                                 int j;
13000
13001                                 printf("malloc failed for %zd bytes!",
13002                                        local_dma_sglist[i].len);
13003                                 for (j = 0; j < i; j++) {
13004                                         free(local_sglist[j].addr, M_CTL);
13005                                 }
13006                                 ctl_set_internal_failure(&io->scsiio,
13007                                                          /*sks_valid*/ 1,
13008                                                          /*retry_count*/ 4857);
13009                                 retval = 1;
13010                                 goto bailout_error;
13011                                 
13012                         }
13013                         /* XXX KDM do we need a sync here? */
13014
13015                         len_to_go -= local_sglist[i].len;
13016                 }
13017                 /*
13018                  * Reset the number of S/G entries accordingly.  The
13019                  * original number of S/G entries is available in
13020                  * rem_sg_entries.
13021                  */
13022                 io->scsiio.kern_sg_entries = i;
13023
13024 #if 0
13025                 printf("%s: kern_sg_entries = %d\n", __func__,
13026                        io->scsiio.kern_sg_entries);
13027                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13028                         printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13029                                local_sglist[i].addr, local_sglist[i].len,
13030                                local_dma_sglist[i].len);
13031 #endif
13032         }
13033
13034
13035         return (retval);
13036
13037 bailout_error:
13038
13039         ctl_send_datamove_done(io, /*have_lock*/ 0);
13040
13041         return (retval);
13042 }
13043
13044 static int
13045 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13046                          ctl_ha_dt_cb callback)
13047 {
13048         struct ctl_ha_dt_req *rq;
13049         struct ctl_sg_entry *remote_sglist, *local_sglist;
13050         struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13051         uint32_t local_used, remote_used, total_used;
13052         int retval;
13053         int i, j;
13054
13055         retval = 0;
13056
13057         rq = ctl_dt_req_alloc();
13058
13059         /*
13060          * If we failed to allocate the request, and if the DMA didn't fail
13061          * anyway, set busy status.  This is just a resource allocation
13062          * failure.
13063          */
13064         if ((rq == NULL)
13065          && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13066                 ctl_set_busy(&io->scsiio);
13067
13068         if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13069
13070                 if (rq != NULL)
13071                         ctl_dt_req_free(rq);
13072
13073                 /*
13074                  * The data move failed.  We need to return status back
13075                  * to the other controller.  No point in trying to DMA
13076                  * data to the remote controller.
13077                  */
13078
13079                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13080
13081                 retval = 1;
13082
13083                 goto bailout;
13084         }
13085
13086         local_sglist = io->io_hdr.local_sglist;
13087         local_dma_sglist = io->io_hdr.local_dma_sglist;
13088         remote_sglist = io->io_hdr.remote_sglist;
13089         remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13090         local_used = 0;
13091         remote_used = 0;
13092         total_used = 0;
13093
13094         if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13095                 rq->ret = CTL_HA_STATUS_SUCCESS;
13096                 rq->context = io;
13097                 callback(rq);
13098                 goto bailout;
13099         }
13100
13101         /*
13102          * Pull/push the data over the wire from/to the other controller.
13103          * This takes into account the possibility that the local and
13104          * remote sglists may not be identical in terms of the size of
13105          * the elements and the number of elements.
13106          *
13107          * One fundamental assumption here is that the length allocated for
13108          * both the local and remote sglists is identical.  Otherwise, we've
13109          * essentially got a coding error of some sort.
13110          */
13111         for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13112                 int isc_ret;
13113                 uint32_t cur_len, dma_length;
13114                 uint8_t *tmp_ptr;
13115
13116                 rq->id = CTL_HA_DATA_CTL;
13117                 rq->command = command;
13118                 rq->context = io;
13119
13120                 /*
13121                  * Both pointers should be aligned.  But it is possible
13122                  * that the allocation length is not.  They should both
13123                  * also have enough slack left over at the end, though,
13124                  * to round up to the next 8 byte boundary.
13125                  */
13126                 cur_len = ctl_min(local_sglist[i].len - local_used,
13127                                   remote_sglist[j].len - remote_used);
13128
13129                 /*
13130                  * In this case, we have a size issue and need to decrease
13131                  * the size, except in the case where we actually have less
13132                  * than 8 bytes left.  In that case, we need to increase
13133                  * the DMA length to get the last bit.
13134                  */
13135                 if ((cur_len & 0x7) != 0) {
13136                         if (cur_len > 0x7) {
13137                                 cur_len = cur_len - (cur_len & 0x7);
13138                                 dma_length = cur_len;
13139                         } else {
13140                                 CTL_SIZE_8B(dma_length, cur_len);
13141                         }
13142
13143                 } else
13144                         dma_length = cur_len;
13145
13146                 /*
13147                  * If we had to allocate memory for this I/O, instead of using
13148                  * the non-cached mirror memory, we'll need to flush the cache
13149                  * before trying to DMA to the other controller.
13150                  *
13151                  * We could end up doing this multiple times for the same
13152                  * segment if we have a larger local segment than remote
13153                  * segment.  That shouldn't be an issue.
13154                  */
13155                 if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13156                         /*
13157                          * XXX KDM use bus_dmamap_sync() here.
13158                          */
13159                 }
13160
13161                 rq->size = dma_length;
13162
13163                 tmp_ptr = (uint8_t *)local_sglist[i].addr;
13164                 tmp_ptr += local_used;
13165
13166                 /* Use physical addresses when talking to ISC hardware */
13167                 if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13168                         /* XXX KDM use busdma */
13169 #if 0
13170                         rq->local = vtophys(tmp_ptr);
13171 #endif
13172                 } else
13173                         rq->local = tmp_ptr;
13174
13175                 tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13176                 tmp_ptr += remote_used;
13177                 rq->remote = tmp_ptr;
13178
13179                 rq->callback = NULL;
13180
13181                 local_used += cur_len;
13182                 if (local_used >= local_sglist[i].len) {
13183                         i++;
13184                         local_used = 0;
13185                 }
13186
13187                 remote_used += cur_len;
13188                 if (remote_used >= remote_sglist[j].len) {
13189                         j++;
13190                         remote_used = 0;
13191                 }
13192                 total_used += cur_len;
13193
13194                 if (total_used >= io->scsiio.kern_data_len)
13195                         rq->callback = callback;
13196
13197                 if ((rq->size & 0x7) != 0) {
13198                         printf("%s: warning: size %d is not on 8b boundary\n",
13199                                __func__, rq->size);
13200                 }
13201                 if (((uintptr_t)rq->local & 0x7) != 0) {
13202                         printf("%s: warning: local %p not on 8b boundary\n",
13203                                __func__, rq->local);
13204                 }
13205                 if (((uintptr_t)rq->remote & 0x7) != 0) {
13206                         printf("%s: warning: remote %p not on 8b boundary\n",
13207                                __func__, rq->local);
13208                 }
13209 #if 0
13210                 printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13211                        (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13212                        rq->local, rq->remote, rq->size);
13213 #endif
13214
13215                 isc_ret = ctl_dt_single(rq);
13216                 if (isc_ret == CTL_HA_STATUS_WAIT)
13217                         continue;
13218
13219                 if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13220                         rq->ret = CTL_HA_STATUS_SUCCESS;
13221                 } else {
13222                         rq->ret = isc_ret;
13223                 }
13224                 callback(rq);
13225                 goto bailout;
13226         }
13227
13228 bailout:
13229         return (retval);
13230
13231 }
13232
13233 static void
13234 ctl_datamove_remote_read(union ctl_io *io)
13235 {
13236         int retval;
13237         int i;
13238
13239         /*
13240          * This will send an error to the other controller in the case of a
13241          * failure.
13242          */
13243         retval = ctl_datamove_remote_sgl_setup(io);
13244         if (retval != 0)
13245                 return;
13246
13247         retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13248                                           ctl_datamove_remote_read_cb);
13249         if ((retval != 0)
13250          && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13251                 /*
13252                  * Make sure we free memory if there was an error..  The
13253                  * ctl_datamove_remote_xfer() function will send the
13254                  * datamove done message, or call the callback with an
13255                  * error if there is a problem.
13256                  */
13257                 for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13258                         free(io->io_hdr.local_sglist[i].addr, M_CTL);
13259         }
13260
13261         return;
13262 }
13263
13264 /*
13265  * Process a datamove request from the other controller.  This is used for
13266  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13267  * first.  Once that is complete, the data gets DMAed into the remote
13268  * controller's memory.  For reads, we DMA from the remote controller's
13269  * memory into our memory first, and then move it out to the FETD.
13270  */
13271 static void
13272 ctl_datamove_remote(union ctl_io *io)
13273 {
13274         struct ctl_softc *softc;
13275
13276         softc = control_softc;
13277
13278         mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13279
13280         /*
13281          * Note that we look for an aborted I/O here, but don't do some of
13282          * the other checks that ctl_datamove() normally does.
13283          * We don't need to run the datamove delay code, since that should
13284          * have been done if need be on the other controller.
13285          */
13286         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13287                 printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13288                        io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13289                        io->io_hdr.nexus.targ_port,
13290                        io->io_hdr.nexus.targ_target.id,
13291                        io->io_hdr.nexus.targ_lun);
13292                 io->io_hdr.port_status = 31338;
13293                 ctl_send_datamove_done(io, /*have_lock*/ 0);
13294                 return;
13295         }
13296
13297         if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13298                 ctl_datamove_remote_write(io);
13299         } else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13300                 ctl_datamove_remote_read(io);
13301         } else {
13302                 union ctl_ha_msg msg;
13303                 struct scsi_sense_data *sense;
13304                 uint8_t sks[3];
13305                 int retry_count;
13306
13307                 memset(&msg, 0, sizeof(msg));
13308
13309                 msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13310                 msg.hdr.status = CTL_SCSI_ERROR;
13311                 msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13312
13313                 retry_count = 4243;
13314
13315                 sense = &msg.scsi.sense_data;
13316                 sks[0] = SSD_SCS_VALID;
13317                 sks[1] = (retry_count >> 8) & 0xff;
13318                 sks[2] = retry_count & 0xff;
13319
13320                 /* "Internal target failure" */
13321                 scsi_set_sense_data(sense,
13322                                     /*sense_format*/ SSD_TYPE_NONE,
13323                                     /*current_error*/ 1,
13324                                     /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13325                                     /*asc*/ 0x44,
13326                                     /*ascq*/ 0x00,
13327                                     /*type*/ SSD_ELEM_SKS,
13328                                     /*size*/ sizeof(sks),
13329                                     /*data*/ sks,
13330                                     SSD_ELEM_NONE);
13331
13332                 io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13333                 if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13334                         ctl_failover_io(io, /*have_lock*/ 1);
13335                         return;
13336                 }
13337
13338                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13339                     CTL_HA_STATUS_SUCCESS) {
13340                         /* XXX KDM what to do if this fails? */
13341                 }
13342                 return;
13343         }
13344         
13345 }
13346
13347 static int
13348 ctl_process_done(union ctl_io *io)
13349 {
13350         struct ctl_lun *lun;
13351         struct ctl_softc *ctl_softc = control_softc;
13352         void (*fe_done)(union ctl_io *io);
13353         uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13354
13355         CTL_DEBUG_PRINT(("ctl_process_done\n"));
13356
13357         fe_done =
13358             control_softc->ctl_ports[targ_port]->fe_done;
13359
13360 #ifdef CTL_TIME_IO
13361         if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13362                 char str[256];
13363                 char path_str[64];
13364                 struct sbuf sb;
13365
13366                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
13367                 sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13368
13369                 sbuf_cat(&sb, path_str);
13370                 switch (io->io_hdr.io_type) {
13371                 case CTL_IO_SCSI:
13372                         ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13373                         sbuf_printf(&sb, "\n");
13374                         sbuf_cat(&sb, path_str);
13375                         sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13376                                     io->scsiio.tag_num, io->scsiio.tag_type);
13377                         break;
13378                 case CTL_IO_TASK:
13379                         sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13380                                     "Tag Type: %d\n", io->taskio.task_action,
13381                                     io->taskio.tag_num, io->taskio.tag_type);
13382                         break;
13383                 default:
13384                         printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13385                         panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13386                         break;
13387                 }
13388                 sbuf_cat(&sb, path_str);
13389                 sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13390                             (intmax_t)time_uptime - io->io_hdr.start_time);
13391                 sbuf_finish(&sb);
13392                 printf("%s", sbuf_data(&sb));
13393         }
13394 #endif /* CTL_TIME_IO */
13395
13396         switch (io->io_hdr.io_type) {
13397         case CTL_IO_SCSI:
13398                 break;
13399         case CTL_IO_TASK:
13400                 if (bootverbose || (ctl_debug & CTL_DEBUG_INFO))
13401                         ctl_io_error_print(io, NULL);
13402                 if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13403                         ctl_free_io(io);
13404                 else
13405                         fe_done(io);
13406                 return (CTL_RETVAL_COMPLETE);
13407         default:
13408                 panic("ctl_process_done: invalid io type %d\n",
13409                       io->io_hdr.io_type);
13410                 break; /* NOTREACHED */
13411         }
13412
13413         lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13414         if (lun == NULL) {
13415                 CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13416                                  io->io_hdr.nexus.targ_mapped_lun));
13417                 goto bailout;
13418         }
13419
13420         mtx_lock(&lun->lun_lock);
13421
13422         /*
13423          * Check to see if we have any errors to inject here.  We only
13424          * inject errors for commands that don't already have errors set.
13425          */
13426         if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13427             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13428             ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13429                 ctl_inject_error(lun, io);
13430
13431         /*
13432          * XXX KDM how do we treat commands that aren't completed
13433          * successfully?
13434          *
13435          * XXX KDM should we also track I/O latency?
13436          */
13437         if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13438             io->io_hdr.io_type == CTL_IO_SCSI) {
13439 #ifdef CTL_TIME_IO
13440                 struct bintime cur_bt;
13441 #endif
13442                 int type;
13443
13444                 if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13445                     CTL_FLAG_DATA_IN)
13446                         type = CTL_STATS_READ;
13447                 else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13448                     CTL_FLAG_DATA_OUT)
13449                         type = CTL_STATS_WRITE;
13450                 else
13451                         type = CTL_STATS_NO_IO;
13452
13453                 lun->stats.ports[targ_port].bytes[type] +=
13454                     io->scsiio.kern_total_len;
13455                 lun->stats.ports[targ_port].operations[type]++;
13456 #ifdef CTL_TIME_IO
13457                 bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13458                    &io->io_hdr.dma_bt);
13459                 lun->stats.ports[targ_port].num_dmas[type] +=
13460                     io->io_hdr.num_dmas;
13461                 getbintime(&cur_bt);
13462                 bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13463                 bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13464 #endif
13465         }
13466
13467         /*
13468          * Remove this from the OOA queue.
13469          */
13470         TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13471
13472         /*
13473          * Run through the blocked queue on this LUN and see if anything
13474          * has become unblocked, now that this transaction is done.
13475          */
13476         ctl_check_blocked(lun);
13477
13478         /*
13479          * If the LUN has been invalidated, free it if there is nothing
13480          * left on its OOA queue.
13481          */
13482         if ((lun->flags & CTL_LUN_INVALID)
13483          && TAILQ_EMPTY(&lun->ooa_queue)) {
13484                 mtx_unlock(&lun->lun_lock);
13485                 mtx_lock(&ctl_softc->ctl_lock);
13486                 ctl_free_lun(lun);
13487                 mtx_unlock(&ctl_softc->ctl_lock);
13488         } else
13489                 mtx_unlock(&lun->lun_lock);
13490
13491 bailout:
13492
13493         /*
13494          * If this command has been aborted, make sure we set the status
13495          * properly.  The FETD is responsible for freeing the I/O and doing
13496          * whatever it needs to do to clean up its state.
13497          */
13498         if (io->io_hdr.flags & CTL_FLAG_ABORT)
13499                 ctl_set_task_aborted(&io->scsiio);
13500
13501         /*
13502          * If enabled, print command error status.
13503          * We don't print UAs unless debugging was enabled explicitly.
13504          */
13505         do {
13506                 if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)
13507                         break;
13508                 if (!bootverbose && (ctl_debug & CTL_DEBUG_INFO) == 0)
13509                         break;
13510                 if ((ctl_debug & CTL_DEBUG_INFO) == 0 &&
13511                     ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR) &&
13512                      (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13513                         int error_code, sense_key, asc, ascq;
13514
13515                         scsi_extract_sense_len(&io->scsiio.sense_data,
13516                             io->scsiio.sense_len, &error_code, &sense_key,
13517                             &asc, &ascq, /*show_errors*/ 0);
13518                         if (sense_key == SSD_KEY_UNIT_ATTENTION)
13519                                 break;
13520                 }
13521
13522                 ctl_io_error_print(io, NULL);
13523         } while (0);
13524
13525         /*
13526          * Tell the FETD or the other shelf controller we're done with this
13527          * command.  Note that only SCSI commands get to this point.  Task
13528          * management commands are completed above.
13529          *
13530          * We only send status to the other controller if we're in XFER
13531          * mode.  In SER_ONLY mode, the I/O is done on the controller that
13532          * received the I/O (from CTL's perspective), and so the status is
13533          * generated there.
13534          * 
13535          * XXX KDM if we hold the lock here, we could cause a deadlock
13536          * if the frontend comes back in in this context to queue
13537          * something.
13538          */
13539         if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13540          && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13541                 union ctl_ha_msg msg;
13542
13543                 memset(&msg, 0, sizeof(msg));
13544                 msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13545                 msg.hdr.original_sc = io->io_hdr.original_sc;
13546                 msg.hdr.nexus = io->io_hdr.nexus;
13547                 msg.hdr.status = io->io_hdr.status;
13548                 msg.scsi.scsi_status = io->scsiio.scsi_status;
13549                 msg.scsi.tag_num = io->scsiio.tag_num;
13550                 msg.scsi.tag_type = io->scsiio.tag_type;
13551                 msg.scsi.sense_len = io->scsiio.sense_len;
13552                 msg.scsi.sense_residual = io->scsiio.sense_residual;
13553                 msg.scsi.residual = io->scsiio.residual;
13554                 memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13555                        sizeof(io->scsiio.sense_data));
13556                 /*
13557                  * We copy this whether or not this is an I/O-related
13558                  * command.  Otherwise, we'd have to go and check to see
13559                  * whether it's a read/write command, and it really isn't
13560                  * worth it.
13561                  */
13562                 memcpy(&msg.scsi.lbalen,
13563                        &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13564                        sizeof(msg.scsi.lbalen));
13565
13566                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13567                                 sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13568                         /* XXX do something here */
13569                 }
13570
13571                 ctl_free_io(io);
13572         } else 
13573                 fe_done(io);
13574
13575         return (CTL_RETVAL_COMPLETE);
13576 }
13577
13578 #ifdef CTL_WITH_CA
13579 /*
13580  * Front end should call this if it doesn't do autosense.  When the request
13581  * sense comes back in from the initiator, we'll dequeue this and send it.
13582  */
13583 int
13584 ctl_queue_sense(union ctl_io *io)
13585 {
13586         struct ctl_lun *lun;
13587         struct ctl_softc *ctl_softc;
13588         uint32_t initidx, targ_lun;
13589
13590         ctl_softc = control_softc;
13591
13592         CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13593
13594         /*
13595          * LUN lookup will likely move to the ctl_work_thread() once we
13596          * have our new queueing infrastructure (that doesn't put things on
13597          * a per-LUN queue initially).  That is so that we can handle
13598          * things like an INQUIRY to a LUN that we don't have enabled.  We
13599          * can't deal with that right now.
13600          */
13601         mtx_lock(&ctl_softc->ctl_lock);
13602
13603         /*
13604          * If we don't have a LUN for this, just toss the sense
13605          * information.
13606          */
13607         targ_lun = io->io_hdr.nexus.targ_lun;
13608         targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13609         if ((targ_lun < CTL_MAX_LUNS)
13610          && (ctl_softc->ctl_luns[targ_lun] != NULL))
13611                 lun = ctl_softc->ctl_luns[targ_lun];
13612         else
13613                 goto bailout;
13614
13615         initidx = ctl_get_initindex(&io->io_hdr.nexus);
13616
13617         mtx_lock(&lun->lun_lock);
13618         /*
13619          * Already have CA set for this LUN...toss the sense information.
13620          */
13621         if (ctl_is_set(lun->have_ca, initidx)) {
13622                 mtx_unlock(&lun->lun_lock);
13623                 goto bailout;
13624         }
13625
13626         memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13627                ctl_min(sizeof(lun->pending_sense[initidx]),
13628                sizeof(io->scsiio.sense_data)));
13629         ctl_set_mask(lun->have_ca, initidx);
13630         mtx_unlock(&lun->lun_lock);
13631
13632 bailout:
13633         mtx_unlock(&ctl_softc->ctl_lock);
13634
13635         ctl_free_io(io);
13636
13637         return (CTL_RETVAL_COMPLETE);
13638 }
13639 #endif
13640
13641 /*
13642  * Primary command inlet from frontend ports.  All SCSI and task I/O
13643  * requests must go through this function.
13644  */
13645 int
13646 ctl_queue(union ctl_io *io)
13647 {
13648         struct ctl_softc *ctl_softc;
13649
13650         CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13651
13652         ctl_softc = control_softc;
13653
13654 #ifdef CTL_TIME_IO
13655         io->io_hdr.start_time = time_uptime;
13656         getbintime(&io->io_hdr.start_bt);
13657 #endif /* CTL_TIME_IO */
13658
13659         /* Map FE-specific LUN ID into global one. */
13660         io->io_hdr.nexus.targ_mapped_lun =
13661             ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13662
13663         switch (io->io_hdr.io_type) {
13664         case CTL_IO_SCSI:
13665         case CTL_IO_TASK:
13666                 if (ctl_debug & CTL_DEBUG_CDB)
13667                         ctl_io_print(io);
13668                 ctl_enqueue_incoming(io);
13669                 break;
13670         default:
13671                 printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13672                 return (EINVAL);
13673         }
13674
13675         return (CTL_RETVAL_COMPLETE);
13676 }
13677
13678 #ifdef CTL_IO_DELAY
13679 static void
13680 ctl_done_timer_wakeup(void *arg)
13681 {
13682         union ctl_io *io;
13683
13684         io = (union ctl_io *)arg;
13685         ctl_done(io);
13686 }
13687 #endif /* CTL_IO_DELAY */
13688
13689 void
13690 ctl_done(union ctl_io *io)
13691 {
13692         struct ctl_softc *ctl_softc;
13693
13694         ctl_softc = control_softc;
13695
13696         /*
13697          * Enable this to catch duplicate completion issues.
13698          */
13699 #if 0
13700         if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13701                 printf("%s: type %d msg %d cdb %x iptl: "
13702                        "%d:%d:%d:%d tag 0x%04x "
13703                        "flag %#x status %x\n",
13704                         __func__,
13705                         io->io_hdr.io_type,
13706                         io->io_hdr.msg_type,
13707                         io->scsiio.cdb[0],
13708                         io->io_hdr.nexus.initid.id,
13709                         io->io_hdr.nexus.targ_port,
13710                         io->io_hdr.nexus.targ_target.id,
13711                         io->io_hdr.nexus.targ_lun,
13712                         (io->io_hdr.io_type ==
13713                         CTL_IO_TASK) ?
13714                         io->taskio.tag_num :
13715                         io->scsiio.tag_num,
13716                         io->io_hdr.flags,
13717                         io->io_hdr.status);
13718         } else
13719                 io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13720 #endif
13721
13722         /*
13723          * This is an internal copy of an I/O, and should not go through
13724          * the normal done processing logic.
13725          */
13726         if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13727                 return;
13728
13729         /*
13730          * We need to send a msg to the serializing shelf to finish the IO
13731          * as well.  We don't send a finish message to the other shelf if
13732          * this is a task management command.  Task management commands
13733          * aren't serialized in the OOA queue, but rather just executed on
13734          * both shelf controllers for commands that originated on that
13735          * controller.
13736          */
13737         if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13738          && (io->io_hdr.io_type != CTL_IO_TASK)) {
13739                 union ctl_ha_msg msg_io;
13740
13741                 msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13742                 msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13743                 if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13744                     sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13745                 }
13746                 /* continue on to finish IO */
13747         }
13748 #ifdef CTL_IO_DELAY
13749         if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13750                 struct ctl_lun *lun;
13751
13752                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13753
13754                 io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13755         } else {
13756                 struct ctl_lun *lun;
13757
13758                 lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13759
13760                 if ((lun != NULL)
13761                  && (lun->delay_info.done_delay > 0)) {
13762                         struct callout *callout;
13763
13764                         callout = (struct callout *)&io->io_hdr.timer_bytes;
13765                         callout_init(callout, /*mpsafe*/ 1);
13766                         io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13767                         callout_reset(callout,
13768                                       lun->delay_info.done_delay * hz,
13769                                       ctl_done_timer_wakeup, io);
13770                         if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13771                                 lun->delay_info.done_delay = 0;
13772                         return;
13773                 }
13774         }
13775 #endif /* CTL_IO_DELAY */
13776
13777         ctl_enqueue_done(io);
13778 }
13779
13780 int
13781 ctl_isc(struct ctl_scsiio *ctsio)
13782 {
13783         struct ctl_lun *lun;
13784         int retval;
13785
13786         lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13787
13788         CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13789
13790         CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13791
13792         retval = lun->backend->data_submit((union ctl_io *)ctsio);
13793
13794         return (retval);
13795 }
13796
13797
13798 static void
13799 ctl_work_thread(void *arg)
13800 {
13801         struct ctl_thread *thr = (struct ctl_thread *)arg;
13802         struct ctl_softc *softc = thr->ctl_softc;
13803         union ctl_io *io;
13804         int retval;
13805
13806         CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13807
13808         for (;;) {
13809                 retval = 0;
13810
13811                 /*
13812                  * We handle the queues in this order:
13813                  * - ISC
13814                  * - done queue (to free up resources, unblock other commands)
13815                  * - RtR queue
13816                  * - incoming queue
13817                  *
13818                  * If those queues are empty, we break out of the loop and
13819                  * go to sleep.
13820                  */
13821                 mtx_lock(&thr->queue_lock);
13822                 io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13823                 if (io != NULL) {
13824                         STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13825                         mtx_unlock(&thr->queue_lock);
13826                         ctl_handle_isc(io);
13827                         continue;
13828                 }
13829                 io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13830                 if (io != NULL) {
13831                         STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13832                         /* clear any blocked commands, call fe_done */
13833                         mtx_unlock(&thr->queue_lock);
13834                         retval = ctl_process_done(io);
13835                         continue;
13836                 }
13837                 io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13838                 if (io != NULL) {
13839                         STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13840                         mtx_unlock(&thr->queue_lock);
13841                         if (io->io_hdr.io_type == CTL_IO_TASK)
13842                                 ctl_run_task(io);
13843                         else
13844                                 ctl_scsiio_precheck(softc, &io->scsiio);
13845                         continue;
13846                 }
13847                 if (!ctl_pause_rtr) {
13848                         io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13849                         if (io != NULL) {
13850                                 STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13851                                 mtx_unlock(&thr->queue_lock);
13852                                 retval = ctl_scsiio(&io->scsiio);
13853                                 if (retval != CTL_RETVAL_COMPLETE)
13854                                         CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13855                                 continue;
13856                         }
13857                 }
13858
13859                 /* Sleep until we have something to do. */
13860                 mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13861         }
13862 }
13863
13864 static void
13865 ctl_lun_thread(void *arg)
13866 {
13867         struct ctl_softc *softc = (struct ctl_softc *)arg;
13868         struct ctl_be_lun *be_lun;
13869         int retval;
13870
13871         CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13872
13873         for (;;) {
13874                 retval = 0;
13875                 mtx_lock(&softc->ctl_lock);
13876                 be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13877                 if (be_lun != NULL) {
13878                         STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13879                         mtx_unlock(&softc->ctl_lock);
13880                         ctl_create_lun(be_lun);
13881                         continue;
13882                 }
13883
13884                 /* Sleep until we have something to do. */
13885                 mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13886                     PDROP | PRIBIO, "-", 0);
13887         }
13888 }
13889
13890 static void
13891 ctl_thresh_thread(void *arg)
13892 {
13893         struct ctl_softc *softc = (struct ctl_softc *)arg;
13894         struct ctl_lun *lun;
13895         struct ctl_be_lun *be_lun;
13896         struct scsi_da_rw_recovery_page *rwpage;
13897         struct ctl_logical_block_provisioning_page *page;
13898         const char *attr;
13899         uint64_t thres, val;
13900         int i, e;
13901
13902         CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13903
13904         for (;;) {
13905                 mtx_lock(&softc->ctl_lock);
13906                 STAILQ_FOREACH(lun, &softc->lun_list, links) {
13907                         be_lun = lun->be_lun;
13908                         if ((lun->flags & CTL_LUN_DISABLED) ||
13909                             (lun->flags & CTL_LUN_OFFLINE) ||
13910                             (be_lun->flags & CTL_LUN_FLAG_UNMAP) == 0 ||
13911                             lun->backend->lun_attr == NULL)
13912                                 continue;
13913                         rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13914                         if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13915                                 continue;
13916                         e = 0;
13917                         page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13918                         for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13919                                 if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13920                                         continue;
13921                                 thres = scsi_4btoul(page->descr[i].count);
13922                                 thres <<= CTL_LBP_EXPONENT;
13923                                 switch (page->descr[i].resource) {
13924                                 case 0x01:
13925                                         attr = "blocksavail";
13926                                         break;
13927                                 case 0x02:
13928                                         attr = "blocksused";
13929                                         break;
13930                                 case 0xf1:
13931                                         attr = "poolblocksavail";
13932                                         break;
13933                                 case 0xf2:
13934                                         attr = "poolblocksused";
13935                                         break;
13936                                 default:
13937                                         continue;
13938                                 }
13939                                 mtx_unlock(&softc->ctl_lock); // XXX
13940                                 val = lun->backend->lun_attr(
13941                                     lun->be_lun->be_lun, attr);
13942                                 mtx_lock(&softc->ctl_lock);
13943                                 if (val == UINT64_MAX)
13944                                         continue;
13945                                 if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13946                                     == SLBPPD_ARMING_INC)
13947                                         e |= (val >= thres);
13948                                 else
13949                                         e |= (val <= thres);
13950                         }
13951                         mtx_lock(&lun->lun_lock);
13952                         if (e) {
13953                                 if (lun->lasttpt == 0 ||
13954                                     time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13955                                         lun->lasttpt = time_uptime;
13956                                         for (i = 0; i < CTL_MAX_INITIATORS; i++)
13957                                                 lun->pending_ua[i] |=
13958                                                     CTL_UA_THIN_PROV_THRES;
13959                                 }
13960                         } else {
13961                                 lun->lasttpt = 0;
13962                                 for (i = 0; i < CTL_MAX_INITIATORS; i++)
13963                                         lun->pending_ua[i] &= ~CTL_UA_THIN_PROV_THRES;
13964                         }
13965                         mtx_unlock(&lun->lun_lock);
13966                 }
13967                 mtx_unlock(&softc->ctl_lock);
13968                 pause("-", CTL_LBP_PERIOD * hz);
13969         }
13970 }
13971
13972 static void
13973 ctl_enqueue_incoming(union ctl_io *io)
13974 {
13975         struct ctl_softc *softc = control_softc;
13976         struct ctl_thread *thr;
13977         u_int idx;
13978
13979         idx = (io->io_hdr.nexus.targ_port * 127 +
13980                io->io_hdr.nexus.initid.id) % worker_threads;
13981         thr = &softc->threads[idx];
13982         mtx_lock(&thr->queue_lock);
13983         STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13984         mtx_unlock(&thr->queue_lock);
13985         wakeup(thr);
13986 }
13987
13988 static void
13989 ctl_enqueue_rtr(union ctl_io *io)
13990 {
13991         struct ctl_softc *softc = control_softc;
13992         struct ctl_thread *thr;
13993
13994         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13995         mtx_lock(&thr->queue_lock);
13996         STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13997         mtx_unlock(&thr->queue_lock);
13998         wakeup(thr);
13999 }
14000
14001 static void
14002 ctl_enqueue_done(union ctl_io *io)
14003 {
14004         struct ctl_softc *softc = control_softc;
14005         struct ctl_thread *thr;
14006
14007         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14008         mtx_lock(&thr->queue_lock);
14009         STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14010         mtx_unlock(&thr->queue_lock);
14011         wakeup(thr);
14012 }
14013
14014 static void
14015 ctl_enqueue_isc(union ctl_io *io)
14016 {
14017         struct ctl_softc *softc = control_softc;
14018         struct ctl_thread *thr;
14019
14020         thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14021         mtx_lock(&thr->queue_lock);
14022         STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14023         mtx_unlock(&thr->queue_lock);
14024         wakeup(thr);
14025 }
14026
14027 /* Initialization and failover */
14028
14029 void
14030 ctl_init_isc_msg(void)
14031 {
14032         printf("CTL: Still calling this thing\n");
14033 }
14034
14035 /*
14036  * Init component
14037  *      Initializes component into configuration defined by bootMode
14038  *      (see hasc-sv.c)
14039  *      returns hasc_Status:
14040  *              OK
14041  *              ERROR - fatal error
14042  */
14043 static ctl_ha_comp_status
14044 ctl_isc_init(struct ctl_ha_component *c)
14045 {
14046         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14047
14048         c->status = ret;
14049         return ret;
14050 }
14051
14052 /* Start component
14053  *      Starts component in state requested. If component starts successfully,
14054  *      it must set its own state to the requestrd state
14055  *      When requested state is HASC_STATE_HA, the component may refine it
14056  *      by adding _SLAVE or _MASTER flags.
14057  *      Currently allowed state transitions are:
14058  *      UNKNOWN->HA             - initial startup
14059  *      UNKNOWN->SINGLE - initial startup when no parter detected
14060  *      HA->SINGLE              - failover
14061  * returns ctl_ha_comp_status:
14062  *              OK      - component successfully started in requested state
14063  *              FAILED  - could not start the requested state, failover may
14064  *                        be possible
14065  *              ERROR   - fatal error detected, no future startup possible
14066  */
14067 static ctl_ha_comp_status
14068 ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14069 {
14070         ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14071
14072         printf("%s: go\n", __func__);
14073
14074         // UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14075         if (c->state == CTL_HA_STATE_UNKNOWN ) {
14076                 control_softc->is_single = 0;
14077                 if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14078                     != CTL_HA_STATUS_SUCCESS) {
14079                         printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14080                         ret = CTL_HA_COMP_STATUS_ERROR;
14081                 }
14082         } else if (CTL_HA_STATE_IS_HA(c->state)
14083                 && CTL_HA_STATE_IS_SINGLE(state)){
14084                 // HA->SINGLE transition
14085                 ctl_failover();
14086                 control_softc->is_single = 1;
14087         } else {
14088                 printf("ctl_isc_start:Invalid state transition %X->%X\n",
14089                        c->state, state);
14090                 ret = CTL_HA_COMP_STATUS_ERROR;
14091         }
14092         if (CTL_HA_STATE_IS_SINGLE(state))
14093                 control_softc->is_single = 1;
14094
14095         c->state = state;
14096         c->status = ret;
14097         return ret;
14098 }
14099
14100 /*
14101  * Quiesce component
14102  * The component must clear any error conditions (set status to OK) and
14103  * prepare itself to another Start call
14104  * returns ctl_ha_comp_status:
14105  *      OK
14106  *      ERROR
14107  */
14108 static ctl_ha_comp_status
14109 ctl_isc_quiesce(struct ctl_ha_component *c)
14110 {
14111         int ret = CTL_HA_COMP_STATUS_OK;
14112
14113         ctl_pause_rtr = 1;
14114         c->status = ret;
14115         return ret;
14116 }
14117
14118 struct ctl_ha_component ctl_ha_component_ctlisc =
14119 {
14120         .name = "CTL ISC",
14121         .state = CTL_HA_STATE_UNKNOWN,
14122         .init = ctl_isc_init,
14123         .start = ctl_isc_start,
14124         .quiesce = ctl_isc_quiesce
14125 };
14126
14127 /*
14128  *  vim: ts=8
14129  */