1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2003-2009 Silicon Graphics International Corp.
5  * Copyright (c) 2012 The FreeBSD Foundation
6  * Copyright (c) 2014-2017 Alexander Motin <mav@FreeBSD.org>
7  * Copyright (c) 2017 Jakub Wojciech Klama <jceel@FreeBSD.org>
8  * Copyright (c) 2018 Marcelo Araujo <araujo@FreeBSD.org>
9  * All rights reserved.
10  *
11  * Portions of this software were developed by Edward Tomasz Napierala
12  * under sponsorship from the FreeBSD Foundation.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions, and the following disclaimer,
19  *    without modification.
20  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
21  *    substantially similar to the "NO WARRANTY" disclaimer below
22  *    ("Disclaimer") and any redistribution must be conditioned upon
23  *    including a substantially similar Disclaimer requirement for further
24  *    binary redistribution.
25  *
26  * NO WARRANTY
27  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
30  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
35  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
36  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37  * POSSIBILITY OF SUCH DAMAGES.
38  *
39  * $Id$
40  */
41 /*
42  * CAM Target Layer, a SCSI device emulation subsystem.
43  *
44  * Author: Ken Merry <ken@FreeBSD.org>
45  */
46 
47 #include <sys/cdefs.h>
48 __FBSDID("$FreeBSD: stable/12/sys/cam/ctl/ctl.c 372544 2022-09-14 17:29:45Z mav $");
49 
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/ctype.h>
53 #include <sys/kernel.h>
54 #include <sys/types.h>
55 #include <sys/kthread.h>
56 #include <sys/bio.h>
57 #include <sys/fcntl.h>
58 #include <sys/lock.h>
59 #include <sys/module.h>
60 #include <sys/mutex.h>
61 #include <sys/condvar.h>
62 #include <sys/malloc.h>
63 #include <sys/conf.h>
64 #include <sys/ioccom.h>
65 #include <sys/queue.h>
66 #include <sys/sbuf.h>
67 #include <sys/smp.h>
68 #include <sys/endian.h>
69 #include <sys/proc.h>
70 #include <sys/sched.h>
71 #include <sys/sysctl.h>
72 #include <sys/nv.h>
73 #include <sys/dnv.h>
74 #include <vm/uma.h>
75 
76 #include <cam/cam.h>
77 #include <cam/scsi/scsi_all.h>
78 #include <cam/scsi/scsi_cd.h>
79 #include <cam/scsi/scsi_da.h>
80 #include <cam/ctl/ctl_io.h>
81 #include <cam/ctl/ctl.h>
82 #include <cam/ctl/ctl_frontend.h>
83 #include <cam/ctl/ctl_util.h>
84 #include <cam/ctl/ctl_backend.h>
85 #include <cam/ctl/ctl_ioctl.h>
86 #include <cam/ctl/ctl_ha.h>
87 #include <cam/ctl/ctl_private.h>
88 #include <cam/ctl/ctl_debug.h>
89 #include <cam/ctl/ctl_scsi_all.h>
90 #include <cam/ctl/ctl_error.h>
91 
92 struct ctl_softc *control_softc = NULL;
93 
94 /*
95  * Template mode pages.
96  */
97 
98 /*
99  * Note that these are default values only.  The actual values will be
100  * filled in when the user does a mode sense.
101  */
102 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
103 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
104 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
105 	/*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
106 	/*read_retry_count*/0,
107 	/*correction_span*/0,
108 	/*head_offset_count*/0,
109 	/*data_strobe_offset_cnt*/0,
110 	/*byte8*/SMS_RWER_LBPERE,
111 	/*write_retry_count*/0,
112 	/*reserved2*/0,
113 	/*recovery_time_limit*/{0, 0},
114 };
115 
116 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
117 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
118 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
119 	/*byte3*/SMS_RWER_PER,
120 	/*read_retry_count*/0,
121 	/*correction_span*/0,
122 	/*head_offset_count*/0,
123 	/*data_strobe_offset_cnt*/0,
124 	/*byte8*/SMS_RWER_LBPERE,
125 	/*write_retry_count*/0,
126 	/*reserved2*/0,
127 	/*recovery_time_limit*/{0, 0},
128 };
129 
130 const static struct scsi_format_page format_page_default = {
131 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
132 	/*page_length*/sizeof(struct scsi_format_page) - 2,
133 	/*tracks_per_zone*/ {0, 0},
134 	/*alt_sectors_per_zone*/ {0, 0},
135 	/*alt_tracks_per_zone*/ {0, 0},
136 	/*alt_tracks_per_lun*/ {0, 0},
137 	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
138 			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
139 	/*bytes_per_sector*/ {0, 0},
140 	/*interleave*/ {0, 0},
141 	/*track_skew*/ {0, 0},
142 	/*cylinder_skew*/ {0, 0},
143 	/*flags*/ SFP_HSEC,
144 	/*reserved*/ {0, 0, 0}
145 };
146 
147 const static struct scsi_format_page format_page_changeable = {
148 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
149 	/*page_length*/sizeof(struct scsi_format_page) - 2,
150 	/*tracks_per_zone*/ {0, 0},
151 	/*alt_sectors_per_zone*/ {0, 0},
152 	/*alt_tracks_per_zone*/ {0, 0},
153 	/*alt_tracks_per_lun*/ {0, 0},
154 	/*sectors_per_track*/ {0, 0},
155 	/*bytes_per_sector*/ {0, 0},
156 	/*interleave*/ {0, 0},
157 	/*track_skew*/ {0, 0},
158 	/*cylinder_skew*/ {0, 0},
159 	/*flags*/ 0,
160 	/*reserved*/ {0, 0, 0}
161 };
162 
163 const static struct scsi_rigid_disk_page rigid_disk_page_default = {
164 	/*page_code*/SMS_RIGID_DISK_PAGE,
165 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
166 	/*cylinders*/ {0, 0, 0},
167 	/*heads*/ CTL_DEFAULT_HEADS,
168 	/*start_write_precomp*/ {0, 0, 0},
169 	/*start_reduced_current*/ {0, 0, 0},
170 	/*step_rate*/ {0, 0},
171 	/*landing_zone_cylinder*/ {0, 0, 0},
172 	/*rpl*/ SRDP_RPL_DISABLED,
173 	/*rotational_offset*/ 0,
174 	/*reserved1*/ 0,
175 	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
176 			   CTL_DEFAULT_ROTATION_RATE & 0xff},
177 	/*reserved2*/ {0, 0}
178 };
179 
180 const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
181 	/*page_code*/SMS_RIGID_DISK_PAGE,
182 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
183 	/*cylinders*/ {0, 0, 0},
184 	/*heads*/ 0,
185 	/*start_write_precomp*/ {0, 0, 0},
186 	/*start_reduced_current*/ {0, 0, 0},
187 	/*step_rate*/ {0, 0},
188 	/*landing_zone_cylinder*/ {0, 0, 0},
189 	/*rpl*/ 0,
190 	/*rotational_offset*/ 0,
191 	/*reserved1*/ 0,
192 	/*rotation_rate*/ {0, 0},
193 	/*reserved2*/ {0, 0}
194 };
195 
196 const static struct scsi_da_verify_recovery_page verify_er_page_default = {
197 	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
198 	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
199 	/*byte3*/0,
200 	/*read_retry_count*/0,
201 	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
202 	/*recovery_time_limit*/{0, 0},
203 };
204 
205 const static struct scsi_da_verify_recovery_page verify_er_page_changeable = {
206 	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
207 	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
208 	/*byte3*/SMS_VER_PER,
209 	/*read_retry_count*/0,
210 	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
211 	/*recovery_time_limit*/{0, 0},
212 };
213 
214 const static struct scsi_caching_page caching_page_default = {
215 	/*page_code*/SMS_CACHING_PAGE,
216 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
217 	/*flags1*/ SCP_DISC | SCP_WCE,
218 	/*ret_priority*/ 0,
219 	/*disable_pf_transfer_len*/ {0xff, 0xff},
220 	/*min_prefetch*/ {0, 0},
221 	/*max_prefetch*/ {0xff, 0xff},
222 	/*max_pf_ceiling*/ {0xff, 0xff},
223 	/*flags2*/ 0,
224 	/*cache_segments*/ 0,
225 	/*cache_seg_size*/ {0, 0},
226 	/*reserved*/ 0,
227 	/*non_cache_seg_size*/ {0, 0, 0}
228 };
229 
230 const static struct scsi_caching_page caching_page_changeable = {
231 	/*page_code*/SMS_CACHING_PAGE,
232 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
233 	/*flags1*/ SCP_WCE | SCP_RCD,
234 	/*ret_priority*/ 0,
235 	/*disable_pf_transfer_len*/ {0, 0},
236 	/*min_prefetch*/ {0, 0},
237 	/*max_prefetch*/ {0, 0},
238 	/*max_pf_ceiling*/ {0, 0},
239 	/*flags2*/ 0,
240 	/*cache_segments*/ 0,
241 	/*cache_seg_size*/ {0, 0},
242 	/*reserved*/ 0,
243 	/*non_cache_seg_size*/ {0, 0, 0}
244 };
245 
246 const static struct scsi_control_page control_page_default = {
247 	/*page_code*/SMS_CONTROL_MODE_PAGE,
248 	/*page_length*/sizeof(struct scsi_control_page) - 2,
249 	/*rlec*/0,
250 	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
251 	/*eca_and_aen*/0,
252 	/*flags4*/SCP_TAS,
253 	/*aen_holdoff_period*/{0, 0},
254 	/*busy_timeout_period*/{0, 0},
255 	/*extended_selftest_completion_time*/{0, 0}
256 };
257 
258 const static struct scsi_control_page control_page_changeable = {
259 	/*page_code*/SMS_CONTROL_MODE_PAGE,
260 	/*page_length*/sizeof(struct scsi_control_page) - 2,
261 	/*rlec*/SCP_DSENSE,
262 	/*queue_flags*/SCP_QUEUE_ALG_MASK | SCP_NUAR,
263 	/*eca_and_aen*/SCP_SWP,
264 	/*flags4*/0,
265 	/*aen_holdoff_period*/{0, 0},
266 	/*busy_timeout_period*/{0, 0},
267 	/*extended_selftest_completion_time*/{0, 0}
268 };
269 
270 #define CTL_CEM_LEN	(sizeof(struct scsi_control_ext_page) - 4)
271 
272 const static struct scsi_control_ext_page control_ext_page_default = {
273 	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
274 	/*subpage_code*/0x01,
275 	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
276 	/*flags*/0,
277 	/*prio*/0,
278 	/*max_sense*/0
279 };
280 
281 const static struct scsi_control_ext_page control_ext_page_changeable = {
282 	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
283 	/*subpage_code*/0x01,
284 	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
285 	/*flags*/0,
286 	/*prio*/0,
287 	/*max_sense*/0xff
288 };
289 
290 const static struct scsi_info_exceptions_page ie_page_default = {
291 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
292 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
293 	/*info_flags*/SIEP_FLAGS_EWASC,
294 	/*mrie*/SIEP_MRIE_NO,
295 	/*interval_timer*/{0, 0, 0, 0},
296 	/*report_count*/{0, 0, 0, 1}
297 };
298 
299 const static struct scsi_info_exceptions_page ie_page_changeable = {
300 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
301 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
302 	/*info_flags*/SIEP_FLAGS_EWASC | SIEP_FLAGS_DEXCPT | SIEP_FLAGS_TEST |
303 	    SIEP_FLAGS_LOGERR,
304 	/*mrie*/0x0f,
305 	/*interval_timer*/{0xff, 0xff, 0xff, 0xff},
306 	/*report_count*/{0xff, 0xff, 0xff, 0xff}
307 };
308 
309 #define CTL_LBPM_LEN	(sizeof(struct ctl_logical_block_provisioning_page) - 4)
310 
311 const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
312 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
313 	/*subpage_code*/0x02,
314 	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
315 	/*flags*/0,
316 	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
317 	/*descr*/{}},
318 	{{/*flags*/0,
319 	  /*resource*/0x01,
320 	  /*reserved*/{0, 0},
321 	  /*count*/{0, 0, 0, 0}},
322 	 {/*flags*/0,
323 	  /*resource*/0x02,
324 	  /*reserved*/{0, 0},
325 	  /*count*/{0, 0, 0, 0}},
326 	 {/*flags*/0,
327 	  /*resource*/0xf1,
328 	  /*reserved*/{0, 0},
329 	  /*count*/{0, 0, 0, 0}},
330 	 {/*flags*/0,
331 	  /*resource*/0xf2,
332 	  /*reserved*/{0, 0},
333 	  /*count*/{0, 0, 0, 0}}
334 	}
335 };
336 
337 const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
338 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
339 	/*subpage_code*/0x02,
340 	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
341 	/*flags*/SLBPP_SITUA,
342 	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
343 	/*descr*/{}},
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 	 {/*flags*/0,
353 	  /*resource*/0,
354 	  /*reserved*/{0, 0},
355 	  /*count*/{0, 0, 0, 0}},
356 	 {/*flags*/0,
357 	  /*resource*/0,
358 	  /*reserved*/{0, 0},
359 	  /*count*/{0, 0, 0, 0}}
360 	}
361 };
362 
363 const static struct scsi_cddvd_capabilities_page cddvd_page_default = {
364 	/*page_code*/SMS_CDDVD_CAPS_PAGE,
365 	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
366 	/*caps1*/0x3f,
367 	/*caps2*/0x00,
368 	/*caps3*/0xf0,
369 	/*caps4*/0x00,
370 	/*caps5*/0x29,
371 	/*caps6*/0x00,
372 	/*obsolete*/{0, 0},
373 	/*nvol_levels*/{0, 0},
374 	/*buffer_size*/{8, 0},
375 	/*obsolete2*/{0, 0},
376 	/*reserved*/0,
377 	/*digital*/0,
378 	/*obsolete3*/0,
379 	/*copy_management*/0,
380 	/*reserved2*/0,
381 	/*rotation_control*/0,
382 	/*cur_write_speed*/0,
383 	/*num_speed_descr*/0,
384 };
385 
386 const static struct scsi_cddvd_capabilities_page cddvd_page_changeable = {
387 	/*page_code*/SMS_CDDVD_CAPS_PAGE,
388 	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
389 	/*caps1*/0,
390 	/*caps2*/0,
391 	/*caps3*/0,
392 	/*caps4*/0,
393 	/*caps5*/0,
394 	/*caps6*/0,
395 	/*obsolete*/{0, 0},
396 	/*nvol_levels*/{0, 0},
397 	/*buffer_size*/{0, 0},
398 	/*obsolete2*/{0, 0},
399 	/*reserved*/0,
400 	/*digital*/0,
401 	/*obsolete3*/0,
402 	/*copy_management*/0,
403 	/*reserved2*/0,
404 	/*rotation_control*/0,
405 	/*cur_write_speed*/0,
406 	/*num_speed_descr*/0,
407 };
408 
409 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
410 static int worker_threads = -1;
411 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
412     &worker_threads, 1, "Number of worker threads");
413 static int ctl_debug = CTL_DEBUG_NONE;
414 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
415     &ctl_debug, 0, "Enabled debug flags");
416 static int ctl_lun_map_size = 1024;
417 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, lun_map_size, CTLFLAG_RWTUN,
418     &ctl_lun_map_size, 0, "Size of per-port LUN map (max LUN + 1)");
419 #ifdef  CTL_TIME_IO
420 static int ctl_time_io_secs = CTL_TIME_IO_DEFAULT_SECS;
421 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, time_io_secs, CTLFLAG_RWTUN,
422     &ctl_time_io_secs, 0, "Log requests taking more seconds");
423 #endif
424 
425 /*
426  * Maximum number of LUNs we support.  MUST be a power of 2.
427  */
428 #define	CTL_DEFAULT_MAX_LUNS	1024
429 static int ctl_max_luns = CTL_DEFAULT_MAX_LUNS;
430 TUNABLE_INT("kern.cam.ctl.max_luns", &ctl_max_luns);
431 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, max_luns, CTLFLAG_RDTUN,
432     &ctl_max_luns, CTL_DEFAULT_MAX_LUNS, "Maximum number of LUNs");
433 
434 /*
435  * Maximum number of ports registered at one time.
436  */
437 #define	CTL_DEFAULT_MAX_PORTS		256
438 static int ctl_max_ports = CTL_DEFAULT_MAX_PORTS;
439 TUNABLE_INT("kern.cam.ctl.max_ports", &ctl_max_ports);
440 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, max_ports, CTLFLAG_RDTUN,
441     &ctl_max_ports, CTL_DEFAULT_MAX_LUNS, "Maximum number of ports");
442 
443 /*
444  * Maximum number of initiators we support.
445  */
446 #define	CTL_MAX_INITIATORS	(CTL_MAX_INIT_PER_PORT * ctl_max_ports)
447 
448 /*
449  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
450  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
451  * SCSI Ports (0x88), Third-party Copy (0x8F), SCSI Feature Sets (0x92),
452  * Block limits (0xB0), Block Device Characteristics (0xB1) and
453  * Logical Block Provisioning (0xB2)
454  */
455 #define SCSI_EVPD_NUM_SUPPORTED_PAGES	11
456 
457 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
458 				  int param);
459 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
460 static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
461 static int ctl_init(void);
462 static int ctl_shutdown(void);
463 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
464 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
465 static void ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
466 static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
467 			      struct ctl_ooa *ooa_hdr,
468 			      struct ctl_ooa_entry *kern_entries);
469 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
470 		     struct thread *td);
471 static int ctl_enable_lun(struct ctl_lun *lun);
472 static int ctl_disable_lun(struct ctl_lun *lun);
473 static int ctl_free_lun(struct ctl_lun *lun);
474 
475 static int ctl_do_mode_select(union ctl_io *io);
476 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
477 			   uint64_t res_key, uint64_t sa_res_key,
478 			   uint8_t type, uint32_t residx,
479 			   struct ctl_scsiio *ctsio,
480 			   struct scsi_per_res_out *cdb,
481 			   struct scsi_per_res_out_parms* param);
482 static void ctl_pro_preempt_other(struct ctl_lun *lun,
483 				  union ctl_ha_msg *msg);
484 static void ctl_hndl_per_res_out_on_other_sc(union ctl_io *io);
485 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
486 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
487 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
488 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
489 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
490 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
491 					 int alloc_len);
492 static int ctl_inquiry_evpd_sfs(struct ctl_scsiio *ctsio, int alloc_len);
493 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
494 					 int alloc_len);
495 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
496 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
497 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
498 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
499 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
500 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
501     bool seq);
502 static ctl_action ctl_seq_check(union ctl_io *io1, union ctl_io *io2);
503 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
504     union ctl_io *pending_io, const uint8_t *serialize_row,
505     union ctl_io *ooa_io);
506 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
507 				union ctl_io **starting_io);
508 static void ctl_try_unblock_io(struct ctl_lun *lun, union ctl_io *io,
509     bool skip);
510 static void ctl_try_unblock_others(struct ctl_lun *lun, union ctl_io *io,
511     bool skip);
512 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
513 				const struct ctl_cmd_entry *entry,
514 				struct ctl_scsiio *ctsio);
515 static void ctl_failover_lun(union ctl_io *io);
516 static void ctl_scsiio_precheck(struct ctl_scsiio *ctsio);
517 static int ctl_scsiio(struct ctl_scsiio *ctsio);
518 
519 static int ctl_target_reset(union ctl_io *io);
520 static void ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx,
521 			 ctl_ua_type ua_type);
522 static int ctl_lun_reset(union ctl_io *io);
523 static int ctl_abort_task(union ctl_io *io);
524 static int ctl_abort_task_set(union ctl_io *io);
525 static int ctl_query_task(union ctl_io *io, int task_set);
526 static void ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
527 			      ctl_ua_type ua_type);
528 static int ctl_i_t_nexus_reset(union ctl_io *io);
529 static int ctl_query_async_event(union ctl_io *io);
530 static void ctl_run_task(union ctl_io *io);
531 #ifdef CTL_IO_DELAY
532 static void ctl_datamove_timer_wakeup(void *arg);
533 static void ctl_done_timer_wakeup(void *arg);
534 #endif /* CTL_IO_DELAY */
535 
536 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
537 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
538 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io, bool samethr);
539 static void ctl_datamove_remote_write(union ctl_io *io);
540 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io, bool samethr);
541 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
542 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
543 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
544 				    ctl_ha_dt_cb callback);
545 static void ctl_datamove_remote_read(union ctl_io *io);
546 static void ctl_datamove_remote(union ctl_io *io);
547 static void ctl_process_done(union ctl_io *io);
548 static void ctl_thresh_thread(void *arg);
549 static void ctl_work_thread(void *arg);
550 static void ctl_enqueue_incoming(union ctl_io *io);
551 static void ctl_enqueue_rtr(union ctl_io *io);
552 static void ctl_enqueue_done(union ctl_io *io);
553 static void ctl_enqueue_isc(union ctl_io *io);
554 static const struct ctl_cmd_entry *
555     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
556 static const struct ctl_cmd_entry *
557     ctl_validate_command(struct ctl_scsiio *ctsio);
558 static int ctl_cmd_applicable(uint8_t lun_type,
559     const struct ctl_cmd_entry *entry);
560 static int ctl_ha_init(void);
561 static int ctl_ha_shutdown(void);
562 
563 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
564 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
565 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
566 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
567 
568 /*
569  * Load the serialization table.  This isn't very pretty, but is probably
570  * the easiest way to do it.
571  */
572 #include "ctl_ser_table.c"
573 
574 /*
575  * We only need to define open, close and ioctl routines for this driver.
576  */
577 static struct cdevsw ctl_cdevsw = {
578 	.d_version =	D_VERSION,
579 	.d_flags =	0,
580 	.d_open =	ctl_open,
581 	.d_close =	ctl_close,
582 	.d_ioctl =	ctl_ioctl,
583 	.d_name =	"ctl",
584 };
585 
586 
587 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
588 
589 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
590 
591 static moduledata_t ctl_moduledata = {
592 	"ctl",
593 	ctl_module_event_handler,
594 	NULL
595 };
596 
597 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
598 MODULE_VERSION(ctl, 1);
599 
600 static struct ctl_frontend ha_frontend =
601 {
602 	.name = "ha",
603 	.init = ctl_ha_init,
604 	.shutdown = ctl_ha_shutdown,
605 };
606 
607 static int
ctl_ha_init(void)608 ctl_ha_init(void)
609 {
610 	struct ctl_softc *softc = control_softc;
611 
612 	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
613 	                    &softc->othersc_pool) != 0)
614 		return (ENOMEM);
615 	if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
616 		ctl_pool_free(softc->othersc_pool);
617 		return (EIO);
618 	}
619 	if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
620 	    != CTL_HA_STATUS_SUCCESS) {
621 		ctl_ha_msg_destroy(softc);
622 		ctl_pool_free(softc->othersc_pool);
623 		return (EIO);
624 	}
625 	return (0);
626 };
627 
628 static int
ctl_ha_shutdown(void)629 ctl_ha_shutdown(void)
630 {
631 	struct ctl_softc *softc = control_softc;
632 	struct ctl_port *port;
633 
634 	ctl_ha_msg_shutdown(softc);
635 	if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL) != CTL_HA_STATUS_SUCCESS)
636 		return (EIO);
637 	if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
638 		return (EIO);
639 	ctl_pool_free(softc->othersc_pool);
640 	while ((port = STAILQ_FIRST(&ha_frontend.port_list)) != NULL) {
641 		ctl_port_deregister(port);
642 		free(port->port_name, M_CTL);
643 		free(port, M_CTL);
644 	}
645 	return (0);
646 };
647 
648 static void
ctl_ha_datamove(union ctl_io * io)649 ctl_ha_datamove(union ctl_io *io)
650 {
651 	struct ctl_lun *lun = CTL_LUN(io);
652 	struct ctl_sg_entry *sgl;
653 	union ctl_ha_msg msg;
654 	uint32_t sg_entries_sent;
655 	int do_sg_copy, i, j;
656 
657 	memset(&msg.dt, 0, sizeof(msg.dt));
658 	msg.hdr.msg_type = CTL_MSG_DATAMOVE;
659 	msg.hdr.original_sc = io->io_hdr.remote_io;
660 	msg.hdr.serializing_sc = io;
661 	msg.hdr.nexus = io->io_hdr.nexus;
662 	msg.hdr.status = io->io_hdr.status;
663 	msg.dt.flags = io->io_hdr.flags;
664 
665 	/*
666 	 * We convert everything into a S/G list here.  We can't
667 	 * pass by reference, only by value between controllers.
668 	 * So we can't pass a pointer to the S/G list, only as many
669 	 * S/G entries as we can fit in here.  If it's possible for
670 	 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
671 	 * then we need to break this up into multiple transfers.
672 	 */
673 	if (io->scsiio.kern_sg_entries == 0) {
674 		msg.dt.kern_sg_entries = 1;
675 #if 0
676 		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
677 			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
678 		} else {
679 			/* XXX KDM use busdma here! */
680 			msg.dt.sg_list[0].addr =
681 			    (void *)vtophys(io->scsiio.kern_data_ptr);
682 		}
683 #else
684 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
685 		    ("HA does not support BUS_ADDR"));
686 		msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
687 #endif
688 		msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
689 		do_sg_copy = 0;
690 	} else {
691 		msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
692 		do_sg_copy = 1;
693 	}
694 
695 	msg.dt.kern_data_len = io->scsiio.kern_data_len;
696 	msg.dt.kern_total_len = io->scsiio.kern_total_len;
697 	msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
698 	msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
699 	msg.dt.sg_sequence = 0;
700 
701 	/*
702 	 * Loop until we've sent all of the S/G entries.  On the
703 	 * other end, we'll recompose these S/G entries into one
704 	 * contiguous list before processing.
705 	 */
706 	for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
707 	    msg.dt.sg_sequence++) {
708 		msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
709 		    sizeof(msg.dt.sg_list[0])),
710 		    msg.dt.kern_sg_entries - sg_entries_sent);
711 		if (do_sg_copy != 0) {
712 			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
713 			for (i = sg_entries_sent, j = 0;
714 			     i < msg.dt.cur_sg_entries; i++, j++) {
715 #if 0
716 				if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
717 					msg.dt.sg_list[j].addr = sgl[i].addr;
718 				} else {
719 					/* XXX KDM use busdma here! */
720 					msg.dt.sg_list[j].addr =
721 					    (void *)vtophys(sgl[i].addr);
722 				}
723 #else
724 				KASSERT((io->io_hdr.flags &
725 				    CTL_FLAG_BUS_ADDR) == 0,
726 				    ("HA does not support BUS_ADDR"));
727 				msg.dt.sg_list[j].addr = sgl[i].addr;
728 #endif
729 				msg.dt.sg_list[j].len = sgl[i].len;
730 			}
731 		}
732 
733 		sg_entries_sent += msg.dt.cur_sg_entries;
734 		msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
735 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
736 		    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
737 		    sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
738 		    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
739 			io->io_hdr.port_status = 31341;
740 			ctl_datamove_done(io, true);
741 			return;
742 		}
743 		msg.dt.sent_sg_entries = sg_entries_sent;
744 	}
745 
746 	/*
747 	 * Officially handover the request from us to peer.
748 	 * If failover has just happened, then we must return error.
749 	 * If failover happen just after, then it is not our problem.
750 	 */
751 	if (lun)
752 		mtx_lock(&lun->lun_lock);
753 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
754 		if (lun)
755 			mtx_unlock(&lun->lun_lock);
756 		io->io_hdr.port_status = 31342;
757 		ctl_datamove_done(io, true);
758 		return;
759 	}
760 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
761 	io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
762 	if (lun)
763 		mtx_unlock(&lun->lun_lock);
764 }
765 
766 static void
ctl_ha_done(union ctl_io * io)767 ctl_ha_done(union ctl_io *io)
768 {
769 	union ctl_ha_msg msg;
770 
771 	if (io->io_hdr.io_type == CTL_IO_SCSI) {
772 		memset(&msg, 0, sizeof(msg));
773 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
774 		msg.hdr.original_sc = io->io_hdr.remote_io;
775 		msg.hdr.nexus = io->io_hdr.nexus;
776 		msg.hdr.status = io->io_hdr.status;
777 		msg.scsi.scsi_status = io->scsiio.scsi_status;
778 		msg.scsi.tag_num = io->scsiio.tag_num;
779 		msg.scsi.tag_type = io->scsiio.tag_type;
780 		msg.scsi.sense_len = io->scsiio.sense_len;
781 		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
782 		    io->scsiio.sense_len);
783 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
784 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
785 		    msg.scsi.sense_len, M_WAITOK);
786 	}
787 	ctl_free_io(io);
788 }
789 
790 static void
ctl_isc_handler_finish_xfer(struct ctl_softc * ctl_softc,union ctl_ha_msg * msg_info)791 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
792 			    union ctl_ha_msg *msg_info)
793 {
794 	struct ctl_scsiio *ctsio;
795 
796 	if (msg_info->hdr.original_sc == NULL) {
797 		printf("%s: original_sc == NULL!\n", __func__);
798 		/* XXX KDM now what? */
799 		return;
800 	}
801 
802 	ctsio = &msg_info->hdr.original_sc->scsiio;
803 	ctsio->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
804 	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
805 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
806 	ctsio->io_hdr.status = msg_info->hdr.status;
807 	ctsio->scsi_status = msg_info->scsi.scsi_status;
808 	ctsio->sense_len = msg_info->scsi.sense_len;
809 	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
810 	       msg_info->scsi.sense_len);
811 	ctl_enqueue_isc((union ctl_io *)ctsio);
812 }
813 
814 static void
ctl_isc_handler_finish_ser_only(struct ctl_softc * ctl_softc,union ctl_ha_msg * msg_info)815 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
816 				union ctl_ha_msg *msg_info)
817 {
818 	struct ctl_scsiio *ctsio;
819 
820 	if (msg_info->hdr.serializing_sc == NULL) {
821 		printf("%s: serializing_sc == NULL!\n", __func__);
822 		/* XXX KDM now what? */
823 		return;
824 	}
825 
826 	ctsio = &msg_info->hdr.serializing_sc->scsiio;
827 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
828 	ctl_enqueue_isc((union ctl_io *)ctsio);
829 }
830 
831 void
ctl_isc_announce_lun(struct ctl_lun * lun)832 ctl_isc_announce_lun(struct ctl_lun *lun)
833 {
834 	struct ctl_softc *softc = lun->ctl_softc;
835 	union ctl_ha_msg *msg;
836 	struct ctl_ha_msg_lun_pr_key pr_key;
837 	int i, k;
838 
839 	if (softc->ha_link != CTL_HA_LINK_ONLINE)
840 		return;
841 	mtx_lock(&lun->lun_lock);
842 	i = sizeof(msg->lun);
843 	if (lun->lun_devid)
844 		i += lun->lun_devid->len;
845 	i += sizeof(pr_key) * lun->pr_key_count;
846 alloc:
847 	mtx_unlock(&lun->lun_lock);
848 	msg = malloc(i, M_CTL, M_WAITOK);
849 	mtx_lock(&lun->lun_lock);
850 	k = sizeof(msg->lun);
851 	if (lun->lun_devid)
852 		k += lun->lun_devid->len;
853 	k += sizeof(pr_key) * lun->pr_key_count;
854 	if (i < k) {
855 		free(msg, M_CTL);
856 		i = k;
857 		goto alloc;
858 	}
859 	bzero(&msg->lun, sizeof(msg->lun));
860 	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
861 	msg->hdr.nexus.targ_lun = lun->lun;
862 	msg->hdr.nexus.targ_mapped_lun = lun->lun;
863 	msg->lun.flags = lun->flags;
864 	msg->lun.pr_generation = lun->pr_generation;
865 	msg->lun.pr_res_idx = lun->pr_res_idx;
866 	msg->lun.pr_res_type = lun->pr_res_type;
867 	msg->lun.pr_key_count = lun->pr_key_count;
868 	i = 0;
869 	if (lun->lun_devid) {
870 		msg->lun.lun_devid_len = lun->lun_devid->len;
871 		memcpy(&msg->lun.data[i], lun->lun_devid->data,
872 		    msg->lun.lun_devid_len);
873 		i += msg->lun.lun_devid_len;
874 	}
875 	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
876 		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
877 			continue;
878 		pr_key.pr_iid = k;
879 		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
880 		i += sizeof(pr_key);
881 	}
882 	mtx_unlock(&lun->lun_lock);
883 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->lun, sizeof(msg->lun) + i,
884 	    M_WAITOK);
885 	free(msg, M_CTL);
886 
887 	if (lun->flags & CTL_LUN_PRIMARY_SC) {
888 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
889 			ctl_isc_announce_mode(lun, -1,
890 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
891 			    lun->mode_pages.index[i].subpage);
892 		}
893 	}
894 }
895 
896 void
ctl_isc_announce_port(struct ctl_port * port)897 ctl_isc_announce_port(struct ctl_port *port)
898 {
899 	struct ctl_softc *softc = port->ctl_softc;
900 	union ctl_ha_msg *msg;
901 	int i;
902 
903 	if (port->targ_port < softc->port_min ||
904 	    port->targ_port >= softc->port_max ||
905 	    softc->ha_link != CTL_HA_LINK_ONLINE)
906 		return;
907 	i = sizeof(msg->port) + strlen(port->port_name) + 1;
908 	if (port->lun_map)
909 		i += port->lun_map_size * sizeof(uint32_t);
910 	if (port->port_devid)
911 		i += port->port_devid->len;
912 	if (port->target_devid)
913 		i += port->target_devid->len;
914 	if (port->init_devid)
915 		i += port->init_devid->len;
916 	msg = malloc(i, M_CTL, M_WAITOK);
917 	bzero(&msg->port, sizeof(msg->port));
918 	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
919 	msg->hdr.nexus.targ_port = port->targ_port;
920 	msg->port.port_type = port->port_type;
921 	msg->port.physical_port = port->physical_port;
922 	msg->port.virtual_port = port->virtual_port;
923 	msg->port.status = port->status;
924 	i = 0;
925 	msg->port.name_len = sprintf(&msg->port.data[i],
926 	    "%d:%s", softc->ha_id, port->port_name) + 1;
927 	i += msg->port.name_len;
928 	if (port->lun_map) {
929 		msg->port.lun_map_len = port->lun_map_size * sizeof(uint32_t);
930 		memcpy(&msg->port.data[i], port->lun_map,
931 		    msg->port.lun_map_len);
932 		i += msg->port.lun_map_len;
933 	}
934 	if (port->port_devid) {
935 		msg->port.port_devid_len = port->port_devid->len;
936 		memcpy(&msg->port.data[i], port->port_devid->data,
937 		    msg->port.port_devid_len);
938 		i += msg->port.port_devid_len;
939 	}
940 	if (port->target_devid) {
941 		msg->port.target_devid_len = port->target_devid->len;
942 		memcpy(&msg->port.data[i], port->target_devid->data,
943 		    msg->port.target_devid_len);
944 		i += msg->port.target_devid_len;
945 	}
946 	if (port->init_devid) {
947 		msg->port.init_devid_len = port->init_devid->len;
948 		memcpy(&msg->port.data[i], port->init_devid->data,
949 		    msg->port.init_devid_len);
950 		i += msg->port.init_devid_len;
951 	}
952 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
953 	    M_WAITOK);
954 	free(msg, M_CTL);
955 }
956 
957 void
ctl_isc_announce_iid(struct ctl_port * port,int iid)958 ctl_isc_announce_iid(struct ctl_port *port, int iid)
959 {
960 	struct ctl_softc *softc = port->ctl_softc;
961 	union ctl_ha_msg *msg;
962 	int i, l;
963 
964 	if (port->targ_port < softc->port_min ||
965 	    port->targ_port >= softc->port_max ||
966 	    softc->ha_link != CTL_HA_LINK_ONLINE)
967 		return;
968 	mtx_lock(&softc->ctl_lock);
969 	i = sizeof(msg->iid);
970 	l = 0;
971 	if (port->wwpn_iid[iid].name)
972 		l = strlen(port->wwpn_iid[iid].name) + 1;
973 	i += l;
974 	msg = malloc(i, M_CTL, M_NOWAIT);
975 	if (msg == NULL) {
976 		mtx_unlock(&softc->ctl_lock);
977 		return;
978 	}
979 	bzero(&msg->iid, sizeof(msg->iid));
980 	msg->hdr.msg_type = CTL_MSG_IID_SYNC;
981 	msg->hdr.nexus.targ_port = port->targ_port;
982 	msg->hdr.nexus.initid = iid;
983 	msg->iid.in_use = port->wwpn_iid[iid].in_use;
984 	msg->iid.name_len = l;
985 	msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
986 	if (port->wwpn_iid[iid].name)
987 		strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
988 	mtx_unlock(&softc->ctl_lock);
989 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
990 	free(msg, M_CTL);
991 }
992 
993 void
ctl_isc_announce_mode(struct ctl_lun * lun,uint32_t initidx,uint8_t page,uint8_t subpage)994 ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
995     uint8_t page, uint8_t subpage)
996 {
997 	struct ctl_softc *softc = lun->ctl_softc;
998 	union ctl_ha_msg *msg;
999 	u_int i, l;
1000 
1001 	if (softc->ha_link != CTL_HA_LINK_ONLINE)
1002 		return;
1003 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1004 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1005 		    page && lun->mode_pages.index[i].subpage == subpage)
1006 			break;
1007 	}
1008 	if (i == CTL_NUM_MODE_PAGES)
1009 		return;
1010 
1011 	/* Don't try to replicate pages not present on this device. */
1012 	if (lun->mode_pages.index[i].page_data == NULL)
1013 		return;
1014 
1015 	l = sizeof(msg->mode) + lun->mode_pages.index[i].page_len;
1016 	msg = malloc(l, M_CTL, M_WAITOK | M_ZERO);
1017 	msg->hdr.msg_type = CTL_MSG_MODE_SYNC;
1018 	msg->hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
1019 	msg->hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
1020 	msg->hdr.nexus.targ_lun = lun->lun;
1021 	msg->hdr.nexus.targ_mapped_lun = lun->lun;
1022 	msg->mode.page_code = page;
1023 	msg->mode.subpage = subpage;
1024 	msg->mode.page_len = lun->mode_pages.index[i].page_len;
1025 	memcpy(msg->mode.data, lun->mode_pages.index[i].page_data,
1026 	    msg->mode.page_len);
1027 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->mode, l, M_WAITOK);
1028 	free(msg, M_CTL);
1029 }
1030 
1031 static void
ctl_isc_ha_link_up(struct ctl_softc * softc)1032 ctl_isc_ha_link_up(struct ctl_softc *softc)
1033 {
1034 	struct ctl_port *port;
1035 	struct ctl_lun *lun;
1036 	union ctl_ha_msg msg;
1037 	int i;
1038 
1039 	/* Announce this node parameters to peer for validation. */
1040 	msg.login.msg_type = CTL_MSG_LOGIN;
1041 	msg.login.version = CTL_HA_VERSION;
1042 	msg.login.ha_mode = softc->ha_mode;
1043 	msg.login.ha_id = softc->ha_id;
1044 	msg.login.max_luns = ctl_max_luns;
1045 	msg.login.max_ports = ctl_max_ports;
1046 	msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
1047 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
1048 	    M_WAITOK);
1049 
1050 	STAILQ_FOREACH(port, &softc->port_list, links) {
1051 		ctl_isc_announce_port(port);
1052 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1053 			if (port->wwpn_iid[i].in_use)
1054 				ctl_isc_announce_iid(port, i);
1055 		}
1056 	}
1057 	STAILQ_FOREACH(lun, &softc->lun_list, links)
1058 		ctl_isc_announce_lun(lun);
1059 }
1060 
1061 static void
ctl_isc_ha_link_down(struct ctl_softc * softc)1062 ctl_isc_ha_link_down(struct ctl_softc *softc)
1063 {
1064 	struct ctl_port *port;
1065 	struct ctl_lun *lun;
1066 	union ctl_io *io;
1067 	int i;
1068 
1069 	mtx_lock(&softc->ctl_lock);
1070 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1071 		mtx_lock(&lun->lun_lock);
1072 		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
1073 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1074 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1075 		}
1076 		mtx_unlock(&lun->lun_lock);
1077 
1078 		mtx_unlock(&softc->ctl_lock);
1079 		io = ctl_alloc_io(softc->othersc_pool);
1080 		mtx_lock(&softc->ctl_lock);
1081 		ctl_zero_io(io);
1082 		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1083 		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1084 		ctl_enqueue_isc(io);
1085 	}
1086 
1087 	STAILQ_FOREACH(port, &softc->port_list, links) {
1088 		if (port->targ_port >= softc->port_min &&
1089 		    port->targ_port < softc->port_max)
1090 			continue;
1091 		port->status &= ~CTL_PORT_STATUS_ONLINE;
1092 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1093 			port->wwpn_iid[i].in_use = 0;
1094 			free(port->wwpn_iid[i].name, M_CTL);
1095 			port->wwpn_iid[i].name = NULL;
1096 		}
1097 	}
1098 	mtx_unlock(&softc->ctl_lock);
1099 }
1100 
1101 static void
ctl_isc_ua(struct ctl_softc * softc,union ctl_ha_msg * msg,int len)1102 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1103 {
1104 	struct ctl_lun *lun;
1105 	uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1106 
1107 	mtx_lock(&softc->ctl_lock);
1108 	if (msg->hdr.nexus.targ_mapped_lun >= ctl_max_luns ||
1109 	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) == NULL) {
1110 		mtx_unlock(&softc->ctl_lock);
1111 		return;
1112 	}
1113 	mtx_lock(&lun->lun_lock);
1114 	mtx_unlock(&softc->ctl_lock);
1115 	if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES && msg->ua.ua_set)
1116 		memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1117 	if (msg->ua.ua_all) {
1118 		if (msg->ua.ua_set)
1119 			ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1120 		else
1121 			ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1122 	} else {
1123 		if (msg->ua.ua_set)
1124 			ctl_est_ua(lun, iid, msg->ua.ua_type);
1125 		else
1126 			ctl_clr_ua(lun, iid, msg->ua.ua_type);
1127 	}
1128 	mtx_unlock(&lun->lun_lock);
1129 }
1130 
1131 static void
ctl_isc_lun_sync(struct ctl_softc * softc,union ctl_ha_msg * msg,int len)1132 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1133 {
1134 	struct ctl_lun *lun;
1135 	struct ctl_ha_msg_lun_pr_key pr_key;
1136 	int i, k;
1137 	ctl_lun_flags oflags;
1138 	uint32_t targ_lun;
1139 
1140 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1141 	mtx_lock(&softc->ctl_lock);
1142 	if (targ_lun >= ctl_max_luns ||
1143 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1144 		mtx_unlock(&softc->ctl_lock);
1145 		return;
1146 	}
1147 	mtx_lock(&lun->lun_lock);
1148 	mtx_unlock(&softc->ctl_lock);
1149 	if (lun->flags & CTL_LUN_DISABLED) {
1150 		mtx_unlock(&lun->lun_lock);
1151 		return;
1152 	}
1153 	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1154 	if (msg->lun.lun_devid_len != i || (i > 0 &&
1155 	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1156 		mtx_unlock(&lun->lun_lock);
1157 		printf("%s: Received conflicting HA LUN %d\n",
1158 		    __func__, targ_lun);
1159 		return;
1160 	} else {
1161 		/* Record whether peer is primary. */
1162 		oflags = lun->flags;
1163 		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1164 		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1165 			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1166 		else
1167 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1168 		if (oflags != lun->flags)
1169 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1170 
1171 		/* If peer is primary and we are not -- use data */
1172 		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1173 		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1174 			lun->pr_generation = msg->lun.pr_generation;
1175 			lun->pr_res_idx = msg->lun.pr_res_idx;
1176 			lun->pr_res_type = msg->lun.pr_res_type;
1177 			lun->pr_key_count = msg->lun.pr_key_count;
1178 			for (k = 0; k < CTL_MAX_INITIATORS; k++)
1179 				ctl_clr_prkey(lun, k);
1180 			for (k = 0; k < msg->lun.pr_key_count; k++) {
1181 				memcpy(&pr_key, &msg->lun.data[i],
1182 				    sizeof(pr_key));
1183 				ctl_alloc_prkey(lun, pr_key.pr_iid);
1184 				ctl_set_prkey(lun, pr_key.pr_iid,
1185 				    pr_key.pr_key);
1186 				i += sizeof(pr_key);
1187 			}
1188 		}
1189 
1190 		mtx_unlock(&lun->lun_lock);
1191 		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1192 		    __func__, targ_lun,
1193 		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1194 		    "primary" : "secondary"));
1195 
1196 		/* If we are primary but peer doesn't know -- notify */
1197 		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1198 		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1199 			ctl_isc_announce_lun(lun);
1200 	}
1201 }
1202 
1203 static void
ctl_isc_port_sync(struct ctl_softc * softc,union ctl_ha_msg * msg,int len)1204 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1205 {
1206 	struct ctl_port *port;
1207 	struct ctl_lun *lun;
1208 	int i, new;
1209 
1210 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1211 	if (port == NULL) {
1212 		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1213 		    msg->hdr.nexus.targ_port));
1214 		new = 1;
1215 		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1216 		port->frontend = &ha_frontend;
1217 		port->targ_port = msg->hdr.nexus.targ_port;
1218 		port->fe_datamove = ctl_ha_datamove;
1219 		port->fe_done = ctl_ha_done;
1220 	} else if (port->frontend == &ha_frontend) {
1221 		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1222 		    msg->hdr.nexus.targ_port));
1223 		new = 0;
1224 	} else {
1225 		printf("%s: Received conflicting HA port %d\n",
1226 		    __func__, msg->hdr.nexus.targ_port);
1227 		return;
1228 	}
1229 	port->port_type = msg->port.port_type;
1230 	port->physical_port = msg->port.physical_port;
1231 	port->virtual_port = msg->port.virtual_port;
1232 	port->status = msg->port.status;
1233 	i = 0;
1234 	free(port->port_name, M_CTL);
1235 	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1236 	    M_CTL);
1237 	i += msg->port.name_len;
1238 	if (msg->port.lun_map_len != 0) {
1239 		if (port->lun_map == NULL ||
1240 		    port->lun_map_size * sizeof(uint32_t) <
1241 		    msg->port.lun_map_len) {
1242 			port->lun_map_size = 0;
1243 			free(port->lun_map, M_CTL);
1244 			port->lun_map = malloc(msg->port.lun_map_len,
1245 			    M_CTL, M_WAITOK);
1246 		}
1247 		memcpy(port->lun_map, &msg->port.data[i], msg->port.lun_map_len);
1248 		port->lun_map_size = msg->port.lun_map_len / sizeof(uint32_t);
1249 		i += msg->port.lun_map_len;
1250 	} else {
1251 		port->lun_map_size = 0;
1252 		free(port->lun_map, M_CTL);
1253 		port->lun_map = NULL;
1254 	}
1255 	if (msg->port.port_devid_len != 0) {
1256 		if (port->port_devid == NULL ||
1257 		    port->port_devid->len < msg->port.port_devid_len) {
1258 			free(port->port_devid, M_CTL);
1259 			port->port_devid = malloc(sizeof(struct ctl_devid) +
1260 			    msg->port.port_devid_len, M_CTL, M_WAITOK);
1261 		}
1262 		memcpy(port->port_devid->data, &msg->port.data[i],
1263 		    msg->port.port_devid_len);
1264 		port->port_devid->len = msg->port.port_devid_len;
1265 		i += msg->port.port_devid_len;
1266 	} else {
1267 		free(port->port_devid, M_CTL);
1268 		port->port_devid = NULL;
1269 	}
1270 	if (msg->port.target_devid_len != 0) {
1271 		if (port->target_devid == NULL ||
1272 		    port->target_devid->len < msg->port.target_devid_len) {
1273 			free(port->target_devid, M_CTL);
1274 			port->target_devid = malloc(sizeof(struct ctl_devid) +
1275 			    msg->port.target_devid_len, M_CTL, M_WAITOK);
1276 		}
1277 		memcpy(port->target_devid->data, &msg->port.data[i],
1278 		    msg->port.target_devid_len);
1279 		port->target_devid->len = msg->port.target_devid_len;
1280 		i += msg->port.target_devid_len;
1281 	} else {
1282 		free(port->target_devid, M_CTL);
1283 		port->target_devid = NULL;
1284 	}
1285 	if (msg->port.init_devid_len != 0) {
1286 		if (port->init_devid == NULL ||
1287 		    port->init_devid->len < msg->port.init_devid_len) {
1288 			free(port->init_devid, M_CTL);
1289 			port->init_devid = malloc(sizeof(struct ctl_devid) +
1290 			    msg->port.init_devid_len, M_CTL, M_WAITOK);
1291 		}
1292 		memcpy(port->init_devid->data, &msg->port.data[i],
1293 		    msg->port.init_devid_len);
1294 		port->init_devid->len = msg->port.init_devid_len;
1295 		i += msg->port.init_devid_len;
1296 	} else {
1297 		free(port->init_devid, M_CTL);
1298 		port->init_devid = NULL;
1299 	}
1300 	if (new) {
1301 		if (ctl_port_register(port) != 0) {
1302 			printf("%s: ctl_port_register() failed with error\n",
1303 			    __func__);
1304 		}
1305 	}
1306 	mtx_lock(&softc->ctl_lock);
1307 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1308 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
1309 			continue;
1310 		mtx_lock(&lun->lun_lock);
1311 		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1312 		mtx_unlock(&lun->lun_lock);
1313 	}
1314 	mtx_unlock(&softc->ctl_lock);
1315 }
1316 
1317 static void
ctl_isc_iid_sync(struct ctl_softc * softc,union ctl_ha_msg * msg,int len)1318 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1319 {
1320 	struct ctl_port *port;
1321 	int iid;
1322 
1323 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1324 	if (port == NULL) {
1325 		printf("%s: Received IID for unknown port %d\n",
1326 		    __func__, msg->hdr.nexus.targ_port);
1327 		return;
1328 	}
1329 	iid = msg->hdr.nexus.initid;
1330 	if (port->wwpn_iid[iid].in_use != 0 &&
1331 	    msg->iid.in_use == 0)
1332 		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
1333 	port->wwpn_iid[iid].in_use = msg->iid.in_use;
1334 	port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1335 	free(port->wwpn_iid[iid].name, M_CTL);
1336 	if (msg->iid.name_len) {
1337 		port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1338 		    msg->iid.name_len, M_CTL);
1339 	} else
1340 		port->wwpn_iid[iid].name = NULL;
1341 }
1342 
1343 static void
ctl_isc_login(struct ctl_softc * softc,union ctl_ha_msg * msg,int len)1344 ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1345 {
1346 
1347 	if (msg->login.version != CTL_HA_VERSION) {
1348 		printf("CTL HA peers have different versions %d != %d\n",
1349 		    msg->login.version, CTL_HA_VERSION);
1350 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1351 		return;
1352 	}
1353 	if (msg->login.ha_mode != softc->ha_mode) {
1354 		printf("CTL HA peers have different ha_mode %d != %d\n",
1355 		    msg->login.ha_mode, softc->ha_mode);
1356 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1357 		return;
1358 	}
1359 	if (msg->login.ha_id == softc->ha_id) {
1360 		printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1361 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1362 		return;
1363 	}
1364 	if (msg->login.max_luns != ctl_max_luns ||
1365 	    msg->login.max_ports != ctl_max_ports ||
1366 	    msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1367 		printf("CTL HA peers have different limits\n");
1368 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1369 		return;
1370 	}
1371 }
1372 
1373 static void
ctl_isc_mode_sync(struct ctl_softc * softc,union ctl_ha_msg * msg,int len)1374 ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1375 {
1376 	struct ctl_lun *lun;
1377 	u_int i;
1378 	uint32_t initidx, targ_lun;
1379 
1380 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1381 	mtx_lock(&softc->ctl_lock);
1382 	if (targ_lun >= ctl_max_luns ||
1383 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1384 		mtx_unlock(&softc->ctl_lock);
1385 		return;
1386 	}
1387 	mtx_lock(&lun->lun_lock);
1388 	mtx_unlock(&softc->ctl_lock);
1389 	if (lun->flags & CTL_LUN_DISABLED) {
1390 		mtx_unlock(&lun->lun_lock);
1391 		return;
1392 	}
1393 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1394 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1395 		    msg->mode.page_code &&
1396 		    lun->mode_pages.index[i].subpage == msg->mode.subpage)
1397 			break;
1398 	}
1399 	if (i == CTL_NUM_MODE_PAGES) {
1400 		mtx_unlock(&lun->lun_lock);
1401 		return;
1402 	}
1403 	memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1404 	    lun->mode_pages.index[i].page_len);
1405 	initidx = ctl_get_initindex(&msg->hdr.nexus);
1406 	if (initidx != -1)
1407 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1408 	mtx_unlock(&lun->lun_lock);
1409 }
1410 
1411 /*
1412  * ISC (Inter Shelf Communication) event handler.  Events from the HA
1413  * subsystem come in here.
1414  */
1415 static void
ctl_isc_event_handler(ctl_ha_channel channel,ctl_ha_event event,int param)1416 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1417 {
1418 	struct ctl_softc *softc = control_softc;
1419 	union ctl_io *io;
1420 	struct ctl_prio *presio;
1421 	ctl_ha_status isc_status;
1422 
1423 	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1424 	if (event == CTL_HA_EVT_MSG_RECV) {
1425 		union ctl_ha_msg *msg, msgbuf;
1426 
1427 		if (param > sizeof(msgbuf))
1428 			msg = malloc(param, M_CTL, M_WAITOK);
1429 		else
1430 			msg = &msgbuf;
1431 		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1432 		    M_WAITOK);
1433 		if (isc_status != CTL_HA_STATUS_SUCCESS) {
1434 			printf("%s: Error receiving message: %d\n",
1435 			    __func__, isc_status);
1436 			if (msg != &msgbuf)
1437 				free(msg, M_CTL);
1438 			return;
1439 		}
1440 
1441 		CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->hdr.msg_type));
1442 		switch (msg->hdr.msg_type) {
1443 		case CTL_MSG_SERIALIZE:
1444 			io = ctl_alloc_io(softc->othersc_pool);
1445 			ctl_zero_io(io);
1446 			// populate ctsio from msg
1447 			io->io_hdr.io_type = CTL_IO_SCSI;
1448 			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1449 			io->io_hdr.remote_io = msg->hdr.original_sc;
1450 			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1451 					    CTL_FLAG_IO_ACTIVE;
1452 			/*
1453 			 * If we're in serialization-only mode, we don't
1454 			 * want to go through full done processing.  Thus
1455 			 * the COPY flag.
1456 			 *
1457 			 * XXX KDM add another flag that is more specific.
1458 			 */
1459 			if (softc->ha_mode != CTL_HA_MODE_XFER)
1460 				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1461 			io->io_hdr.nexus = msg->hdr.nexus;
1462 			io->scsiio.priority = msg->scsi.priority;
1463 			io->scsiio.tag_num = msg->scsi.tag_num;
1464 			io->scsiio.tag_type = msg->scsi.tag_type;
1465 #ifdef CTL_TIME_IO
1466 			io->io_hdr.start_time = time_uptime;
1467 			getbinuptime(&io->io_hdr.start_bt);
1468 #endif /* CTL_TIME_IO */
1469 			io->scsiio.cdb_len = msg->scsi.cdb_len;
1470 			memcpy(io->scsiio.cdb, msg->scsi.cdb,
1471 			       CTL_MAX_CDBLEN);
1472 			if (softc->ha_mode == CTL_HA_MODE_XFER) {
1473 				const struct ctl_cmd_entry *entry;
1474 
1475 				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1476 				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1477 				io->io_hdr.flags |=
1478 					entry->flags & CTL_FLAG_DATA_MASK;
1479 			}
1480 			ctl_enqueue_isc(io);
1481 			break;
1482 
1483 		/* Performed on the Originating SC, XFER mode only */
1484 		case CTL_MSG_DATAMOVE: {
1485 			struct ctl_sg_entry *sgl;
1486 			int i, j;
1487 
1488 			io = msg->hdr.original_sc;
1489 			if (io == NULL) {
1490 				printf("%s: original_sc == NULL!\n", __func__);
1491 				/* XXX KDM do something here */
1492 				break;
1493 			}
1494 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1495 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1496 			/*
1497 			 * Keep track of this, we need to send it back over
1498 			 * when the datamove is complete.
1499 			 */
1500 			io->io_hdr.remote_io = msg->hdr.serializing_sc;
1501 			if (msg->hdr.status == CTL_SUCCESS)
1502 				io->io_hdr.status = msg->hdr.status;
1503 
1504 			if (msg->dt.sg_sequence == 0) {
1505 #ifdef CTL_TIME_IO
1506 				getbinuptime(&io->io_hdr.dma_start_bt);
1507 #endif
1508 				i = msg->dt.kern_sg_entries +
1509 				    msg->dt.kern_data_len /
1510 				    CTL_HA_DATAMOVE_SEGMENT + 1;
1511 				sgl = malloc(sizeof(*sgl) * i, M_CTL,
1512 				    M_WAITOK | M_ZERO);
1513 				CTL_RSGL(io) = sgl;
1514 				CTL_LSGL(io) = &sgl[msg->dt.kern_sg_entries];
1515 
1516 				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1517 
1518 				io->scsiio.kern_sg_entries =
1519 					msg->dt.kern_sg_entries;
1520 				io->scsiio.rem_sg_entries =
1521 					msg->dt.kern_sg_entries;
1522 				io->scsiio.kern_data_len =
1523 					msg->dt.kern_data_len;
1524 				io->scsiio.kern_total_len =
1525 					msg->dt.kern_total_len;
1526 				io->scsiio.kern_data_resid =
1527 					msg->dt.kern_data_resid;
1528 				io->scsiio.kern_rel_offset =
1529 					msg->dt.kern_rel_offset;
1530 				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1531 				io->io_hdr.flags |= msg->dt.flags &
1532 				    CTL_FLAG_BUS_ADDR;
1533 			} else
1534 				sgl = (struct ctl_sg_entry *)
1535 					io->scsiio.kern_data_ptr;
1536 
1537 			for (i = msg->dt.sent_sg_entries, j = 0;
1538 			     i < (msg->dt.sent_sg_entries +
1539 			     msg->dt.cur_sg_entries); i++, j++) {
1540 				sgl[i].addr = msg->dt.sg_list[j].addr;
1541 				sgl[i].len = msg->dt.sg_list[j].len;
1542 			}
1543 
1544 			/*
1545 			 * If this is the last piece of the I/O, we've got
1546 			 * the full S/G list.  Queue processing in the thread.
1547 			 * Otherwise wait for the next piece.
1548 			 */
1549 			if (msg->dt.sg_last != 0)
1550 				ctl_enqueue_isc(io);
1551 			break;
1552 		}
1553 		/* Performed on the Serializing (primary) SC, XFER mode only */
1554 		case CTL_MSG_DATAMOVE_DONE: {
1555 			if (msg->hdr.serializing_sc == NULL) {
1556 				printf("%s: serializing_sc == NULL!\n",
1557 				       __func__);
1558 				/* XXX KDM now what? */
1559 				break;
1560 			}
1561 			/*
1562 			 * We grab the sense information here in case
1563 			 * there was a failure, so we can return status
1564 			 * back to the initiator.
1565 			 */
1566 			io = msg->hdr.serializing_sc;
1567 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1568 			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1569 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1570 			io->io_hdr.port_status = msg->scsi.port_status;
1571 			io->scsiio.kern_data_resid = msg->scsi.kern_data_resid;
1572 			if (msg->hdr.status != CTL_STATUS_NONE) {
1573 				io->io_hdr.status = msg->hdr.status;
1574 				io->scsiio.scsi_status = msg->scsi.scsi_status;
1575 				io->scsiio.sense_len = msg->scsi.sense_len;
1576 				memcpy(&io->scsiio.sense_data,
1577 				    &msg->scsi.sense_data,
1578 				    msg->scsi.sense_len);
1579 				if (msg->hdr.status == CTL_SUCCESS)
1580 					io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1581 			}
1582 			ctl_enqueue_isc(io);
1583 			break;
1584 		}
1585 
1586 		/* Preformed on Originating SC, SER_ONLY mode */
1587 		case CTL_MSG_R2R:
1588 			io = msg->hdr.original_sc;
1589 			if (io == NULL) {
1590 				printf("%s: original_sc == NULL!\n",
1591 				    __func__);
1592 				break;
1593 			}
1594 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1595 			io->io_hdr.msg_type = CTL_MSG_R2R;
1596 			io->io_hdr.remote_io = msg->hdr.serializing_sc;
1597 			ctl_enqueue_isc(io);
1598 			break;
1599 
1600 		/*
1601 		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1602 		 * mode.
1603 		 * Performed on the Originating (i.e. secondary) SC in XFER
1604 		 * mode
1605 		 */
1606 		case CTL_MSG_FINISH_IO:
1607 			if (softc->ha_mode == CTL_HA_MODE_XFER)
1608 				ctl_isc_handler_finish_xfer(softc, msg);
1609 			else
1610 				ctl_isc_handler_finish_ser_only(softc, msg);
1611 			break;
1612 
1613 		/* Preformed on Originating SC */
1614 		case CTL_MSG_BAD_JUJU:
1615 			io = msg->hdr.original_sc;
1616 			if (io == NULL) {
1617 				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1618 				       __func__);
1619 				break;
1620 			}
1621 			ctl_copy_sense_data(msg, io);
1622 			/*
1623 			 * IO should have already been cleaned up on other
1624 			 * SC so clear this flag so we won't send a message
1625 			 * back to finish the IO there.
1626 			 */
1627 			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1628 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1629 
1630 			/* io = msg->hdr.serializing_sc; */
1631 			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1632 			ctl_enqueue_isc(io);
1633 			break;
1634 
1635 		/* Handle resets sent from the other side */
1636 		case CTL_MSG_MANAGE_TASKS: {
1637 			struct ctl_taskio *taskio;
1638 			taskio = (struct ctl_taskio *)ctl_alloc_io(
1639 			    softc->othersc_pool);
1640 			ctl_zero_io((union ctl_io *)taskio);
1641 			taskio->io_hdr.io_type = CTL_IO_TASK;
1642 			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1643 			taskio->io_hdr.nexus = msg->hdr.nexus;
1644 			taskio->task_action = msg->task.task_action;
1645 			taskio->tag_num = msg->task.tag_num;
1646 			taskio->tag_type = msg->task.tag_type;
1647 #ifdef CTL_TIME_IO
1648 			taskio->io_hdr.start_time = time_uptime;
1649 			getbinuptime(&taskio->io_hdr.start_bt);
1650 #endif /* CTL_TIME_IO */
1651 			ctl_run_task((union ctl_io *)taskio);
1652 			break;
1653 		}
1654 		/* Persistent Reserve action which needs attention */
1655 		case CTL_MSG_PERS_ACTION:
1656 			presio = (struct ctl_prio *)ctl_alloc_io(
1657 			    softc->othersc_pool);
1658 			ctl_zero_io((union ctl_io *)presio);
1659 			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1660 			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1661 			presio->io_hdr.nexus = msg->hdr.nexus;
1662 			presio->pr_msg = msg->pr;
1663 			ctl_enqueue_isc((union ctl_io *)presio);
1664 			break;
1665 		case CTL_MSG_UA:
1666 			ctl_isc_ua(softc, msg, param);
1667 			break;
1668 		case CTL_MSG_PORT_SYNC:
1669 			ctl_isc_port_sync(softc, msg, param);
1670 			break;
1671 		case CTL_MSG_LUN_SYNC:
1672 			ctl_isc_lun_sync(softc, msg, param);
1673 			break;
1674 		case CTL_MSG_IID_SYNC:
1675 			ctl_isc_iid_sync(softc, msg, param);
1676 			break;
1677 		case CTL_MSG_LOGIN:
1678 			ctl_isc_login(softc, msg, param);
1679 			break;
1680 		case CTL_MSG_MODE_SYNC:
1681 			ctl_isc_mode_sync(softc, msg, param);
1682 			break;
1683 		default:
1684 			printf("Received HA message of unknown type %d\n",
1685 			    msg->hdr.msg_type);
1686 			ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1687 			break;
1688 		}
1689 		if (msg != &msgbuf)
1690 			free(msg, M_CTL);
1691 	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1692 		printf("CTL: HA link status changed from %d to %d\n",
1693 		    softc->ha_link, param);
1694 		if (param == softc->ha_link)
1695 			return;
1696 		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1697 			softc->ha_link = param;
1698 			ctl_isc_ha_link_down(softc);
1699 		} else {
1700 			softc->ha_link = param;
1701 			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1702 				ctl_isc_ha_link_up(softc);
1703 		}
1704 		return;
1705 	} else {
1706 		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1707 		return;
1708 	}
1709 }
1710 
1711 static void
ctl_copy_sense_data(union ctl_ha_msg * src,union ctl_io * dest)1712 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1713 {
1714 
1715 	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1716 	    src->scsi.sense_len);
1717 	dest->scsiio.scsi_status = src->scsi.scsi_status;
1718 	dest->scsiio.sense_len = src->scsi.sense_len;
1719 	dest->io_hdr.status = src->hdr.status;
1720 }
1721 
1722 static void
ctl_copy_sense_data_back(union ctl_io * src,union ctl_ha_msg * dest)1723 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1724 {
1725 
1726 	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1727 	    src->scsiio.sense_len);
1728 	dest->scsi.scsi_status = src->scsiio.scsi_status;
1729 	dest->scsi.sense_len = src->scsiio.sense_len;
1730 	dest->hdr.status = src->io_hdr.status;
1731 }
1732 
1733 void
ctl_est_ua(struct ctl_lun * lun,uint32_t initidx,ctl_ua_type ua)1734 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1735 {
1736 	struct ctl_softc *softc = lun->ctl_softc;
1737 	ctl_ua_type *pu;
1738 
1739 	if (initidx < softc->init_min || initidx >= softc->init_max)
1740 		return;
1741 	mtx_assert(&lun->lun_lock, MA_OWNED);
1742 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1743 	if (pu == NULL)
1744 		return;
1745 	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1746 }
1747 
1748 void
ctl_est_ua_port(struct ctl_lun * lun,int port,uint32_t except,ctl_ua_type ua)1749 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1750 {
1751 	int i;
1752 
1753 	mtx_assert(&lun->lun_lock, MA_OWNED);
1754 	if (lun->pending_ua[port] == NULL)
1755 		return;
1756 	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1757 		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1758 			continue;
1759 		lun->pending_ua[port][i] |= ua;
1760 	}
1761 }
1762 
1763 void
ctl_est_ua_all(struct ctl_lun * lun,uint32_t except,ctl_ua_type ua)1764 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1765 {
1766 	struct ctl_softc *softc = lun->ctl_softc;
1767 	int i;
1768 
1769 	mtx_assert(&lun->lun_lock, MA_OWNED);
1770 	for (i = softc->port_min; i < softc->port_max; i++)
1771 		ctl_est_ua_port(lun, i, except, ua);
1772 }
1773 
1774 void
ctl_clr_ua(struct ctl_lun * lun,uint32_t initidx,ctl_ua_type ua)1775 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1776 {
1777 	struct ctl_softc *softc = lun->ctl_softc;
1778 	ctl_ua_type *pu;
1779 
1780 	if (initidx < softc->init_min || initidx >= softc->init_max)
1781 		return;
1782 	mtx_assert(&lun->lun_lock, MA_OWNED);
1783 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1784 	if (pu == NULL)
1785 		return;
1786 	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1787 }
1788 
1789 void
ctl_clr_ua_all(struct ctl_lun * lun,uint32_t except,ctl_ua_type ua)1790 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1791 {
1792 	struct ctl_softc *softc = lun->ctl_softc;
1793 	int i, j;
1794 
1795 	mtx_assert(&lun->lun_lock, MA_OWNED);
1796 	for (i = softc->port_min; i < softc->port_max; i++) {
1797 		if (lun->pending_ua[i] == NULL)
1798 			continue;
1799 		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1800 			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1801 				continue;
1802 			lun->pending_ua[i][j] &= ~ua;
1803 		}
1804 	}
1805 }
1806 
1807 void
ctl_clr_ua_allluns(struct ctl_softc * ctl_softc,uint32_t initidx,ctl_ua_type ua_type)1808 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1809     ctl_ua_type ua_type)
1810 {
1811 	struct ctl_lun *lun;
1812 
1813 	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1814 	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1815 		mtx_lock(&lun->lun_lock);
1816 		ctl_clr_ua(lun, initidx, ua_type);
1817 		mtx_unlock(&lun->lun_lock);
1818 	}
1819 }
1820 
1821 static int
ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)1822 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1823 {
1824 	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1825 	struct ctl_lun *lun;
1826 	struct ctl_lun_req ireq;
1827 	int error, value;
1828 
1829 	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1830 	error = sysctl_handle_int(oidp, &value, 0, req);
1831 	if ((error != 0) || (req->newptr == NULL))
1832 		return (error);
1833 
1834 	mtx_lock(&softc->ctl_lock);
1835 	if (value == 0)
1836 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1837 	else
1838 		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1839 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1840 		mtx_unlock(&softc->ctl_lock);
1841 		bzero(&ireq, sizeof(ireq));
1842 		ireq.reqtype = CTL_LUNREQ_MODIFY;
1843 		ireq.reqdata.modify.lun_id = lun->lun;
1844 		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1845 		    curthread);
1846 		if (ireq.status != CTL_LUN_OK) {
1847 			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1848 			    __func__, ireq.status, ireq.error_str);
1849 		}
1850 		mtx_lock(&softc->ctl_lock);
1851 	}
1852 	mtx_unlock(&softc->ctl_lock);
1853 	return (0);
1854 }
1855 
1856 static int
ctl_init(void)1857 ctl_init(void)
1858 {
1859 	struct make_dev_args args;
1860 	struct ctl_softc *softc;
1861 	int i, error;
1862 
1863 	softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1864 			       M_WAITOK | M_ZERO);
1865 
1866 	make_dev_args_init(&args);
1867 	args.mda_devsw = &ctl_cdevsw;
1868 	args.mda_uid = UID_ROOT;
1869 	args.mda_gid = GID_OPERATOR;
1870 	args.mda_mode = 0600;
1871 	args.mda_si_drv1 = softc;
1872 	args.mda_si_drv2 = NULL;
1873 	error = make_dev_s(&args, &softc->dev, "cam/ctl");
1874 	if (error != 0) {
1875 		free(softc, M_DEVBUF);
1876 		control_softc = NULL;
1877 		return (error);
1878 	}
1879 
1880 	sysctl_ctx_init(&softc->sysctl_ctx);
1881 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1882 		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1883 		CTLFLAG_RD, 0, "CAM Target Layer");
1884 
1885 	if (softc->sysctl_tree == NULL) {
1886 		printf("%s: unable to allocate sysctl tree\n", __func__);
1887 		destroy_dev(softc->dev);
1888 		free(softc, M_DEVBUF);
1889 		control_softc = NULL;
1890 		return (ENOMEM);
1891 	}
1892 
1893 	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1894 	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1895 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1896 	softc->flags = 0;
1897 
1898 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1899 	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1900 	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1901 
1902 	if (ctl_max_luns <= 0 || powerof2(ctl_max_luns) == 0) {
1903 		printf("Bad value %d for kern.cam.ctl.max_luns, must be a power of two, using %d\n",
1904 		    ctl_max_luns, CTL_DEFAULT_MAX_LUNS);
1905 		ctl_max_luns = CTL_DEFAULT_MAX_LUNS;
1906 	}
1907 	softc->ctl_luns = malloc(sizeof(struct ctl_lun *) * ctl_max_luns,
1908 	    M_DEVBUF, M_WAITOK | M_ZERO);
1909 	softc->ctl_lun_mask = malloc(sizeof(uint32_t) *
1910 	    ((ctl_max_luns + 31) / 32), M_DEVBUF, M_WAITOK | M_ZERO);
1911 	if (ctl_max_ports <= 0 || powerof2(ctl_max_ports) == 0) {
1912 		printf("Bad value %d for kern.cam.ctl.max_ports, must be a power of two, using %d\n",
1913 		    ctl_max_ports, CTL_DEFAULT_MAX_PORTS);
1914 		ctl_max_ports = CTL_DEFAULT_MAX_PORTS;
1915 	}
1916 	softc->ctl_port_mask = malloc(sizeof(uint32_t) *
1917 	  ((ctl_max_ports + 31) / 32), M_DEVBUF, M_WAITOK | M_ZERO);
1918 	softc->ctl_ports = malloc(sizeof(struct ctl_port *) * ctl_max_ports,
1919 	     M_DEVBUF, M_WAITOK | M_ZERO);
1920 
1921 
1922 	/*
1923 	 * In Copan's HA scheme, the "master" and "slave" roles are
1924 	 * figured out through the slot the controller is in.  Although it
1925 	 * is an active/active system, someone has to be in charge.
1926 	 */
1927 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1928 	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1929 	    "HA head ID (0 - no HA)");
1930 	if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
1931 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1932 		softc->is_single = 1;
1933 		softc->port_cnt = ctl_max_ports;
1934 		softc->port_min = 0;
1935 	} else {
1936 		softc->port_cnt = ctl_max_ports / NUM_HA_SHELVES;
1937 		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1938 	}
1939 	softc->port_max = softc->port_min + softc->port_cnt;
1940 	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1941 	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1942 
1943 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1944 	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1945 	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
1946 
1947 	STAILQ_INIT(&softc->lun_list);
1948 	STAILQ_INIT(&softc->fe_list);
1949 	STAILQ_INIT(&softc->port_list);
1950 	STAILQ_INIT(&softc->be_list);
1951 	ctl_tpc_init(softc);
1952 
1953 	if (worker_threads <= 0)
1954 		worker_threads = max(1, mp_ncpus / 4);
1955 	if (worker_threads > CTL_MAX_THREADS)
1956 		worker_threads = CTL_MAX_THREADS;
1957 
1958 	for (i = 0; i < worker_threads; i++) {
1959 		struct ctl_thread *thr = &softc->threads[i];
1960 
1961 		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1962 		thr->ctl_softc = softc;
1963 		STAILQ_INIT(&thr->incoming_queue);
1964 		STAILQ_INIT(&thr->rtr_queue);
1965 		STAILQ_INIT(&thr->done_queue);
1966 		STAILQ_INIT(&thr->isc_queue);
1967 
1968 		error = kproc_kthread_add(ctl_work_thread, thr,
1969 		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1970 		if (error != 0) {
1971 			printf("error creating CTL work thread!\n");
1972 			return (error);
1973 		}
1974 	}
1975 	error = kproc_kthread_add(ctl_thresh_thread, softc,
1976 	    &softc->ctl_proc, &softc->thresh_thread, 0, 0, "ctl", "thresh");
1977 	if (error != 0) {
1978 		printf("error creating CTL threshold thread!\n");
1979 		return (error);
1980 	}
1981 
1982 	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1983 	    OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1984 	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1985 
1986 	if (softc->is_single == 0) {
1987 		if (ctl_frontend_register(&ha_frontend) != 0)
1988 			softc->is_single = 1;
1989 	}
1990 	return (0);
1991 }
1992 
1993 static int
ctl_shutdown(void)1994 ctl_shutdown(void)
1995 {
1996 	struct ctl_softc *softc = control_softc;
1997 	int i;
1998 
1999 	if (softc->is_single == 0)
2000 		ctl_frontend_deregister(&ha_frontend);
2001 
2002 	destroy_dev(softc->dev);
2003 
2004 	/* Shutdown CTL threads. */
2005 	softc->shutdown = 1;
2006 	for (i = 0; i < worker_threads; i++) {
2007 		struct ctl_thread *thr = &softc->threads[i];
2008 		while (thr->thread != NULL) {
2009 			wakeup(thr);
2010 			if (thr->thread != NULL)
2011 				pause("CTL thr shutdown", 1);
2012 		}
2013 		mtx_destroy(&thr->queue_lock);
2014 	}
2015 	while (softc->thresh_thread != NULL) {
2016 		wakeup(softc->thresh_thread);
2017 		if (softc->thresh_thread != NULL)
2018 			pause("CTL thr shutdown", 1);
2019 	}
2020 
2021 	ctl_tpc_shutdown(softc);
2022 	uma_zdestroy(softc->io_zone);
2023 	mtx_destroy(&softc->ctl_lock);
2024 
2025 	free(softc->ctl_luns, M_DEVBUF);
2026 	free(softc->ctl_lun_mask, M_DEVBUF);
2027 	free(softc->ctl_port_mask, M_DEVBUF);
2028 	free(softc->ctl_ports, M_DEVBUF);
2029 
2030 	sysctl_ctx_free(&softc->sysctl_ctx);
2031 
2032 	free(softc, M_DEVBUF);
2033 	control_softc = NULL;
2034 	return (0);
2035 }
2036 
2037 static int
ctl_module_event_handler(module_t mod,int what,void * arg)2038 ctl_module_event_handler(module_t mod, int what, void *arg)
2039 {
2040 
2041 	switch (what) {
2042 	case MOD_LOAD:
2043 		return (ctl_init());
2044 	case MOD_UNLOAD:
2045 		return (ctl_shutdown());
2046 	default:
2047 		return (EOPNOTSUPP);
2048 	}
2049 }
2050 
2051 /*
2052  * XXX KDM should we do some access checks here?  Bump a reference count to
2053  * prevent a CTL module from being unloaded while someone has it open?
2054  */
2055 static int
ctl_open(struct cdev * dev,int flags,int fmt,struct thread * td)2056 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
2057 {
2058 	return (0);
2059 }
2060 
2061 static int
ctl_close(struct cdev * dev,int flags,int fmt,struct thread * td)2062 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
2063 {
2064 	return (0);
2065 }
2066 
2067 /*
2068  * Remove an initiator by port number and initiator ID.
2069  * Returns 0 for success, -1 for failure.
2070  */
2071 int
ctl_remove_initiator(struct ctl_port * port,int iid)2072 ctl_remove_initiator(struct ctl_port *port, int iid)
2073 {
2074 	struct ctl_softc *softc = port->ctl_softc;
2075 	int last;
2076 
2077 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2078 
2079 	if (iid > CTL_MAX_INIT_PER_PORT) {
2080 		printf("%s: initiator ID %u > maximun %u!\n",
2081 		       __func__, iid, CTL_MAX_INIT_PER_PORT);
2082 		return (-1);
2083 	}
2084 
2085 	mtx_lock(&softc->ctl_lock);
2086 	last = (--port->wwpn_iid[iid].in_use == 0);
2087 	port->wwpn_iid[iid].last_use = time_uptime;
2088 	mtx_unlock(&softc->ctl_lock);
2089 	if (last)
2090 		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
2091 	ctl_isc_announce_iid(port, iid);
2092 
2093 	return (0);
2094 }
2095 
2096 /*
2097  * Add an initiator to the initiator map.
2098  * Returns iid for success, < 0 for failure.
2099  */
2100 int
ctl_add_initiator(struct ctl_port * port,int iid,uint64_t wwpn,char * name)2101 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2102 {
2103 	struct ctl_softc *softc = port->ctl_softc;
2104 	time_t best_time;
2105 	int i, best;
2106 
2107 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2108 
2109 	if (iid >= CTL_MAX_INIT_PER_PORT) {
2110 		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2111 		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2112 		free(name, M_CTL);
2113 		return (-1);
2114 	}
2115 
2116 	mtx_lock(&softc->ctl_lock);
2117 
2118 	if (iid < 0 && (wwpn != 0 || name != NULL)) {
2119 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2120 			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2121 				iid = i;
2122 				break;
2123 			}
2124 			if (name != NULL && port->wwpn_iid[i].name != NULL &&
2125 			    strcmp(name, port->wwpn_iid[i].name) == 0) {
2126 				iid = i;
2127 				break;
2128 			}
2129 		}
2130 	}
2131 
2132 	if (iid < 0) {
2133 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2134 			if (port->wwpn_iid[i].in_use == 0 &&
2135 			    port->wwpn_iid[i].wwpn == 0 &&
2136 			    port->wwpn_iid[i].name == NULL) {
2137 				iid = i;
2138 				break;
2139 			}
2140 		}
2141 	}
2142 
2143 	if (iid < 0) {
2144 		best = -1;
2145 		best_time = INT32_MAX;
2146 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2147 			if (port->wwpn_iid[i].in_use == 0) {
2148 				if (port->wwpn_iid[i].last_use < best_time) {
2149 					best = i;
2150 					best_time = port->wwpn_iid[i].last_use;
2151 				}
2152 			}
2153 		}
2154 		iid = best;
2155 	}
2156 
2157 	if (iid < 0) {
2158 		mtx_unlock(&softc->ctl_lock);
2159 		free(name, M_CTL);
2160 		return (-2);
2161 	}
2162 
2163 	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2164 		/*
2165 		 * This is not an error yet.
2166 		 */
2167 		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2168 #if 0
2169 			printf("%s: port %d iid %u WWPN %#jx arrived"
2170 			    " again\n", __func__, port->targ_port,
2171 			    iid, (uintmax_t)wwpn);
2172 #endif
2173 			goto take;
2174 		}
2175 		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2176 		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
2177 #if 0
2178 			printf("%s: port %d iid %u name '%s' arrived"
2179 			    " again\n", __func__, port->targ_port,
2180 			    iid, name);
2181 #endif
2182 			goto take;
2183 		}
2184 
2185 		/*
2186 		 * This is an error, but what do we do about it?  The
2187 		 * driver is telling us we have a new WWPN for this
2188 		 * initiator ID, so we pretty much need to use it.
2189 		 */
2190 		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2191 		    " but WWPN %#jx '%s' is still at that address\n",
2192 		    __func__, port->targ_port, iid, wwpn, name,
2193 		    (uintmax_t)port->wwpn_iid[iid].wwpn,
2194 		    port->wwpn_iid[iid].name);
2195 	}
2196 take:
2197 	free(port->wwpn_iid[iid].name, M_CTL);
2198 	port->wwpn_iid[iid].name = name;
2199 	port->wwpn_iid[iid].wwpn = wwpn;
2200 	port->wwpn_iid[iid].in_use++;
2201 	mtx_unlock(&softc->ctl_lock);
2202 	ctl_isc_announce_iid(port, iid);
2203 
2204 	return (iid);
2205 }
2206 
2207 static int
ctl_create_iid(struct ctl_port * port,int iid,uint8_t * buf)2208 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2209 {
2210 	int len;
2211 
2212 	switch (port->port_type) {
2213 	case CTL_PORT_FC:
2214 	{
2215 		struct scsi_transportid_fcp *id =
2216 		    (struct scsi_transportid_fcp *)buf;
2217 		if (port->wwpn_iid[iid].wwpn == 0)
2218 			return (0);
2219 		memset(id, 0, sizeof(*id));
2220 		id->format_protocol = SCSI_PROTO_FC;
2221 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2222 		return (sizeof(*id));
2223 	}
2224 	case CTL_PORT_ISCSI:
2225 	{
2226 		struct scsi_transportid_iscsi_port *id =
2227 		    (struct scsi_transportid_iscsi_port *)buf;
2228 		if (port->wwpn_iid[iid].name == NULL)
2229 			return (0);
2230 		memset(id, 0, 256);
2231 		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2232 		    SCSI_PROTO_ISCSI;
2233 		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2234 		len = roundup2(min(len, 252), 4);
2235 		scsi_ulto2b(len, id->additional_length);
2236 		return (sizeof(*id) + len);
2237 	}
2238 	case CTL_PORT_SAS:
2239 	{
2240 		struct scsi_transportid_sas *id =
2241 		    (struct scsi_transportid_sas *)buf;
2242 		if (port->wwpn_iid[iid].wwpn == 0)
2243 			return (0);
2244 		memset(id, 0, sizeof(*id));
2245 		id->format_protocol = SCSI_PROTO_SAS;
2246 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2247 		return (sizeof(*id));
2248 	}
2249 	default:
2250 	{
2251 		struct scsi_transportid_spi *id =
2252 		    (struct scsi_transportid_spi *)buf;
2253 		memset(id, 0, sizeof(*id));
2254 		id->format_protocol = SCSI_PROTO_SPI;
2255 		scsi_ulto2b(iid, id->scsi_addr);
2256 		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2257 		return (sizeof(*id));
2258 	}
2259 	}
2260 }
2261 
2262 /*
2263  * Serialize a command that went down the "wrong" side, and so was sent to
2264  * this controller for execution.  The logic is a little different than the
2265  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2266  * sent back to the other side, but in the success case, we execute the
2267  * command on this side (XFER mode) or tell the other side to execute it
2268  * (SER_ONLY mode).
2269  */
2270 static void
ctl_serialize_other_sc_cmd(struct ctl_scsiio * ctsio)2271 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2272 {
2273 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
2274 	struct ctl_port *port = CTL_PORT(ctsio);
2275 	union ctl_ha_msg msg_info;
2276 	struct ctl_lun *lun;
2277 	const struct ctl_cmd_entry *entry;
2278 	union ctl_io *bio;
2279 	uint32_t targ_lun;
2280 
2281 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2282 
2283 	/* Make sure that we know about this port. */
2284 	if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2285 		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2286 					 /*retry_count*/ 1);
2287 		goto badjuju;
2288 	}
2289 
2290 	/* Make sure that we know about this LUN. */
2291 	mtx_lock(&softc->ctl_lock);
2292 	if (targ_lun >= ctl_max_luns ||
2293 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
2294 		mtx_unlock(&softc->ctl_lock);
2295 
2296 		/*
2297 		 * The other node would not send this request to us unless
2298 		 * received announce that we are primary node for this LUN.
2299 		 * If this LUN does not exist now, it is probably result of
2300 		 * a race, so respond to initiator in the most opaque way.
2301 		 */
2302 		ctl_set_busy(ctsio);
2303 		goto badjuju;
2304 	}
2305 	mtx_lock(&lun->lun_lock);
2306 	mtx_unlock(&softc->ctl_lock);
2307 
2308 	/*
2309 	 * If the LUN is invalid, pretend that it doesn't exist.
2310 	 * It will go away as soon as all pending I/Os completed.
2311 	 */
2312 	if (lun->flags & CTL_LUN_DISABLED) {
2313 		mtx_unlock(&lun->lun_lock);
2314 		ctl_set_busy(ctsio);
2315 		goto badjuju;
2316 	}
2317 
2318 	entry = ctl_get_cmd_entry(ctsio, NULL);
2319 	ctsio->seridx = entry->seridx;
2320 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2321 		mtx_unlock(&lun->lun_lock);
2322 		goto badjuju;
2323 	}
2324 
2325 	CTL_LUN(ctsio) = lun;
2326 	CTL_BACKEND_LUN(ctsio) = lun->be_lun;
2327 
2328 	/*
2329 	 * Every I/O goes into the OOA queue for a
2330 	 * particular LUN, and stays there until completion.
2331 	 */
2332 #ifdef CTL_TIME_IO
2333 	if (LIST_EMPTY(&lun->ooa_queue))
2334 		lun->idle_time += getsbinuptime() - lun->last_busy;
2335 #endif
2336 	LIST_INSERT_HEAD(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2337 
2338 	bio = (union ctl_io *)LIST_NEXT(&ctsio->io_hdr, ooa_links);
2339 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio, &bio)) {
2340 	case CTL_ACTION_PASS:
2341 	case CTL_ACTION_SKIP:
2342 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
2343 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2344 			ctl_enqueue_rtr((union ctl_io *)ctsio);
2345 			mtx_unlock(&lun->lun_lock);
2346 		} else {
2347 			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2348 			mtx_unlock(&lun->lun_lock);
2349 
2350 			/* send msg back to other side */
2351 			msg_info.hdr.original_sc = ctsio->io_hdr.remote_io;
2352 			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2353 			msg_info.hdr.msg_type = CTL_MSG_R2R;
2354 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2355 			    sizeof(msg_info.hdr), M_WAITOK);
2356 		}
2357 		break;
2358 	case CTL_ACTION_BLOCK:
2359 		ctsio->io_hdr.blocker = bio;
2360 		TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue, &ctsio->io_hdr,
2361 				  blocked_links);
2362 		mtx_unlock(&lun->lun_lock);
2363 		break;
2364 	case CTL_ACTION_OVERLAP:
2365 		LIST_REMOVE(&ctsio->io_hdr, ooa_links);
2366 		mtx_unlock(&lun->lun_lock);
2367 		ctl_set_overlapped_cmd(ctsio);
2368 		goto badjuju;
2369 	case CTL_ACTION_OVERLAP_TAG:
2370 		LIST_REMOVE(&ctsio->io_hdr, ooa_links);
2371 		mtx_unlock(&lun->lun_lock);
2372 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2373 badjuju:
2374 		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2375 		msg_info.hdr.original_sc = ctsio->io_hdr.remote_io;
2376 		msg_info.hdr.serializing_sc = NULL;
2377 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2378 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2379 		    sizeof(msg_info.scsi), M_WAITOK);
2380 		ctl_free_io((union ctl_io *)ctsio);
2381 		break;
2382 	default:
2383 		__assert_unreachable();
2384 	}
2385 }
2386 
2387 /*
2388  * Returns 0 for success, errno for failure.
2389  */
2390 static void
ctl_ioctl_fill_ooa(struct ctl_lun * lun,uint32_t * cur_fill_num,struct ctl_ooa * ooa_hdr,struct ctl_ooa_entry * kern_entries)2391 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2392 		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2393 {
2394 	struct ctl_io_hdr *ioh;
2395 
2396 	mtx_lock(&lun->lun_lock);
2397 	ioh = LIST_FIRST(&lun->ooa_queue);
2398 	if (ioh == NULL) {
2399 		mtx_unlock(&lun->lun_lock);
2400 		return;
2401 	}
2402 	while (LIST_NEXT(ioh, ooa_links) != NULL)
2403 		ioh = LIST_NEXT(ioh, ooa_links);
2404 	for ( ; ioh; ioh = LIST_PREV(ioh, &lun->ooa_queue, ctl_io_hdr, ooa_links)) {
2405 		union ctl_io *io = (union ctl_io *)ioh;
2406 		struct ctl_ooa_entry *entry;
2407 
2408 		/*
2409 		 * If we've got more than we can fit, just count the
2410 		 * remaining entries.
2411 		 */
2412 		if (*cur_fill_num >= ooa_hdr->alloc_num) {
2413 			(*cur_fill_num)++;
2414 			continue;
2415 		}
2416 
2417 		entry = &kern_entries[*cur_fill_num];
2418 
2419 		entry->tag_num = io->scsiio.tag_num;
2420 		entry->lun_num = lun->lun;
2421 #ifdef CTL_TIME_IO
2422 		entry->start_bt = io->io_hdr.start_bt;
2423 #endif
2424 		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2425 		entry->cdb_len = io->scsiio.cdb_len;
2426 		if (io->io_hdr.blocker != NULL)
2427 			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2428 
2429 		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2430 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2431 
2432 		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2433 			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2434 
2435 		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2436 			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2437 
2438 		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2439 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2440 
2441 		if (io->io_hdr.flags & CTL_FLAG_STATUS_QUEUED)
2442 			entry->cmd_flags |= CTL_OOACMD_FLAG_STATUS_QUEUED;
2443 
2444 		if (io->io_hdr.flags & CTL_FLAG_STATUS_SENT)
2445 			entry->cmd_flags |= CTL_OOACMD_FLAG_STATUS_SENT;
2446 		(*cur_fill_num)++;
2447 	}
2448 	mtx_unlock(&lun->lun_lock);
2449 }
2450 
2451 /*
2452  * Escape characters that are illegal or not recommended in XML.
2453  */
2454 int
ctl_sbuf_printf_esc(struct sbuf * sb,char * str,int size)2455 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2456 {
2457 	char *end = str + size;
2458 	int retval;
2459 
2460 	retval = 0;
2461 
2462 	for (; *str && str < end; str++) {
2463 		switch (*str) {
2464 		case '&':
2465 			retval = sbuf_printf(sb, "&amp;");
2466 			break;
2467 		case '>':
2468 			retval = sbuf_printf(sb, "&gt;");
2469 			break;
2470 		case '<':
2471 			retval = sbuf_printf(sb, "&lt;");
2472 			break;
2473 		default:
2474 			retval = sbuf_putc(sb, *str);
2475 			break;
2476 		}
2477 
2478 		if (retval != 0)
2479 			break;
2480 
2481 	}
2482 
2483 	return (retval);
2484 }
2485 
2486 static void
ctl_id_sbuf(struct ctl_devid * id,struct sbuf * sb)2487 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2488 {
2489 	struct scsi_vpd_id_descriptor *desc;
2490 	int i;
2491 
2492 	if (id == NULL || id->len < 4)
2493 		return;
2494 	desc = (struct scsi_vpd_id_descriptor *)id->data;
2495 	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2496 	case SVPD_ID_TYPE_T10:
2497 		sbuf_printf(sb, "t10.");
2498 		break;
2499 	case SVPD_ID_TYPE_EUI64:
2500 		sbuf_printf(sb, "eui.");
2501 		break;
2502 	case SVPD_ID_TYPE_NAA:
2503 		sbuf_printf(sb, "naa.");
2504 		break;
2505 	case SVPD_ID_TYPE_SCSI_NAME:
2506 		break;
2507 	}
2508 	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2509 	case SVPD_ID_CODESET_BINARY:
2510 		for (i = 0; i < desc->length; i++)
2511 			sbuf_printf(sb, "%02x", desc->identifier[i]);
2512 		break;
2513 	case SVPD_ID_CODESET_ASCII:
2514 		sbuf_printf(sb, "%.*s", (int)desc->length,
2515 		    (char *)desc->identifier);
2516 		break;
2517 	case SVPD_ID_CODESET_UTF8:
2518 		sbuf_printf(sb, "%s", (char *)desc->identifier);
2519 		break;
2520 	}
2521 }
2522 
2523 static int
ctl_ioctl(struct cdev * dev,u_long cmd,caddr_t addr,int flag,struct thread * td)2524 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2525 	  struct thread *td)
2526 {
2527 	struct ctl_softc *softc = dev->si_drv1;
2528 	struct ctl_port *port;
2529 	struct ctl_lun *lun;
2530 	int retval;
2531 
2532 	retval = 0;
2533 
2534 	switch (cmd) {
2535 	case CTL_IO:
2536 		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2537 		break;
2538 	case CTL_ENABLE_PORT:
2539 	case CTL_DISABLE_PORT:
2540 	case CTL_SET_PORT_WWNS: {
2541 		struct ctl_port *port;
2542 		struct ctl_port_entry *entry;
2543 
2544 		entry = (struct ctl_port_entry *)addr;
2545 
2546 		mtx_lock(&softc->ctl_lock);
2547 		STAILQ_FOREACH(port, &softc->port_list, links) {
2548 			int action, done;
2549 
2550 			if (port->targ_port < softc->port_min ||
2551 			    port->targ_port >= softc->port_max)
2552 				continue;
2553 
2554 			action = 0;
2555 			done = 0;
2556 			if ((entry->port_type == CTL_PORT_NONE)
2557 			 && (entry->targ_port == port->targ_port)) {
2558 				/*
2559 				 * If the user only wants to enable or
2560 				 * disable or set WWNs on a specific port,
2561 				 * do the operation and we're done.
2562 				 */
2563 				action = 1;
2564 				done = 1;
2565 			} else if (entry->port_type & port->port_type) {
2566 				/*
2567 				 * Compare the user's type mask with the
2568 				 * particular frontend type to see if we
2569 				 * have a match.
2570 				 */
2571 				action = 1;
2572 				done = 0;
2573 
2574 				/*
2575 				 * Make sure the user isn't trying to set
2576 				 * WWNs on multiple ports at the same time.
2577 				 */
2578 				if (cmd == CTL_SET_PORT_WWNS) {
2579 					printf("%s: Can't set WWNs on "
2580 					       "multiple ports\n", __func__);
2581 					retval = EINVAL;
2582 					break;
2583 				}
2584 			}
2585 			if (action == 0)
2586 				continue;
2587 
2588 			/*
2589 			 * XXX KDM we have to drop the lock here, because
2590 			 * the online/offline operations can potentially
2591 			 * block.  We need to reference count the frontends
2592 			 * so they can't go away,
2593 			 */
2594 			if (cmd == CTL_ENABLE_PORT) {
2595 				mtx_unlock(&softc->ctl_lock);
2596 				ctl_port_online(port);
2597 				mtx_lock(&softc->ctl_lock);
2598 			} else if (cmd == CTL_DISABLE_PORT) {
2599 				mtx_unlock(&softc->ctl_lock);
2600 				ctl_port_offline(port);
2601 				mtx_lock(&softc->ctl_lock);
2602 			} else if (cmd == CTL_SET_PORT_WWNS) {
2603 				ctl_port_set_wwns(port,
2604 				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2605 				    1 : 0, entry->wwnn,
2606 				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2607 				    1 : 0, entry->wwpn);
2608 			}
2609 			if (done != 0)
2610 				break;
2611 		}
2612 		mtx_unlock(&softc->ctl_lock);
2613 		break;
2614 	}
2615 	case CTL_GET_OOA: {
2616 		struct ctl_ooa *ooa_hdr;
2617 		struct ctl_ooa_entry *entries;
2618 		uint32_t cur_fill_num;
2619 
2620 		ooa_hdr = (struct ctl_ooa *)addr;
2621 
2622 		if ((ooa_hdr->alloc_len == 0)
2623 		 || (ooa_hdr->alloc_num == 0)) {
2624 			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2625 			       "must be non-zero\n", __func__,
2626 			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2627 			retval = EINVAL;
2628 			break;
2629 		}
2630 
2631 		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2632 		    sizeof(struct ctl_ooa_entry))) {
2633 			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2634 			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2635 			       __func__, ooa_hdr->alloc_len,
2636 			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2637 			retval = EINVAL;
2638 			break;
2639 		}
2640 
2641 		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2642 		if (entries == NULL) {
2643 			printf("%s: could not allocate %d bytes for OOA "
2644 			       "dump\n", __func__, ooa_hdr->alloc_len);
2645 			retval = ENOMEM;
2646 			break;
2647 		}
2648 
2649 		mtx_lock(&softc->ctl_lock);
2650 		if ((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0 &&
2651 		    (ooa_hdr->lun_num >= ctl_max_luns ||
2652 		     softc->ctl_luns[ooa_hdr->lun_num] == NULL)) {
2653 			mtx_unlock(&softc->ctl_lock);
2654 			free(entries, M_CTL);
2655 			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2656 			       __func__, (uintmax_t)ooa_hdr->lun_num);
2657 			retval = EINVAL;
2658 			break;
2659 		}
2660 
2661 		cur_fill_num = 0;
2662 
2663 		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2664 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2665 				ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2666 				    ooa_hdr, entries);
2667 			}
2668 		} else {
2669 			lun = softc->ctl_luns[ooa_hdr->lun_num];
2670 			ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2671 			    entries);
2672 		}
2673 		mtx_unlock(&softc->ctl_lock);
2674 
2675 		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2676 		ooa_hdr->fill_len = ooa_hdr->fill_num *
2677 			sizeof(struct ctl_ooa_entry);
2678 		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2679 		if (retval != 0) {
2680 			printf("%s: error copying out %d bytes for OOA dump\n",
2681 			       __func__, ooa_hdr->fill_len);
2682 		}
2683 
2684 		getbinuptime(&ooa_hdr->cur_bt);
2685 
2686 		if (cur_fill_num > ooa_hdr->alloc_num) {
2687 			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2688 			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2689 		} else {
2690 			ooa_hdr->dropped_num = 0;
2691 			ooa_hdr->status = CTL_OOA_OK;
2692 		}
2693 
2694 		free(entries, M_CTL);
2695 		break;
2696 	}
2697 	case CTL_DELAY_IO: {
2698 		struct ctl_io_delay_info *delay_info;
2699 
2700 		delay_info = (struct ctl_io_delay_info *)addr;
2701 
2702 #ifdef CTL_IO_DELAY
2703 		mtx_lock(&softc->ctl_lock);
2704 		if (delay_info->lun_id >= ctl_max_luns ||
2705 		    (lun = softc->ctl_luns[delay_info->lun_id]) == NULL) {
2706 			mtx_unlock(&softc->ctl_lock);
2707 			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2708 			break;
2709 		}
2710 		mtx_lock(&lun->lun_lock);
2711 		mtx_unlock(&softc->ctl_lock);
2712 		delay_info->status = CTL_DELAY_STATUS_OK;
2713 		switch (delay_info->delay_type) {
2714 		case CTL_DELAY_TYPE_CONT:
2715 		case CTL_DELAY_TYPE_ONESHOT:
2716 			break;
2717 		default:
2718 			delay_info->status = CTL_DELAY_STATUS_INVALID_TYPE;
2719 			break;
2720 		}
2721 		switch (delay_info->delay_loc) {
2722 		case CTL_DELAY_LOC_DATAMOVE:
2723 			lun->delay_info.datamove_type = delay_info->delay_type;
2724 			lun->delay_info.datamove_delay = delay_info->delay_secs;
2725 			break;
2726 		case CTL_DELAY_LOC_DONE:
2727 			lun->delay_info.done_type = delay_info->delay_type;
2728 			lun->delay_info.done_delay = delay_info->delay_secs;
2729 			break;
2730 		default:
2731 			delay_info->status = CTL_DELAY_STATUS_INVALID_LOC;
2732 			break;
2733 		}
2734 		mtx_unlock(&lun->lun_lock);
2735 #else
2736 		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2737 #endif /* CTL_IO_DELAY */
2738 		break;
2739 	}
2740 	case CTL_ERROR_INJECT: {
2741 		struct ctl_error_desc *err_desc, *new_err_desc;
2742 
2743 		err_desc = (struct ctl_error_desc *)addr;
2744 
2745 		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2746 				      M_WAITOK | M_ZERO);
2747 		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2748 
2749 		mtx_lock(&softc->ctl_lock);
2750 		if (err_desc->lun_id >= ctl_max_luns ||
2751 		    (lun = softc->ctl_luns[err_desc->lun_id]) == NULL) {
2752 			mtx_unlock(&softc->ctl_lock);
2753 			free(new_err_desc, M_CTL);
2754 			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2755 			       __func__, (uintmax_t)err_desc->lun_id);
2756 			retval = EINVAL;
2757 			break;
2758 		}
2759 		mtx_lock(&lun->lun_lock);
2760 		mtx_unlock(&softc->ctl_lock);
2761 
2762 		/*
2763 		 * We could do some checking here to verify the validity
2764 		 * of the request, but given the complexity of error
2765 		 * injection requests, the checking logic would be fairly
2766 		 * complex.
2767 		 *
2768 		 * For now, if the request is invalid, it just won't get
2769 		 * executed and might get deleted.
2770 		 */
2771 		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2772 
2773 		/*
2774 		 * XXX KDM check to make sure the serial number is unique,
2775 		 * in case we somehow manage to wrap.  That shouldn't
2776 		 * happen for a very long time, but it's the right thing to
2777 		 * do.
2778 		 */
2779 		new_err_desc->serial = lun->error_serial;
2780 		err_desc->serial = lun->error_serial;
2781 		lun->error_serial++;
2782 
2783 		mtx_unlock(&lun->lun_lock);
2784 		break;
2785 	}
2786 	case CTL_ERROR_INJECT_DELETE: {
2787 		struct ctl_error_desc *delete_desc, *desc, *desc2;
2788 		int delete_done;
2789 
2790 		delete_desc = (struct ctl_error_desc *)addr;
2791 		delete_done = 0;
2792 
2793 		mtx_lock(&softc->ctl_lock);
2794 		if (delete_desc->lun_id >= ctl_max_luns ||
2795 		    (lun = softc->ctl_luns[delete_desc->lun_id]) == NULL) {
2796 			mtx_unlock(&softc->ctl_lock);
2797 			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2798 			       __func__, (uintmax_t)delete_desc->lun_id);
2799 			retval = EINVAL;
2800 			break;
2801 		}
2802 		mtx_lock(&lun->lun_lock);
2803 		mtx_unlock(&softc->ctl_lock);
2804 		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2805 			if (desc->serial != delete_desc->serial)
2806 				continue;
2807 
2808 			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2809 				      links);
2810 			free(desc, M_CTL);
2811 			delete_done = 1;
2812 		}
2813 		mtx_unlock(&lun->lun_lock);
2814 		if (delete_done == 0) {
2815 			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2816 			       "error serial %ju on LUN %u\n", __func__,
2817 			       delete_desc->serial, delete_desc->lun_id);
2818 			retval = EINVAL;
2819 			break;
2820 		}
2821 		break;
2822 	}
2823 	case CTL_DUMP_STRUCTS: {
2824 		int j, k;
2825 		struct ctl_port *port;
2826 		struct ctl_frontend *fe;
2827 
2828 		mtx_lock(&softc->ctl_lock);
2829 		printf("CTL Persistent Reservation information start:\n");
2830 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2831 			mtx_lock(&lun->lun_lock);
2832 			if ((lun->flags & CTL_LUN_DISABLED) != 0) {
2833 				mtx_unlock(&lun->lun_lock);
2834 				continue;
2835 			}
2836 
2837 			for (j = 0; j < ctl_max_ports; j++) {
2838 				if (lun->pr_keys[j] == NULL)
2839 					continue;
2840 				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2841 					if (lun->pr_keys[j][k] == 0)
2842 						continue;
2843 					printf("  LUN %ju port %d iid %d key "
2844 					       "%#jx\n", lun->lun, j, k,
2845 					       (uintmax_t)lun->pr_keys[j][k]);
2846 				}
2847 			}
2848 			mtx_unlock(&lun->lun_lock);
2849 		}
2850 		printf("CTL Persistent Reservation information end\n");
2851 		printf("CTL Ports:\n");
2852 		STAILQ_FOREACH(port, &softc->port_list, links) {
2853 			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2854 			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2855 			       port->frontend->name, port->port_type,
2856 			       port->physical_port, port->virtual_port,
2857 			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2858 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2859 				if (port->wwpn_iid[j].in_use == 0 &&
2860 				    port->wwpn_iid[j].wwpn == 0 &&
2861 				    port->wwpn_iid[j].name == NULL)
2862 					continue;
2863 
2864 				printf("    iid %u use %d WWPN %#jx '%s'\n",
2865 				    j, port->wwpn_iid[j].in_use,
2866 				    (uintmax_t)port->wwpn_iid[j].wwpn,
2867 				    port->wwpn_iid[j].name);
2868 			}
2869 		}
2870 		printf("CTL Port information end\n");
2871 		mtx_unlock(&softc->ctl_lock);
2872 		/*
2873 		 * XXX KDM calling this without a lock.  We'd likely want
2874 		 * to drop the lock before calling the frontend's dump
2875 		 * routine anyway.
2876 		 */
2877 		printf("CTL Frontends:\n");
2878 		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2879 			printf("  Frontend '%s'\n", fe->name);
2880 			if (fe->fe_dump != NULL)
2881 				fe->fe_dump();
2882 		}
2883 		printf("CTL Frontend information end\n");
2884 		break;
2885 	}
2886 	case CTL_LUN_REQ: {
2887 		struct ctl_lun_req *lun_req;
2888 		struct ctl_backend_driver *backend;
2889 		void *packed;
2890 		nvlist_t *tmp_args_nvl;
2891 		size_t packed_len;
2892 
2893 		lun_req = (struct ctl_lun_req *)addr;
2894 		tmp_args_nvl = lun_req->args_nvl;
2895 
2896 		backend = ctl_backend_find(lun_req->backend);
2897 		if (backend == NULL) {
2898 			lun_req->status = CTL_LUN_ERROR;
2899 			snprintf(lun_req->error_str,
2900 				 sizeof(lun_req->error_str),
2901 				 "Backend \"%s\" not found.",
2902 				 lun_req->backend);
2903 			break;
2904 		}
2905 
2906 		if (lun_req->args != NULL) {
2907 			if (lun_req->args_len > CTL_MAX_ARGS_LEN) {
2908 				lun_req->status = CTL_LUN_ERROR;
2909 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2910 				    "Too big args.");
2911 				break;
2912 			}
2913 			packed = malloc(lun_req->args_len, M_CTL, M_WAITOK);
2914 			if (copyin(lun_req->args, packed, lun_req->args_len) != 0) {
2915 				free(packed, M_CTL);
2916 				lun_req->status = CTL_LUN_ERROR;
2917 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2918 				    "Cannot copyin args.");
2919 				break;
2920 			}
2921 			lun_req->args_nvl = nvlist_unpack(packed,
2922 			    lun_req->args_len, 0);
2923 			free(packed, M_CTL);
2924 
2925 			if (lun_req->args_nvl == NULL) {
2926 				lun_req->status = CTL_LUN_ERROR;
2927 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2928 				    "Cannot unpack args nvlist.");
2929 				break;
2930 			}
2931 		} else
2932 			lun_req->args_nvl = nvlist_create(0);
2933 
2934 		lun_req->result_nvl = NULL;
2935 		retval = backend->ioctl(dev, cmd, addr, flag, td);
2936 		nvlist_destroy(lun_req->args_nvl);
2937 		lun_req->args_nvl = tmp_args_nvl;
2938 
2939 		if (lun_req->result_nvl != NULL) {
2940 			if (lun_req->result != NULL) {
2941 				packed = nvlist_pack(lun_req->result_nvl,
2942 				    &packed_len);
2943 				if (packed == NULL) {
2944 					lun_req->status = CTL_LUN_ERROR;
2945 					snprintf(lun_req->error_str,
2946 					    sizeof(lun_req->error_str),
2947 					    "Cannot pack result nvlist.");
2948 					break;
2949 				}
2950 
2951 				if (packed_len > lun_req->result_len) {
2952 					lun_req->status = CTL_LUN_ERROR;
2953 					snprintf(lun_req->error_str,
2954 					    sizeof(lun_req->error_str),
2955 					    "Result nvlist too large.");
2956 					free(packed, M_NVLIST);
2957 					break;
2958 				}
2959 
2960 				if (copyout(packed, lun_req->result, packed_len)) {
2961 					lun_req->status = CTL_LUN_ERROR;
2962 					snprintf(lun_req->error_str,
2963 					    sizeof(lun_req->error_str),
2964 					    "Cannot copyout() the result.");
2965 					free(packed, M_NVLIST);
2966 					break;
2967 				}
2968 
2969 				lun_req->result_len = packed_len;
2970 				free(packed, M_NVLIST);
2971 			}
2972 
2973 			nvlist_destroy(lun_req->result_nvl);
2974 		}
2975 		break;
2976 	}
2977 	case CTL_LUN_LIST: {
2978 		struct sbuf *sb;
2979 		struct ctl_lun_list *list;
2980 		const char *name, *value;
2981 		void *cookie;
2982 		int type;
2983 
2984 		list = (struct ctl_lun_list *)addr;
2985 
2986 		/*
2987 		 * Allocate a fixed length sbuf here, based on the length
2988 		 * of the user's buffer.  We could allocate an auto-extending
2989 		 * buffer, and then tell the user how much larger our
2990 		 * amount of data is than his buffer, but that presents
2991 		 * some problems:
2992 		 *
2993 		 * 1.  The sbuf(9) routines use a blocking malloc, and so
2994 		 *     we can't hold a lock while calling them with an
2995 		 *     auto-extending buffer.
2996  		 *
2997 		 * 2.  There is not currently a LUN reference counting
2998 		 *     mechanism, outside of outstanding transactions on
2999 		 *     the LUN's OOA queue.  So a LUN could go away on us
3000 		 *     while we're getting the LUN number, backend-specific
3001 		 *     information, etc.  Thus, given the way things
3002 		 *     currently work, we need to hold the CTL lock while
3003 		 *     grabbing LUN information.
3004 		 *
3005 		 * So, from the user's standpoint, the best thing to do is
3006 		 * allocate what he thinks is a reasonable buffer length,
3007 		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3008 		 * double the buffer length and try again.  (And repeat
3009 		 * that until he succeeds.)
3010 		 */
3011 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3012 		if (sb == NULL) {
3013 			list->status = CTL_LUN_LIST_ERROR;
3014 			snprintf(list->error_str, sizeof(list->error_str),
3015 				 "Unable to allocate %d bytes for LUN list",
3016 				 list->alloc_len);
3017 			break;
3018 		}
3019 
3020 		sbuf_printf(sb, "<ctllunlist>\n");
3021 
3022 		mtx_lock(&softc->ctl_lock);
3023 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3024 			mtx_lock(&lun->lun_lock);
3025 			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3026 					     (uintmax_t)lun->lun);
3027 
3028 			/*
3029 			 * Bail out as soon as we see that we've overfilled
3030 			 * the buffer.
3031 			 */
3032 			if (retval != 0)
3033 				break;
3034 
3035 			retval = sbuf_printf(sb, "\t<backend_type>%s"
3036 					     "</backend_type>\n",
3037 					     (lun->backend == NULL) ?  "none" :
3038 					     lun->backend->name);
3039 
3040 			if (retval != 0)
3041 				break;
3042 
3043 			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3044 					     lun->be_lun->lun_type);
3045 
3046 			if (retval != 0)
3047 				break;
3048 
3049 			if (lun->backend == NULL) {
3050 				retval = sbuf_printf(sb, "</lun>\n");
3051 				if (retval != 0)
3052 					break;
3053 				continue;
3054 			}
3055 
3056 			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3057 					     (lun->be_lun->maxlba > 0) ?
3058 					     lun->be_lun->maxlba + 1 : 0);
3059 
3060 			if (retval != 0)
3061 				break;
3062 
3063 			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3064 					     lun->be_lun->blocksize);
3065 
3066 			if (retval != 0)
3067 				break;
3068 
3069 			retval = sbuf_printf(sb, "\t<serial_number>");
3070 
3071 			if (retval != 0)
3072 				break;
3073 
3074 			retval = ctl_sbuf_printf_esc(sb,
3075 			    lun->be_lun->serial_num,
3076 			    sizeof(lun->be_lun->serial_num));
3077 
3078 			if (retval != 0)
3079 				break;
3080 
3081 			retval = sbuf_printf(sb, "</serial_number>\n");
3082 
3083 			if (retval != 0)
3084 				break;
3085 
3086 			retval = sbuf_printf(sb, "\t<device_id>");
3087 
3088 			if (retval != 0)
3089 				break;
3090 
3091 			retval = ctl_sbuf_printf_esc(sb,
3092 			    lun->be_lun->device_id,
3093 			    sizeof(lun->be_lun->device_id));
3094 
3095 			if (retval != 0)
3096 				break;
3097 
3098 			retval = sbuf_printf(sb, "</device_id>\n");
3099 
3100 			if (retval != 0)
3101 				break;
3102 
3103 			if (lun->backend->lun_info != NULL) {
3104 				retval = lun->backend->lun_info(lun->be_lun, sb);
3105 				if (retval != 0)
3106 					break;
3107 			}
3108 
3109 			cookie = NULL;
3110 			while ((name = nvlist_next(lun->be_lun->options, &type,
3111 			    &cookie)) != NULL) {
3112 				sbuf_printf(sb, "\t<%s>", name);
3113 
3114 				if (type == NV_TYPE_STRING) {
3115 					value = dnvlist_get_string(
3116 					    lun->be_lun->options, name, NULL);
3117 					if (value != NULL)
3118 						sbuf_printf(sb, "%s", value);
3119 				}
3120 
3121 				sbuf_printf(sb, "</%s>\n", name);
3122 			}
3123 
3124 			retval = sbuf_printf(sb, "</lun>\n");
3125 
3126 			if (retval != 0)
3127 				break;
3128 			mtx_unlock(&lun->lun_lock);
3129 		}
3130 		if (lun != NULL)
3131 			mtx_unlock(&lun->lun_lock);
3132 		mtx_unlock(&softc->ctl_lock);
3133 
3134 		if ((retval != 0)
3135 		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3136 			retval = 0;
3137 			sbuf_delete(sb);
3138 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3139 			snprintf(list->error_str, sizeof(list->error_str),
3140 				 "Out of space, %d bytes is too small",
3141 				 list->alloc_len);
3142 			break;
3143 		}
3144 
3145 		sbuf_finish(sb);
3146 
3147 		retval = copyout(sbuf_data(sb), list->lun_xml,
3148 				 sbuf_len(sb) + 1);
3149 
3150 		list->fill_len = sbuf_len(sb) + 1;
3151 		list->status = CTL_LUN_LIST_OK;
3152 		sbuf_delete(sb);
3153 		break;
3154 	}
3155 	case CTL_ISCSI: {
3156 		struct ctl_iscsi *ci;
3157 		struct ctl_frontend *fe;
3158 
3159 		ci = (struct ctl_iscsi *)addr;
3160 
3161 		fe = ctl_frontend_find("iscsi");
3162 		if (fe == NULL) {
3163 			ci->status = CTL_ISCSI_ERROR;
3164 			snprintf(ci->error_str, sizeof(ci->error_str),
3165 			    "Frontend \"iscsi\" not found.");
3166 			break;
3167 		}
3168 
3169 		retval = fe->ioctl(dev, cmd, addr, flag, td);
3170 		break;
3171 	}
3172 	case CTL_PORT_REQ: {
3173 		struct ctl_req *req;
3174 		struct ctl_frontend *fe;
3175 		void *packed;
3176 		nvlist_t *tmp_args_nvl;
3177 		size_t packed_len;
3178 
3179 		req = (struct ctl_req *)addr;
3180 		tmp_args_nvl = req->args_nvl;
3181 
3182 		fe = ctl_frontend_find(req->driver);
3183 		if (fe == NULL) {
3184 			req->status = CTL_LUN_ERROR;
3185 			snprintf(req->error_str, sizeof(req->error_str),
3186 			    "Frontend \"%s\" not found.", req->driver);
3187 			break;
3188 		}
3189 
3190 		if (req->args != NULL) {
3191 			if (req->args_len > CTL_MAX_ARGS_LEN) {
3192 				req->status = CTL_LUN_ERROR;
3193 				snprintf(req->error_str, sizeof(req->error_str),
3194 				    "Too big args.");
3195 				break;
3196 			}
3197 			packed = malloc(req->args_len, M_CTL, M_WAITOK);
3198 			if (copyin(req->args, packed, req->args_len) != 0) {
3199 				free(packed, M_CTL);
3200 				req->status = CTL_LUN_ERROR;
3201 				snprintf(req->error_str, sizeof(req->error_str),
3202 				    "Cannot copyin args.");
3203 				break;
3204 			}
3205 			req->args_nvl = nvlist_unpack(packed,
3206 			    req->args_len, 0);
3207 			free(packed, M_CTL);
3208 
3209 			if (req->args_nvl == NULL) {
3210 				req->status = CTL_LUN_ERROR;
3211 				snprintf(req->error_str, sizeof(req->error_str),
3212 				    "Cannot unpack args nvlist.");
3213 				break;
3214 			}
3215 		} else
3216 			req->args_nvl = nvlist_create(0);
3217 
3218 		req->result_nvl = NULL;
3219 		if (fe->ioctl)
3220 			retval = fe->ioctl(dev, cmd, addr, flag, td);
3221 		else
3222 			retval = ENODEV;
3223 
3224 		nvlist_destroy(req->args_nvl);
3225 		req->args_nvl = tmp_args_nvl;
3226 
3227 		if (req->result_nvl != NULL) {
3228 			if (req->result != NULL) {
3229 				packed = nvlist_pack(req->result_nvl,
3230 				    &packed_len);
3231 				if (packed == NULL) {
3232 					req->status = CTL_LUN_ERROR;
3233 					snprintf(req->error_str,
3234 					    sizeof(req->error_str),
3235 					    "Cannot pack result nvlist.");
3236 					break;
3237 				}
3238 
3239 				if (packed_len > req->result_len) {
3240 					req->status = CTL_LUN_ERROR;
3241 					snprintf(req->error_str,
3242 					    sizeof(req->error_str),
3243 					    "Result nvlist too large.");
3244 					free(packed, M_NVLIST);
3245 					break;
3246 				}
3247 
3248 				if (copyout(packed, req->result, packed_len)) {
3249 					req->status = CTL_LUN_ERROR;
3250 					snprintf(req->error_str,
3251 					    sizeof(req->error_str),
3252 					    "Cannot copyout() the result.");
3253 					free(packed, M_NVLIST);
3254 					break;
3255 				}
3256 
3257 				req->result_len = packed_len;
3258 				free(packed, M_NVLIST);
3259 			}
3260 
3261 			nvlist_destroy(req->result_nvl);
3262 		}
3263 		break;
3264 	}
3265 	case CTL_PORT_LIST: {
3266 		struct sbuf *sb;
3267 		struct ctl_port *port;
3268 		struct ctl_lun_list *list;
3269 		const char *name, *value;
3270 		void *cookie;
3271 		int j, type;
3272 		uint32_t plun;
3273 
3274 		list = (struct ctl_lun_list *)addr;
3275 
3276 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3277 		if (sb == NULL) {
3278 			list->status = CTL_LUN_LIST_ERROR;
3279 			snprintf(list->error_str, sizeof(list->error_str),
3280 				 "Unable to allocate %d bytes for LUN list",
3281 				 list->alloc_len);
3282 			break;
3283 		}
3284 
3285 		sbuf_printf(sb, "<ctlportlist>\n");
3286 
3287 		mtx_lock(&softc->ctl_lock);
3288 		STAILQ_FOREACH(port, &softc->port_list, links) {
3289 			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3290 					     (uintmax_t)port->targ_port);
3291 
3292 			/*
3293 			 * Bail out as soon as we see that we've overfilled
3294 			 * the buffer.
3295 			 */
3296 			if (retval != 0)
3297 				break;
3298 
3299 			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3300 			    "</frontend_type>\n", port->frontend->name);
3301 			if (retval != 0)
3302 				break;
3303 
3304 			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3305 					     port->port_type);
3306 			if (retval != 0)
3307 				break;
3308 
3309 			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3310 			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3311 			if (retval != 0)
3312 				break;
3313 
3314 			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3315 			    port->port_name);
3316 			if (retval != 0)
3317 				break;
3318 
3319 			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3320 			    port->physical_port);
3321 			if (retval != 0)
3322 				break;
3323 
3324 			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3325 			    port->virtual_port);
3326 			if (retval != 0)
3327 				break;
3328 
3329 			if (port->target_devid != NULL) {
3330 				sbuf_printf(sb, "\t<target>");
3331 				ctl_id_sbuf(port->target_devid, sb);
3332 				sbuf_printf(sb, "</target>\n");
3333 			}
3334 
3335 			if (port->port_devid != NULL) {
3336 				sbuf_printf(sb, "\t<port>");
3337 				ctl_id_sbuf(port->port_devid, sb);
3338 				sbuf_printf(sb, "</port>\n");
3339 			}
3340 
3341 			if (port->port_info != NULL) {
3342 				retval = port->port_info(port->onoff_arg, sb);
3343 				if (retval != 0)
3344 					break;
3345 			}
3346 
3347 			cookie = NULL;
3348 			while ((name = nvlist_next(port->options, &type,
3349 			    &cookie)) != NULL) {
3350 				sbuf_printf(sb, "\t<%s>", name);
3351 
3352 				if (type == NV_TYPE_STRING) {
3353 					value = dnvlist_get_string(port->options,
3354 					    name, NULL);
3355 					if (value != NULL)
3356 						sbuf_printf(sb, "%s", value);
3357 				}
3358 
3359 				sbuf_printf(sb, "</%s>\n", name);
3360 			}
3361 
3362 			if (port->lun_map != NULL) {
3363 				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3364 				for (j = 0; j < port->lun_map_size; j++) {
3365 					plun = ctl_lun_map_from_port(port, j);
3366 					if (plun == UINT32_MAX)
3367 						continue;
3368 					sbuf_printf(sb,
3369 					    "\t<lun id=\"%u\">%u</lun>\n",
3370 					    j, plun);
3371 				}
3372 			}
3373 
3374 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3375 				if (port->wwpn_iid[j].in_use == 0 ||
3376 				    (port->wwpn_iid[j].wwpn == 0 &&
3377 				     port->wwpn_iid[j].name == NULL))
3378 					continue;
3379 
3380 				if (port->wwpn_iid[j].name != NULL)
3381 					retval = sbuf_printf(sb,
3382 					    "\t<initiator id=\"%u\">%s</initiator>\n",
3383 					    j, port->wwpn_iid[j].name);
3384 				else
3385 					retval = sbuf_printf(sb,
3386 					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3387 					    j, port->wwpn_iid[j].wwpn);
3388 				if (retval != 0)
3389 					break;
3390 			}
3391 			if (retval != 0)
3392 				break;
3393 
3394 			retval = sbuf_printf(sb, "</targ_port>\n");
3395 			if (retval != 0)
3396 				break;
3397 		}
3398 		mtx_unlock(&softc->ctl_lock);
3399 
3400 		if ((retval != 0)
3401 		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3402 			retval = 0;
3403 			sbuf_delete(sb);
3404 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3405 			snprintf(list->error_str, sizeof(list->error_str),
3406 				 "Out of space, %d bytes is too small",
3407 				 list->alloc_len);
3408 			break;
3409 		}
3410 
3411 		sbuf_finish(sb);
3412 
3413 		retval = copyout(sbuf_data(sb), list->lun_xml,
3414 				 sbuf_len(sb) + 1);
3415 
3416 		list->fill_len = sbuf_len(sb) + 1;
3417 		list->status = CTL_LUN_LIST_OK;
3418 		sbuf_delete(sb);
3419 		break;
3420 	}
3421 	case CTL_LUN_MAP: {
3422 		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3423 		struct ctl_port *port;
3424 
3425 		mtx_lock(&softc->ctl_lock);
3426 		if (lm->port < softc->port_min ||
3427 		    lm->port >= softc->port_max ||
3428 		    (port = softc->ctl_ports[lm->port]) == NULL) {
3429 			mtx_unlock(&softc->ctl_lock);
3430 			return (ENXIO);
3431 		}
3432 		if (port->status & CTL_PORT_STATUS_ONLINE) {
3433 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3434 				if (ctl_lun_map_to_port(port, lun->lun) ==
3435 				    UINT32_MAX)
3436 					continue;
3437 				mtx_lock(&lun->lun_lock);
3438 				ctl_est_ua_port(lun, lm->port, -1,
3439 				    CTL_UA_LUN_CHANGE);
3440 				mtx_unlock(&lun->lun_lock);
3441 			}
3442 		}
3443 		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3444 		if (lm->plun != UINT32_MAX) {
3445 			if (lm->lun == UINT32_MAX)
3446 				retval = ctl_lun_map_unset(port, lm->plun);
3447 			else if (lm->lun < ctl_max_luns &&
3448 			    softc->ctl_luns[lm->lun] != NULL)
3449 				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3450 			else
3451 				return (ENXIO);
3452 		} else {
3453 			if (lm->lun == UINT32_MAX)
3454 				retval = ctl_lun_map_deinit(port);
3455 			else
3456 				retval = ctl_lun_map_init(port);
3457 		}
3458 		if (port->status & CTL_PORT_STATUS_ONLINE)
3459 			ctl_isc_announce_port(port);
3460 		break;
3461 	}
3462 	case CTL_GET_LUN_STATS: {
3463 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3464 		int i;
3465 
3466 		/*
3467 		 * XXX KDM no locking here.  If the LUN list changes,
3468 		 * things can blow up.
3469 		 */
3470 		i = 0;
3471 		stats->status = CTL_SS_OK;
3472 		stats->fill_len = 0;
3473 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3474 			if (lun->lun < stats->first_item)
3475 				continue;
3476 			if (stats->fill_len + sizeof(lun->stats) >
3477 			    stats->alloc_len) {
3478 				stats->status = CTL_SS_NEED_MORE_SPACE;
3479 				break;
3480 			}
3481 			retval = copyout(&lun->stats, &stats->stats[i++],
3482 					 sizeof(lun->stats));
3483 			if (retval != 0)
3484 				break;
3485 			stats->fill_len += sizeof(lun->stats);
3486 		}
3487 		stats->num_items = softc->num_luns;
3488 		stats->flags = CTL_STATS_FLAG_NONE;
3489 #ifdef CTL_TIME_IO
3490 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3491 #endif
3492 		getnanouptime(&stats->timestamp);
3493 		break;
3494 	}
3495 	case CTL_GET_PORT_STATS: {
3496 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3497 		int i;
3498 
3499 		/*
3500 		 * XXX KDM no locking here.  If the LUN list changes,
3501 		 * things can blow up.
3502 		 */
3503 		i = 0;
3504 		stats->status = CTL_SS_OK;
3505 		stats->fill_len = 0;
3506 		STAILQ_FOREACH(port, &softc->port_list, links) {
3507 			if (port->targ_port < stats->first_item)
3508 				continue;
3509 			if (stats->fill_len + sizeof(port->stats) >
3510 			    stats->alloc_len) {
3511 				stats->status = CTL_SS_NEED_MORE_SPACE;
3512 				break;
3513 			}
3514 			retval = copyout(&port->stats, &stats->stats[i++],
3515 					 sizeof(port->stats));
3516 			if (retval != 0)
3517 				break;
3518 			stats->fill_len += sizeof(port->stats);
3519 		}
3520 		stats->num_items = softc->num_ports;
3521 		stats->flags = CTL_STATS_FLAG_NONE;
3522 #ifdef CTL_TIME_IO
3523 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3524 #endif
3525 		getnanouptime(&stats->timestamp);
3526 		break;
3527 	}
3528 	default: {
3529 		/* XXX KDM should we fix this? */
3530 #if 0
3531 		struct ctl_backend_driver *backend;
3532 		unsigned int type;
3533 		int found;
3534 
3535 		found = 0;
3536 
3537 		/*
3538 		 * We encode the backend type as the ioctl type for backend
3539 		 * ioctls.  So parse it out here, and then search for a
3540 		 * backend of this type.
3541 		 */
3542 		type = _IOC_TYPE(cmd);
3543 
3544 		STAILQ_FOREACH(backend, &softc->be_list, links) {
3545 			if (backend->type == type) {
3546 				found = 1;
3547 				break;
3548 			}
3549 		}
3550 		if (found == 0) {
3551 			printf("ctl: unknown ioctl command %#lx or backend "
3552 			       "%d\n", cmd, type);
3553 			retval = EINVAL;
3554 			break;
3555 		}
3556 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3557 #endif
3558 		retval = ENOTTY;
3559 		break;
3560 	}
3561 	}
3562 	return (retval);
3563 }
3564 
3565 uint32_t
ctl_get_initindex(struct ctl_nexus * nexus)3566 ctl_get_initindex(struct ctl_nexus *nexus)
3567 {
3568 	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3569 }
3570 
3571 int
ctl_lun_map_init(struct ctl_port * port)3572 ctl_lun_map_init(struct ctl_port *port)
3573 {
3574 	struct ctl_softc *softc = port->ctl_softc;
3575 	struct ctl_lun *lun;
3576 	int size = ctl_lun_map_size;
3577 	uint32_t i;
3578 
3579 	if (port->lun_map == NULL || port->lun_map_size < size) {
3580 		port->lun_map_size = 0;
3581 		free(port->lun_map, M_CTL);
3582 		port->lun_map = malloc(size * sizeof(uint32_t),
3583 		    M_CTL, M_NOWAIT);
3584 	}
3585 	if (port->lun_map == NULL)
3586 		return (ENOMEM);
3587 	for (i = 0; i < size; i++)
3588 		port->lun_map[i] = UINT32_MAX;
3589 	port->lun_map_size = size;
3590 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3591 		if (port->lun_disable != NULL) {
3592 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3593 				port->lun_disable(port->targ_lun_arg, lun->lun);
3594 		}
3595 		ctl_isc_announce_port(port);
3596 	}
3597 	return (0);
3598 }
3599 
3600 int
ctl_lun_map_deinit(struct ctl_port * port)3601 ctl_lun_map_deinit(struct ctl_port *port)
3602 {
3603 	struct ctl_softc *softc = port->ctl_softc;
3604 	struct ctl_lun *lun;
3605 
3606 	if (port->lun_map == NULL)
3607 		return (0);
3608 	port->lun_map_size = 0;
3609 	free(port->lun_map, M_CTL);
3610 	port->lun_map = NULL;
3611 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3612 		if (port->lun_enable != NULL) {
3613 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3614 				port->lun_enable(port->targ_lun_arg, lun->lun);
3615 		}
3616 		ctl_isc_announce_port(port);
3617 	}
3618 	return (0);
3619 }
3620 
3621 int
ctl_lun_map_set(struct ctl_port * port,uint32_t plun,uint32_t glun)3622 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3623 {
3624 	int status;
3625 	uint32_t old;
3626 
3627 	if (port->lun_map == NULL) {
3628 		status = ctl_lun_map_init(port);
3629 		if (status != 0)
3630 			return (status);
3631 	}
3632 	if (plun >= port->lun_map_size)
3633 		return (EINVAL);
3634 	old = port->lun_map[plun];
3635 	port->lun_map[plun] = glun;
3636 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old == UINT32_MAX) {
3637 		if (port->lun_enable != NULL)
3638 			port->lun_enable(port->targ_lun_arg, plun);
3639 		ctl_isc_announce_port(port);
3640 	}
3641 	return (0);
3642 }
3643 
3644 int
ctl_lun_map_unset(struct ctl_port * port,uint32_t plun)3645 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3646 {
3647 	uint32_t old;
3648 
3649 	if (port->lun_map == NULL || plun >= port->lun_map_size)
3650 		return (0);
3651 	old = port->lun_map[plun];
3652 	port->lun_map[plun] = UINT32_MAX;
3653 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old != UINT32_MAX) {
3654 		if (port->lun_disable != NULL)
3655 			port->lun_disable(port->targ_lun_arg, plun);
3656 		ctl_isc_announce_port(port);
3657 	}
3658 	return (0);
3659 }
3660 
3661 uint32_t
ctl_lun_map_from_port(struct ctl_port * port,uint32_t lun_id)3662 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3663 {
3664 
3665 	if (port == NULL)
3666 		return (UINT32_MAX);
3667 	if (port->lun_map == NULL)
3668 		return (lun_id);
3669 	if (lun_id > port->lun_map_size)
3670 		return (UINT32_MAX);
3671 	return (port->lun_map[lun_id]);
3672 }
3673 
3674 uint32_t
ctl_lun_map_to_port(struct ctl_port * port,uint32_t lun_id)3675 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3676 {
3677 	uint32_t i;
3678 
3679 	if (port == NULL)
3680 		return (UINT32_MAX);
3681 	if (port->lun_map == NULL)
3682 		return (lun_id);
3683 	for (i = 0; i < port->lun_map_size; i++) {
3684 		if (port->lun_map[i] == lun_id)
3685 			return (i);
3686 	}
3687 	return (UINT32_MAX);
3688 }
3689 
3690 uint32_t
ctl_decode_lun(uint64_t encoded)3691 ctl_decode_lun(uint64_t encoded)
3692 {
3693 	uint8_t lun[8];
3694 	uint32_t result = 0xffffffff;
3695 
3696 	be64enc(lun, encoded);
3697 	switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3698 	case RPL_LUNDATA_ATYP_PERIPH:
3699 		if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3700 		    lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3701 			result = lun[1];
3702 		break;
3703 	case RPL_LUNDATA_ATYP_FLAT:
3704 		if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3705 		    lun[6] == 0 && lun[7] == 0)
3706 			result = ((lun[0] & 0x3f) << 8) + lun[1];
3707 		break;
3708 	case RPL_LUNDATA_ATYP_EXTLUN:
3709 		switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3710 		case 0x02:
3711 			switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3712 			case 0x00:
3713 				result = lun[1];
3714 				break;
3715 			case 0x10:
3716 				result = (lun[1] << 16) + (lun[2] << 8) +
3717 				    lun[3];
3718 				break;
3719 			case 0x20:
3720 				if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3721 					result = (lun[2] << 24) +
3722 					    (lun[3] << 16) + (lun[4] << 8) +
3723 					    lun[5];
3724 				break;
3725 			}
3726 			break;
3727 		case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3728 			result = 0xffffffff;
3729 			break;
3730 		}
3731 		break;
3732 	}
3733 	return (result);
3734 }
3735 
3736 uint64_t
ctl_encode_lun(uint32_t decoded)3737 ctl_encode_lun(uint32_t decoded)
3738 {
3739 	uint64_t l = decoded;
3740 
3741 	if (l <= 0xff)
3742 		return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3743 	if (l <= 0x3fff)
3744 		return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3745 	if (l <= 0xffffff)
3746 		return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3747 		    (l << 32));
3748 	return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3749 }
3750 
3751 int
ctl_ffz(uint32_t * mask,uint32_t first,uint32_t last)3752 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3753 {
3754 	int i;
3755 
3756 	for (i = first; i < last; i++) {
3757 		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3758 			return (i);
3759 	}
3760 	return (-1);
3761 }
3762 
3763 int
ctl_set_mask(uint32_t * mask,uint32_t bit)3764 ctl_set_mask(uint32_t *mask, uint32_t bit)
3765 {
3766 	uint32_t chunk, piece;
3767 
3768 	chunk = bit >> 5;
3769 	piece = bit % (sizeof(uint32_t) * 8);
3770 
3771 	if ((mask[chunk] & (1 << piece)) != 0)
3772 		return (-1);
3773 	else
3774 		mask[chunk] |= (1 << piece);
3775 
3776 	return (0);
3777 }
3778 
3779 int
ctl_clear_mask(uint32_t * mask,uint32_t bit)3780 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3781 {
3782 	uint32_t chunk, piece;
3783 
3784 	chunk = bit >> 5;
3785 	piece = bit % (sizeof(uint32_t) * 8);
3786 
3787 	if ((mask[chunk] & (1 << piece)) == 0)
3788 		return (-1);
3789 	else
3790 		mask[chunk] &= ~(1 << piece);
3791 
3792 	return (0);
3793 }
3794 
3795 int
ctl_is_set(uint32_t * mask,uint32_t bit)3796 ctl_is_set(uint32_t *mask, uint32_t bit)
3797 {
3798 	uint32_t chunk, piece;
3799 
3800 	chunk = bit >> 5;
3801 	piece = bit % (sizeof(uint32_t) * 8);
3802 
3803 	if ((mask[chunk] & (1 << piece)) == 0)
3804 		return (0);
3805 	else
3806 		return (1);
3807 }
3808 
3809 static uint64_t
ctl_get_prkey(struct ctl_lun * lun,uint32_t residx)3810 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3811 {
3812 	uint64_t *t;
3813 
3814 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3815 	if (t == NULL)
3816 		return (0);
3817 	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3818 }
3819 
3820 static void
ctl_clr_prkey(struct ctl_lun * lun,uint32_t residx)3821 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3822 {
3823 	uint64_t *t;
3824 
3825 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3826 	if (t == NULL)
3827 		return;
3828 	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3829 }
3830 
3831 static void
ctl_alloc_prkey(struct ctl_lun * lun,uint32_t residx)3832 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3833 {
3834 	uint64_t *p;
3835 	u_int i;
3836 
3837 	i = residx/CTL_MAX_INIT_PER_PORT;
3838 	if (lun->pr_keys[i] != NULL)
3839 		return;
3840 	mtx_unlock(&lun->lun_lock);
3841 	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3842 	    M_WAITOK | M_ZERO);
3843 	mtx_lock(&lun->lun_lock);
3844 	if (lun->pr_keys[i] == NULL)
3845 		lun->pr_keys[i] = p;
3846 	else
3847 		free(p, M_CTL);
3848 }
3849 
3850 static void
ctl_set_prkey(struct ctl_lun * lun,uint32_t residx,uint64_t key)3851 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3852 {
3853 	uint64_t *t;
3854 
3855 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3856 	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3857 	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3858 }
3859 
3860 /*
3861  * ctl_softc, pool_name, total_ctl_io are passed in.
3862  * npool is passed out.
3863  */
3864 int
ctl_pool_create(struct ctl_softc * ctl_softc,const char * pool_name,uint32_t total_ctl_io,void ** npool)3865 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3866 		uint32_t total_ctl_io, void **npool)
3867 {
3868 	struct ctl_io_pool *pool;
3869 
3870 	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3871 					    M_NOWAIT | M_ZERO);
3872 	if (pool == NULL)
3873 		return (ENOMEM);
3874 
3875 	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3876 	pool->ctl_softc = ctl_softc;
3877 #ifdef IO_POOLS
3878 	pool->zone = uma_zsecond_create(pool->name, NULL,
3879 	    NULL, NULL, NULL, ctl_softc->io_zone);
3880 	/* uma_prealloc(pool->zone, total_ctl_io); */
3881 #else
3882 	pool->zone = ctl_softc->io_zone;
3883 #endif
3884 
3885 	*npool = pool;
3886 	return (0);
3887 }
3888 
3889 void
ctl_pool_free(struct ctl_io_pool * pool)3890 ctl_pool_free(struct ctl_io_pool *pool)
3891 {
3892 
3893 	if (pool == NULL)
3894 		return;
3895 
3896 #ifdef IO_POOLS
3897 	uma_zdestroy(pool->zone);
3898 #endif
3899 	free(pool, M_CTL);
3900 }
3901 
3902 union ctl_io *
ctl_alloc_io(void * pool_ref)3903 ctl_alloc_io(void *pool_ref)
3904 {
3905 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3906 	union ctl_io *io;
3907 
3908 	io = uma_zalloc(pool->zone, M_WAITOK);
3909 	if (io != NULL) {
3910 		io->io_hdr.pool = pool_ref;
3911 		CTL_SOFTC(io) = pool->ctl_softc;
3912 		TAILQ_INIT(&io->io_hdr.blocked_queue);
3913 	}
3914 	return (io);
3915 }
3916 
3917 union ctl_io *
ctl_alloc_io_nowait(void * pool_ref)3918 ctl_alloc_io_nowait(void *pool_ref)
3919 {
3920 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3921 	union ctl_io *io;
3922 
3923 	io = uma_zalloc(pool->zone, M_NOWAIT);
3924 	if (io != NULL) {
3925 		io->io_hdr.pool = pool_ref;
3926 		CTL_SOFTC(io) = pool->ctl_softc;
3927 		TAILQ_INIT(&io->io_hdr.blocked_queue);
3928 	}
3929 	return (io);
3930 }
3931 
3932 void
ctl_free_io(union ctl_io * io)3933 ctl_free_io(union ctl_io *io)
3934 {
3935 	struct ctl_io_pool *pool;
3936 
3937 	if (io == NULL)
3938 		return;
3939 
3940 	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3941 	uma_zfree(pool->zone, io);
3942 }
3943 
3944 void
ctl_zero_io(union ctl_io * io)3945 ctl_zero_io(union ctl_io *io)
3946 {
3947 	struct ctl_io_pool *pool;
3948 
3949 	if (io == NULL)
3950 		return;
3951 
3952 	/*
3953 	 * May need to preserve linked list pointers at some point too.
3954 	 */
3955 	pool = io->io_hdr.pool;
3956 	memset(io, 0, sizeof(*io));
3957 	io->io_hdr.pool = pool;
3958 	CTL_SOFTC(io) = pool->ctl_softc;
3959 	TAILQ_INIT(&io->io_hdr.blocked_queue);
3960 }
3961 
3962 int
ctl_expand_number(const char * buf,uint64_t * num)3963 ctl_expand_number(const char *buf, uint64_t *num)
3964 {
3965 	char *endptr;
3966 	uint64_t number;
3967 	unsigned shift;
3968 
3969 	number = strtoq(buf, &endptr, 0);
3970 
3971 	switch (tolower((unsigned char)*endptr)) {
3972 	case 'e':
3973 		shift = 60;
3974 		break;
3975 	case 'p':
3976 		shift = 50;
3977 		break;
3978 	case 't':
3979 		shift = 40;
3980 		break;
3981 	case 'g':
3982 		shift = 30;
3983 		break;
3984 	case 'm':
3985 		shift = 20;
3986 		break;
3987 	case 'k':
3988 		shift = 10;
3989 		break;
3990 	case 'b':
3991 	case '\0': /* No unit. */
3992 		*num = number;
3993 		return (0);
3994 	default:
3995 		/* Unrecognized unit. */
3996 		return (-1);
3997 	}
3998 
3999 	if ((number << shift) >> shift != number) {
4000 		/* Overflow */
4001 		return (-1);
4002 	}
4003 	*num = number << shift;
4004 	return (0);
4005 }
4006 
4007 
4008 /*
4009  * This routine could be used in the future to load default and/or saved
4010  * mode page parameters for a particuar lun.
4011  */
4012 static int
ctl_init_page_index(struct ctl_lun * lun)4013 ctl_init_page_index(struct ctl_lun *lun)
4014 {
4015 	int i, page_code;
4016 	struct ctl_page_index *page_index;
4017 	const char *value;
4018 	uint64_t ival;
4019 
4020 	memcpy(&lun->mode_pages.index, page_index_template,
4021 	       sizeof(page_index_template));
4022 
4023 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4024 
4025 		page_index = &lun->mode_pages.index[i];
4026 		if (lun->be_lun->lun_type == T_DIRECT &&
4027 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4028 			continue;
4029 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4030 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4031 			continue;
4032 		if (lun->be_lun->lun_type == T_CDROM &&
4033 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4034 			continue;
4035 
4036 		page_code = page_index->page_code & SMPH_PC_MASK;
4037 		switch (page_code) {
4038 		case SMS_RW_ERROR_RECOVERY_PAGE: {
4039 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4040 			    ("subpage %#x for page %#x is incorrect!",
4041 			    page_index->subpage, page_code));
4042 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4043 			       &rw_er_page_default,
4044 			       sizeof(rw_er_page_default));
4045 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4046 			       &rw_er_page_changeable,
4047 			       sizeof(rw_er_page_changeable));
4048 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4049 			       &rw_er_page_default,
4050 			       sizeof(rw_er_page_default));
4051 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4052 			       &rw_er_page_default,
4053 			       sizeof(rw_er_page_default));
4054 			page_index->page_data =
4055 				(uint8_t *)lun->mode_pages.rw_er_page;
4056 			break;
4057 		}
4058 		case SMS_FORMAT_DEVICE_PAGE: {
4059 			struct scsi_format_page *format_page;
4060 
4061 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4062 			    ("subpage %#x for page %#x is incorrect!",
4063 			    page_index->subpage, page_code));
4064 
4065 			/*
4066 			 * Sectors per track are set above.  Bytes per
4067 			 * sector need to be set here on a per-LUN basis.
4068 			 */
4069 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4070 			       &format_page_default,
4071 			       sizeof(format_page_default));
4072 			memcpy(&lun->mode_pages.format_page[
4073 			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4074 			       sizeof(format_page_changeable));
4075 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4076 			       &format_page_default,
4077 			       sizeof(format_page_default));
4078 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4079 			       &format_page_default,
4080 			       sizeof(format_page_default));
4081 
4082 			format_page = &lun->mode_pages.format_page[
4083 				CTL_PAGE_CURRENT];
4084 			scsi_ulto2b(lun->be_lun->blocksize,
4085 				    format_page->bytes_per_sector);
4086 
4087 			format_page = &lun->mode_pages.format_page[
4088 				CTL_PAGE_DEFAULT];
4089 			scsi_ulto2b(lun->be_lun->blocksize,
4090 				    format_page->bytes_per_sector);
4091 
4092 			format_page = &lun->mode_pages.format_page[
4093 				CTL_PAGE_SAVED];
4094 			scsi_ulto2b(lun->be_lun->blocksize,
4095 				    format_page->bytes_per_sector);
4096 
4097 			page_index->page_data =
4098 				(uint8_t *)lun->mode_pages.format_page;
4099 			break;
4100 		}
4101 		case SMS_RIGID_DISK_PAGE: {
4102 			struct scsi_rigid_disk_page *rigid_disk_page;
4103 			uint32_t sectors_per_cylinder;
4104 			uint64_t cylinders;
4105 #ifndef	__XSCALE__
4106 			int shift;
4107 #endif /* !__XSCALE__ */
4108 
4109 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4110 			    ("subpage %#x for page %#x is incorrect!",
4111 			    page_index->subpage, page_code));
4112 
4113 			/*
4114 			 * Rotation rate and sectors per track are set
4115 			 * above.  We calculate the cylinders here based on
4116 			 * capacity.  Due to the number of heads and
4117 			 * sectors per track we're using, smaller arrays
4118 			 * may turn out to have 0 cylinders.  Linux and
4119 			 * FreeBSD don't pay attention to these mode pages
4120 			 * to figure out capacity, but Solaris does.  It
4121 			 * seems to deal with 0 cylinders just fine, and
4122 			 * works out a fake geometry based on the capacity.
4123 			 */
4124 			memcpy(&lun->mode_pages.rigid_disk_page[
4125 			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4126 			       sizeof(rigid_disk_page_default));
4127 			memcpy(&lun->mode_pages.rigid_disk_page[
4128 			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4129 			       sizeof(rigid_disk_page_changeable));
4130 
4131 			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4132 				CTL_DEFAULT_HEADS;
4133 
4134 			/*
4135 			 * The divide method here will be more accurate,
4136 			 * probably, but results in floating point being
4137 			 * used in the kernel on i386 (__udivdi3()).  On the
4138 			 * XScale, though, __udivdi3() is implemented in
4139 			 * software.
4140 			 *
4141 			 * The shift method for cylinder calculation is
4142 			 * accurate if sectors_per_cylinder is a power of
4143 			 * 2.  Otherwise it might be slightly off -- you
4144 			 * might have a bit of a truncation problem.
4145 			 */
4146 #ifdef	__XSCALE__
4147 			cylinders = (lun->be_lun->maxlba + 1) /
4148 				sectors_per_cylinder;
4149 #else
4150 			for (shift = 31; shift > 0; shift--) {
4151 				if (sectors_per_cylinder & (1 << shift))
4152 					break;
4153 			}
4154 			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4155 #endif
4156 
4157 			/*
4158 			 * We've basically got 3 bytes, or 24 bits for the
4159 			 * cylinder size in the mode page.  If we're over,
4160 			 * just round down to 2^24.
4161 			 */
4162 			if (cylinders > 0xffffff)
4163 				cylinders = 0xffffff;
4164 
4165 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4166 				CTL_PAGE_DEFAULT];
4167 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4168 
4169 			if ((value = dnvlist_get_string(lun->be_lun->options,
4170 			    "rpm", NULL)) != NULL) {
4171 				scsi_ulto2b(strtol(value, NULL, 0),
4172 				     rigid_disk_page->rotation_rate);
4173 			}
4174 
4175 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4176 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4177 			       sizeof(rigid_disk_page_default));
4178 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4179 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4180 			       sizeof(rigid_disk_page_default));
4181 
4182 			page_index->page_data =
4183 				(uint8_t *)lun->mode_pages.rigid_disk_page;
4184 			break;
4185 		}
4186 		case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4187 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4188 			    ("subpage %#x for page %#x is incorrect!",
4189 			    page_index->subpage, page_code));
4190 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4191 			       &verify_er_page_default,
4192 			       sizeof(verify_er_page_default));
4193 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4194 			       &verify_er_page_changeable,
4195 			       sizeof(verify_er_page_changeable));
4196 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4197 			       &verify_er_page_default,
4198 			       sizeof(verify_er_page_default));
4199 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4200 			       &verify_er_page_default,
4201 			       sizeof(verify_er_page_default));
4202 			page_index->page_data =
4203 				(uint8_t *)lun->mode_pages.verify_er_page;
4204 			break;
4205 		}
4206 		case SMS_CACHING_PAGE: {
4207 			struct scsi_caching_page *caching_page;
4208 
4209 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4210 			    ("subpage %#x for page %#x is incorrect!",
4211 			    page_index->subpage, page_code));
4212 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4213 			       &caching_page_default,
4214 			       sizeof(caching_page_default));
4215 			memcpy(&lun->mode_pages.caching_page[
4216 			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4217 			       sizeof(caching_page_changeable));
4218 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4219 			       &caching_page_default,
4220 			       sizeof(caching_page_default));
4221 			caching_page = &lun->mode_pages.caching_page[
4222 			    CTL_PAGE_SAVED];
4223 			value = dnvlist_get_string(lun->be_lun->options,
4224 			    "writecache", NULL);
4225 			if (value != NULL && strcmp(value, "off") == 0)
4226 				caching_page->flags1 &= ~SCP_WCE;
4227 			value = dnvlist_get_string(lun->be_lun->options,
4228 			    "readcache", NULL);
4229 			if (value != NULL && strcmp(value, "off") == 0)
4230 				caching_page->flags1 |= SCP_RCD;
4231 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4232 			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4233 			       sizeof(caching_page_default));
4234 			page_index->page_data =
4235 				(uint8_t *)lun->mode_pages.caching_page;
4236 			break;
4237 		}
4238 		case SMS_CONTROL_MODE_PAGE: {
4239 			switch (page_index->subpage) {
4240 			case SMS_SUBPAGE_PAGE_0: {
4241 				struct scsi_control_page *control_page;
4242 
4243 				memcpy(&lun->mode_pages.control_page[
4244 				    CTL_PAGE_DEFAULT],
4245 				       &control_page_default,
4246 				       sizeof(control_page_default));
4247 				memcpy(&lun->mode_pages.control_page[
4248 				    CTL_PAGE_CHANGEABLE],
4249 				       &control_page_changeable,
4250 				       sizeof(control_page_changeable));
4251 				memcpy(&lun->mode_pages.control_page[
4252 				    CTL_PAGE_SAVED],
4253 				       &control_page_default,
4254 				       sizeof(control_page_default));
4255 				control_page = &lun->mode_pages.control_page[
4256 				    CTL_PAGE_SAVED];
4257 				value = dnvlist_get_string(lun->be_lun->options,
4258 				    "reordering", NULL);
4259 				if (value != NULL &&
4260 				    strcmp(value, "unrestricted") == 0) {
4261 					control_page->queue_flags &=
4262 					    ~SCP_QUEUE_ALG_MASK;
4263 					control_page->queue_flags |=
4264 					    SCP_QUEUE_ALG_UNRESTRICTED;
4265 				}
4266 				memcpy(&lun->mode_pages.control_page[
4267 				    CTL_PAGE_CURRENT],
4268 				       &lun->mode_pages.control_page[
4269 				    CTL_PAGE_SAVED],
4270 				       sizeof(control_page_default));
4271 				page_index->page_data =
4272 				    (uint8_t *)lun->mode_pages.control_page;
4273 				break;
4274 			}
4275 			case 0x01:
4276 				memcpy(&lun->mode_pages.control_ext_page[
4277 				    CTL_PAGE_DEFAULT],
4278 				       &control_ext_page_default,
4279 				       sizeof(control_ext_page_default));
4280 				memcpy(&lun->mode_pages.control_ext_page[
4281 				    CTL_PAGE_CHANGEABLE],
4282 				       &control_ext_page_changeable,
4283 				       sizeof(control_ext_page_changeable));
4284 				memcpy(&lun->mode_pages.control_ext_page[
4285 				    CTL_PAGE_SAVED],
4286 				       &control_ext_page_default,
4287 				       sizeof(control_ext_page_default));
4288 				memcpy(&lun->mode_pages.control_ext_page[
4289 				    CTL_PAGE_CURRENT],
4290 				       &lun->mode_pages.control_ext_page[
4291 				    CTL_PAGE_SAVED],
4292 				       sizeof(control_ext_page_default));
4293 				page_index->page_data =
4294 				    (uint8_t *)lun->mode_pages.control_ext_page;
4295 				break;
4296 			default:
4297 				panic("subpage %#x for page %#x is incorrect!",
4298 				      page_index->subpage, page_code);
4299 			}
4300 			break;
4301 		}
4302 		case SMS_INFO_EXCEPTIONS_PAGE: {
4303 			switch (page_index->subpage) {
4304 			case SMS_SUBPAGE_PAGE_0:
4305 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4306 				       &ie_page_default,
4307 				       sizeof(ie_page_default));
4308 				memcpy(&lun->mode_pages.ie_page[
4309 				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4310 				       sizeof(ie_page_changeable));
4311 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4312 				       &ie_page_default,
4313 				       sizeof(ie_page_default));
4314 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4315 				       &ie_page_default,
4316 				       sizeof(ie_page_default));
4317 				page_index->page_data =
4318 					(uint8_t *)lun->mode_pages.ie_page;
4319 				break;
4320 			case 0x02: {
4321 				struct ctl_logical_block_provisioning_page *page;
4322 
4323 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4324 				       &lbp_page_default,
4325 				       sizeof(lbp_page_default));
4326 				memcpy(&lun->mode_pages.lbp_page[
4327 				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4328 				       sizeof(lbp_page_changeable));
4329 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4330 				       &lbp_page_default,
4331 				       sizeof(lbp_page_default));
4332 				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4333 				value = dnvlist_get_string(lun->be_lun->options,
4334 				    "avail-threshold", NULL);
4335 				if (value != NULL &&
4336 				    ctl_expand_number(value, &ival) == 0) {
4337 					page->descr[0].flags |= SLBPPD_ENABLED |
4338 					    SLBPPD_ARMING_DEC;
4339 					if (lun->be_lun->blocksize)
4340 						ival /= lun->be_lun->blocksize;
4341 					else
4342 						ival /= 512;
4343 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4344 					    page->descr[0].count);
4345 				}
4346 				value = dnvlist_get_string(lun->be_lun->options,
4347 				    "used-threshold", NULL);
4348 				if (value != NULL &&
4349 				    ctl_expand_number(value, &ival) == 0) {
4350 					page->descr[1].flags |= SLBPPD_ENABLED |
4351 					    SLBPPD_ARMING_INC;
4352 					if (lun->be_lun->blocksize)
4353 						ival /= lun->be_lun->blocksize;
4354 					else
4355 						ival /= 512;
4356 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4357 					    page->descr[1].count);
4358 				}
4359 				value = dnvlist_get_string(lun->be_lun->options,
4360 				    "pool-avail-threshold", NULL);
4361 				if (value != NULL &&
4362 				    ctl_expand_number(value, &ival) == 0) {
4363 					page->descr[2].flags |= SLBPPD_ENABLED |
4364 					    SLBPPD_ARMING_DEC;
4365 					if (lun->be_lun->blocksize)
4366 						ival /= lun->be_lun->blocksize;
4367 					else
4368 						ival /= 512;
4369 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4370 					    page->descr[2].count);
4371 				}
4372 				value = dnvlist_get_string(lun->be_lun->options,
4373 				    "pool-used-threshold", NULL);
4374 				if (value != NULL &&
4375 				    ctl_expand_number(value, &ival) == 0) {
4376 					page->descr[3].flags |= SLBPPD_ENABLED |
4377 					    SLBPPD_ARMING_INC;
4378 					if (lun->be_lun->blocksize)
4379 						ival /= lun->be_lun->blocksize;
4380 					else
4381 						ival /= 512;
4382 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4383 					    page->descr[3].count);
4384 				}
4385 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4386 				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4387 				       sizeof(lbp_page_default));
4388 				page_index->page_data =
4389 					(uint8_t *)lun->mode_pages.lbp_page;
4390 				break;
4391 			}
4392 			default:
4393 				panic("subpage %#x for page %#x is incorrect!",
4394 				      page_index->subpage, page_code);
4395 			}
4396 			break;
4397 		}
4398 		case SMS_CDDVD_CAPS_PAGE:{
4399 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4400 			    ("subpage %#x for page %#x is incorrect!",
4401 			    page_index->subpage, page_code));
4402 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4403 			       &cddvd_page_default,
4404 			       sizeof(cddvd_page_default));
4405 			memcpy(&lun->mode_pages.cddvd_page[
4406 			       CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4407 			       sizeof(cddvd_page_changeable));
4408 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4409 			       &cddvd_page_default,
4410 			       sizeof(cddvd_page_default));
4411 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4412 			       &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4413 			       sizeof(cddvd_page_default));
4414 			page_index->page_data =
4415 				(uint8_t *)lun->mode_pages.cddvd_page;
4416 			break;
4417 		}
4418 		default:
4419 			panic("invalid page code value %#x", page_code);
4420 		}
4421 	}
4422 
4423 	return (CTL_RETVAL_COMPLETE);
4424 }
4425 
4426 static int
ctl_init_log_page_index(struct ctl_lun * lun)4427 ctl_init_log_page_index(struct ctl_lun *lun)
4428 {
4429 	struct ctl_page_index *page_index;
4430 	int i, j, k, prev;
4431 
4432 	memcpy(&lun->log_pages.index, log_page_index_template,
4433 	       sizeof(log_page_index_template));
4434 
4435 	prev = -1;
4436 	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4437 
4438 		page_index = &lun->log_pages.index[i];
4439 		if (lun->be_lun->lun_type == T_DIRECT &&
4440 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4441 			continue;
4442 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4443 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4444 			continue;
4445 		if (lun->be_lun->lun_type == T_CDROM &&
4446 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4447 			continue;
4448 
4449 		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4450 		    lun->backend->lun_attr == NULL)
4451 			continue;
4452 
4453 		if (page_index->page_code != prev) {
4454 			lun->log_pages.pages_page[j] = page_index->page_code;
4455 			prev = page_index->page_code;
4456 			j++;
4457 		}
4458 		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4459 		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4460 		k++;
4461 	}
4462 	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4463 	lun->log_pages.index[0].page_len = j;
4464 	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4465 	lun->log_pages.index[1].page_len = k * 2;
4466 	lun->log_pages.index[2].page_data = (uint8_t *)&lun->log_pages.temp_page;
4467 	lun->log_pages.index[2].page_len = sizeof(lun->log_pages.temp_page);
4468 	lun->log_pages.index[3].page_data = &lun->log_pages.lbp_page[0];
4469 	lun->log_pages.index[3].page_len = 12*CTL_NUM_LBP_PARAMS;
4470 	lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.stat_page;
4471 	lun->log_pages.index[4].page_len = sizeof(lun->log_pages.stat_page);
4472 	lun->log_pages.index[5].page_data = (uint8_t *)&lun->log_pages.ie_page;
4473 	lun->log_pages.index[5].page_len = sizeof(lun->log_pages.ie_page);
4474 
4475 	return (CTL_RETVAL_COMPLETE);
4476 }
4477 
4478 static int
hex2bin(const char * str,uint8_t * buf,int buf_size)4479 hex2bin(const char *str, uint8_t *buf, int buf_size)
4480 {
4481 	int i;
4482 	u_char c;
4483 
4484 	memset(buf, 0, buf_size);
4485 	while (isspace(str[0]))
4486 		str++;
4487 	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4488 		str += 2;
4489 	buf_size *= 2;
4490 	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4491 		while (str[i] == '-')	/* Skip dashes in UUIDs. */
4492 			str++;
4493 		c = str[i];
4494 		if (isdigit(c))
4495 			c -= '0';
4496 		else if (isalpha(c))
4497 			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4498 		else
4499 			break;
4500 		if (c >= 16)
4501 			break;
4502 		if ((i & 1) == 0)
4503 			buf[i / 2] |= (c << 4);
4504 		else
4505 			buf[i / 2] |= c;
4506 	}
4507 	return ((i + 1) / 2);
4508 }
4509 
4510 /*
4511  * Add LUN.
4512  *
4513  * Returns 0 for success, non-zero (errno) for failure.
4514  */
4515 int
ctl_add_lun(struct ctl_be_lun * be_lun)4516 ctl_add_lun(struct ctl_be_lun *be_lun)
4517 {
4518 	struct ctl_softc *ctl_softc = control_softc;
4519 	struct ctl_lun *nlun, *lun;
4520 	struct scsi_vpd_id_descriptor *desc;
4521 	struct scsi_vpd_id_t10 *t10id;
4522 	const char *eui, *naa, *scsiname, *uuid, *vendor, *value;
4523 	int lun_number;
4524 	int devidlen, idlen1, idlen2 = 0, len;
4525 
4526 	/*
4527 	 * We support only Direct Access, CD-ROM or Processor LUN types.
4528 	 */
4529 	switch (be_lun->lun_type) {
4530 	case T_DIRECT:
4531 	case T_PROCESSOR:
4532 	case T_CDROM:
4533 		break;
4534 	case T_SEQUENTIAL:
4535 	case T_CHANGER:
4536 	default:
4537 		return (EINVAL);
4538 	}
4539 	lun = malloc(sizeof(*lun), M_CTL, M_WAITOK | M_ZERO);
4540 
4541 	lun->pending_sense = malloc(sizeof(struct scsi_sense_data *) *
4542 	    ctl_max_ports, M_DEVBUF, M_WAITOK | M_ZERO);
4543 	lun->pending_ua = malloc(sizeof(ctl_ua_type *) * ctl_max_ports,
4544 	    M_DEVBUF, M_WAITOK | M_ZERO);
4545 	lun->pr_keys = malloc(sizeof(uint64_t *) * ctl_max_ports,
4546 	    M_DEVBUF, M_WAITOK | M_ZERO);
4547 
4548 	/* Generate LUN ID. */
4549 	devidlen = max(CTL_DEVID_MIN_LEN,
4550 	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4551 	idlen1 = sizeof(*t10id) + devidlen;
4552 	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4553 	scsiname = dnvlist_get_string(be_lun->options, "scsiname", NULL);
4554 	if (scsiname != NULL) {
4555 		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4556 		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4557 	}
4558 	eui = dnvlist_get_string(be_lun->options, "eui", NULL);
4559 	if (eui != NULL) {
4560 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4561 	}
4562 	naa = dnvlist_get_string(be_lun->options, "naa", NULL);
4563 	if (naa != NULL) {
4564 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4565 	}
4566 	uuid = dnvlist_get_string(be_lun->options, "uuid", NULL);
4567 	if (uuid != NULL) {
4568 		len += sizeof(struct scsi_vpd_id_descriptor) + 18;
4569 	}
4570 	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4571 	    M_CTL, M_WAITOK | M_ZERO);
4572 	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4573 	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4574 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4575 	desc->length = idlen1;
4576 	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4577 	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4578 	if ((vendor = dnvlist_get_string(be_lun->options, "vendor", NULL)) == NULL) {
4579 		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4580 	} else {
4581 		strncpy(t10id->vendor, vendor,
4582 		    min(sizeof(t10id->vendor), strlen(vendor)));
4583 	}
4584 	strncpy((char *)t10id->vendor_spec_id,
4585 	    (char *)be_lun->device_id, devidlen);
4586 	if (scsiname != NULL) {
4587 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4588 		    desc->length);
4589 		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4590 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4591 		    SVPD_ID_TYPE_SCSI_NAME;
4592 		desc->length = idlen2;
4593 		strlcpy(desc->identifier, scsiname, idlen2);
4594 	}
4595 	if (eui != NULL) {
4596 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4597 		    desc->length);
4598 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4599 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4600 		    SVPD_ID_TYPE_EUI64;
4601 		desc->length = hex2bin(eui, desc->identifier, 16);
4602 		desc->length = desc->length > 12 ? 16 :
4603 		    (desc->length > 8 ? 12 : 8);
4604 		len -= 16 - desc->length;
4605 	}
4606 	if (naa != NULL) {
4607 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4608 		    desc->length);
4609 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4610 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4611 		    SVPD_ID_TYPE_NAA;
4612 		desc->length = hex2bin(naa, desc->identifier, 16);
4613 		desc->length = desc->length > 8 ? 16 : 8;
4614 		len -= 16 - desc->length;
4615 	}
4616 	if (uuid != NULL) {
4617 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4618 		    desc->length);
4619 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4620 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4621 		    SVPD_ID_TYPE_UUID;
4622 		desc->identifier[0] = 0x10;
4623 		hex2bin(uuid, &desc->identifier[2], 16);
4624 		desc->length = 18;
4625 	}
4626 	lun->lun_devid->len = len;
4627 
4628 	mtx_lock(&ctl_softc->ctl_lock);
4629 	/*
4630 	 * See if the caller requested a particular LUN number.  If so, see
4631 	 * if it is available.  Otherwise, allocate the first available LUN.
4632 	 */
4633 	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4634 		if ((be_lun->req_lun_id > (ctl_max_luns - 1))
4635 		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4636 			mtx_unlock(&ctl_softc->ctl_lock);
4637 			if (be_lun->req_lun_id > (ctl_max_luns - 1)) {
4638 				printf("ctl: requested LUN ID %d is higher "
4639 				       "than ctl_max_luns - 1 (%d)\n",
4640 				       be_lun->req_lun_id, ctl_max_luns - 1);
4641 			} else {
4642 				/*
4643 				 * XXX KDM return an error, or just assign
4644 				 * another LUN ID in this case??
4645 				 */
4646 				printf("ctl: requested LUN ID %d is already "
4647 				       "in use\n", be_lun->req_lun_id);
4648 			}
4649 fail:
4650 			free(lun->lun_devid, M_CTL);
4651 			free(lun, M_CTL);
4652 			return (ENOSPC);
4653 		}
4654 		lun_number = be_lun->req_lun_id;
4655 	} else {
4656 		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, ctl_max_luns);
4657 		if (lun_number == -1) {
4658 			mtx_unlock(&ctl_softc->ctl_lock);
4659 			printf("ctl: can't allocate LUN, out of LUNs\n");
4660 			goto fail;
4661 		}
4662 	}
4663 	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4664 	mtx_unlock(&ctl_softc->ctl_lock);
4665 
4666 	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4667 	lun->lun = lun_number;
4668 	lun->be_lun = be_lun;
4669 	/*
4670 	 * The processor LUN is always enabled.  Disk LUNs come on line
4671 	 * disabled, and must be enabled by the backend.
4672 	 */
4673 	lun->flags |= CTL_LUN_DISABLED;
4674 	lun->backend = be_lun->be;
4675 	be_lun->ctl_lun = lun;
4676 	be_lun->lun_id = lun_number;
4677 	if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4678 		lun->flags |= CTL_LUN_EJECTED;
4679 	if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4680 		lun->flags |= CTL_LUN_NO_MEDIA;
4681 	if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4682 		lun->flags |= CTL_LUN_STOPPED;
4683 
4684 	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4685 		lun->flags |= CTL_LUN_PRIMARY_SC;
4686 
4687 	value = dnvlist_get_string(be_lun->options, "removable", NULL);
4688 	if (value != NULL) {
4689 		if (strcmp(value, "on") == 0)
4690 			lun->flags |= CTL_LUN_REMOVABLE;
4691 	} else if (be_lun->lun_type == T_CDROM)
4692 		lun->flags |= CTL_LUN_REMOVABLE;
4693 
4694 	lun->ctl_softc = ctl_softc;
4695 #ifdef CTL_TIME_IO
4696 	lun->last_busy = getsbinuptime();
4697 #endif
4698 	LIST_INIT(&lun->ooa_queue);
4699 	STAILQ_INIT(&lun->error_list);
4700 	lun->ie_reported = 1;
4701 	callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4702 	ctl_tpc_lun_init(lun);
4703 	if (lun->flags & CTL_LUN_REMOVABLE) {
4704 		lun->prevent = malloc((CTL_MAX_INITIATORS + 31) / 32 * 4,
4705 		    M_CTL, M_WAITOK);
4706 	}
4707 
4708 	/*
4709 	 * Initialize the mode and log page index.
4710 	 */
4711 	ctl_init_page_index(lun);
4712 	ctl_init_log_page_index(lun);
4713 
4714 	/* Setup statistics gathering */
4715 	lun->stats.item = lun_number;
4716 
4717 	/*
4718 	 * Now, before we insert this lun on the lun list, set the lun
4719 	 * inventory changed UA for all other luns.
4720 	 */
4721 	mtx_lock(&ctl_softc->ctl_lock);
4722 	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4723 		mtx_lock(&nlun->lun_lock);
4724 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4725 		mtx_unlock(&nlun->lun_lock);
4726 	}
4727 	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4728 	ctl_softc->ctl_luns[lun_number] = lun;
4729 	ctl_softc->num_luns++;
4730 	mtx_unlock(&ctl_softc->ctl_lock);
4731 
4732 	/*
4733 	 * We successfully added the LUN, attempt to enable it.
4734 	 */
4735 	if (ctl_enable_lun(lun) != 0) {
4736 		printf("%s: ctl_enable_lun() failed!\n", __func__);
4737 		mtx_lock(&ctl_softc->ctl_lock);
4738 		STAILQ_REMOVE(&ctl_softc->lun_list, lun, ctl_lun, links);
4739 		ctl_clear_mask(ctl_softc->ctl_lun_mask, lun_number);
4740 		ctl_softc->ctl_luns[lun_number] = NULL;
4741 		ctl_softc->num_luns--;
4742 		mtx_unlock(&ctl_softc->ctl_lock);
4743 		free(lun->lun_devid, M_CTL);
4744 		free(lun, M_CTL);
4745 		return (EIO);
4746 	}
4747 
4748 	return (0);
4749 }
4750 
4751 /*
4752  * Free LUN that has no active requests.
4753  */
4754 static int
ctl_free_lun(struct ctl_lun * lun)4755 ctl_free_lun(struct ctl_lun *lun)
4756 {
4757 	struct ctl_softc *softc = lun->ctl_softc;
4758 	struct ctl_lun *nlun;
4759 	int i;
4760 
4761 	KASSERT(LIST_EMPTY(&lun->ooa_queue),
4762 	    ("Freeing a LUN %p with outstanding I/O!\n", lun));
4763 
4764 	mtx_lock(&softc->ctl_lock);
4765 	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4766 	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4767 	softc->ctl_luns[lun->lun] = NULL;
4768 	softc->num_luns--;
4769 	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4770 		mtx_lock(&nlun->lun_lock);
4771 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4772 		mtx_unlock(&nlun->lun_lock);
4773 	}
4774 	mtx_unlock(&softc->ctl_lock);
4775 
4776 	/*
4777 	 * Tell the backend to free resources, if this LUN has a backend.
4778 	 */
4779 	lun->be_lun->lun_shutdown(lun->be_lun);
4780 
4781 	lun->ie_reportcnt = UINT32_MAX;
4782 	callout_drain(&lun->ie_callout);
4783 	ctl_tpc_lun_shutdown(lun);
4784 	mtx_destroy(&lun->lun_lock);
4785 	free(lun->lun_devid, M_CTL);
4786 	for (i = 0; i < ctl_max_ports; i++)
4787 		free(lun->pending_ua[i], M_CTL);
4788 	free(lun->pending_ua, M_DEVBUF);
4789 	for (i = 0; i < ctl_max_ports; i++)
4790 		free(lun->pr_keys[i], M_CTL);
4791 	free(lun->pr_keys, M_DEVBUF);
4792 	free(lun->write_buffer, M_CTL);
4793 	free(lun->prevent, M_CTL);
4794 	free(lun, M_CTL);
4795 
4796 	return (0);
4797 }
4798 
4799 static int
ctl_enable_lun(struct ctl_lun * lun)4800 ctl_enable_lun(struct ctl_lun *lun)
4801 {
4802 	struct ctl_softc *softc;
4803 	struct ctl_port *port, *nport;
4804 	int retval;
4805 
4806 	softc = lun->ctl_softc;
4807 
4808 	mtx_lock(&softc->ctl_lock);
4809 	mtx_lock(&lun->lun_lock);
4810 	KASSERT((lun->flags & CTL_LUN_DISABLED) != 0,
4811 	    ("%s: LUN not disabled", __func__));
4812 	lun->flags &= ~CTL_LUN_DISABLED;
4813 	mtx_unlock(&lun->lun_lock);
4814 
4815 	STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4816 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4817 		    port->lun_map != NULL || port->lun_enable == NULL)
4818 			continue;
4819 
4820 		/*
4821 		 * Drop the lock while we call the FETD's enable routine.
4822 		 * This can lead to a callback into CTL (at least in the
4823 		 * case of the internal initiator frontend.
4824 		 */
4825 		mtx_unlock(&softc->ctl_lock);
4826 		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4827 		mtx_lock(&softc->ctl_lock);
4828 		if (retval != 0) {
4829 			printf("%s: FETD %s port %d returned error "
4830 			       "%d for lun_enable on lun %jd\n",
4831 			       __func__, port->port_name, port->targ_port,
4832 			       retval, (intmax_t)lun->lun);
4833 		}
4834 	}
4835 
4836 	mtx_unlock(&softc->ctl_lock);
4837 	ctl_isc_announce_lun(lun);
4838 
4839 	return (0);
4840 }
4841 
4842 static int
ctl_disable_lun(struct ctl_lun * lun)4843 ctl_disable_lun(struct ctl_lun *lun)
4844 {
4845 	struct ctl_softc *softc;
4846 	struct ctl_port *port;
4847 	int retval;
4848 
4849 	softc = lun->ctl_softc;
4850 
4851 	mtx_lock(&softc->ctl_lock);
4852 	mtx_lock(&lun->lun_lock);
4853 	KASSERT((lun->flags & CTL_LUN_DISABLED) == 0,
4854 	    ("%s: LUN not enabled", __func__));
4855 	lun->flags |= CTL_LUN_DISABLED;
4856 	mtx_unlock(&lun->lun_lock);
4857 
4858 	STAILQ_FOREACH(port, &softc->port_list, links) {
4859 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4860 		    port->lun_map != NULL || port->lun_disable == NULL)
4861 			continue;
4862 
4863 		/*
4864 		 * Drop the lock before we call the frontend's disable
4865 		 * routine, to avoid lock order reversals.
4866 		 *
4867 		 * XXX KDM what happens if the frontend list changes while
4868 		 * we're traversing it?  It's unlikely, but should be handled.
4869 		 */
4870 		mtx_unlock(&softc->ctl_lock);
4871 		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4872 		mtx_lock(&softc->ctl_lock);
4873 		if (retval != 0) {
4874 			printf("%s: FETD %s port %d returned error "
4875 			       "%d for lun_disable on lun %jd\n",
4876 			       __func__, port->port_name, port->targ_port,
4877 			       retval, (intmax_t)lun->lun);
4878 		}
4879 	}
4880 
4881 	mtx_unlock(&softc->ctl_lock);
4882 	ctl_isc_announce_lun(lun);
4883 
4884 	return (0);
4885 }
4886 
4887 int
ctl_start_lun(struct ctl_be_lun * be_lun)4888 ctl_start_lun(struct ctl_be_lun *be_lun)
4889 {
4890 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4891 
4892 	mtx_lock(&lun->lun_lock);
4893 	lun->flags &= ~CTL_LUN_STOPPED;
4894 	mtx_unlock(&lun->lun_lock);
4895 	return (0);
4896 }
4897 
4898 int
ctl_stop_lun(struct ctl_be_lun * be_lun)4899 ctl_stop_lun(struct ctl_be_lun *be_lun)
4900 {
4901 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4902 
4903 	mtx_lock(&lun->lun_lock);
4904 	lun->flags |= CTL_LUN_STOPPED;
4905 	mtx_unlock(&lun->lun_lock);
4906 	return (0);
4907 }
4908 
4909 int
ctl_lun_no_media(struct ctl_be_lun * be_lun)4910 ctl_lun_no_media(struct ctl_be_lun *be_lun)
4911 {
4912 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4913 
4914 	mtx_lock(&lun->lun_lock);
4915 	lun->flags |= CTL_LUN_NO_MEDIA;
4916 	mtx_unlock(&lun->lun_lock);
4917 	return (0);
4918 }
4919 
4920 int
ctl_lun_has_media(struct ctl_be_lun * be_lun)4921 ctl_lun_has_media(struct ctl_be_lun *be_lun)
4922 {
4923 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4924 	union ctl_ha_msg msg;
4925 
4926 	mtx_lock(&lun->lun_lock);
4927 	lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4928 	if (lun->flags & CTL_LUN_REMOVABLE)
4929 		ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4930 	mtx_unlock(&lun->lun_lock);
4931 	if ((lun->flags & CTL_LUN_REMOVABLE) &&
4932 	    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4933 		bzero(&msg.ua, sizeof(msg.ua));
4934 		msg.hdr.msg_type = CTL_MSG_UA;
4935 		msg.hdr.nexus.initid = -1;
4936 		msg.hdr.nexus.targ_port = -1;
4937 		msg.hdr.nexus.targ_lun = lun->lun;
4938 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4939 		msg.ua.ua_all = 1;
4940 		msg.ua.ua_set = 1;
4941 		msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4942 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4943 		    M_WAITOK);
4944 	}
4945 	return (0);
4946 }
4947 
4948 int
ctl_lun_ejected(struct ctl_be_lun * be_lun)4949 ctl_lun_ejected(struct ctl_be_lun *be_lun)
4950 {
4951 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4952 
4953 	mtx_lock(&lun->lun_lock);
4954 	lun->flags |= CTL_LUN_EJECTED;
4955 	mtx_unlock(&lun->lun_lock);
4956 	return (0);
4957 }
4958 
4959 int
ctl_lun_primary(struct ctl_be_lun * be_lun)4960 ctl_lun_primary(struct ctl_be_lun *be_lun)
4961 {
4962 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4963 
4964 	mtx_lock(&lun->lun_lock);
4965 	lun->flags |= CTL_LUN_PRIMARY_SC;
4966 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4967 	mtx_unlock(&lun->lun_lock);
4968 	ctl_isc_announce_lun(lun);
4969 	return (0);
4970 }
4971 
4972 int
ctl_lun_secondary(struct ctl_be_lun * be_lun)4973 ctl_lun_secondary(struct ctl_be_lun *be_lun)
4974 {
4975 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4976 
4977 	mtx_lock(&lun->lun_lock);
4978 	lun->flags &= ~CTL_LUN_PRIMARY_SC;
4979 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4980 	mtx_unlock(&lun->lun_lock);
4981 	ctl_isc_announce_lun(lun);
4982 	return (0);
4983 }
4984 
4985 /*
4986  * Remove LUN.  If there are active requests, wait for completion.
4987  *
4988  * Returns 0 for success, non-zero (errno) for failure.
4989  * Completion is reported to backed via the lun_shutdown() method.
4990  */
4991 int
ctl_remove_lun(struct ctl_be_lun * be_lun)4992 ctl_remove_lun(struct ctl_be_lun *be_lun)
4993 {
4994 	struct ctl_lun *lun;
4995 
4996 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4997 
4998 	ctl_disable_lun(lun);
4999 
5000 	mtx_lock(&lun->lun_lock);
5001 	lun->flags |= CTL_LUN_INVALID;
5002 
5003 	/*
5004 	 * If there is nothing in the OOA queue, go ahead and free the LUN.
5005 	 * If we have something in the OOA queue, we'll free it when the
5006 	 * last I/O completes.
5007 	 */
5008 	if (LIST_EMPTY(&lun->ooa_queue)) {
5009 		mtx_unlock(&lun->lun_lock);
5010 		ctl_free_lun(lun);
5011 	} else
5012 		mtx_unlock(&lun->lun_lock);
5013 
5014 	return (0);
5015 }
5016 
5017 void
ctl_lun_capacity_changed(struct ctl_be_lun * be_lun)5018 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5019 {
5020 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5021 	union ctl_ha_msg msg;
5022 
5023 	mtx_lock(&lun->lun_lock);
5024 	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
5025 	mtx_unlock(&lun->lun_lock);
5026 	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
5027 		/* Send msg to other side. */
5028 		bzero(&msg.ua, sizeof(msg.ua));
5029 		msg.hdr.msg_type = CTL_MSG_UA;
5030 		msg.hdr.nexus.initid = -1;
5031 		msg.hdr.nexus.targ_port = -1;
5032 		msg.hdr.nexus.targ_lun = lun->lun;
5033 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
5034 		msg.ua.ua_all = 1;
5035 		msg.ua.ua_set = 1;
5036 		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
5037 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
5038 		    M_WAITOK);
5039 	}
5040 }
5041 
5042 /*
5043  * Backend "memory move is complete" callback for requests that never
5044  * make it down to say RAIDCore's configuration code.
5045  */
5046 int
ctl_config_move_done(union ctl_io * io,bool samethr)5047 ctl_config_move_done(union ctl_io *io, bool samethr)
5048 {
5049 	int retval;
5050 
5051 	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5052 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5053 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
5054 
5055 	if (ctl_debug & CTL_DEBUG_CDB_DATA)
5056 		ctl_data_print(io);
5057 	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5058 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5059 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5060 	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5061 		/*
5062 		 * XXX KDM just assuming a single pointer here, and not a
5063 		 * S/G list.  If we start using S/G lists for config data,
5064 		 * we'll need to know how to clean them up here as well.
5065 		 */
5066 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5067 			free(io->scsiio.kern_data_ptr, M_CTL);
5068 		ctl_done(io);
5069 		retval = CTL_RETVAL_COMPLETE;
5070 	} else {
5071 		/*
5072 		 * XXX KDM now we need to continue data movement.  Some
5073 		 * options:
5074 		 * - call ctl_scsiio() again?  We don't do this for data
5075 		 *   writes, because for those at least we know ahead of
5076 		 *   time where the write will go and how long it is.  For
5077 		 *   config writes, though, that information is largely
5078 		 *   contained within the write itself, thus we need to
5079 		 *   parse out the data again.
5080 		 *
5081 		 * - Call some other function once the data is in?
5082 		 */
5083 
5084 		/*
5085 		 * XXX KDM call ctl_scsiio() again for now, and check flag
5086 		 * bits to see whether we're allocated or not.
5087 		 */
5088 		retval = ctl_scsiio(&io->scsiio);
5089 	}
5090 	return (retval);
5091 }
5092 
5093 /*
5094  * This gets called by a backend driver when it is done with a
5095  * data_submit method.
5096  */
5097 void
ctl_data_submit_done(union ctl_io * io)5098 ctl_data_submit_done(union ctl_io *io)
5099 {
5100 	/*
5101 	 * If the IO_CONT flag is set, we need to call the supplied
5102 	 * function to continue processing the I/O, instead of completing
5103 	 * the I/O just yet.
5104 	 *
5105 	 * If there is an error, though, we don't want to keep processing.
5106 	 * Instead, just send status back to the initiator.
5107 	 */
5108 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5109 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5110 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5111 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5112 		io->scsiio.io_cont(io);
5113 		return;
5114 	}
5115 	ctl_done(io);
5116 }
5117 
5118 /*
5119  * This gets called by a backend driver when it is done with a
5120  * configuration write.
5121  */
5122 void
ctl_config_write_done(union ctl_io * io)5123 ctl_config_write_done(union ctl_io *io)
5124 {
5125 	uint8_t *buf;
5126 
5127 	/*
5128 	 * If the IO_CONT flag is set, we need to call the supplied
5129 	 * function to continue processing the I/O, instead of completing
5130 	 * the I/O just yet.
5131 	 *
5132 	 * If there is an error, though, we don't want to keep processing.
5133 	 * Instead, just send status back to the initiator.
5134 	 */
5135 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5136 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5137 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5138 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5139 		io->scsiio.io_cont(io);
5140 		return;
5141 	}
5142 	/*
5143 	 * Since a configuration write can be done for commands that actually
5144 	 * have data allocated, like write buffer, and commands that have
5145 	 * no data, like start/stop unit, we need to check here.
5146 	 */
5147 	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5148 		buf = io->scsiio.kern_data_ptr;
5149 	else
5150 		buf = NULL;
5151 	ctl_done(io);
5152 	if (buf)
5153 		free(buf, M_CTL);
5154 }
5155 
5156 void
ctl_config_read_done(union ctl_io * io)5157 ctl_config_read_done(union ctl_io *io)
5158 {
5159 	uint8_t *buf;
5160 
5161 	/*
5162 	 * If there is some error -- we are done, skip data transfer.
5163 	 */
5164 	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5165 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5166 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5167 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5168 			buf = io->scsiio.kern_data_ptr;
5169 		else
5170 			buf = NULL;
5171 		ctl_done(io);
5172 		if (buf)
5173 			free(buf, M_CTL);
5174 		return;
5175 	}
5176 
5177 	/*
5178 	 * If the IO_CONT flag is set, we need to call the supplied
5179 	 * function to continue processing the I/O, instead of completing
5180 	 * the I/O just yet.
5181 	 */
5182 	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5183 		io->scsiio.io_cont(io);
5184 		return;
5185 	}
5186 
5187 	ctl_datamove(io);
5188 }
5189 
5190 /*
5191  * SCSI release command.
5192  */
5193 int
ctl_scsi_release(struct ctl_scsiio * ctsio)5194 ctl_scsi_release(struct ctl_scsiio *ctsio)
5195 {
5196 	struct ctl_lun *lun = CTL_LUN(ctsio);
5197 	uint32_t residx;
5198 
5199 	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5200 
5201 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5202 
5203 	/*
5204 	 * XXX KDM right now, we only support LUN reservation.  We don't
5205 	 * support 3rd party reservations, or extent reservations, which
5206 	 * might actually need the parameter list.  If we've gotten this
5207 	 * far, we've got a LUN reservation.  Anything else got kicked out
5208 	 * above.  So, according to SPC, ignore the length.
5209 	 */
5210 
5211 	mtx_lock(&lun->lun_lock);
5212 
5213 	/*
5214 	 * According to SPC, it is not an error for an intiator to attempt
5215 	 * to release a reservation on a LUN that isn't reserved, or that
5216 	 * is reserved by another initiator.  The reservation can only be
5217 	 * released, though, by the initiator who made it or by one of
5218 	 * several reset type events.
5219 	 */
5220 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5221 			lun->flags &= ~CTL_LUN_RESERVED;
5222 
5223 	mtx_unlock(&lun->lun_lock);
5224 
5225 	ctl_set_success(ctsio);
5226 	ctl_done((union ctl_io *)ctsio);
5227 	return (CTL_RETVAL_COMPLETE);
5228 }
5229 
5230 int
ctl_scsi_reserve(struct ctl_scsiio * ctsio)5231 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5232 {
5233 	struct ctl_lun *lun = CTL_LUN(ctsio);
5234 	uint32_t residx;
5235 
5236 	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5237 
5238 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5239 
5240 	/*
5241 	 * XXX KDM right now, we only support LUN reservation.  We don't
5242 	 * support 3rd party reservations, or extent reservations, which
5243 	 * might actually need the parameter list.  If we've gotten this
5244 	 * far, we've got a LUN reservation.  Anything else got kicked out
5245 	 * above.  So, according to SPC, ignore the length.
5246 	 */
5247 
5248 	mtx_lock(&lun->lun_lock);
5249 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5250 		ctl_set_reservation_conflict(ctsio);
5251 		goto bailout;
5252 	}
5253 
5254 	/* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5255 	if (lun->flags & CTL_LUN_PR_RESERVED) {
5256 		ctl_set_success(ctsio);
5257 		goto bailout;
5258 	}
5259 
5260 	lun->flags |= CTL_LUN_RESERVED;
5261 	lun->res_idx = residx;
5262 	ctl_set_success(ctsio);
5263 
5264 bailout:
5265 	mtx_unlock(&lun->lun_lock);
5266 	ctl_done((union ctl_io *)ctsio);
5267 	return (CTL_RETVAL_COMPLETE);
5268 }
5269 
5270 int
ctl_start_stop(struct ctl_scsiio * ctsio)5271 ctl_start_stop(struct ctl_scsiio *ctsio)
5272 {
5273 	struct ctl_lun *lun = CTL_LUN(ctsio);
5274 	struct scsi_start_stop_unit *cdb;
5275 	int retval;
5276 
5277 	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5278 
5279 	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5280 
5281 	if ((cdb->how & SSS_PC_MASK) == 0) {
5282 		if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5283 		    (cdb->how & SSS_START) == 0) {
5284 			uint32_t residx;
5285 
5286 			residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5287 			if (ctl_get_prkey(lun, residx) == 0 ||
5288 			    (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5289 
5290 				ctl_set_reservation_conflict(ctsio);
5291 				ctl_done((union ctl_io *)ctsio);
5292 				return (CTL_RETVAL_COMPLETE);
5293 			}
5294 		}
5295 
5296 		if ((cdb->how & SSS_LOEJ) &&
5297 		    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5298 			ctl_set_invalid_field(ctsio,
5299 					      /*sks_valid*/ 1,
5300 					      /*command*/ 1,
5301 					      /*field*/ 4,
5302 					      /*bit_valid*/ 1,
5303 					      /*bit*/ 1);
5304 			ctl_done((union ctl_io *)ctsio);
5305 			return (CTL_RETVAL_COMPLETE);
5306 		}
5307 
5308 		if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5309 		    lun->prevent_count > 0) {
5310 			/* "Medium removal prevented" */
5311 			ctl_set_sense(ctsio, /*current_error*/ 1,
5312 			    /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5313 			     SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5314 			    /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5315 			ctl_done((union ctl_io *)ctsio);
5316 			return (CTL_RETVAL_COMPLETE);
5317 		}
5318 	}
5319 
5320 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5321 	return (retval);
5322 }
5323 
5324 int
ctl_prevent_allow(struct ctl_scsiio * ctsio)5325 ctl_prevent_allow(struct ctl_scsiio *ctsio)
5326 {
5327 	struct ctl_lun *lun = CTL_LUN(ctsio);
5328 	struct scsi_prevent *cdb;
5329 	int retval;
5330 	uint32_t initidx;
5331 
5332 	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5333 
5334 	cdb = (struct scsi_prevent *)ctsio->cdb;
5335 
5336 	if ((lun->flags & CTL_LUN_REMOVABLE) == 0 || lun->prevent == NULL) {
5337 		ctl_set_invalid_opcode(ctsio);
5338 		ctl_done((union ctl_io *)ctsio);
5339 		return (CTL_RETVAL_COMPLETE);
5340 	}
5341 
5342 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5343 	mtx_lock(&lun->lun_lock);
5344 	if ((cdb->how & PR_PREVENT) &&
5345 	    ctl_is_set(lun->prevent, initidx) == 0) {
5346 		ctl_set_mask(lun->prevent, initidx);
5347 		lun->prevent_count++;
5348 	} else if ((cdb->how & PR_PREVENT) == 0 &&
5349 	    ctl_is_set(lun->prevent, initidx)) {
5350 		ctl_clear_mask(lun->prevent, initidx);
5351 		lun->prevent_count--;
5352 	}
5353 	mtx_unlock(&lun->lun_lock);
5354 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5355 	return (retval);
5356 }
5357 
5358 /*
5359  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5360  * we don't really do anything with the LBA and length fields if the user
5361  * passes them in.  Instead we'll just flush out the cache for the entire
5362  * LUN.
5363  */
5364 int
ctl_sync_cache(struct ctl_scsiio * ctsio)5365 ctl_sync_cache(struct ctl_scsiio *ctsio)
5366 {
5367 	struct ctl_lun *lun = CTL_LUN(ctsio);
5368 	struct ctl_lba_len_flags *lbalen;
5369 	uint64_t starting_lba;
5370 	uint32_t block_count;
5371 	int retval;
5372 	uint8_t byte2;
5373 
5374 	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5375 
5376 	retval = 0;
5377 
5378 	switch (ctsio->cdb[0]) {
5379 	case SYNCHRONIZE_CACHE: {
5380 		struct scsi_sync_cache *cdb;
5381 		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5382 
5383 		starting_lba = scsi_4btoul(cdb->begin_lba);
5384 		block_count = scsi_2btoul(cdb->lb_count);
5385 		byte2 = cdb->byte2;
5386 		break;
5387 	}
5388 	case SYNCHRONIZE_CACHE_16: {
5389 		struct scsi_sync_cache_16 *cdb;
5390 		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5391 
5392 		starting_lba = scsi_8btou64(cdb->begin_lba);
5393 		block_count = scsi_4btoul(cdb->lb_count);
5394 		byte2 = cdb->byte2;
5395 		break;
5396 	}
5397 	default:
5398 		ctl_set_invalid_opcode(ctsio);
5399 		ctl_done((union ctl_io *)ctsio);
5400 		goto bailout;
5401 		break; /* NOTREACHED */
5402 	}
5403 
5404 	/*
5405 	 * We check the LBA and length, but don't do anything with them.
5406 	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5407 	 * get flushed.  This check will just help satisfy anyone who wants
5408 	 * to see an error for an out of range LBA.
5409 	 */
5410 	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5411 		ctl_set_lba_out_of_range(ctsio,
5412 		    MAX(starting_lba, lun->be_lun->maxlba + 1));
5413 		ctl_done((union ctl_io *)ctsio);
5414 		goto bailout;
5415 	}
5416 
5417 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5418 	lbalen->lba = starting_lba;
5419 	lbalen->len = block_count;
5420 	lbalen->flags = byte2;
5421 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5422 
5423 bailout:
5424 	return (retval);
5425 }
5426 
5427 int
ctl_format(struct ctl_scsiio * ctsio)5428 ctl_format(struct ctl_scsiio *ctsio)
5429 {
5430 	struct scsi_format *cdb;
5431 	int length, defect_list_len;
5432 
5433 	CTL_DEBUG_PRINT(("ctl_format\n"));
5434 
5435 	cdb = (struct scsi_format *)ctsio->cdb;
5436 
5437 	length = 0;
5438 	if (cdb->byte2 & SF_FMTDATA) {
5439 		if (cdb->byte2 & SF_LONGLIST)
5440 			length = sizeof(struct scsi_format_header_long);
5441 		else
5442 			length = sizeof(struct scsi_format_header_short);
5443 	}
5444 
5445 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5446 	 && (length > 0)) {
5447 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5448 		ctsio->kern_data_len = length;
5449 		ctsio->kern_total_len = length;
5450 		ctsio->kern_rel_offset = 0;
5451 		ctsio->kern_sg_entries = 0;
5452 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5453 		ctsio->be_move_done = ctl_config_move_done;
5454 		ctl_datamove((union ctl_io *)ctsio);
5455 
5456 		return (CTL_RETVAL_COMPLETE);
5457 	}
5458 
5459 	defect_list_len = 0;
5460 
5461 	if (cdb->byte2 & SF_FMTDATA) {
5462 		if (cdb->byte2 & SF_LONGLIST) {
5463 			struct scsi_format_header_long *header;
5464 
5465 			header = (struct scsi_format_header_long *)
5466 				ctsio->kern_data_ptr;
5467 
5468 			defect_list_len = scsi_4btoul(header->defect_list_len);
5469 			if (defect_list_len != 0) {
5470 				ctl_set_invalid_field(ctsio,
5471 						      /*sks_valid*/ 1,
5472 						      /*command*/ 0,
5473 						      /*field*/ 2,
5474 						      /*bit_valid*/ 0,
5475 						      /*bit*/ 0);
5476 				goto bailout;
5477 			}
5478 		} else {
5479 			struct scsi_format_header_short *header;
5480 
5481 			header = (struct scsi_format_header_short *)
5482 				ctsio->kern_data_ptr;
5483 
5484 			defect_list_len = scsi_2btoul(header->defect_list_len);
5485 			if (defect_list_len != 0) {
5486 				ctl_set_invalid_field(ctsio,
5487 						      /*sks_valid*/ 1,
5488 						      /*command*/ 0,
5489 						      /*field*/ 2,
5490 						      /*bit_valid*/ 0,
5491 						      /*bit*/ 0);
5492 				goto bailout;
5493 			}
5494 		}
5495 	}
5496 
5497 	ctl_set_success(ctsio);
5498 bailout:
5499 
5500 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5501 		free(ctsio->kern_data_ptr, M_CTL);
5502 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5503 	}
5504 
5505 	ctl_done((union ctl_io *)ctsio);
5506 	return (CTL_RETVAL_COMPLETE);
5507 }
5508 
5509 int
ctl_read_buffer(struct ctl_scsiio * ctsio)5510 ctl_read_buffer(struct ctl_scsiio *ctsio)
5511 {
5512 	struct ctl_lun *lun = CTL_LUN(ctsio);
5513 	uint64_t buffer_offset;
5514 	uint32_t len;
5515 	uint8_t byte2;
5516 	static uint8_t descr[4];
5517 	static uint8_t echo_descr[4] = { 0 };
5518 
5519 	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5520 
5521 	switch (ctsio->cdb[0]) {
5522 	case READ_BUFFER: {
5523 		struct scsi_read_buffer *cdb;
5524 
5525 		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5526 		buffer_offset = scsi_3btoul(cdb->offset);
5527 		len = scsi_3btoul(cdb->length);
5528 		byte2 = cdb->byte2;
5529 		break;
5530 	}
5531 	case READ_BUFFER_16: {
5532 		struct scsi_read_buffer_16 *cdb;
5533 
5534 		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5535 		buffer_offset = scsi_8btou64(cdb->offset);
5536 		len = scsi_4btoul(cdb->length);
5537 		byte2 = cdb->byte2;
5538 		break;
5539 	}
5540 	default: /* This shouldn't happen. */
5541 		ctl_set_invalid_opcode(ctsio);
5542 		ctl_done((union ctl_io *)ctsio);
5543 		return (CTL_RETVAL_COMPLETE);
5544 	}
5545 
5546 	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5547 	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5548 		ctl_set_invalid_field(ctsio,
5549 				      /*sks_valid*/ 1,
5550 				      /*command*/ 1,
5551 				      /*field*/ 6,
5552 				      /*bit_valid*/ 0,
5553 				      /*bit*/ 0);
5554 		ctl_done((union ctl_io *)ctsio);
5555 		return (CTL_RETVAL_COMPLETE);
5556 	}
5557 
5558 	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5559 		descr[0] = 0;
5560 		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5561 		ctsio->kern_data_ptr = descr;
5562 		len = min(len, sizeof(descr));
5563 	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5564 		ctsio->kern_data_ptr = echo_descr;
5565 		len = min(len, sizeof(echo_descr));
5566 	} else {
5567 		if (lun->write_buffer == NULL) {
5568 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5569 			    M_CTL, M_WAITOK);
5570 		}
5571 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5572 	}
5573 	ctsio->kern_data_len = len;
5574 	ctsio->kern_total_len = len;
5575 	ctsio->kern_rel_offset = 0;
5576 	ctsio->kern_sg_entries = 0;
5577 	ctl_set_success(ctsio);
5578 	ctsio->be_move_done = ctl_config_move_done;
5579 	ctl_datamove((union ctl_io *)ctsio);
5580 	return (CTL_RETVAL_COMPLETE);
5581 }
5582 
5583 int
ctl_write_buffer(struct ctl_scsiio * ctsio)5584 ctl_write_buffer(struct ctl_scsiio *ctsio)
5585 {
5586 	struct ctl_lun *lun = CTL_LUN(ctsio);
5587 	struct scsi_write_buffer *cdb;
5588 	int buffer_offset, len;
5589 
5590 	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5591 
5592 	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5593 
5594 	len = scsi_3btoul(cdb->length);
5595 	buffer_offset = scsi_3btoul(cdb->offset);
5596 
5597 	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5598 		ctl_set_invalid_field(ctsio,
5599 				      /*sks_valid*/ 1,
5600 				      /*command*/ 1,
5601 				      /*field*/ 6,
5602 				      /*bit_valid*/ 0,
5603 				      /*bit*/ 0);
5604 		ctl_done((union ctl_io *)ctsio);
5605 		return (CTL_RETVAL_COMPLETE);
5606 	}
5607 
5608 	/*
5609 	 * If we've got a kernel request that hasn't been malloced yet,
5610 	 * malloc it and tell the caller the data buffer is here.
5611 	 */
5612 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5613 		if (lun->write_buffer == NULL) {
5614 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5615 			    M_CTL, M_WAITOK);
5616 		}
5617 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5618 		ctsio->kern_data_len = len;
5619 		ctsio->kern_total_len = len;
5620 		ctsio->kern_rel_offset = 0;
5621 		ctsio->kern_sg_entries = 0;
5622 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5623 		ctsio->be_move_done = ctl_config_move_done;
5624 		ctl_datamove((union ctl_io *)ctsio);
5625 
5626 		return (CTL_RETVAL_COMPLETE);
5627 	}
5628 
5629 	ctl_set_success(ctsio);
5630 	ctl_done((union ctl_io *)ctsio);
5631 	return (CTL_RETVAL_COMPLETE);
5632 }
5633 
5634 static int
ctl_write_same_cont(union ctl_io * io)5635 ctl_write_same_cont(union ctl_io *io)
5636 {
5637 	struct ctl_lun *lun = CTL_LUN(io);
5638 	struct ctl_scsiio *ctsio;
5639 	struct ctl_lba_len_flags *lbalen;
5640 	int retval;
5641 
5642 	ctsio = &io->scsiio;
5643 	ctsio->io_hdr.status = CTL_STATUS_NONE;
5644 	lbalen = (struct ctl_lba_len_flags *)
5645 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5646 	lbalen->lba += lbalen->len;
5647 	if ((lun->be_lun->maxlba + 1) - lbalen->lba <= UINT32_MAX) {
5648 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
5649 		lbalen->len = (lun->be_lun->maxlba + 1) - lbalen->lba;
5650 	}
5651 
5652 	CTL_DEBUG_PRINT(("ctl_write_same_cont: calling config_write()\n"));
5653 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5654 	return (retval);
5655 }
5656 
5657 int
ctl_write_same(struct ctl_scsiio * ctsio)5658 ctl_write_same(struct ctl_scsiio *ctsio)
5659 {
5660 	struct ctl_lun *lun = CTL_LUN(ctsio);
5661 	struct ctl_lba_len_flags *lbalen;
5662 	const char *val;
5663 	uint64_t lba, ival;
5664 	uint32_t num_blocks;
5665 	int len, retval;
5666 	uint8_t byte2;
5667 
5668 	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5669 
5670 	switch (ctsio->cdb[0]) {
5671 	case WRITE_SAME_10: {
5672 		struct scsi_write_same_10 *cdb;
5673 
5674 		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5675 
5676 		lba = scsi_4btoul(cdb->addr);
5677 		num_blocks = scsi_2btoul(cdb->length);
5678 		byte2 = cdb->byte2;
5679 		break;
5680 	}
5681 	case WRITE_SAME_16: {
5682 		struct scsi_write_same_16 *cdb;
5683 
5684 		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5685 
5686 		lba = scsi_8btou64(cdb->addr);
5687 		num_blocks = scsi_4btoul(cdb->length);
5688 		byte2 = cdb->byte2;
5689 		break;
5690 	}
5691 	default:
5692 		/*
5693 		 * We got a command we don't support.  This shouldn't
5694 		 * happen, commands should be filtered out above us.
5695 		 */
5696 		ctl_set_invalid_opcode(ctsio);
5697 		ctl_done((union ctl_io *)ctsio);
5698 
5699 		return (CTL_RETVAL_COMPLETE);
5700 		break; /* NOTREACHED */
5701 	}
5702 
5703 	/* ANCHOR flag can be used only together with UNMAP */
5704 	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5705 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5706 		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5707 		ctl_done((union ctl_io *)ctsio);
5708 		return (CTL_RETVAL_COMPLETE);
5709 	}
5710 
5711 	/*
5712 	 * The first check is to make sure we're in bounds, the second
5713 	 * check is to catch wrap-around problems.  If the lba + num blocks
5714 	 * is less than the lba, then we've wrapped around and the block
5715 	 * range is invalid anyway.
5716 	 */
5717 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5718 	 || ((lba + num_blocks) < lba)) {
5719 		ctl_set_lba_out_of_range(ctsio,
5720 		    MAX(lba, lun->be_lun->maxlba + 1));
5721 		ctl_done((union ctl_io *)ctsio);
5722 		return (CTL_RETVAL_COMPLETE);
5723 	}
5724 
5725 	/* Zero number of blocks means "to the last logical block" */
5726 	if (num_blocks == 0) {
5727 		ival = UINT64_MAX;
5728 		val = dnvlist_get_string(lun->be_lun->options,
5729 		    "write_same_max_lba", NULL);
5730 		if (val != NULL)
5731 			ctl_expand_number(val, &ival);
5732 		if ((lun->be_lun->maxlba + 1) - lba > ival) {
5733 			ctl_set_invalid_field(ctsio,
5734 			    /*sks_valid*/ 1, /*command*/ 1,
5735 			    /*field*/ ctsio->cdb[0] == WRITE_SAME_10 ? 7 : 10,
5736 			    /*bit_valid*/ 0, /*bit*/ 0);
5737 			ctl_done((union ctl_io *)ctsio);
5738 			return (CTL_RETVAL_COMPLETE);
5739 		}
5740 		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5741 			ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
5742 			ctsio->io_cont = ctl_write_same_cont;
5743 			num_blocks = 1 << 31;
5744 		} else
5745 			num_blocks = (lun->be_lun->maxlba + 1) - lba;
5746 	}
5747 
5748 	len = lun->be_lun->blocksize;
5749 
5750 	/*
5751 	 * If we've got a kernel request that hasn't been malloced yet,
5752 	 * malloc it and tell the caller the data buffer is here.
5753 	 */
5754 	if ((byte2 & SWS_NDOB) == 0 &&
5755 	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5756 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5757 		ctsio->kern_data_len = len;
5758 		ctsio->kern_total_len = len;
5759 		ctsio->kern_rel_offset = 0;
5760 		ctsio->kern_sg_entries = 0;
5761 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5762 		ctsio->be_move_done = ctl_config_move_done;
5763 		ctl_datamove((union ctl_io *)ctsio);
5764 
5765 		return (CTL_RETVAL_COMPLETE);
5766 	}
5767 
5768 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5769 	lbalen->lba = lba;
5770 	lbalen->len = num_blocks;
5771 	lbalen->flags = byte2;
5772 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5773 
5774 	return (retval);
5775 }
5776 
5777 int
ctl_unmap(struct ctl_scsiio * ctsio)5778 ctl_unmap(struct ctl_scsiio *ctsio)
5779 {
5780 	struct ctl_lun *lun = CTL_LUN(ctsio);
5781 	struct scsi_unmap *cdb;
5782 	struct ctl_ptr_len_flags *ptrlen;
5783 	struct scsi_unmap_header *hdr;
5784 	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5785 	uint64_t lba;
5786 	uint32_t num_blocks;
5787 	int len, retval;
5788 	uint8_t byte2;
5789 
5790 	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5791 
5792 	cdb = (struct scsi_unmap *)ctsio->cdb;
5793 	len = scsi_2btoul(cdb->length);
5794 	byte2 = cdb->byte2;
5795 
5796 	/*
5797 	 * If we've got a kernel request that hasn't been malloced yet,
5798 	 * malloc it and tell the caller the data buffer is here.
5799 	 */
5800 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5801 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5802 		ctsio->kern_data_len = len;
5803 		ctsio->kern_total_len = len;
5804 		ctsio->kern_rel_offset = 0;
5805 		ctsio->kern_sg_entries = 0;
5806 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5807 		ctsio->be_move_done = ctl_config_move_done;
5808 		ctl_datamove((union ctl_io *)ctsio);
5809 
5810 		return (CTL_RETVAL_COMPLETE);
5811 	}
5812 
5813 	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5814 	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5815 	if (len < sizeof (*hdr) ||
5816 	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5817 	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5818 	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5819 		ctl_set_invalid_field(ctsio,
5820 				      /*sks_valid*/ 0,
5821 				      /*command*/ 0,
5822 				      /*field*/ 0,
5823 				      /*bit_valid*/ 0,
5824 				      /*bit*/ 0);
5825 		goto done;
5826 	}
5827 	len = scsi_2btoul(hdr->desc_length);
5828 	buf = (struct scsi_unmap_desc *)(hdr + 1);
5829 	end = buf + len / sizeof(*buf);
5830 
5831 	endnz = buf;
5832 	for (range = buf; range < end; range++) {
5833 		lba = scsi_8btou64(range->lba);
5834 		num_blocks = scsi_4btoul(range->length);
5835 		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5836 		 || ((lba + num_blocks) < lba)) {
5837 			ctl_set_lba_out_of_range(ctsio,
5838 			    MAX(lba, lun->be_lun->maxlba + 1));
5839 			ctl_done((union ctl_io *)ctsio);
5840 			return (CTL_RETVAL_COMPLETE);
5841 		}
5842 		if (num_blocks != 0)
5843 			endnz = range + 1;
5844 	}
5845 
5846 	/*
5847 	 * Block backend can not handle zero last range.
5848 	 * Filter it out and return if there is nothing left.
5849 	 */
5850 	len = (uint8_t *)endnz - (uint8_t *)buf;
5851 	if (len == 0) {
5852 		ctl_set_success(ctsio);
5853 		goto done;
5854 	}
5855 
5856 	mtx_lock(&lun->lun_lock);
5857 	ptrlen = (struct ctl_ptr_len_flags *)
5858 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5859 	ptrlen->ptr = (void *)buf;
5860 	ptrlen->len = len;
5861 	ptrlen->flags = byte2;
5862 	ctl_try_unblock_others(lun, (union ctl_io *)ctsio, FALSE);
5863 	mtx_unlock(&lun->lun_lock);
5864 
5865 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5866 	return (retval);
5867 
5868 done:
5869 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5870 		free(ctsio->kern_data_ptr, M_CTL);
5871 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5872 	}
5873 	ctl_done((union ctl_io *)ctsio);
5874 	return (CTL_RETVAL_COMPLETE);
5875 }
5876 
5877 int
ctl_default_page_handler(struct ctl_scsiio * ctsio,struct ctl_page_index * page_index,uint8_t * page_ptr)5878 ctl_default_page_handler(struct ctl_scsiio *ctsio,
5879 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5880 {
5881 	struct ctl_lun *lun = CTL_LUN(ctsio);
5882 	uint8_t *current_cp;
5883 	int set_ua;
5884 	uint32_t initidx;
5885 
5886 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5887 	set_ua = 0;
5888 
5889 	current_cp = (page_index->page_data + (page_index->page_len *
5890 	    CTL_PAGE_CURRENT));
5891 
5892 	mtx_lock(&lun->lun_lock);
5893 	if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5894 		memcpy(current_cp, page_ptr, page_index->page_len);
5895 		set_ua = 1;
5896 	}
5897 	if (set_ua != 0)
5898 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5899 	mtx_unlock(&lun->lun_lock);
5900 	if (set_ua) {
5901 		ctl_isc_announce_mode(lun,
5902 		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5903 		    page_index->page_code, page_index->subpage);
5904 	}
5905 	return (CTL_RETVAL_COMPLETE);
5906 }
5907 
5908 static void
ctl_ie_timer(void * arg)5909 ctl_ie_timer(void *arg)
5910 {
5911 	struct ctl_lun *lun = arg;
5912 	uint64_t t;
5913 
5914 	if (lun->ie_asc == 0)
5915 		return;
5916 
5917 	if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5918 		ctl_est_ua_all(lun, -1, CTL_UA_IE);
5919 	else
5920 		lun->ie_reported = 0;
5921 
5922 	if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5923 		lun->ie_reportcnt++;
5924 		t = scsi_4btoul(lun->MODE_IE.interval_timer);
5925 		if (t == 0 || t == UINT32_MAX)
5926 			t = 3000;  /* 5 min */
5927 		callout_schedule(&lun->ie_callout, t * hz / 10);
5928 	}
5929 }
5930 
5931 int
ctl_ie_page_handler(struct ctl_scsiio * ctsio,struct ctl_page_index * page_index,uint8_t * page_ptr)5932 ctl_ie_page_handler(struct ctl_scsiio *ctsio,
5933 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5934 {
5935 	struct ctl_lun *lun = CTL_LUN(ctsio);
5936 	struct scsi_info_exceptions_page *pg;
5937 	uint64_t t;
5938 
5939 	(void)ctl_default_page_handler(ctsio, page_index, page_ptr);
5940 
5941 	pg = (struct scsi_info_exceptions_page *)page_ptr;
5942 	mtx_lock(&lun->lun_lock);
5943 	if (pg->info_flags & SIEP_FLAGS_TEST) {
5944 		lun->ie_asc = 0x5d;
5945 		lun->ie_ascq = 0xff;
5946 		if (pg->mrie == SIEP_MRIE_UA) {
5947 			ctl_est_ua_all(lun, -1, CTL_UA_IE);
5948 			lun->ie_reported = 1;
5949 		} else {
5950 			ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5951 			lun->ie_reported = -1;
5952 		}
5953 		lun->ie_reportcnt = 1;
5954 		if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
5955 			lun->ie_reportcnt++;
5956 			t = scsi_4btoul(pg->interval_timer);
5957 			if (t == 0 || t == UINT32_MAX)
5958 				t = 3000;  /* 5 min */
5959 			callout_reset(&lun->ie_callout, t * hz / 10,
5960 			    ctl_ie_timer, lun);
5961 		}
5962 	} else {
5963 		lun->ie_asc = 0;
5964 		lun->ie_ascq = 0;
5965 		lun->ie_reported = 1;
5966 		ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5967 		lun->ie_reportcnt = UINT32_MAX;
5968 		callout_stop(&lun->ie_callout);
5969 	}
5970 	mtx_unlock(&lun->lun_lock);
5971 	return (CTL_RETVAL_COMPLETE);
5972 }
5973 
5974 static int
ctl_do_mode_select(union ctl_io * io)5975 ctl_do_mode_select(union ctl_io *io)
5976 {
5977 	struct ctl_lun *lun = CTL_LUN(io);
5978 	struct scsi_mode_page_header *page_header;
5979 	struct ctl_page_index *page_index;
5980 	struct ctl_scsiio *ctsio;
5981 	int page_len, page_len_offset, page_len_size;
5982 	union ctl_modepage_info *modepage_info;
5983 	uint16_t *len_left, *len_used;
5984 	int retval, i;
5985 
5986 	ctsio = &io->scsiio;
5987 	page_index = NULL;
5988 	page_len = 0;
5989 
5990 	modepage_info = (union ctl_modepage_info *)
5991 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5992 	len_left = &modepage_info->header.len_left;
5993 	len_used = &modepage_info->header.len_used;
5994 
5995 do_next_page:
5996 
5997 	page_header = (struct scsi_mode_page_header *)
5998 		(ctsio->kern_data_ptr + *len_used);
5999 
6000 	if (*len_left == 0) {
6001 		free(ctsio->kern_data_ptr, M_CTL);
6002 		ctl_set_success(ctsio);
6003 		ctl_done((union ctl_io *)ctsio);
6004 		return (CTL_RETVAL_COMPLETE);
6005 	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6006 
6007 		free(ctsio->kern_data_ptr, M_CTL);
6008 		ctl_set_param_len_error(ctsio);
6009 		ctl_done((union ctl_io *)ctsio);
6010 		return (CTL_RETVAL_COMPLETE);
6011 
6012 	} else if ((page_header->page_code & SMPH_SPF)
6013 		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6014 
6015 		free(ctsio->kern_data_ptr, M_CTL);
6016 		ctl_set_param_len_error(ctsio);
6017 		ctl_done((union ctl_io *)ctsio);
6018 		return (CTL_RETVAL_COMPLETE);
6019 	}
6020 
6021 
6022 	/*
6023 	 * XXX KDM should we do something with the block descriptor?
6024 	 */
6025 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6026 		page_index = &lun->mode_pages.index[i];
6027 		if (lun->be_lun->lun_type == T_DIRECT &&
6028 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6029 			continue;
6030 		if (lun->be_lun->lun_type == T_PROCESSOR &&
6031 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6032 			continue;
6033 		if (lun->be_lun->lun_type == T_CDROM &&
6034 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6035 			continue;
6036 
6037 		if ((page_index->page_code & SMPH_PC_MASK) !=
6038 		    (page_header->page_code & SMPH_PC_MASK))
6039 			continue;
6040 
6041 		/*
6042 		 * If neither page has a subpage code, then we've got a
6043 		 * match.
6044 		 */
6045 		if (((page_index->page_code & SMPH_SPF) == 0)
6046 		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6047 			page_len = page_header->page_length;
6048 			break;
6049 		}
6050 
6051 		/*
6052 		 * If both pages have subpages, then the subpage numbers
6053 		 * have to match.
6054 		 */
6055 		if ((page_index->page_code & SMPH_SPF)
6056 		  && (page_header->page_code & SMPH_SPF)) {
6057 			struct scsi_mode_page_header_sp *sph;
6058 
6059 			sph = (struct scsi_mode_page_header_sp *)page_header;
6060 			if (page_index->subpage == sph->subpage) {
6061 				page_len = scsi_2btoul(sph->page_length);
6062 				break;
6063 			}
6064 		}
6065 	}
6066 
6067 	/*
6068 	 * If we couldn't find the page, or if we don't have a mode select
6069 	 * handler for it, send back an error to the user.
6070 	 */
6071 	if ((i >= CTL_NUM_MODE_PAGES)
6072 	 || (page_index->select_handler == NULL)) {
6073 		ctl_set_invalid_field(ctsio,
6074 				      /*sks_valid*/ 1,
6075 				      /*command*/ 0,
6076 				      /*field*/ *len_used,
6077 				      /*bit_valid*/ 0,
6078 				      /*bit*/ 0);
6079 		free(ctsio->kern_data_ptr, M_CTL);
6080 		ctl_done((union ctl_io *)ctsio);
6081 		return (CTL_RETVAL_COMPLETE);
6082 	}
6083 
6084 	if (page_index->page_code & SMPH_SPF) {
6085 		page_len_offset = 2;
6086 		page_len_size = 2;
6087 	} else {
6088 		page_len_size = 1;
6089 		page_len_offset = 1;
6090 	}
6091 
6092 	/*
6093 	 * If the length the initiator gives us isn't the one we specify in
6094 	 * the mode page header, or if they didn't specify enough data in
6095 	 * the CDB to avoid truncating this page, kick out the request.
6096 	 */
6097 	if (page_len != page_index->page_len - page_len_offset - page_len_size) {
6098 		ctl_set_invalid_field(ctsio,
6099 				      /*sks_valid*/ 1,
6100 				      /*command*/ 0,
6101 				      /*field*/ *len_used + page_len_offset,
6102 				      /*bit_valid*/ 0,
6103 				      /*bit*/ 0);
6104 		free(ctsio->kern_data_ptr, M_CTL);
6105 		ctl_done((union ctl_io *)ctsio);
6106 		return (CTL_RETVAL_COMPLETE);
6107 	}
6108 	if (*len_left < page_index->page_len) {
6109 		free(ctsio->kern_data_ptr, M_CTL);
6110 		ctl_set_param_len_error(ctsio);
6111 		ctl_done((union ctl_io *)ctsio);
6112 		return (CTL_RETVAL_COMPLETE);
6113 	}
6114 
6115 	/*
6116 	 * Run through the mode page, checking to make sure that the bits
6117 	 * the user changed are actually legal for him to change.
6118 	 */
6119 	for (i = 0; i < page_index->page_len; i++) {
6120 		uint8_t *user_byte, *change_mask, *current_byte;
6121 		int bad_bit;
6122 		int j;
6123 
6124 		user_byte = (uint8_t *)page_header + i;
6125 		change_mask = page_index->page_data +
6126 			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6127 		current_byte = page_index->page_data +
6128 			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6129 
6130 		/*
6131 		 * Check to see whether the user set any bits in this byte
6132 		 * that he is not allowed to set.
6133 		 */
6134 		if ((*user_byte & ~(*change_mask)) ==
6135 		    (*current_byte & ~(*change_mask)))
6136 			continue;
6137 
6138 		/*
6139 		 * Go through bit by bit to determine which one is illegal.
6140 		 */
6141 		bad_bit = 0;
6142 		for (j = 7; j >= 0; j--) {
6143 			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6144 			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6145 				bad_bit = i;
6146 				break;
6147 			}
6148 		}
6149 		ctl_set_invalid_field(ctsio,
6150 				      /*sks_valid*/ 1,
6151 				      /*command*/ 0,
6152 				      /*field*/ *len_used + i,
6153 				      /*bit_valid*/ 1,
6154 				      /*bit*/ bad_bit);
6155 		free(ctsio->kern_data_ptr, M_CTL);
6156 		ctl_done((union ctl_io *)ctsio);
6157 		return (CTL_RETVAL_COMPLETE);
6158 	}
6159 
6160 	/*
6161 	 * Decrement these before we call the page handler, since we may
6162 	 * end up getting called back one way or another before the handler
6163 	 * returns to this context.
6164 	 */
6165 	*len_left -= page_index->page_len;
6166 	*len_used += page_index->page_len;
6167 
6168 	retval = page_index->select_handler(ctsio, page_index,
6169 					    (uint8_t *)page_header);
6170 
6171 	/*
6172 	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6173 	 * wait until this queued command completes to finish processing
6174 	 * the mode page.  If it returns anything other than
6175 	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6176 	 * already set the sense information, freed the data pointer, and
6177 	 * completed the io for us.
6178 	 */
6179 	if (retval != CTL_RETVAL_COMPLETE)
6180 		goto bailout_no_done;
6181 
6182 	/*
6183 	 * If the initiator sent us more than one page, parse the next one.
6184 	 */
6185 	if (*len_left > 0)
6186 		goto do_next_page;
6187 
6188 	ctl_set_success(ctsio);
6189 	free(ctsio->kern_data_ptr, M_CTL);
6190 	ctl_done((union ctl_io *)ctsio);
6191 
6192 bailout_no_done:
6193 
6194 	return (CTL_RETVAL_COMPLETE);
6195 
6196 }
6197 
6198 int
ctl_mode_select(struct ctl_scsiio * ctsio)6199 ctl_mode_select(struct ctl_scsiio *ctsio)
6200 {
6201 	struct ctl_lun *lun = CTL_LUN(ctsio);
6202 	union ctl_modepage_info *modepage_info;
6203 	int bd_len, i, header_size, param_len, rtd;
6204 	uint32_t initidx;
6205 
6206 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6207 	switch (ctsio->cdb[0]) {
6208 	case MODE_SELECT_6: {
6209 		struct scsi_mode_select_6 *cdb;
6210 
6211 		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6212 
6213 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6214 		param_len = cdb->length;
6215 		header_size = sizeof(struct scsi_mode_header_6);
6216 		break;
6217 	}
6218 	case MODE_SELECT_10: {
6219 		struct scsi_mode_select_10 *cdb;
6220 
6221 		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6222 
6223 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6224 		param_len = scsi_2btoul(cdb->length);
6225 		header_size = sizeof(struct scsi_mode_header_10);
6226 		break;
6227 	}
6228 	default:
6229 		ctl_set_invalid_opcode(ctsio);
6230 		ctl_done((union ctl_io *)ctsio);
6231 		return (CTL_RETVAL_COMPLETE);
6232 	}
6233 
6234 	if (rtd) {
6235 		if (param_len != 0) {
6236 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 0,
6237 			    /*command*/ 1, /*field*/ 0,
6238 			    /*bit_valid*/ 0, /*bit*/ 0);
6239 			ctl_done((union ctl_io *)ctsio);
6240 			return (CTL_RETVAL_COMPLETE);
6241 		}
6242 
6243 		/* Revert to defaults. */
6244 		ctl_init_page_index(lun);
6245 		mtx_lock(&lun->lun_lock);
6246 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6247 		mtx_unlock(&lun->lun_lock);
6248 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6249 			ctl_isc_announce_mode(lun, -1,
6250 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
6251 			    lun->mode_pages.index[i].subpage);
6252 		}
6253 		ctl_set_success(ctsio);
6254 		ctl_done((union ctl_io *)ctsio);
6255 		return (CTL_RETVAL_COMPLETE);
6256 	}
6257 
6258 	/*
6259 	 * From SPC-3:
6260 	 * "A parameter list length of zero indicates that the Data-Out Buffer
6261 	 * shall be empty. This condition shall not be considered as an error."
6262 	 */
6263 	if (param_len == 0) {
6264 		ctl_set_success(ctsio);
6265 		ctl_done((union ctl_io *)ctsio);
6266 		return (CTL_RETVAL_COMPLETE);
6267 	}
6268 
6269 	/*
6270 	 * Since we'll hit this the first time through, prior to
6271 	 * allocation, we don't need to free a data buffer here.
6272 	 */
6273 	if (param_len < header_size) {
6274 		ctl_set_param_len_error(ctsio);
6275 		ctl_done((union ctl_io *)ctsio);
6276 		return (CTL_RETVAL_COMPLETE);
6277 	}
6278 
6279 	/*
6280 	 * Allocate the data buffer and grab the user's data.  In theory,
6281 	 * we shouldn't have to sanity check the parameter list length here
6282 	 * because the maximum size is 64K.  We should be able to malloc
6283 	 * that much without too many problems.
6284 	 */
6285 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6286 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6287 		ctsio->kern_data_len = param_len;
6288 		ctsio->kern_total_len = param_len;
6289 		ctsio->kern_rel_offset = 0;
6290 		ctsio->kern_sg_entries = 0;
6291 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6292 		ctsio->be_move_done = ctl_config_move_done;
6293 		ctl_datamove((union ctl_io *)ctsio);
6294 
6295 		return (CTL_RETVAL_COMPLETE);
6296 	}
6297 
6298 	switch (ctsio->cdb[0]) {
6299 	case MODE_SELECT_6: {
6300 		struct scsi_mode_header_6 *mh6;
6301 
6302 		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6303 		bd_len = mh6->blk_desc_len;
6304 		break;
6305 	}
6306 	case MODE_SELECT_10: {
6307 		struct scsi_mode_header_10 *mh10;
6308 
6309 		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6310 		bd_len = scsi_2btoul(mh10->blk_desc_len);
6311 		break;
6312 	}
6313 	default:
6314 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6315 	}
6316 
6317 	if (param_len < (header_size + bd_len)) {
6318 		free(ctsio->kern_data_ptr, M_CTL);
6319 		ctl_set_param_len_error(ctsio);
6320 		ctl_done((union ctl_io *)ctsio);
6321 		return (CTL_RETVAL_COMPLETE);
6322 	}
6323 
6324 	/*
6325 	 * Set the IO_CONT flag, so that if this I/O gets passed to
6326 	 * ctl_config_write_done(), it'll get passed back to
6327 	 * ctl_do_mode_select() for further processing, or completion if
6328 	 * we're all done.
6329 	 */
6330 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6331 	ctsio->io_cont = ctl_do_mode_select;
6332 
6333 	modepage_info = (union ctl_modepage_info *)
6334 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6335 	memset(modepage_info, 0, sizeof(*modepage_info));
6336 	modepage_info->header.len_left = param_len - header_size - bd_len;
6337 	modepage_info->header.len_used = header_size + bd_len;
6338 
6339 	return (ctl_do_mode_select((union ctl_io *)ctsio));
6340 }
6341 
6342 int
ctl_mode_sense(struct ctl_scsiio * ctsio)6343 ctl_mode_sense(struct ctl_scsiio *ctsio)
6344 {
6345 	struct ctl_lun *lun = CTL_LUN(ctsio);
6346 	int pc, page_code, llba, subpage;
6347 	int alloc_len, page_len, header_len, bd_len, total_len;
6348 	void *block_desc;
6349 	struct ctl_page_index *page_index;
6350 
6351 	llba = 0;
6352 
6353 	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6354 
6355 	switch (ctsio->cdb[0]) {
6356 	case MODE_SENSE_6: {
6357 		struct scsi_mode_sense_6 *cdb;
6358 
6359 		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6360 
6361 		header_len = sizeof(struct scsi_mode_hdr_6);
6362 		if (cdb->byte2 & SMS_DBD)
6363 			bd_len = 0;
6364 		else
6365 			bd_len = sizeof(struct scsi_mode_block_descr);
6366 		header_len += bd_len;
6367 
6368 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6369 		page_code = cdb->page & SMS_PAGE_CODE;
6370 		subpage = cdb->subpage;
6371 		alloc_len = cdb->length;
6372 		break;
6373 	}
6374 	case MODE_SENSE_10: {
6375 		struct scsi_mode_sense_10 *cdb;
6376 
6377 		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6378 
6379 		header_len = sizeof(struct scsi_mode_hdr_10);
6380 		if (cdb->byte2 & SMS_DBD) {
6381 			bd_len = 0;
6382 		} else if (lun->be_lun->lun_type == T_DIRECT) {
6383 			if (cdb->byte2 & SMS10_LLBAA) {
6384 				llba = 1;
6385 				bd_len = sizeof(struct scsi_mode_block_descr_dlong);
6386 			} else
6387 				bd_len = sizeof(struct scsi_mode_block_descr_dshort);
6388 		} else
6389 			bd_len = sizeof(struct scsi_mode_block_descr);
6390 		header_len += bd_len;
6391 
6392 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6393 		page_code = cdb->page & SMS_PAGE_CODE;
6394 		subpage = cdb->subpage;
6395 		alloc_len = scsi_2btoul(cdb->length);
6396 		break;
6397 	}
6398 	default:
6399 		ctl_set_invalid_opcode(ctsio);
6400 		ctl_done((union ctl_io *)ctsio);
6401 		return (CTL_RETVAL_COMPLETE);
6402 		break; /* NOTREACHED */
6403 	}
6404 
6405 	/*
6406 	 * We have to make a first pass through to calculate the size of
6407 	 * the pages that match the user's query.  Then we allocate enough
6408 	 * memory to hold it, and actually copy the data into the buffer.
6409 	 */
6410 	switch (page_code) {
6411 	case SMS_ALL_PAGES_PAGE: {
6412 		u_int i;
6413 
6414 		page_len = 0;
6415 
6416 		/*
6417 		 * At the moment, values other than 0 and 0xff here are
6418 		 * reserved according to SPC-3.
6419 		 */
6420 		if ((subpage != SMS_SUBPAGE_PAGE_0)
6421 		 && (subpage != SMS_SUBPAGE_ALL)) {
6422 			ctl_set_invalid_field(ctsio,
6423 					      /*sks_valid*/ 1,
6424 					      /*command*/ 1,
6425 					      /*field*/ 3,
6426 					      /*bit_valid*/ 0,
6427 					      /*bit*/ 0);
6428 			ctl_done((union ctl_io *)ctsio);
6429 			return (CTL_RETVAL_COMPLETE);
6430 		}
6431 
6432 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6433 			page_index = &lun->mode_pages.index[i];
6434 
6435 			/* Make sure the page is supported for this dev type */
6436 			if (lun->be_lun->lun_type == T_DIRECT &&
6437 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6438 				continue;
6439 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6440 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6441 				continue;
6442 			if (lun->be_lun->lun_type == T_CDROM &&
6443 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6444 				continue;
6445 
6446 			/*
6447 			 * We don't use this subpage if the user didn't
6448 			 * request all subpages.
6449 			 */
6450 			if ((page_index->subpage != 0)
6451 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6452 				continue;
6453 
6454 			page_len += page_index->page_len;
6455 		}
6456 		break;
6457 	}
6458 	default: {
6459 		u_int i;
6460 
6461 		page_len = 0;
6462 
6463 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6464 			page_index = &lun->mode_pages.index[i];
6465 
6466 			/* Make sure the page is supported for this dev type */
6467 			if (lun->be_lun->lun_type == T_DIRECT &&
6468 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6469 				continue;
6470 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6471 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6472 				continue;
6473 			if (lun->be_lun->lun_type == T_CDROM &&
6474 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6475 				continue;
6476 
6477 			/* Look for the right page code */
6478 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6479 				continue;
6480 
6481 			/* Look for the right subpage or the subpage wildcard*/
6482 			if ((page_index->subpage != subpage)
6483 			 && (subpage != SMS_SUBPAGE_ALL))
6484 				continue;
6485 
6486 			page_len += page_index->page_len;
6487 		}
6488 
6489 		if (page_len == 0) {
6490 			ctl_set_invalid_field(ctsio,
6491 					      /*sks_valid*/ 1,
6492 					      /*command*/ 1,
6493 					      /*field*/ 2,
6494 					      /*bit_valid*/ 1,
6495 					      /*bit*/ 5);
6496 			ctl_done((union ctl_io *)ctsio);
6497 			return (CTL_RETVAL_COMPLETE);
6498 		}
6499 		break;
6500 	}
6501 	}
6502 
6503 	total_len = header_len + page_len;
6504 
6505 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6506 	ctsio->kern_sg_entries = 0;
6507 	ctsio->kern_rel_offset = 0;
6508 	ctsio->kern_data_len = min(total_len, alloc_len);
6509 	ctsio->kern_total_len = ctsio->kern_data_len;
6510 
6511 	switch (ctsio->cdb[0]) {
6512 	case MODE_SENSE_6: {
6513 		struct scsi_mode_hdr_6 *header;
6514 
6515 		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6516 
6517 		header->datalen = MIN(total_len - 1, 254);
6518 		if (lun->be_lun->lun_type == T_DIRECT) {
6519 			header->dev_specific = 0x10; /* DPOFUA */
6520 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6521 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6522 				header->dev_specific |= 0x80; /* WP */
6523 		}
6524 		header->block_descr_len = bd_len;
6525 		block_desc = &header[1];
6526 		break;
6527 	}
6528 	case MODE_SENSE_10: {
6529 		struct scsi_mode_hdr_10 *header;
6530 		int datalen;
6531 
6532 		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6533 
6534 		datalen = MIN(total_len - 2, 65533);
6535 		scsi_ulto2b(datalen, header->datalen);
6536 		if (lun->be_lun->lun_type == T_DIRECT) {
6537 			header->dev_specific = 0x10; /* DPOFUA */
6538 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6539 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6540 				header->dev_specific |= 0x80; /* WP */
6541 		}
6542 		if (llba)
6543 			header->flags |= SMH_LONGLBA;
6544 		scsi_ulto2b(bd_len, header->block_descr_len);
6545 		block_desc = &header[1];
6546 		break;
6547 	}
6548 	default:
6549 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6550 	}
6551 
6552 	/*
6553 	 * If we've got a disk, use its blocksize in the block
6554 	 * descriptor.  Otherwise, just set it to 0.
6555 	 */
6556 	if (bd_len > 0) {
6557 		if (lun->be_lun->lun_type == T_DIRECT) {
6558 			if (llba) {
6559 				struct scsi_mode_block_descr_dlong *bd = block_desc;
6560 				if (lun->be_lun->maxlba != 0)
6561 					scsi_u64to8b(lun->be_lun->maxlba + 1,
6562 					    bd->num_blocks);
6563 				scsi_ulto4b(lun->be_lun->blocksize,
6564 				    bd->block_len);
6565 			} else {
6566 				struct scsi_mode_block_descr_dshort *bd = block_desc;
6567 				if (lun->be_lun->maxlba != 0)
6568 					scsi_ulto4b(MIN(lun->be_lun->maxlba+1,
6569 					    UINT32_MAX), bd->num_blocks);
6570 				scsi_ulto3b(lun->be_lun->blocksize,
6571 				    bd->block_len);
6572 			}
6573 		} else {
6574 			struct scsi_mode_block_descr *bd = block_desc;
6575 			scsi_ulto3b(0, bd->block_len);
6576 		}
6577 	}
6578 
6579 	switch (page_code) {
6580 	case SMS_ALL_PAGES_PAGE: {
6581 		int i, data_used;
6582 
6583 		data_used = header_len;
6584 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6585 			struct ctl_page_index *page_index;
6586 
6587 			page_index = &lun->mode_pages.index[i];
6588 			if (lun->be_lun->lun_type == T_DIRECT &&
6589 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6590 				continue;
6591 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6592 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6593 				continue;
6594 			if (lun->be_lun->lun_type == T_CDROM &&
6595 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6596 				continue;
6597 
6598 			/*
6599 			 * We don't use this subpage if the user didn't
6600 			 * request all subpages.  We already checked (above)
6601 			 * to make sure the user only specified a subpage
6602 			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6603 			 */
6604 			if ((page_index->subpage != 0)
6605 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6606 				continue;
6607 
6608 			/*
6609 			 * Call the handler, if it exists, to update the
6610 			 * page to the latest values.
6611 			 */
6612 			if (page_index->sense_handler != NULL)
6613 				page_index->sense_handler(ctsio, page_index,pc);
6614 
6615 			memcpy(ctsio->kern_data_ptr + data_used,
6616 			       page_index->page_data +
6617 			       (page_index->page_len * pc),
6618 			       page_index->page_len);
6619 			data_used += page_index->page_len;
6620 		}
6621 		break;
6622 	}
6623 	default: {
6624 		int i, data_used;
6625 
6626 		data_used = header_len;
6627 
6628 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6629 			struct ctl_page_index *page_index;
6630 
6631 			page_index = &lun->mode_pages.index[i];
6632 
6633 			/* Look for the right page code */
6634 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6635 				continue;
6636 
6637 			/* Look for the right subpage or the subpage wildcard*/
6638 			if ((page_index->subpage != subpage)
6639 			 && (subpage != SMS_SUBPAGE_ALL))
6640 				continue;
6641 
6642 			/* Make sure the page is supported for this dev type */
6643 			if (lun->be_lun->lun_type == T_DIRECT &&
6644 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6645 				continue;
6646 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6647 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6648 				continue;
6649 			if (lun->be_lun->lun_type == T_CDROM &&
6650 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6651 				continue;
6652 
6653 			/*
6654 			 * Call the handler, if it exists, to update the
6655 			 * page to the latest values.
6656 			 */
6657 			if (page_index->sense_handler != NULL)
6658 				page_index->sense_handler(ctsio, page_index,pc);
6659 
6660 			memcpy(ctsio->kern_data_ptr + data_used,
6661 			       page_index->page_data +
6662 			       (page_index->page_len * pc),
6663 			       page_index->page_len);
6664 			data_used += page_index->page_len;
6665 		}
6666 		break;
6667 	}
6668 	}
6669 
6670 	ctl_set_success(ctsio);
6671 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6672 	ctsio->be_move_done = ctl_config_move_done;
6673 	ctl_datamove((union ctl_io *)ctsio);
6674 	return (CTL_RETVAL_COMPLETE);
6675 }
6676 
6677 int
ctl_temp_log_sense_handler(struct ctl_scsiio * ctsio,struct ctl_page_index * page_index,int pc)6678 ctl_temp_log_sense_handler(struct ctl_scsiio *ctsio,
6679 			       struct ctl_page_index *page_index,
6680 			       int pc)
6681 {
6682 	struct ctl_lun *lun = CTL_LUN(ctsio);
6683 	struct scsi_log_temperature *data;
6684 	const char *value;
6685 
6686 	data = (struct scsi_log_temperature *)page_index->page_data;
6687 
6688 	scsi_ulto2b(SLP_TEMPERATURE, data->hdr.param_code);
6689 	data->hdr.param_control = SLP_LBIN;
6690 	data->hdr.param_len = sizeof(struct scsi_log_temperature) -
6691 	    sizeof(struct scsi_log_param_header);
6692 	if ((value = dnvlist_get_string(lun->be_lun->options, "temperature",
6693 	    NULL)) != NULL)
6694 		data->temperature = strtol(value, NULL, 0);
6695 	else
6696 		data->temperature = 0xff;
6697 	data++;
6698 
6699 	scsi_ulto2b(SLP_REFTEMPERATURE, data->hdr.param_code);
6700 	data->hdr.param_control = SLP_LBIN;
6701 	data->hdr.param_len = sizeof(struct scsi_log_temperature) -
6702 	    sizeof(struct scsi_log_param_header);
6703 	if ((value = dnvlist_get_string(lun->be_lun->options, "reftemperature",
6704 	    NULL)) != NULL)
6705 		data->temperature = strtol(value, NULL, 0);
6706 	else
6707 		data->temperature = 0xff;
6708 	return (0);
6709 }
6710 
6711 int
ctl_lbp_log_sense_handler(struct ctl_scsiio * ctsio,struct ctl_page_index * page_index,int pc)6712 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6713 			       struct ctl_page_index *page_index,
6714 			       int pc)
6715 {
6716 	struct ctl_lun *lun = CTL_LUN(ctsio);
6717 	struct scsi_log_param_header *phdr;
6718 	uint8_t *data;
6719 	uint64_t val;
6720 
6721 	data = page_index->page_data;
6722 
6723 	if (lun->backend->lun_attr != NULL &&
6724 	    (val = lun->backend->lun_attr(lun->be_lun, "blocksavail"))
6725 	     != UINT64_MAX) {
6726 		phdr = (struct scsi_log_param_header *)data;
6727 		scsi_ulto2b(0x0001, phdr->param_code);
6728 		phdr->param_control = SLP_LBIN | SLP_LP;
6729 		phdr->param_len = 8;
6730 		data = (uint8_t *)(phdr + 1);
6731 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6732 		data[4] = 0x02; /* per-pool */
6733 		data += phdr->param_len;
6734 	}
6735 
6736 	if (lun->backend->lun_attr != NULL &&
6737 	    (val = lun->backend->lun_attr(lun->be_lun, "blocksused"))
6738 	     != UINT64_MAX) {
6739 		phdr = (struct scsi_log_param_header *)data;
6740 		scsi_ulto2b(0x0002, phdr->param_code);
6741 		phdr->param_control = SLP_LBIN | SLP_LP;
6742 		phdr->param_len = 8;
6743 		data = (uint8_t *)(phdr + 1);
6744 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6745 		data[4] = 0x01; /* per-LUN */
6746 		data += phdr->param_len;
6747 	}
6748 
6749 	if (lun->backend->lun_attr != NULL &&
6750 	    (val = lun->backend->lun_attr(lun->be_lun, "poolblocksavail"))
6751 	     != UINT64_MAX) {
6752 		phdr = (struct scsi_log_param_header *)data;
6753 		scsi_ulto2b(0x00f1, phdr->param_code);
6754 		phdr->param_control = SLP_LBIN | SLP_LP;
6755 		phdr->param_len = 8;
6756 		data = (uint8_t *)(phdr + 1);
6757 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6758 		data[4] = 0x02; /* per-pool */
6759 		data += phdr->param_len;
6760 	}
6761 
6762 	if (lun->backend->lun_attr != NULL &&
6763 	    (val = lun->backend->lun_attr(lun->be_lun, "poolblocksused"))
6764 	     != UINT64_MAX) {
6765 		phdr = (struct scsi_log_param_header *)data;
6766 		scsi_ulto2b(0x00f2, phdr->param_code);
6767 		phdr->param_control = SLP_LBIN | SLP_LP;
6768 		phdr->param_len = 8;
6769 		data = (uint8_t *)(phdr + 1);
6770 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6771 		data[4] = 0x02; /* per-pool */
6772 		data += phdr->param_len;
6773 	}
6774 
6775 	page_index->page_len = data - page_index->page_data;
6776 	return (0);
6777 }
6778 
6779 int
ctl_sap_log_sense_handler(struct ctl_scsiio * ctsio,struct ctl_page_index * page_index,int pc)6780 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6781 			       struct ctl_page_index *page_index,
6782 			       int pc)
6783 {
6784 	struct ctl_lun *lun = CTL_LUN(ctsio);
6785 	struct stat_page *data;
6786 	struct bintime *t;
6787 
6788 	data = (struct stat_page *)page_index->page_data;
6789 
6790 	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6791 	data->sap.hdr.param_control = SLP_LBIN;
6792 	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6793 	    sizeof(struct scsi_log_param_header);
6794 	scsi_u64to8b(lun->stats.operations[CTL_STATS_READ],
6795 	    data->sap.read_num);
6796 	scsi_u64to8b(lun->stats.operations[CTL_STATS_WRITE],
6797 	    data->sap.write_num);
6798 	if (lun->be_lun->blocksize > 0) {
6799 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_WRITE] /
6800 		    lun->be_lun->blocksize, data->sap.recvieved_lba);
6801 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_READ] /
6802 		    lun->be_lun->blocksize, data->sap.transmitted_lba);
6803 	}
6804 	t = &lun->stats.time[CTL_STATS_READ];
6805 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6806 	    data->sap.read_int);
6807 	t = &lun->stats.time[CTL_STATS_WRITE];
6808 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6809 	    data->sap.write_int);
6810 	scsi_u64to8b(0, data->sap.weighted_num);
6811 	scsi_u64to8b(0, data->sap.weighted_int);
6812 	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6813 	data->it.hdr.param_control = SLP_LBIN;
6814 	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6815 	    sizeof(struct scsi_log_param_header);
6816 #ifdef CTL_TIME_IO
6817 	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6818 #endif
6819 	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6820 	data->it.hdr.param_control = SLP_LBIN;
6821 	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6822 	    sizeof(struct scsi_log_param_header);
6823 	scsi_ulto4b(3, data->ti.exponent);
6824 	scsi_ulto4b(1, data->ti.integer);
6825 	return (0);
6826 }
6827 
6828 int
ctl_ie_log_sense_handler(struct ctl_scsiio * ctsio,struct ctl_page_index * page_index,int pc)6829 ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6830 			       struct ctl_page_index *page_index,
6831 			       int pc)
6832 {
6833 	struct ctl_lun *lun = CTL_LUN(ctsio);
6834 	struct scsi_log_informational_exceptions *data;
6835 	const char *value;
6836 
6837 	data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6838 
6839 	scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6840 	data->hdr.param_control = SLP_LBIN;
6841 	data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6842 	    sizeof(struct scsi_log_param_header);
6843 	data->ie_asc = lun->ie_asc;
6844 	data->ie_ascq = lun->ie_ascq;
6845 	if ((value = dnvlist_get_string(lun->be_lun->options, "temperature",
6846 	    NULL)) != NULL)
6847 		data->temperature = strtol(value, NULL, 0);
6848 	else
6849 		data->temperature = 0xff;
6850 	return (0);
6851 }
6852 
6853 int
ctl_log_sense(struct ctl_scsiio * ctsio)6854 ctl_log_sense(struct ctl_scsiio *ctsio)
6855 {
6856 	struct ctl_lun *lun = CTL_LUN(ctsio);
6857 	int i, pc, page_code, subpage;
6858 	int alloc_len, total_len;
6859 	struct ctl_page_index *page_index;
6860 	struct scsi_log_sense *cdb;
6861 	struct scsi_log_header *header;
6862 
6863 	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6864 
6865 	cdb = (struct scsi_log_sense *)ctsio->cdb;
6866 	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6867 	page_code = cdb->page & SLS_PAGE_CODE;
6868 	subpage = cdb->subpage;
6869 	alloc_len = scsi_2btoul(cdb->length);
6870 
6871 	page_index = NULL;
6872 	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6873 		page_index = &lun->log_pages.index[i];
6874 
6875 		/* Look for the right page code */
6876 		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6877 			continue;
6878 
6879 		/* Look for the right subpage or the subpage wildcard*/
6880 		if (page_index->subpage != subpage)
6881 			continue;
6882 
6883 		break;
6884 	}
6885 	if (i >= CTL_NUM_LOG_PAGES) {
6886 		ctl_set_invalid_field(ctsio,
6887 				      /*sks_valid*/ 1,
6888 				      /*command*/ 1,
6889 				      /*field*/ 2,
6890 				      /*bit_valid*/ 0,
6891 				      /*bit*/ 0);
6892 		ctl_done((union ctl_io *)ctsio);
6893 		return (CTL_RETVAL_COMPLETE);
6894 	}
6895 
6896 	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6897 
6898 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6899 	ctsio->kern_sg_entries = 0;
6900 	ctsio->kern_rel_offset = 0;
6901 	ctsio->kern_data_len = min(total_len, alloc_len);
6902 	ctsio->kern_total_len = ctsio->kern_data_len;
6903 
6904 	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6905 	header->page = page_index->page_code;
6906 	if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6907 		header->page |= SL_DS;
6908 	if (page_index->subpage) {
6909 		header->page |= SL_SPF;
6910 		header->subpage = page_index->subpage;
6911 	}
6912 	scsi_ulto2b(page_index->page_len, header->datalen);
6913 
6914 	/*
6915 	 * Call the handler, if it exists, to update the
6916 	 * page to the latest values.
6917 	 */
6918 	if (page_index->sense_handler != NULL)
6919 		page_index->sense_handler(ctsio, page_index, pc);
6920 
6921 	memcpy(header + 1, page_index->page_data, page_index->page_len);
6922 
6923 	ctl_set_success(ctsio);
6924 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6925 	ctsio->be_move_done = ctl_config_move_done;
6926 	ctl_datamove((union ctl_io *)ctsio);
6927 	return (CTL_RETVAL_COMPLETE);
6928 }
6929 
6930 int
ctl_read_capacity(struct ctl_scsiio * ctsio)6931 ctl_read_capacity(struct ctl_scsiio *ctsio)
6932 {
6933 	struct ctl_lun *lun = CTL_LUN(ctsio);
6934 	struct scsi_read_capacity *cdb;
6935 	struct scsi_read_capacity_data *data;
6936 	uint32_t lba;
6937 
6938 	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6939 
6940 	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6941 
6942 	lba = scsi_4btoul(cdb->addr);
6943 	if (((cdb->pmi & SRC_PMI) == 0)
6944 	 && (lba != 0)) {
6945 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6946 				      /*sks_valid*/ 1,
6947 				      /*command*/ 1,
6948 				      /*field*/ 2,
6949 				      /*bit_valid*/ 0,
6950 				      /*bit*/ 0);
6951 		ctl_done((union ctl_io *)ctsio);
6952 		return (CTL_RETVAL_COMPLETE);
6953 	}
6954 
6955 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6956 	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6957 	ctsio->kern_data_len = sizeof(*data);
6958 	ctsio->kern_total_len = sizeof(*data);
6959 	ctsio->kern_rel_offset = 0;
6960 	ctsio->kern_sg_entries = 0;
6961 
6962 	/*
6963 	 * If the maximum LBA is greater than 0xfffffffe, the user must
6964 	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6965 	 * serivce action set.
6966 	 */
6967 	if (lun->be_lun->maxlba > 0xfffffffe)
6968 		scsi_ulto4b(0xffffffff, data->addr);
6969 	else
6970 		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6971 
6972 	/*
6973 	 * XXX KDM this may not be 512 bytes...
6974 	 */
6975 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6976 
6977 	ctl_set_success(ctsio);
6978 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6979 	ctsio->be_move_done = ctl_config_move_done;
6980 	ctl_datamove((union ctl_io *)ctsio);
6981 	return (CTL_RETVAL_COMPLETE);
6982 }
6983 
6984 int
ctl_read_capacity_16(struct ctl_scsiio * ctsio)6985 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6986 {
6987 	struct ctl_lun *lun = CTL_LUN(ctsio);
6988 	struct scsi_read_capacity_16 *cdb;
6989 	struct scsi_read_capacity_data_long *data;
6990 	uint64_t lba;
6991 	uint32_t alloc_len;
6992 
6993 	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6994 
6995 	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6996 
6997 	alloc_len = scsi_4btoul(cdb->alloc_len);
6998 	lba = scsi_8btou64(cdb->addr);
6999 
7000 	if ((cdb->reladr & SRC16_PMI)
7001 	 && (lba != 0)) {
7002 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7003 				      /*sks_valid*/ 1,
7004 				      /*command*/ 1,
7005 				      /*field*/ 2,
7006 				      /*bit_valid*/ 0,
7007 				      /*bit*/ 0);
7008 		ctl_done((union ctl_io *)ctsio);
7009 		return (CTL_RETVAL_COMPLETE);
7010 	}
7011 
7012 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7013 	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7014 	ctsio->kern_rel_offset = 0;
7015 	ctsio->kern_sg_entries = 0;
7016 	ctsio->kern_data_len = min(sizeof(*data), alloc_len);
7017 	ctsio->kern_total_len = ctsio->kern_data_len;
7018 
7019 	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7020 	/* XXX KDM this may not be 512 bytes... */
7021 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7022 	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7023 	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7024 	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7025 		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7026 
7027 	ctl_set_success(ctsio);
7028 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7029 	ctsio->be_move_done = ctl_config_move_done;
7030 	ctl_datamove((union ctl_io *)ctsio);
7031 	return (CTL_RETVAL_COMPLETE);
7032 }
7033 
7034 int
ctl_get_lba_status(struct ctl_scsiio * ctsio)7035 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7036 {
7037 	struct ctl_lun *lun = CTL_LUN(ctsio);
7038 	struct scsi_get_lba_status *cdb;
7039 	struct scsi_get_lba_status_data *data;
7040 	struct ctl_lba_len_flags *lbalen;
7041 	uint64_t lba;
7042 	uint32_t alloc_len, total_len;
7043 	int retval;
7044 
7045 	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7046 
7047 	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7048 	lba = scsi_8btou64(cdb->addr);
7049 	alloc_len = scsi_4btoul(cdb->alloc_len);
7050 
7051 	if (lba > lun->be_lun->maxlba) {
7052 		ctl_set_lba_out_of_range(ctsio, lba);
7053 		ctl_done((union ctl_io *)ctsio);
7054 		return (CTL_RETVAL_COMPLETE);
7055 	}
7056 
7057 	total_len = sizeof(*data) + sizeof(data->descr[0]);
7058 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7059 	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7060 	ctsio->kern_rel_offset = 0;
7061 	ctsio->kern_sg_entries = 0;
7062 	ctsio->kern_data_len = min(total_len, alloc_len);
7063 	ctsio->kern_total_len = ctsio->kern_data_len;
7064 
7065 	/* Fill dummy data in case backend can't tell anything. */
7066 	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7067 	scsi_u64to8b(lba, data->descr[0].addr);
7068 	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7069 	    data->descr[0].length);
7070 	data->descr[0].status = 0; /* Mapped or unknown. */
7071 
7072 	ctl_set_success(ctsio);
7073 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7074 	ctsio->be_move_done = ctl_config_move_done;
7075 
7076 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7077 	lbalen->lba = lba;
7078 	lbalen->len = total_len;
7079 	lbalen->flags = 0;
7080 	retval = lun->backend->config_read((union ctl_io *)ctsio);
7081 	return (retval);
7082 }
7083 
7084 int
ctl_read_defect(struct ctl_scsiio * ctsio)7085 ctl_read_defect(struct ctl_scsiio *ctsio)
7086 {
7087 	struct scsi_read_defect_data_10 *ccb10;
7088 	struct scsi_read_defect_data_12 *ccb12;
7089 	struct scsi_read_defect_data_hdr_10 *data10;
7090 	struct scsi_read_defect_data_hdr_12 *data12;
7091 	uint32_t alloc_len, data_len;
7092 	uint8_t format;
7093 
7094 	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7095 
7096 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7097 		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7098 		format = ccb10->format;
7099 		alloc_len = scsi_2btoul(ccb10->alloc_length);
7100 		data_len = sizeof(*data10);
7101 	} else {
7102 		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7103 		format = ccb12->format;
7104 		alloc_len = scsi_4btoul(ccb12->alloc_length);
7105 		data_len = sizeof(*data12);
7106 	}
7107 	if (alloc_len == 0) {
7108 		ctl_set_success(ctsio);
7109 		ctl_done((union ctl_io *)ctsio);
7110 		return (CTL_RETVAL_COMPLETE);
7111 	}
7112 
7113 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7114 	ctsio->kern_rel_offset = 0;
7115 	ctsio->kern_sg_entries = 0;
7116 	ctsio->kern_data_len = min(data_len, alloc_len);
7117 	ctsio->kern_total_len = ctsio->kern_data_len;
7118 
7119 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7120 		data10 = (struct scsi_read_defect_data_hdr_10 *)
7121 		    ctsio->kern_data_ptr;
7122 		data10->format = format;
7123 		scsi_ulto2b(0, data10->length);
7124 	} else {
7125 		data12 = (struct scsi_read_defect_data_hdr_12 *)
7126 		    ctsio->kern_data_ptr;
7127 		data12->format = format;
7128 		scsi_ulto2b(0, data12->generation);
7129 		scsi_ulto4b(0, data12->length);
7130 	}
7131 
7132 	ctl_set_success(ctsio);
7133 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7134 	ctsio->be_move_done = ctl_config_move_done;
7135 	ctl_datamove((union ctl_io *)ctsio);
7136 	return (CTL_RETVAL_COMPLETE);
7137 }
7138 
7139 int
ctl_report_ident_info(struct ctl_scsiio * ctsio)7140 ctl_report_ident_info(struct ctl_scsiio *ctsio)
7141 {
7142 	struct ctl_lun *lun = CTL_LUN(ctsio);
7143 	struct scsi_report_ident_info *cdb;
7144 	struct scsi_report_ident_info_data *rii_ptr;
7145 	struct scsi_report_ident_info_descr *riid_ptr;
7146 	const char *oii, *otii;
7147 	int retval, alloc_len, total_len = 0, len = 0;
7148 
7149 	CTL_DEBUG_PRINT(("ctl_report_ident_info\n"));
7150 
7151 	cdb = (struct scsi_report_ident_info *)ctsio->cdb;
7152 	retval = CTL_RETVAL_COMPLETE;
7153 
7154 	total_len = sizeof(struct scsi_report_ident_info_data);
7155 	switch (cdb->type) {
7156 	case RII_LUII:
7157 		oii = dnvlist_get_string(lun->be_lun->options,
7158 		    "ident_info", NULL);
7159 		if (oii)
7160 			len = strlen(oii);	/* Approximately */
7161 		break;
7162 	case RII_LUTII:
7163 		otii = dnvlist_get_string(lun->be_lun->options,
7164 		    "text_ident_info", NULL);
7165 		if (otii)
7166 			len = strlen(otii) + 1;	/* NULL-terminated */
7167 		break;
7168 	case RII_IIS:
7169 		len = 2 * sizeof(struct scsi_report_ident_info_descr);
7170 		break;
7171 	default:
7172 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7173 				      /*sks_valid*/ 1,
7174 				      /*command*/ 1,
7175 				      /*field*/ 11,
7176 				      /*bit_valid*/ 1,
7177 				      /*bit*/ 2);
7178 		ctl_done((union ctl_io *)ctsio);
7179 		return(retval);
7180 	}
7181 	total_len += len;
7182 	alloc_len = scsi_4btoul(cdb->length);
7183 
7184 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7185 	ctsio->kern_sg_entries = 0;
7186 	ctsio->kern_rel_offset = 0;
7187 	ctsio->kern_data_len = min(total_len, alloc_len);
7188 	ctsio->kern_total_len = ctsio->kern_data_len;
7189 
7190 	rii_ptr = (struct scsi_report_ident_info_data *)ctsio->kern_data_ptr;
7191 	switch (cdb->type) {
7192 	case RII_LUII:
7193 		if (oii) {
7194 			if (oii[0] == '0' && oii[1] == 'x')
7195 				len = hex2bin(oii, (uint8_t *)(rii_ptr + 1), len);
7196 			else
7197 				strncpy((uint8_t *)(rii_ptr + 1), oii, len);
7198 		}
7199 		break;
7200 	case RII_LUTII:
7201 		if (otii)
7202 			strlcpy((uint8_t *)(rii_ptr + 1), otii, len);
7203 		break;
7204 	case RII_IIS:
7205 		riid_ptr = (struct scsi_report_ident_info_descr *)(rii_ptr + 1);
7206 		riid_ptr->type = RII_LUII;
7207 		scsi_ulto2b(0xffff, riid_ptr->length);
7208 		riid_ptr++;
7209 		riid_ptr->type = RII_LUTII;
7210 		scsi_ulto2b(0xffff, riid_ptr->length);
7211 	}
7212 	scsi_ulto2b(len, rii_ptr->length);
7213 
7214 	ctl_set_success(ctsio);
7215 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7216 	ctsio->be_move_done = ctl_config_move_done;
7217 	ctl_datamove((union ctl_io *)ctsio);
7218 	return(retval);
7219 }
7220 
7221 int
ctl_report_tagret_port_groups(struct ctl_scsiio * ctsio)7222 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7223 {
7224 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7225 	struct ctl_lun *lun = CTL_LUN(ctsio);
7226 	struct scsi_maintenance_in *cdb;
7227 	int retval;
7228 	int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7229 	int num_ha_groups, num_target_ports, shared_group;
7230 	struct ctl_port *port;
7231 	struct scsi_target_group_data *rtg_ptr;
7232 	struct scsi_target_group_data_extended *rtg_ext_ptr;
7233 	struct scsi_target_port_group_descriptor *tpg_desc;
7234 
7235 	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7236 
7237 	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7238 	retval = CTL_RETVAL_COMPLETE;
7239 
7240 	switch (cdb->byte2 & STG_PDF_MASK) {
7241 	case STG_PDF_LENGTH:
7242 		ext = 0;
7243 		break;
7244 	case STG_PDF_EXTENDED:
7245 		ext = 1;
7246 		break;
7247 	default:
7248 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7249 				      /*sks_valid*/ 1,
7250 				      /*command*/ 1,
7251 				      /*field*/ 2,
7252 				      /*bit_valid*/ 1,
7253 				      /*bit*/ 5);
7254 		ctl_done((union ctl_io *)ctsio);
7255 		return(retval);
7256 	}
7257 
7258 	num_target_ports = 0;
7259 	shared_group = (softc->is_single != 0);
7260 	mtx_lock(&softc->ctl_lock);
7261 	STAILQ_FOREACH(port, &softc->port_list, links) {
7262 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7263 			continue;
7264 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7265 			continue;
7266 		num_target_ports++;
7267 		if (port->status & CTL_PORT_STATUS_HA_SHARED)
7268 			shared_group = 1;
7269 	}
7270 	mtx_unlock(&softc->ctl_lock);
7271 	num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7272 
7273 	if (ext)
7274 		total_len = sizeof(struct scsi_target_group_data_extended);
7275 	else
7276 		total_len = sizeof(struct scsi_target_group_data);
7277 	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7278 		(shared_group + num_ha_groups) +
7279 	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7280 
7281 	alloc_len = scsi_4btoul(cdb->length);
7282 
7283 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7284 	ctsio->kern_sg_entries = 0;
7285 	ctsio->kern_rel_offset = 0;
7286 	ctsio->kern_data_len = min(total_len, alloc_len);
7287 	ctsio->kern_total_len = ctsio->kern_data_len;
7288 
7289 	if (ext) {
7290 		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7291 		    ctsio->kern_data_ptr;
7292 		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7293 		rtg_ext_ptr->format_type = 0x10;
7294 		rtg_ext_ptr->implicit_transition_time = 0;
7295 		tpg_desc = &rtg_ext_ptr->groups[0];
7296 	} else {
7297 		rtg_ptr = (struct scsi_target_group_data *)
7298 		    ctsio->kern_data_ptr;
7299 		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7300 		tpg_desc = &rtg_ptr->groups[0];
7301 	}
7302 
7303 	mtx_lock(&softc->ctl_lock);
7304 	pg = softc->port_min / softc->port_cnt;
7305 	if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7306 		/* Some shelf is known to be primary. */
7307 		if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7308 			os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7309 		else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7310 			os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7311 		else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7312 			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7313 		else
7314 			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7315 		if (lun->flags & CTL_LUN_PRIMARY_SC) {
7316 			ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7317 		} else {
7318 			ts = os;
7319 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7320 		}
7321 	} else {
7322 		/* No known primary shelf. */
7323 		if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7324 			ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7325 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7326 		} else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7327 			ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7328 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7329 		} else {
7330 			ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7331 		}
7332 	}
7333 	if (shared_group) {
7334 		tpg_desc->pref_state = ts;
7335 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7336 		    TPG_U_SUP | TPG_T_SUP;
7337 		scsi_ulto2b(1, tpg_desc->target_port_group);
7338 		tpg_desc->status = TPG_IMPLICIT;
7339 		pc = 0;
7340 		STAILQ_FOREACH(port, &softc->port_list, links) {
7341 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7342 				continue;
7343 			if (!softc->is_single &&
7344 			    (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7345 				continue;
7346 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7347 				continue;
7348 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7349 			    relative_target_port_identifier);
7350 			pc++;
7351 		}
7352 		tpg_desc->target_port_count = pc;
7353 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7354 		    &tpg_desc->descriptors[pc];
7355 	}
7356 	for (g = 0; g < num_ha_groups; g++) {
7357 		tpg_desc->pref_state = (g == pg) ? ts : os;
7358 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7359 		    TPG_U_SUP | TPG_T_SUP;
7360 		scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7361 		tpg_desc->status = TPG_IMPLICIT;
7362 		pc = 0;
7363 		STAILQ_FOREACH(port, &softc->port_list, links) {
7364 			if (port->targ_port < g * softc->port_cnt ||
7365 			    port->targ_port >= (g + 1) * softc->port_cnt)
7366 				continue;
7367 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7368 				continue;
7369 			if (port->status & CTL_PORT_STATUS_HA_SHARED)
7370 				continue;
7371 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7372 				continue;
7373 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7374 			    relative_target_port_identifier);
7375 			pc++;
7376 		}
7377 		tpg_desc->target_port_count = pc;
7378 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7379 		    &tpg_desc->descriptors[pc];
7380 	}
7381 	mtx_unlock(&softc->ctl_lock);
7382 
7383 	ctl_set_success(ctsio);
7384 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7385 	ctsio->be_move_done = ctl_config_move_done;
7386 	ctl_datamove((union ctl_io *)ctsio);
7387 	return(retval);
7388 }
7389 
7390 int
ctl_report_supported_opcodes(struct ctl_scsiio * ctsio)7391 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7392 {
7393 	struct ctl_lun *lun = CTL_LUN(ctsio);
7394 	struct scsi_report_supported_opcodes *cdb;
7395 	const struct ctl_cmd_entry *entry, *sentry;
7396 	struct scsi_report_supported_opcodes_all *all;
7397 	struct scsi_report_supported_opcodes_descr *descr;
7398 	struct scsi_report_supported_opcodes_one *one;
7399 	int retval;
7400 	int alloc_len, total_len;
7401 	int opcode, service_action, i, j, num;
7402 
7403 	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7404 
7405 	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7406 	retval = CTL_RETVAL_COMPLETE;
7407 
7408 	opcode = cdb->requested_opcode;
7409 	service_action = scsi_2btoul(cdb->requested_service_action);
7410 	switch (cdb->options & RSO_OPTIONS_MASK) {
7411 	case RSO_OPTIONS_ALL:
7412 		num = 0;
7413 		for (i = 0; i < 256; i++) {
7414 			entry = &ctl_cmd_table[i];
7415 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7416 				for (j = 0; j < 32; j++) {
7417 					sentry = &((const struct ctl_cmd_entry *)
7418 					    entry->execute)[j];
7419 					if (ctl_cmd_applicable(
7420 					    lun->be_lun->lun_type, sentry))
7421 						num++;
7422 				}
7423 			} else {
7424 				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7425 				    entry))
7426 					num++;
7427 			}
7428 		}
7429 		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7430 		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7431 		break;
7432 	case RSO_OPTIONS_OC:
7433 		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7434 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7435 					      /*sks_valid*/ 1,
7436 					      /*command*/ 1,
7437 					      /*field*/ 2,
7438 					      /*bit_valid*/ 1,
7439 					      /*bit*/ 2);
7440 			ctl_done((union ctl_io *)ctsio);
7441 			return (CTL_RETVAL_COMPLETE);
7442 		}
7443 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7444 		break;
7445 	case RSO_OPTIONS_OC_SA:
7446 		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7447 		    service_action >= 32) {
7448 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7449 					      /*sks_valid*/ 1,
7450 					      /*command*/ 1,
7451 					      /*field*/ 2,
7452 					      /*bit_valid*/ 1,
7453 					      /*bit*/ 2);
7454 			ctl_done((union ctl_io *)ctsio);
7455 			return (CTL_RETVAL_COMPLETE);
7456 		}
7457 		/* FALLTHROUGH */
7458 	case RSO_OPTIONS_OC_ASA:
7459 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7460 		break;
7461 	default:
7462 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7463 				      /*sks_valid*/ 1,
7464 				      /*command*/ 1,
7465 				      /*field*/ 2,
7466 				      /*bit_valid*/ 1,
7467 				      /*bit*/ 2);
7468 		ctl_done((union ctl_io *)ctsio);
7469 		return (CTL_RETVAL_COMPLETE);
7470 	}
7471 
7472 	alloc_len = scsi_4btoul(cdb->length);
7473 
7474 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7475 	ctsio->kern_sg_entries = 0;
7476 	ctsio->kern_rel_offset = 0;
7477 	ctsio->kern_data_len = min(total_len, alloc_len);
7478 	ctsio->kern_total_len = ctsio->kern_data_len;
7479 
7480 	switch (cdb->options & RSO_OPTIONS_MASK) {
7481 	case RSO_OPTIONS_ALL:
7482 		all = (struct scsi_report_supported_opcodes_all *)
7483 		    ctsio->kern_data_ptr;
7484 		num = 0;
7485 		for (i = 0; i < 256; i++) {
7486 			entry = &ctl_cmd_table[i];
7487 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7488 				for (j = 0; j < 32; j++) {
7489 					sentry = &((const struct ctl_cmd_entry *)
7490 					    entry->execute)[j];
7491 					if (!ctl_cmd_applicable(
7492 					    lun->be_lun->lun_type, sentry))
7493 						continue;
7494 					descr = &all->descr[num++];
7495 					descr->opcode = i;
7496 					scsi_ulto2b(j, descr->service_action);
7497 					descr->flags = RSO_SERVACTV;
7498 					scsi_ulto2b(sentry->length,
7499 					    descr->cdb_length);
7500 				}
7501 			} else {
7502 				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7503 				    entry))
7504 					continue;
7505 				descr = &all->descr[num++];
7506 				descr->opcode = i;
7507 				scsi_ulto2b(0, descr->service_action);
7508 				descr->flags = 0;
7509 				scsi_ulto2b(entry->length, descr->cdb_length);
7510 			}
7511 		}
7512 		scsi_ulto4b(
7513 		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7514 		    all->length);
7515 		break;
7516 	case RSO_OPTIONS_OC:
7517 		one = (struct scsi_report_supported_opcodes_one *)
7518 		    ctsio->kern_data_ptr;
7519 		entry = &ctl_cmd_table[opcode];
7520 		goto fill_one;
7521 	case RSO_OPTIONS_OC_SA:
7522 		one = (struct scsi_report_supported_opcodes_one *)
7523 		    ctsio->kern_data_ptr;
7524 		entry = &ctl_cmd_table[opcode];
7525 		entry = &((const struct ctl_cmd_entry *)
7526 		    entry->execute)[service_action];
7527 fill_one:
7528 		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7529 			one->support = 3;
7530 			scsi_ulto2b(entry->length, one->cdb_length);
7531 			one->cdb_usage[0] = opcode;
7532 			memcpy(&one->cdb_usage[1], entry->usage,
7533 			    entry->length - 1);
7534 		} else
7535 			one->support = 1;
7536 		break;
7537 	case RSO_OPTIONS_OC_ASA:
7538 		one = (struct scsi_report_supported_opcodes_one *)
7539 		    ctsio->kern_data_ptr;
7540 		entry = &ctl_cmd_table[opcode];
7541 		if (entry->flags & CTL_CMD_FLAG_SA5) {
7542 			entry = &((const struct ctl_cmd_entry *)
7543 			    entry->execute)[service_action];
7544 		} else if (service_action != 0) {
7545 			one->support = 1;
7546 			break;
7547 		}
7548 		goto fill_one;
7549 	}
7550 
7551 	ctl_set_success(ctsio);
7552 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7553 	ctsio->be_move_done = ctl_config_move_done;
7554 	ctl_datamove((union ctl_io *)ctsio);
7555 	return(retval);
7556 }
7557 
7558 int
ctl_report_supported_tmf(struct ctl_scsiio * ctsio)7559 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7560 {
7561 	struct scsi_report_supported_tmf *cdb;
7562 	struct scsi_report_supported_tmf_ext_data *data;
7563 	int retval;
7564 	int alloc_len, total_len;
7565 
7566 	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7567 
7568 	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7569 
7570 	retval = CTL_RETVAL_COMPLETE;
7571 
7572 	if (cdb->options & RST_REPD)
7573 		total_len = sizeof(struct scsi_report_supported_tmf_ext_data);
7574 	else
7575 		total_len = sizeof(struct scsi_report_supported_tmf_data);
7576 	alloc_len = scsi_4btoul(cdb->length);
7577 
7578 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7579 	ctsio->kern_sg_entries = 0;
7580 	ctsio->kern_rel_offset = 0;
7581 	ctsio->kern_data_len = min(total_len, alloc_len);
7582 	ctsio->kern_total_len = ctsio->kern_data_len;
7583 
7584 	data = (struct scsi_report_supported_tmf_ext_data *)ctsio->kern_data_ptr;
7585 	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7586 	    RST_TRS;
7587 	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7588 	data->length = total_len - 4;
7589 
7590 	ctl_set_success(ctsio);
7591 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7592 	ctsio->be_move_done = ctl_config_move_done;
7593 	ctl_datamove((union ctl_io *)ctsio);
7594 	return (retval);
7595 }
7596 
7597 int
ctl_report_timestamp(struct ctl_scsiio * ctsio)7598 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7599 {
7600 	struct scsi_report_timestamp *cdb;
7601 	struct scsi_report_timestamp_data *data;
7602 	struct timeval tv;
7603 	int64_t timestamp;
7604 	int retval;
7605 	int alloc_len, total_len;
7606 
7607 	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7608 
7609 	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7610 
7611 	retval = CTL_RETVAL_COMPLETE;
7612 
7613 	total_len = sizeof(struct scsi_report_timestamp_data);
7614 	alloc_len = scsi_4btoul(cdb->length);
7615 
7616 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7617 	ctsio->kern_sg_entries = 0;
7618 	ctsio->kern_rel_offset = 0;
7619 	ctsio->kern_data_len = min(total_len, alloc_len);
7620 	ctsio->kern_total_len = ctsio->kern_data_len;
7621 
7622 	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7623 	scsi_ulto2b(sizeof(*data) - 2, data->length);
7624 	data->origin = RTS_ORIG_OUTSIDE;
7625 	getmicrotime(&tv);
7626 	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7627 	scsi_ulto4b(timestamp >> 16, data->timestamp);
7628 	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7629 
7630 	ctl_set_success(ctsio);
7631 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7632 	ctsio->be_move_done = ctl_config_move_done;
7633 	ctl_datamove((union ctl_io *)ctsio);
7634 	return (retval);
7635 }
7636 
7637 int
ctl_persistent_reserve_in(struct ctl_scsiio * ctsio)7638 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7639 {
7640 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7641 	struct ctl_lun *lun = CTL_LUN(ctsio);
7642 	struct scsi_per_res_in *cdb;
7643 	int alloc_len, total_len = 0;
7644 	/* struct scsi_per_res_in_rsrv in_data; */
7645 	uint64_t key;
7646 
7647 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7648 
7649 	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7650 
7651 	alloc_len = scsi_2btoul(cdb->length);
7652 
7653 retry:
7654 	mtx_lock(&lun->lun_lock);
7655 	switch (cdb->action) {
7656 	case SPRI_RK: /* read keys */
7657 		total_len = sizeof(struct scsi_per_res_in_keys) +
7658 			lun->pr_key_count *
7659 			sizeof(struct scsi_per_res_key);
7660 		break;
7661 	case SPRI_RR: /* read reservation */
7662 		if (lun->flags & CTL_LUN_PR_RESERVED)
7663 			total_len = sizeof(struct scsi_per_res_in_rsrv);
7664 		else
7665 			total_len = sizeof(struct scsi_per_res_in_header);
7666 		break;
7667 	case SPRI_RC: /* report capabilities */
7668 		total_len = sizeof(struct scsi_per_res_cap);
7669 		break;
7670 	case SPRI_RS: /* read full status */
7671 		total_len = sizeof(struct scsi_per_res_in_header) +
7672 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7673 		    lun->pr_key_count;
7674 		break;
7675 	default:
7676 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7677 	}
7678 	mtx_unlock(&lun->lun_lock);
7679 
7680 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7681 	ctsio->kern_rel_offset = 0;
7682 	ctsio->kern_sg_entries = 0;
7683 	ctsio->kern_data_len = min(total_len, alloc_len);
7684 	ctsio->kern_total_len = ctsio->kern_data_len;
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->pr_generation, 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 < 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 				key_count++;
7729 				continue;
7730 			}
7731 			scsi_u64to8b(key, res_keys->keys[key_count].key);
7732 			key_count++;
7733 		}
7734 		break;
7735 	}
7736 	case SPRI_RR: { // read reservation
7737 		struct scsi_per_res_in_rsrv *res;
7738 		int tmp_len, header_only;
7739 
7740 		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7741 
7742 		scsi_ulto4b(lun->pr_generation, res->header.generation);
7743 
7744 		if (lun->flags & CTL_LUN_PR_RESERVED)
7745 		{
7746 			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7747 			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7748 				    res->header.length);
7749 			header_only = 0;
7750 		} else {
7751 			tmp_len = sizeof(struct scsi_per_res_in_header);
7752 			scsi_ulto4b(0, res->header.length);
7753 			header_only = 1;
7754 		}
7755 
7756 		/*
7757 		 * We had to drop the lock to allocate our buffer, which
7758 		 * leaves time for someone to come in with another
7759 		 * persistent reservation.  (That is unlikely, though,
7760 		 * since this should be the only persistent reservation
7761 		 * command active right now.)
7762 		 */
7763 		if (tmp_len != total_len) {
7764 			mtx_unlock(&lun->lun_lock);
7765 			free(ctsio->kern_data_ptr, M_CTL);
7766 			printf("%s: reservation status changed, retrying\n",
7767 			       __func__);
7768 			goto retry;
7769 		}
7770 
7771 		/*
7772 		 * No reservation held, so we're done.
7773 		 */
7774 		if (header_only != 0)
7775 			break;
7776 
7777 		/*
7778 		 * If the registration is an All Registrants type, the key
7779 		 * is 0, since it doesn't really matter.
7780 		 */
7781 		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7782 			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7783 			    res->data.reservation);
7784 		}
7785 		res->data.scopetype = lun->pr_res_type;
7786 		break;
7787 	}
7788 	case SPRI_RC:     //report capabilities
7789 	{
7790 		struct scsi_per_res_cap *res_cap;
7791 		uint16_t type_mask;
7792 
7793 		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7794 		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7795 		res_cap->flags1 = SPRI_CRH;
7796 		res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7797 		type_mask = SPRI_TM_WR_EX_AR |
7798 			    SPRI_TM_EX_AC_RO |
7799 			    SPRI_TM_WR_EX_RO |
7800 			    SPRI_TM_EX_AC |
7801 			    SPRI_TM_WR_EX |
7802 			    SPRI_TM_EX_AC_AR;
7803 		scsi_ulto2b(type_mask, res_cap->type_mask);
7804 		break;
7805 	}
7806 	case SPRI_RS: { // read full status
7807 		struct scsi_per_res_in_full *res_status;
7808 		struct scsi_per_res_in_full_desc *res_desc;
7809 		struct ctl_port *port;
7810 		int i, len;
7811 
7812 		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7813 
7814 		/*
7815 		 * We had to drop the lock to allocate our buffer, which
7816 		 * leaves time for someone to come in with another
7817 		 * persistent reservation.  (That is unlikely, though,
7818 		 * since this should be the only persistent reservation
7819 		 * command active right now.)
7820 		 */
7821 		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7822 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7823 		     lun->pr_key_count)){
7824 			mtx_unlock(&lun->lun_lock);
7825 			free(ctsio->kern_data_ptr, M_CTL);
7826 			printf("%s: reservation length changed, retrying\n",
7827 			       __func__);
7828 			goto retry;
7829 		}
7830 
7831 		scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7832 
7833 		res_desc = &res_status->desc[0];
7834 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7835 			if ((key = ctl_get_prkey(lun, i)) == 0)
7836 				continue;
7837 
7838 			scsi_u64to8b(key, res_desc->res_key.key);
7839 			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7840 			    (lun->pr_res_idx == i ||
7841 			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7842 				res_desc->flags = SPRI_FULL_R_HOLDER;
7843 				res_desc->scopetype = lun->pr_res_type;
7844 			}
7845 			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7846 			    res_desc->rel_trgt_port_id);
7847 			len = 0;
7848 			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7849 			if (port != NULL)
7850 				len = ctl_create_iid(port,
7851 				    i % CTL_MAX_INIT_PER_PORT,
7852 				    res_desc->transport_id);
7853 			scsi_ulto4b(len, res_desc->additional_length);
7854 			res_desc = (struct scsi_per_res_in_full_desc *)
7855 			    &res_desc->transport_id[len];
7856 		}
7857 		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7858 		    res_status->header.length);
7859 		break;
7860 	}
7861 	default:
7862 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7863 	}
7864 	mtx_unlock(&lun->lun_lock);
7865 
7866 	ctl_set_success(ctsio);
7867 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7868 	ctsio->be_move_done = ctl_config_move_done;
7869 	ctl_datamove((union ctl_io *)ctsio);
7870 	return (CTL_RETVAL_COMPLETE);
7871 }
7872 
7873 /*
7874  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7875  * it should return.
7876  */
7877 static int
ctl_pro_preempt(struct ctl_softc * softc,struct ctl_lun * lun,uint64_t res_key,uint64_t sa_res_key,uint8_t type,uint32_t residx,struct ctl_scsiio * ctsio,struct scsi_per_res_out * cdb,struct scsi_per_res_out_parms * param)7878 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7879 		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7880 		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7881 		struct scsi_per_res_out_parms* param)
7882 {
7883 	union ctl_ha_msg persis_io;
7884 	int i;
7885 
7886 	mtx_lock(&lun->lun_lock);
7887 	if (sa_res_key == 0) {
7888 		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7889 			/* validate scope and type */
7890 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7891 			     SPR_LU_SCOPE) {
7892 				mtx_unlock(&lun->lun_lock);
7893 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7894 						      /*sks_valid*/ 1,
7895 						      /*command*/ 1,
7896 						      /*field*/ 2,
7897 						      /*bit_valid*/ 1,
7898 						      /*bit*/ 4);
7899 				ctl_done((union ctl_io *)ctsio);
7900 				return (1);
7901 			}
7902 
7903 		        if (type>8 || type==2 || type==4 || type==0) {
7904 				mtx_unlock(&lun->lun_lock);
7905 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7906        	           				      /*sks_valid*/ 1,
7907 						      /*command*/ 1,
7908 						      /*field*/ 2,
7909 						      /*bit_valid*/ 1,
7910 						      /*bit*/ 0);
7911 				ctl_done((union ctl_io *)ctsio);
7912 				return (1);
7913 		        }
7914 
7915 			/*
7916 			 * Unregister everybody else and build UA for
7917 			 * them
7918 			 */
7919 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7920 				if (i == residx || ctl_get_prkey(lun, i) == 0)
7921 					continue;
7922 
7923 				ctl_clr_prkey(lun, i);
7924 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7925 			}
7926 			lun->pr_key_count = 1;
7927 			lun->pr_res_type = type;
7928 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7929 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7930 				lun->pr_res_idx = residx;
7931 			lun->pr_generation++;
7932 			mtx_unlock(&lun->lun_lock);
7933 
7934 			/* send msg to other side */
7935 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7936 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7937 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7938 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7939 			persis_io.pr.pr_info.res_type = type;
7940 			memcpy(persis_io.pr.pr_info.sa_res_key,
7941 			       param->serv_act_res_key,
7942 			       sizeof(param->serv_act_res_key));
7943 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7944 			    sizeof(persis_io.pr), M_WAITOK);
7945 		} else {
7946 			/* not all registrants */
7947 			mtx_unlock(&lun->lun_lock);
7948 			free(ctsio->kern_data_ptr, M_CTL);
7949 			ctl_set_invalid_field(ctsio,
7950 					      /*sks_valid*/ 1,
7951 					      /*command*/ 0,
7952 					      /*field*/ 8,
7953 					      /*bit_valid*/ 0,
7954 					      /*bit*/ 0);
7955 			ctl_done((union ctl_io *)ctsio);
7956 			return (1);
7957 		}
7958 	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7959 		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7960 		int found = 0;
7961 
7962 		if (res_key == sa_res_key) {
7963 			/* special case */
7964 			/*
7965 			 * The spec implies this is not good but doesn't
7966 			 * say what to do. There are two choices either
7967 			 * generate a res conflict or check condition
7968 			 * with illegal field in parameter data. Since
7969 			 * that is what is done when the sa_res_key is
7970 			 * zero I'll take that approach since this has
7971 			 * to do with the sa_res_key.
7972 			 */
7973 			mtx_unlock(&lun->lun_lock);
7974 			free(ctsio->kern_data_ptr, M_CTL);
7975 			ctl_set_invalid_field(ctsio,
7976 					      /*sks_valid*/ 1,
7977 					      /*command*/ 0,
7978 					      /*field*/ 8,
7979 					      /*bit_valid*/ 0,
7980 					      /*bit*/ 0);
7981 			ctl_done((union ctl_io *)ctsio);
7982 			return (1);
7983 		}
7984 
7985 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7986 			if (ctl_get_prkey(lun, i) != sa_res_key)
7987 				continue;
7988 
7989 			found = 1;
7990 			ctl_clr_prkey(lun, i);
7991 			lun->pr_key_count--;
7992 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7993 		}
7994 		if (!found) {
7995 			mtx_unlock(&lun->lun_lock);
7996 			free(ctsio->kern_data_ptr, M_CTL);
7997 			ctl_set_reservation_conflict(ctsio);
7998 			ctl_done((union ctl_io *)ctsio);
7999 			return (CTL_RETVAL_COMPLETE);
8000 		}
8001 		lun->pr_generation++;
8002 		mtx_unlock(&lun->lun_lock);
8003 
8004 		/* send msg to other side */
8005 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8006 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8007 		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8008 		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8009 		persis_io.pr.pr_info.res_type = type;
8010 		memcpy(persis_io.pr.pr_info.sa_res_key,
8011 		       param->serv_act_res_key,
8012 		       sizeof(param->serv_act_res_key));
8013 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8014 		    sizeof(persis_io.pr), M_WAITOK);
8015 	} else {
8016 		/* Reserved but not all registrants */
8017 		/* sa_res_key is res holder */
8018 		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8019 			/* validate scope and type */
8020 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8021 			     SPR_LU_SCOPE) {
8022 				mtx_unlock(&lun->lun_lock);
8023 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8024 						      /*sks_valid*/ 1,
8025 						      /*command*/ 1,
8026 						      /*field*/ 2,
8027 						      /*bit_valid*/ 1,
8028 						      /*bit*/ 4);
8029 				ctl_done((union ctl_io *)ctsio);
8030 				return (1);
8031 			}
8032 
8033 			if (type>8 || type==2 || type==4 || type==0) {
8034 				mtx_unlock(&lun->lun_lock);
8035 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8036 						      /*sks_valid*/ 1,
8037 						      /*command*/ 1,
8038 						      /*field*/ 2,
8039 						      /*bit_valid*/ 1,
8040 						      /*bit*/ 0);
8041 				ctl_done((union ctl_io *)ctsio);
8042 				return (1);
8043 			}
8044 
8045 			/*
8046 			 * Do the following:
8047 			 * if sa_res_key != res_key remove all
8048 			 * registrants w/sa_res_key and generate UA
8049 			 * for these registrants(Registrations
8050 			 * Preempted) if it wasn't an exclusive
8051 			 * reservation generate UA(Reservations
8052 			 * Preempted) for all other registered nexuses
8053 			 * if the type has changed. Establish the new
8054 			 * reservation and holder. If res_key and
8055 			 * sa_res_key are the same do the above
8056 			 * except don't unregister the res holder.
8057 			 */
8058 
8059 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8060 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8061 					continue;
8062 
8063 				if (sa_res_key == ctl_get_prkey(lun, i)) {
8064 					ctl_clr_prkey(lun, i);
8065 					lun->pr_key_count--;
8066 					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8067 				} else if (type != lun->pr_res_type &&
8068 				    (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8069 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8070 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8071 				}
8072 			}
8073 			lun->pr_res_type = type;
8074 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8075 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8076 				lun->pr_res_idx = residx;
8077 			else
8078 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8079 			lun->pr_generation++;
8080 			mtx_unlock(&lun->lun_lock);
8081 
8082 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8083 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8084 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8085 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8086 			persis_io.pr.pr_info.res_type = type;
8087 			memcpy(persis_io.pr.pr_info.sa_res_key,
8088 			       param->serv_act_res_key,
8089 			       sizeof(param->serv_act_res_key));
8090 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8091 			    sizeof(persis_io.pr), M_WAITOK);
8092 		} else {
8093 			/*
8094 			 * sa_res_key is not the res holder just
8095 			 * remove registrants
8096 			 */
8097 			int found=0;
8098 
8099 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8100 				if (sa_res_key != ctl_get_prkey(lun, i))
8101 					continue;
8102 
8103 				found = 1;
8104 				ctl_clr_prkey(lun, i);
8105 				lun->pr_key_count--;
8106 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8107 			}
8108 
8109 			if (!found) {
8110 				mtx_unlock(&lun->lun_lock);
8111 				free(ctsio->kern_data_ptr, M_CTL);
8112 				ctl_set_reservation_conflict(ctsio);
8113 				ctl_done((union ctl_io *)ctsio);
8114 		        	return (1);
8115 			}
8116 			lun->pr_generation++;
8117 			mtx_unlock(&lun->lun_lock);
8118 
8119 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8120 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8121 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8122 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8123 			persis_io.pr.pr_info.res_type = type;
8124 			memcpy(persis_io.pr.pr_info.sa_res_key,
8125 			       param->serv_act_res_key,
8126 			       sizeof(param->serv_act_res_key));
8127 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8128 			    sizeof(persis_io.pr), M_WAITOK);
8129 		}
8130 	}
8131 	return (0);
8132 }
8133 
8134 static void
ctl_pro_preempt_other(struct ctl_lun * lun,union ctl_ha_msg * msg)8135 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8136 {
8137 	uint64_t sa_res_key;
8138 	int i;
8139 
8140 	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8141 
8142 	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8143 	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8144 	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8145 		if (sa_res_key == 0) {
8146 			/*
8147 			 * Unregister everybody else and build UA for
8148 			 * them
8149 			 */
8150 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8151 				if (i == msg->pr.pr_info.residx ||
8152 				    ctl_get_prkey(lun, i) == 0)
8153 					continue;
8154 
8155 				ctl_clr_prkey(lun, i);
8156 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8157 			}
8158 
8159 			lun->pr_key_count = 1;
8160 			lun->pr_res_type = msg->pr.pr_info.res_type;
8161 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8162 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8163 				lun->pr_res_idx = msg->pr.pr_info.residx;
8164 		} else {
8165 		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8166 				if (sa_res_key == ctl_get_prkey(lun, i))
8167 					continue;
8168 
8169 				ctl_clr_prkey(lun, i);
8170 				lun->pr_key_count--;
8171 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8172 			}
8173 		}
8174 	} else {
8175 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8176 			if (i == msg->pr.pr_info.residx ||
8177 			    ctl_get_prkey(lun, i) == 0)
8178 				continue;
8179 
8180 			if (sa_res_key == ctl_get_prkey(lun, i)) {
8181 				ctl_clr_prkey(lun, i);
8182 				lun->pr_key_count--;
8183 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8184 			} else if (msg->pr.pr_info.res_type != lun->pr_res_type
8185 			    && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8186 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8187 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8188 			}
8189 		}
8190 		lun->pr_res_type = msg->pr.pr_info.res_type;
8191 		if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8192 		    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8193 			lun->pr_res_idx = msg->pr.pr_info.residx;
8194 		else
8195 			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8196 	}
8197 	lun->pr_generation++;
8198 
8199 }
8200 
8201 
8202 int
ctl_persistent_reserve_out(struct ctl_scsiio * ctsio)8203 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8204 {
8205 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
8206 	struct ctl_lun *lun = CTL_LUN(ctsio);
8207 	int retval;
8208 	u_int32_t param_len;
8209 	struct scsi_per_res_out *cdb;
8210 	struct scsi_per_res_out_parms* param;
8211 	uint32_t residx;
8212 	uint64_t res_key, sa_res_key, key;
8213 	uint8_t type;
8214 	union ctl_ha_msg persis_io;
8215 	int    i;
8216 
8217 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8218 
8219 	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8220 	retval = CTL_RETVAL_COMPLETE;
8221 
8222 	/*
8223 	 * We only support whole-LUN scope.  The scope & type are ignored for
8224 	 * register, register and ignore existing key and clear.
8225 	 * We sometimes ignore scope and type on preempts too!!
8226 	 * Verify reservation type here as well.
8227 	 */
8228 	type = cdb->scope_type & SPR_TYPE_MASK;
8229 	if ((cdb->action == SPRO_RESERVE)
8230 	 || (cdb->action == SPRO_RELEASE)) {
8231 		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8232 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8233 					      /*sks_valid*/ 1,
8234 					      /*command*/ 1,
8235 					      /*field*/ 2,
8236 					      /*bit_valid*/ 1,
8237 					      /*bit*/ 4);
8238 			ctl_done((union ctl_io *)ctsio);
8239 			return (CTL_RETVAL_COMPLETE);
8240 		}
8241 
8242 		if (type>8 || type==2 || type==4 || type==0) {
8243 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8244 					      /*sks_valid*/ 1,
8245 					      /*command*/ 1,
8246 					      /*field*/ 2,
8247 					      /*bit_valid*/ 1,
8248 					      /*bit*/ 0);
8249 			ctl_done((union ctl_io *)ctsio);
8250 			return (CTL_RETVAL_COMPLETE);
8251 		}
8252 	}
8253 
8254 	param_len = scsi_4btoul(cdb->length);
8255 
8256 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8257 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8258 		ctsio->kern_data_len = param_len;
8259 		ctsio->kern_total_len = param_len;
8260 		ctsio->kern_rel_offset = 0;
8261 		ctsio->kern_sg_entries = 0;
8262 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8263 		ctsio->be_move_done = ctl_config_move_done;
8264 		ctl_datamove((union ctl_io *)ctsio);
8265 
8266 		return (CTL_RETVAL_COMPLETE);
8267 	}
8268 
8269 	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8270 
8271 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8272 	res_key = scsi_8btou64(param->res_key.key);
8273 	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8274 
8275 	/*
8276 	 * Validate the reservation key here except for SPRO_REG_IGNO
8277 	 * This must be done for all other service actions
8278 	 */
8279 	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8280 		mtx_lock(&lun->lun_lock);
8281 		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8282 			if (res_key != key) {
8283 				/*
8284 				 * The current key passed in doesn't match
8285 				 * the one the initiator previously
8286 				 * registered.
8287 				 */
8288 				mtx_unlock(&lun->lun_lock);
8289 				free(ctsio->kern_data_ptr, M_CTL);
8290 				ctl_set_reservation_conflict(ctsio);
8291 				ctl_done((union ctl_io *)ctsio);
8292 				return (CTL_RETVAL_COMPLETE);
8293 			}
8294 		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8295 			/*
8296 			 * We are not registered
8297 			 */
8298 			mtx_unlock(&lun->lun_lock);
8299 			free(ctsio->kern_data_ptr, M_CTL);
8300 			ctl_set_reservation_conflict(ctsio);
8301 			ctl_done((union ctl_io *)ctsio);
8302 			return (CTL_RETVAL_COMPLETE);
8303 		} else if (res_key != 0) {
8304 			/*
8305 			 * We are not registered and trying to register but
8306 			 * the register key isn't zero.
8307 			 */
8308 			mtx_unlock(&lun->lun_lock);
8309 			free(ctsio->kern_data_ptr, M_CTL);
8310 			ctl_set_reservation_conflict(ctsio);
8311 			ctl_done((union ctl_io *)ctsio);
8312 			return (CTL_RETVAL_COMPLETE);
8313 		}
8314 		mtx_unlock(&lun->lun_lock);
8315 	}
8316 
8317 	switch (cdb->action & SPRO_ACTION_MASK) {
8318 	case SPRO_REGISTER:
8319 	case SPRO_REG_IGNO: {
8320 
8321 		/*
8322 		 * We don't support any of these options, as we report in
8323 		 * the read capabilities request (see
8324 		 * ctl_persistent_reserve_in(), above).
8325 		 */
8326 		if ((param->flags & SPR_SPEC_I_PT)
8327 		 || (param->flags & SPR_ALL_TG_PT)
8328 		 || (param->flags & SPR_APTPL)) {
8329 			int bit_ptr;
8330 
8331 			if (param->flags & SPR_APTPL)
8332 				bit_ptr = 0;
8333 			else if (param->flags & SPR_ALL_TG_PT)
8334 				bit_ptr = 2;
8335 			else /* SPR_SPEC_I_PT */
8336 				bit_ptr = 3;
8337 
8338 			free(ctsio->kern_data_ptr, M_CTL);
8339 			ctl_set_invalid_field(ctsio,
8340 					      /*sks_valid*/ 1,
8341 					      /*command*/ 0,
8342 					      /*field*/ 20,
8343 					      /*bit_valid*/ 1,
8344 					      /*bit*/ bit_ptr);
8345 			ctl_done((union ctl_io *)ctsio);
8346 			return (CTL_RETVAL_COMPLETE);
8347 		}
8348 
8349 		mtx_lock(&lun->lun_lock);
8350 
8351 		/*
8352 		 * The initiator wants to clear the
8353 		 * key/unregister.
8354 		 */
8355 		if (sa_res_key == 0) {
8356 			if ((res_key == 0
8357 			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8358 			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8359 			  && ctl_get_prkey(lun, residx) == 0)) {
8360 				mtx_unlock(&lun->lun_lock);
8361 				goto done;
8362 			}
8363 
8364 			ctl_clr_prkey(lun, residx);
8365 			lun->pr_key_count--;
8366 
8367 			if (residx == lun->pr_res_idx) {
8368 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8369 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8370 
8371 				if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8372 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8373 				    lun->pr_key_count) {
8374 					/*
8375 					 * If the reservation is a registrants
8376 					 * only type we need to generate a UA
8377 					 * for other registered inits.  The
8378 					 * sense code should be RESERVATIONS
8379 					 * RELEASED
8380 					 */
8381 
8382 					for (i = softc->init_min; i < softc->init_max; i++){
8383 						if (ctl_get_prkey(lun, i) == 0)
8384 							continue;
8385 						ctl_est_ua(lun, i,
8386 						    CTL_UA_RES_RELEASE);
8387 					}
8388 				}
8389 				lun->pr_res_type = 0;
8390 			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8391 				if (lun->pr_key_count==0) {
8392 					lun->flags &= ~CTL_LUN_PR_RESERVED;
8393 					lun->pr_res_type = 0;
8394 					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8395 				}
8396 			}
8397 			lun->pr_generation++;
8398 			mtx_unlock(&lun->lun_lock);
8399 
8400 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8401 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8402 			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8403 			persis_io.pr.pr_info.residx = residx;
8404 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8405 			    sizeof(persis_io.pr), M_WAITOK);
8406 		} else /* sa_res_key != 0 */ {
8407 
8408 			/*
8409 			 * If we aren't registered currently then increment
8410 			 * the key count and set the registered flag.
8411 			 */
8412 			ctl_alloc_prkey(lun, residx);
8413 			if (ctl_get_prkey(lun, residx) == 0)
8414 				lun->pr_key_count++;
8415 			ctl_set_prkey(lun, residx, sa_res_key);
8416 			lun->pr_generation++;
8417 			mtx_unlock(&lun->lun_lock);
8418 
8419 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8420 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8421 			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8422 			persis_io.pr.pr_info.residx = residx;
8423 			memcpy(persis_io.pr.pr_info.sa_res_key,
8424 			       param->serv_act_res_key,
8425 			       sizeof(param->serv_act_res_key));
8426 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8427 			    sizeof(persis_io.pr), M_WAITOK);
8428 		}
8429 
8430 		break;
8431 	}
8432 	case SPRO_RESERVE:
8433 		mtx_lock(&lun->lun_lock);
8434 		if (lun->flags & CTL_LUN_PR_RESERVED) {
8435 			/*
8436 			 * if this isn't the reservation holder and it's
8437 			 * not a "all registrants" type or if the type is
8438 			 * different then we have a conflict
8439 			 */
8440 			if ((lun->pr_res_idx != residx
8441 			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8442 			 || lun->pr_res_type != type) {
8443 				mtx_unlock(&lun->lun_lock);
8444 				free(ctsio->kern_data_ptr, M_CTL);
8445 				ctl_set_reservation_conflict(ctsio);
8446 				ctl_done((union ctl_io *)ctsio);
8447 				return (CTL_RETVAL_COMPLETE);
8448 			}
8449 			mtx_unlock(&lun->lun_lock);
8450 		} else /* create a reservation */ {
8451 			/*
8452 			 * If it's not an "all registrants" type record
8453 			 * reservation holder
8454 			 */
8455 			if (type != SPR_TYPE_WR_EX_AR
8456 			 && type != SPR_TYPE_EX_AC_AR)
8457 				lun->pr_res_idx = residx; /* Res holder */
8458 			else
8459 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8460 
8461 			lun->flags |= CTL_LUN_PR_RESERVED;
8462 			lun->pr_res_type = type;
8463 
8464 			mtx_unlock(&lun->lun_lock);
8465 
8466 			/* send msg to other side */
8467 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8468 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8469 			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8470 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8471 			persis_io.pr.pr_info.res_type = type;
8472 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8473 			    sizeof(persis_io.pr), M_WAITOK);
8474 		}
8475 		break;
8476 
8477 	case SPRO_RELEASE:
8478 		mtx_lock(&lun->lun_lock);
8479 		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8480 			/* No reservation exists return good status */
8481 			mtx_unlock(&lun->lun_lock);
8482 			goto done;
8483 		}
8484 		/*
8485 		 * Is this nexus a reservation holder?
8486 		 */
8487 		if (lun->pr_res_idx != residx
8488 		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8489 			/*
8490 			 * not a res holder return good status but
8491 			 * do nothing
8492 			 */
8493 			mtx_unlock(&lun->lun_lock);
8494 			goto done;
8495 		}
8496 
8497 		if (lun->pr_res_type != type) {
8498 			mtx_unlock(&lun->lun_lock);
8499 			free(ctsio->kern_data_ptr, M_CTL);
8500 			ctl_set_illegal_pr_release(ctsio);
8501 			ctl_done((union ctl_io *)ctsio);
8502 			return (CTL_RETVAL_COMPLETE);
8503 		}
8504 
8505 		/* okay to release */
8506 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8507 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8508 		lun->pr_res_type = 0;
8509 
8510 		/*
8511 		 * If this isn't an exclusive access reservation and NUAR
8512 		 * is not set, generate UA for all other registrants.
8513 		 */
8514 		if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8515 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8516 			for (i = softc->init_min; i < softc->init_max; i++) {
8517 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8518 					continue;
8519 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8520 			}
8521 		}
8522 		mtx_unlock(&lun->lun_lock);
8523 
8524 		/* Send msg to other side */
8525 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8526 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8527 		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8528 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8529 		     sizeof(persis_io.pr), M_WAITOK);
8530 		break;
8531 
8532 	case SPRO_CLEAR:
8533 		/* send msg to other side */
8534 
8535 		mtx_lock(&lun->lun_lock);
8536 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8537 		lun->pr_res_type = 0;
8538 		lun->pr_key_count = 0;
8539 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8540 
8541 		ctl_clr_prkey(lun, residx);
8542 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8543 			if (ctl_get_prkey(lun, i) != 0) {
8544 				ctl_clr_prkey(lun, i);
8545 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8546 			}
8547 		lun->pr_generation++;
8548 		mtx_unlock(&lun->lun_lock);
8549 
8550 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8551 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8552 		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8553 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8554 		     sizeof(persis_io.pr), M_WAITOK);
8555 		break;
8556 
8557 	case SPRO_PREEMPT:
8558 	case SPRO_PRE_ABO: {
8559 		int nretval;
8560 
8561 		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8562 					  residx, ctsio, cdb, param);
8563 		if (nretval != 0)
8564 			return (CTL_RETVAL_COMPLETE);
8565 		break;
8566 	}
8567 	default:
8568 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
8569 	}
8570 
8571 done:
8572 	free(ctsio->kern_data_ptr, M_CTL);
8573 	ctl_set_success(ctsio);
8574 	ctl_done((union ctl_io *)ctsio);
8575 
8576 	return (retval);
8577 }
8578 
8579 /*
8580  * This routine is for handling a message from the other SC pertaining to
8581  * persistent reserve out. All the error checking will have been done
8582  * so only performing the action need be done here to keep the two
8583  * in sync.
8584  */
8585 static void
ctl_hndl_per_res_out_on_other_sc(union ctl_io * io)8586 ctl_hndl_per_res_out_on_other_sc(union ctl_io *io)
8587 {
8588 	struct ctl_softc *softc = CTL_SOFTC(io);
8589 	union ctl_ha_msg *msg = (union ctl_ha_msg *)&io->presio.pr_msg;
8590 	struct ctl_lun *lun;
8591 	int i;
8592 	uint32_t residx, targ_lun;
8593 
8594 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8595 	mtx_lock(&softc->ctl_lock);
8596 	if (targ_lun >= ctl_max_luns ||
8597 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
8598 		mtx_unlock(&softc->ctl_lock);
8599 		return;
8600 	}
8601 	mtx_lock(&lun->lun_lock);
8602 	mtx_unlock(&softc->ctl_lock);
8603 	if (lun->flags & CTL_LUN_DISABLED) {
8604 		mtx_unlock(&lun->lun_lock);
8605 		return;
8606 	}
8607 	residx = ctl_get_initindex(&msg->hdr.nexus);
8608 	switch(msg->pr.pr_info.action) {
8609 	case CTL_PR_REG_KEY:
8610 		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8611 		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8612 			lun->pr_key_count++;
8613 		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8614 		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8615 		lun->pr_generation++;
8616 		break;
8617 
8618 	case CTL_PR_UNREG_KEY:
8619 		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8620 		lun->pr_key_count--;
8621 
8622 		/* XXX Need to see if the reservation has been released */
8623 		/* if so do we need to generate UA? */
8624 		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8625 			lun->flags &= ~CTL_LUN_PR_RESERVED;
8626 			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8627 
8628 			if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8629 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8630 			    lun->pr_key_count) {
8631 				/*
8632 				 * If the reservation is a registrants
8633 				 * only type we need to generate a UA
8634 				 * for other registered inits.  The
8635 				 * sense code should be RESERVATIONS
8636 				 * RELEASED
8637 				 */
8638 
8639 				for (i = softc->init_min; i < softc->init_max; i++) {
8640 					if (ctl_get_prkey(lun, i) == 0)
8641 						continue;
8642 
8643 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8644 				}
8645 			}
8646 			lun->pr_res_type = 0;
8647 		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8648 			if (lun->pr_key_count==0) {
8649 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8650 				lun->pr_res_type = 0;
8651 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8652 			}
8653 		}
8654 		lun->pr_generation++;
8655 		break;
8656 
8657 	case CTL_PR_RESERVE:
8658 		lun->flags |= CTL_LUN_PR_RESERVED;
8659 		lun->pr_res_type = msg->pr.pr_info.res_type;
8660 		lun->pr_res_idx = msg->pr.pr_info.residx;
8661 
8662 		break;
8663 
8664 	case CTL_PR_RELEASE:
8665 		/*
8666 		 * If this isn't an exclusive access reservation and NUAR
8667 		 * is not set, generate UA for all other registrants.
8668 		 */
8669 		if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8670 		    lun->pr_res_type != SPR_TYPE_WR_EX &&
8671 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8672 			for (i = softc->init_min; i < softc->init_max; i++) {
8673 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8674 					continue;
8675 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8676 			}
8677 		}
8678 
8679 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8680 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8681 		lun->pr_res_type = 0;
8682 		break;
8683 
8684 	case CTL_PR_PREEMPT:
8685 		ctl_pro_preempt_other(lun, msg);
8686 		break;
8687 	case CTL_PR_CLEAR:
8688 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8689 		lun->pr_res_type = 0;
8690 		lun->pr_key_count = 0;
8691 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8692 
8693 		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8694 			if (ctl_get_prkey(lun, i) == 0)
8695 				continue;
8696 			ctl_clr_prkey(lun, i);
8697 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8698 		}
8699 		lun->pr_generation++;
8700 		break;
8701 	}
8702 
8703 	mtx_unlock(&lun->lun_lock);
8704 }
8705 
8706 int
ctl_read_write(struct ctl_scsiio * ctsio)8707 ctl_read_write(struct ctl_scsiio *ctsio)
8708 {
8709 	struct ctl_lun *lun = CTL_LUN(ctsio);
8710 	struct ctl_lba_len_flags *lbalen;
8711 	uint64_t lba;
8712 	uint32_t num_blocks;
8713 	int flags, retval;
8714 	int isread;
8715 
8716 	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8717 
8718 	flags = 0;
8719 	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8720 	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8721 	switch (ctsio->cdb[0]) {
8722 	case READ_6:
8723 	case WRITE_6: {
8724 		struct scsi_rw_6 *cdb;
8725 
8726 		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8727 
8728 		lba = scsi_3btoul(cdb->addr);
8729 		/* only 5 bits are valid in the most significant address byte */
8730 		lba &= 0x1fffff;
8731 		num_blocks = cdb->length;
8732 		/*
8733 		 * This is correct according to SBC-2.
8734 		 */
8735 		if (num_blocks == 0)
8736 			num_blocks = 256;
8737 		break;
8738 	}
8739 	case READ_10:
8740 	case WRITE_10: {
8741 		struct scsi_rw_10 *cdb;
8742 
8743 		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8744 		if (cdb->byte2 & SRW10_FUA)
8745 			flags |= CTL_LLF_FUA;
8746 		if (cdb->byte2 & SRW10_DPO)
8747 			flags |= CTL_LLF_DPO;
8748 		lba = scsi_4btoul(cdb->addr);
8749 		num_blocks = scsi_2btoul(cdb->length);
8750 		break;
8751 	}
8752 	case WRITE_VERIFY_10: {
8753 		struct scsi_write_verify_10 *cdb;
8754 
8755 		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8756 		flags |= CTL_LLF_FUA;
8757 		if (cdb->byte2 & SWV_DPO)
8758 			flags |= CTL_LLF_DPO;
8759 		lba = scsi_4btoul(cdb->addr);
8760 		num_blocks = scsi_2btoul(cdb->length);
8761 		break;
8762 	}
8763 	case READ_12:
8764 	case WRITE_12: {
8765 		struct scsi_rw_12 *cdb;
8766 
8767 		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8768 		if (cdb->byte2 & SRW12_FUA)
8769 			flags |= CTL_LLF_FUA;
8770 		if (cdb->byte2 & SRW12_DPO)
8771 			flags |= CTL_LLF_DPO;
8772 		lba = scsi_4btoul(cdb->addr);
8773 		num_blocks = scsi_4btoul(cdb->length);
8774 		break;
8775 	}
8776 	case WRITE_VERIFY_12: {
8777 		struct scsi_write_verify_12 *cdb;
8778 
8779 		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8780 		flags |= CTL_LLF_FUA;
8781 		if (cdb->byte2 & SWV_DPO)
8782 			flags |= CTL_LLF_DPO;
8783 		lba = scsi_4btoul(cdb->addr);
8784 		num_blocks = scsi_4btoul(cdb->length);
8785 		break;
8786 	}
8787 	case READ_16:
8788 	case WRITE_16: {
8789 		struct scsi_rw_16 *cdb;
8790 
8791 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8792 		if (cdb->byte2 & SRW12_FUA)
8793 			flags |= CTL_LLF_FUA;
8794 		if (cdb->byte2 & SRW12_DPO)
8795 			flags |= CTL_LLF_DPO;
8796 		lba = scsi_8btou64(cdb->addr);
8797 		num_blocks = scsi_4btoul(cdb->length);
8798 		break;
8799 	}
8800 	case WRITE_ATOMIC_16: {
8801 		struct scsi_write_atomic_16 *cdb;
8802 
8803 		if (lun->be_lun->atomicblock == 0) {
8804 			ctl_set_invalid_opcode(ctsio);
8805 			ctl_done((union ctl_io *)ctsio);
8806 			return (CTL_RETVAL_COMPLETE);
8807 		}
8808 
8809 		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8810 		if (cdb->byte2 & SRW12_FUA)
8811 			flags |= CTL_LLF_FUA;
8812 		if (cdb->byte2 & SRW12_DPO)
8813 			flags |= CTL_LLF_DPO;
8814 		lba = scsi_8btou64(cdb->addr);
8815 		num_blocks = scsi_2btoul(cdb->length);
8816 		if (num_blocks > lun->be_lun->atomicblock) {
8817 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8818 			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8819 			    /*bit*/ 0);
8820 			ctl_done((union ctl_io *)ctsio);
8821 			return (CTL_RETVAL_COMPLETE);
8822 		}
8823 		break;
8824 	}
8825 	case WRITE_VERIFY_16: {
8826 		struct scsi_write_verify_16 *cdb;
8827 
8828 		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8829 		flags |= CTL_LLF_FUA;
8830 		if (cdb->byte2 & SWV_DPO)
8831 			flags |= CTL_LLF_DPO;
8832 		lba = scsi_8btou64(cdb->addr);
8833 		num_blocks = scsi_4btoul(cdb->length);
8834 		break;
8835 	}
8836 	default:
8837 		/*
8838 		 * We got a command we don't support.  This shouldn't
8839 		 * happen, commands should be filtered out above us.
8840 		 */
8841 		ctl_set_invalid_opcode(ctsio);
8842 		ctl_done((union ctl_io *)ctsio);
8843 
8844 		return (CTL_RETVAL_COMPLETE);
8845 		break; /* NOTREACHED */
8846 	}
8847 
8848 	/*
8849 	 * The first check is to make sure we're in bounds, the second
8850 	 * check is to catch wrap-around problems.  If the lba + num blocks
8851 	 * is less than the lba, then we've wrapped around and the block
8852 	 * range is invalid anyway.
8853 	 */
8854 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8855 	 || ((lba + num_blocks) < lba)) {
8856 		ctl_set_lba_out_of_range(ctsio,
8857 		    MAX(lba, lun->be_lun->maxlba + 1));
8858 		ctl_done((union ctl_io *)ctsio);
8859 		return (CTL_RETVAL_COMPLETE);
8860 	}
8861 
8862 	/*
8863 	 * According to SBC-3, a transfer length of 0 is not an error.
8864 	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8865 	 * translates to 256 blocks for those commands.
8866 	 */
8867 	if (num_blocks == 0) {
8868 		ctl_set_success(ctsio);
8869 		ctl_done((union ctl_io *)ctsio);
8870 		return (CTL_RETVAL_COMPLETE);
8871 	}
8872 
8873 	/* Set FUA and/or DPO if caches are disabled. */
8874 	if (isread) {
8875 		if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8876 			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8877 	} else {
8878 		if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8879 			flags |= CTL_LLF_FUA;
8880 	}
8881 
8882 	lbalen = (struct ctl_lba_len_flags *)
8883 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8884 	lbalen->lba = lba;
8885 	lbalen->len = num_blocks;
8886 	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8887 
8888 	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8889 	ctsio->kern_rel_offset = 0;
8890 
8891 	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8892 
8893 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8894 	return (retval);
8895 }
8896 
8897 static int
ctl_cnw_cont(union ctl_io * io)8898 ctl_cnw_cont(union ctl_io *io)
8899 {
8900 	struct ctl_lun *lun = CTL_LUN(io);
8901 	struct ctl_scsiio *ctsio;
8902 	struct ctl_lba_len_flags *lbalen;
8903 	int retval;
8904 
8905 	ctsio = &io->scsiio;
8906 	ctsio->io_hdr.status = CTL_STATUS_NONE;
8907 	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8908 	lbalen = (struct ctl_lba_len_flags *)
8909 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8910 	lbalen->flags &= ~CTL_LLF_COMPARE;
8911 	lbalen->flags |= CTL_LLF_WRITE;
8912 
8913 	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8914 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8915 	return (retval);
8916 }
8917 
8918 int
ctl_cnw(struct ctl_scsiio * ctsio)8919 ctl_cnw(struct ctl_scsiio *ctsio)
8920 {
8921 	struct ctl_lun *lun = CTL_LUN(ctsio);
8922 	struct ctl_lba_len_flags *lbalen;
8923 	uint64_t lba;
8924 	uint32_t num_blocks;
8925 	int flags, retval;
8926 
8927 	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8928 
8929 	flags = 0;
8930 	switch (ctsio->cdb[0]) {
8931 	case COMPARE_AND_WRITE: {
8932 		struct scsi_compare_and_write *cdb;
8933 
8934 		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8935 		if (cdb->byte2 & SRW10_FUA)
8936 			flags |= CTL_LLF_FUA;
8937 		if (cdb->byte2 & SRW10_DPO)
8938 			flags |= CTL_LLF_DPO;
8939 		lba = scsi_8btou64(cdb->addr);
8940 		num_blocks = cdb->length;
8941 		break;
8942 	}
8943 	default:
8944 		/*
8945 		 * We got a command we don't support.  This shouldn't
8946 		 * happen, commands should be filtered out above us.
8947 		 */
8948 		ctl_set_invalid_opcode(ctsio);
8949 		ctl_done((union ctl_io *)ctsio);
8950 
8951 		return (CTL_RETVAL_COMPLETE);
8952 		break; /* NOTREACHED */
8953 	}
8954 
8955 	/*
8956 	 * The first check is to make sure we're in bounds, the second
8957 	 * check is to catch wrap-around problems.  If the lba + num blocks
8958 	 * is less than the lba, then we've wrapped around and the block
8959 	 * range is invalid anyway.
8960 	 */
8961 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8962 	 || ((lba + num_blocks) < lba)) {
8963 		ctl_set_lba_out_of_range(ctsio,
8964 		    MAX(lba, lun->be_lun->maxlba + 1));
8965 		ctl_done((union ctl_io *)ctsio);
8966 		return (CTL_RETVAL_COMPLETE);
8967 	}
8968 
8969 	/*
8970 	 * According to SBC-3, a transfer length of 0 is not an error.
8971 	 */
8972 	if (num_blocks == 0) {
8973 		ctl_set_success(ctsio);
8974 		ctl_done((union ctl_io *)ctsio);
8975 		return (CTL_RETVAL_COMPLETE);
8976 	}
8977 
8978 	/* Set FUA if write cache is disabled. */
8979 	if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8980 		flags |= CTL_LLF_FUA;
8981 
8982 	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8983 	ctsio->kern_rel_offset = 0;
8984 
8985 	/*
8986 	 * Set the IO_CONT flag, so that if this I/O gets passed to
8987 	 * ctl_data_submit_done(), it'll get passed back to
8988 	 * ctl_ctl_cnw_cont() for further processing.
8989 	 */
8990 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8991 	ctsio->io_cont = ctl_cnw_cont;
8992 
8993 	lbalen = (struct ctl_lba_len_flags *)
8994 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8995 	lbalen->lba = lba;
8996 	lbalen->len = num_blocks;
8997 	lbalen->flags = CTL_LLF_COMPARE | flags;
8998 
8999 	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9000 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9001 	return (retval);
9002 }
9003 
9004 int
ctl_verify(struct ctl_scsiio * ctsio)9005 ctl_verify(struct ctl_scsiio *ctsio)
9006 {
9007 	struct ctl_lun *lun = CTL_LUN(ctsio);
9008 	struct ctl_lba_len_flags *lbalen;
9009 	uint64_t lba;
9010 	uint32_t num_blocks;
9011 	int bytchk, flags;
9012 	int retval;
9013 
9014 	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9015 
9016 	bytchk = 0;
9017 	flags = CTL_LLF_FUA;
9018 	switch (ctsio->cdb[0]) {
9019 	case VERIFY_10: {
9020 		struct scsi_verify_10 *cdb;
9021 
9022 		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9023 		if (cdb->byte2 & SVFY_BYTCHK)
9024 			bytchk = 1;
9025 		if (cdb->byte2 & SVFY_DPO)
9026 			flags |= CTL_LLF_DPO;
9027 		lba = scsi_4btoul(cdb->addr);
9028 		num_blocks = scsi_2btoul(cdb->length);
9029 		break;
9030 	}
9031 	case VERIFY_12: {
9032 		struct scsi_verify_12 *cdb;
9033 
9034 		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9035 		if (cdb->byte2 & SVFY_BYTCHK)
9036 			bytchk = 1;
9037 		if (cdb->byte2 & SVFY_DPO)
9038 			flags |= CTL_LLF_DPO;
9039 		lba = scsi_4btoul(cdb->addr);
9040 		num_blocks = scsi_4btoul(cdb->length);
9041 		break;
9042 	}
9043 	case VERIFY_16: {
9044 		struct scsi_rw_16 *cdb;
9045 
9046 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9047 		if (cdb->byte2 & SVFY_BYTCHK)
9048 			bytchk = 1;
9049 		if (cdb->byte2 & SVFY_DPO)
9050 			flags |= CTL_LLF_DPO;
9051 		lba = scsi_8btou64(cdb->addr);
9052 		num_blocks = scsi_4btoul(cdb->length);
9053 		break;
9054 	}
9055 	default:
9056 		/*
9057 		 * We got a command we don't support.  This shouldn't
9058 		 * happen, commands should be filtered out above us.
9059 		 */
9060 		ctl_set_invalid_opcode(ctsio);
9061 		ctl_done((union ctl_io *)ctsio);
9062 		return (CTL_RETVAL_COMPLETE);
9063 	}
9064 
9065 	/*
9066 	 * The first check is to make sure we're in bounds, the second
9067 	 * check is to catch wrap-around problems.  If the lba + num blocks
9068 	 * is less than the lba, then we've wrapped around and the block
9069 	 * range is invalid anyway.
9070 	 */
9071 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9072 	 || ((lba + num_blocks) < lba)) {
9073 		ctl_set_lba_out_of_range(ctsio,
9074 		    MAX(lba, lun->be_lun->maxlba + 1));
9075 		ctl_done((union ctl_io *)ctsio);
9076 		return (CTL_RETVAL_COMPLETE);
9077 	}
9078 
9079 	/*
9080 	 * According to SBC-3, a transfer length of 0 is not an error.
9081 	 */
9082 	if (num_blocks == 0) {
9083 		ctl_set_success(ctsio);
9084 		ctl_done((union ctl_io *)ctsio);
9085 		return (CTL_RETVAL_COMPLETE);
9086 	}
9087 
9088 	lbalen = (struct ctl_lba_len_flags *)
9089 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9090 	lbalen->lba = lba;
9091 	lbalen->len = num_blocks;
9092 	if (bytchk) {
9093 		lbalen->flags = CTL_LLF_COMPARE | flags;
9094 		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9095 	} else {
9096 		lbalen->flags = CTL_LLF_VERIFY | flags;
9097 		ctsio->kern_total_len = 0;
9098 	}
9099 	ctsio->kern_rel_offset = 0;
9100 
9101 	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9102 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9103 	return (retval);
9104 }
9105 
9106 int
ctl_report_luns(struct ctl_scsiio * ctsio)9107 ctl_report_luns(struct ctl_scsiio *ctsio)
9108 {
9109 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9110 	struct ctl_port *port = CTL_PORT(ctsio);
9111 	struct ctl_lun *lun, *request_lun = CTL_LUN(ctsio);
9112 	struct scsi_report_luns *cdb;
9113 	struct scsi_report_luns_data *lun_data;
9114 	int num_filled, num_luns, num_port_luns, retval;
9115 	uint32_t alloc_len, lun_datalen;
9116 	uint32_t initidx, targ_lun_id, lun_id;
9117 
9118 	retval = CTL_RETVAL_COMPLETE;
9119 	cdb = (struct scsi_report_luns *)ctsio->cdb;
9120 
9121 	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9122 
9123 	num_luns = 0;
9124 	num_port_luns = port->lun_map ? port->lun_map_size : ctl_max_luns;
9125 	mtx_lock(&softc->ctl_lock);
9126 	for (targ_lun_id = 0; targ_lun_id < num_port_luns; targ_lun_id++) {
9127 		if (ctl_lun_map_from_port(port, targ_lun_id) != UINT32_MAX)
9128 			num_luns++;
9129 	}
9130 	mtx_unlock(&softc->ctl_lock);
9131 
9132 	switch (cdb->select_report) {
9133 	case RPL_REPORT_DEFAULT:
9134 	case RPL_REPORT_ALL:
9135 	case RPL_REPORT_NONSUBSID:
9136 		break;
9137 	case RPL_REPORT_WELLKNOWN:
9138 	case RPL_REPORT_ADMIN:
9139 	case RPL_REPORT_CONGLOM:
9140 		num_luns = 0;
9141 		break;
9142 	default:
9143 		ctl_set_invalid_field(ctsio,
9144 				      /*sks_valid*/ 1,
9145 				      /*command*/ 1,
9146 				      /*field*/ 2,
9147 				      /*bit_valid*/ 0,
9148 				      /*bit*/ 0);
9149 		ctl_done((union ctl_io *)ctsio);
9150 		return (retval);
9151 		break; /* NOTREACHED */
9152 	}
9153 
9154 	alloc_len = scsi_4btoul(cdb->length);
9155 	/*
9156 	 * The initiator has to allocate at least 16 bytes for this request,
9157 	 * so he can at least get the header and the first LUN.  Otherwise
9158 	 * we reject the request (per SPC-3 rev 14, section 6.21).
9159 	 */
9160 	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9161 	    sizeof(struct scsi_report_luns_lundata))) {
9162 		ctl_set_invalid_field(ctsio,
9163 				      /*sks_valid*/ 1,
9164 				      /*command*/ 1,
9165 				      /*field*/ 6,
9166 				      /*bit_valid*/ 0,
9167 				      /*bit*/ 0);
9168 		ctl_done((union ctl_io *)ctsio);
9169 		return (retval);
9170 	}
9171 
9172 	lun_datalen = sizeof(*lun_data) +
9173 		(num_luns * sizeof(struct scsi_report_luns_lundata));
9174 
9175 	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9176 	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9177 	ctsio->kern_sg_entries = 0;
9178 
9179 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9180 
9181 	mtx_lock(&softc->ctl_lock);
9182 	for (targ_lun_id = 0, num_filled = 0;
9183 	    targ_lun_id < num_port_luns && num_filled < num_luns;
9184 	    targ_lun_id++) {
9185 		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9186 		if (lun_id == UINT32_MAX)
9187 			continue;
9188 		lun = softc->ctl_luns[lun_id];
9189 		if (lun == NULL)
9190 			continue;
9191 
9192 		be64enc(lun_data->luns[num_filled++].lundata,
9193 		    ctl_encode_lun(targ_lun_id));
9194 
9195 		/*
9196 		 * According to SPC-3, rev 14 section 6.21:
9197 		 *
9198 		 * "The execution of a REPORT LUNS command to any valid and
9199 		 * installed logical unit shall clear the REPORTED LUNS DATA
9200 		 * HAS CHANGED unit attention condition for all logical
9201 		 * units of that target with respect to the requesting
9202 		 * initiator. A valid and installed logical unit is one
9203 		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9204 		 * INQUIRY data (see 6.4.2)."
9205 		 *
9206 		 * If request_lun is NULL, the LUN this report luns command
9207 		 * was issued to is either disabled or doesn't exist. In that
9208 		 * case, we shouldn't clear any pending lun change unit
9209 		 * attention.
9210 		 */
9211 		if (request_lun != NULL) {
9212 			mtx_lock(&lun->lun_lock);
9213 			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9214 			mtx_unlock(&lun->lun_lock);
9215 		}
9216 	}
9217 	mtx_unlock(&softc->ctl_lock);
9218 
9219 	/*
9220 	 * It's quite possible that we've returned fewer LUNs than we allocated
9221 	 * space for.  Trim it.
9222 	 */
9223 	lun_datalen = sizeof(*lun_data) +
9224 		(num_filled * sizeof(struct scsi_report_luns_lundata));
9225 	ctsio->kern_rel_offset = 0;
9226 	ctsio->kern_sg_entries = 0;
9227 	ctsio->kern_data_len = min(lun_datalen, alloc_len);
9228 	ctsio->kern_total_len = ctsio->kern_data_len;
9229 
9230 	/*
9231 	 * We set this to the actual data length, regardless of how much
9232 	 * space we actually have to return results.  If the user looks at
9233 	 * this value, he'll know whether or not he allocated enough space
9234 	 * and reissue the command if necessary.  We don't support well
9235 	 * known logical units, so if the user asks for that, return none.
9236 	 */
9237 	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9238 
9239 	/*
9240 	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9241 	 * this request.
9242 	 */
9243 	ctl_set_success(ctsio);
9244 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9245 	ctsio->be_move_done = ctl_config_move_done;
9246 	ctl_datamove((union ctl_io *)ctsio);
9247 	return (retval);
9248 }
9249 
9250 int
ctl_request_sense(struct ctl_scsiio * ctsio)9251 ctl_request_sense(struct ctl_scsiio *ctsio)
9252 {
9253 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9254 	struct ctl_lun *lun = CTL_LUN(ctsio);
9255 	struct scsi_request_sense *cdb;
9256 	struct scsi_sense_data *sense_ptr, *ps;
9257 	uint32_t initidx;
9258 	int have_error;
9259 	u_int sense_len = SSD_FULL_SIZE;
9260 	scsi_sense_data_type sense_format;
9261 	ctl_ua_type ua_type;
9262 	uint8_t asc = 0, ascq = 0;
9263 
9264 	cdb = (struct scsi_request_sense *)ctsio->cdb;
9265 
9266 	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9267 
9268 	/*
9269 	 * Determine which sense format the user wants.
9270 	 */
9271 	if (cdb->byte2 & SRS_DESC)
9272 		sense_format = SSD_TYPE_DESC;
9273 	else
9274 		sense_format = SSD_TYPE_FIXED;
9275 
9276 	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9277 	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9278 	ctsio->kern_sg_entries = 0;
9279 	ctsio->kern_rel_offset = 0;
9280 
9281 	/*
9282 	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9283 	 * larger than the largest allowed value for the length field in the
9284 	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9285 	 */
9286 	ctsio->kern_data_len = cdb->length;
9287 	ctsio->kern_total_len = cdb->length;
9288 
9289 	/*
9290 	 * If we don't have a LUN, we don't have any pending sense.
9291 	 */
9292 	if (lun == NULL ||
9293 	    ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9294 	     softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9295 		/* "Logical unit not supported" */
9296 		ctl_set_sense_data(sense_ptr, &sense_len, NULL, sense_format,
9297 		    /*current_error*/ 1,
9298 		    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9299 		    /*asc*/ 0x25,
9300 		    /*ascq*/ 0x00,
9301 		    SSD_ELEM_NONE);
9302 		goto send;
9303 	}
9304 
9305 	have_error = 0;
9306 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9307 	/*
9308 	 * Check for pending sense, and then for pending unit attentions.
9309 	 * Pending sense gets returned first, then pending unit attentions.
9310 	 */
9311 	mtx_lock(&lun->lun_lock);
9312 	ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
9313 	if (ps != NULL)
9314 		ps += initidx % CTL_MAX_INIT_PER_PORT;
9315 	if (ps != NULL && ps->error_code != 0) {
9316 		scsi_sense_data_type stored_format;
9317 
9318 		/*
9319 		 * Check to see which sense format was used for the stored
9320 		 * sense data.
9321 		 */
9322 		stored_format = scsi_sense_type(ps);
9323 
9324 		/*
9325 		 * If the user requested a different sense format than the
9326 		 * one we stored, then we need to convert it to the other
9327 		 * format.  If we're going from descriptor to fixed format
9328 		 * sense data, we may lose things in translation, depending
9329 		 * on what options were used.
9330 		 *
9331 		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9332 		 * for some reason we'll just copy it out as-is.
9333 		 */
9334 		if ((stored_format == SSD_TYPE_FIXED)
9335 		 && (sense_format == SSD_TYPE_DESC))
9336 			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9337 			    ps, (struct scsi_sense_data_desc *)sense_ptr);
9338 		else if ((stored_format == SSD_TYPE_DESC)
9339 		      && (sense_format == SSD_TYPE_FIXED))
9340 			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9341 			    ps, (struct scsi_sense_data_fixed *)sense_ptr);
9342 		else
9343 			memcpy(sense_ptr, ps, sizeof(*sense_ptr));
9344 
9345 		ps->error_code = 0;
9346 		have_error = 1;
9347 	} else {
9348 		ua_type = ctl_build_ua(lun, initidx, sense_ptr, &sense_len,
9349 		    sense_format);
9350 		if (ua_type != CTL_UA_NONE)
9351 			have_error = 1;
9352 	}
9353 	if (have_error == 0) {
9354 		/*
9355 		 * Report informational exception if have one and allowed.
9356 		 */
9357 		if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9358 			asc = lun->ie_asc;
9359 			ascq = lun->ie_ascq;
9360 		}
9361 		ctl_set_sense_data(sense_ptr, &sense_len, lun, sense_format,
9362 		    /*current_error*/ 1,
9363 		    /*sense_key*/ SSD_KEY_NO_SENSE,
9364 		    /*asc*/ asc,
9365 		    /*ascq*/ ascq,
9366 		    SSD_ELEM_NONE);
9367 	}
9368 	mtx_unlock(&lun->lun_lock);
9369 
9370 send:
9371 	/*
9372 	 * We report the SCSI status as OK, since the status of the command
9373 	 * itself is OK.  We're reporting sense as parameter data.
9374 	 */
9375 	ctl_set_success(ctsio);
9376 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9377 	ctsio->be_move_done = ctl_config_move_done;
9378 	ctl_datamove((union ctl_io *)ctsio);
9379 	return (CTL_RETVAL_COMPLETE);
9380 }
9381 
9382 int
ctl_tur(struct ctl_scsiio * ctsio)9383 ctl_tur(struct ctl_scsiio *ctsio)
9384 {
9385 
9386 	CTL_DEBUG_PRINT(("ctl_tur\n"));
9387 
9388 	ctl_set_success(ctsio);
9389 	ctl_done((union ctl_io *)ctsio);
9390 
9391 	return (CTL_RETVAL_COMPLETE);
9392 }
9393 
9394 /*
9395  * SCSI VPD page 0x00, the Supported VPD Pages page.
9396  */
9397 static int
ctl_inquiry_evpd_supported(struct ctl_scsiio * ctsio,int alloc_len)9398 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9399 {
9400 	struct ctl_lun *lun = CTL_LUN(ctsio);
9401 	struct scsi_vpd_supported_pages *pages;
9402 	int sup_page_size;
9403 	int p;
9404 
9405 	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9406 	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9407 	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9408 	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9409 	ctsio->kern_rel_offset = 0;
9410 	ctsio->kern_sg_entries = 0;
9411 	ctsio->kern_data_len = min(sup_page_size, alloc_len);
9412 	ctsio->kern_total_len = ctsio->kern_data_len;
9413 
9414 	/*
9415 	 * The control device is always connected.  The disk device, on the
9416 	 * other hand, may not be online all the time.  Need to change this
9417 	 * to figure out whether the disk device is actually online or not.
9418 	 */
9419 	if (lun != NULL)
9420 		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9421 				lun->be_lun->lun_type;
9422 	else
9423 		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9424 
9425 	p = 0;
9426 	/* Supported VPD pages */
9427 	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9428 	/* Serial Number */
9429 	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9430 	/* Device Identification */
9431 	pages->page_list[p++] = SVPD_DEVICE_ID;
9432 	/* Extended INQUIRY Data */
9433 	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9434 	/* Mode Page Policy */
9435 	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9436 	/* SCSI Ports */
9437 	pages->page_list[p++] = SVPD_SCSI_PORTS;
9438 	/* Third-party Copy */
9439 	pages->page_list[p++] = SVPD_SCSI_TPC;
9440 	/* SCSI Feature Sets */
9441 	pages->page_list[p++] = SVPD_SCSI_SFS;
9442 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9443 		/* Block limits */
9444 		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9445 		/* Block Device Characteristics */
9446 		pages->page_list[p++] = SVPD_BDC;
9447 		/* Logical Block Provisioning */
9448 		pages->page_list[p++] = SVPD_LBP;
9449 	}
9450 	pages->length = p;
9451 
9452 	ctl_set_success(ctsio);
9453 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9454 	ctsio->be_move_done = ctl_config_move_done;
9455 	ctl_datamove((union ctl_io *)ctsio);
9456 	return (CTL_RETVAL_COMPLETE);
9457 }
9458 
9459 /*
9460  * SCSI VPD page 0x80, the Unit Serial Number page.
9461  */
9462 static int
ctl_inquiry_evpd_serial(struct ctl_scsiio * ctsio,int alloc_len)9463 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9464 {
9465 	struct ctl_lun *lun = CTL_LUN(ctsio);
9466 	struct scsi_vpd_unit_serial_number *sn_ptr;
9467 	int data_len;
9468 
9469 	data_len = 4 + CTL_SN_LEN;
9470 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9471 	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9472 	ctsio->kern_rel_offset = 0;
9473 	ctsio->kern_sg_entries = 0;
9474 	ctsio->kern_data_len = min(data_len, alloc_len);
9475 	ctsio->kern_total_len = ctsio->kern_data_len;
9476 
9477 	/*
9478 	 * The control device is always connected.  The disk device, on the
9479 	 * other hand, may not be online all the time.  Need to change this
9480 	 * to figure out whether the disk device is actually online or not.
9481 	 */
9482 	if (lun != NULL)
9483 		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9484 				  lun->be_lun->lun_type;
9485 	else
9486 		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9487 
9488 	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9489 	sn_ptr->length = CTL_SN_LEN;
9490 	/*
9491 	 * If we don't have a LUN, we just leave the serial number as
9492 	 * all spaces.
9493 	 */
9494 	if (lun != NULL) {
9495 		strncpy((char *)sn_ptr->serial_num,
9496 			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9497 	} else
9498 		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9499 
9500 	ctl_set_success(ctsio);
9501 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9502 	ctsio->be_move_done = ctl_config_move_done;
9503 	ctl_datamove((union ctl_io *)ctsio);
9504 	return (CTL_RETVAL_COMPLETE);
9505 }
9506 
9507 
9508 /*
9509  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9510  */
9511 static int
ctl_inquiry_evpd_eid(struct ctl_scsiio * ctsio,int alloc_len)9512 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9513 {
9514 	struct ctl_lun *lun = CTL_LUN(ctsio);
9515 	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9516 	int data_len;
9517 
9518 	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9519 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9520 	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9521 	ctsio->kern_sg_entries = 0;
9522 	ctsio->kern_rel_offset = 0;
9523 	ctsio->kern_data_len = min(data_len, alloc_len);
9524 	ctsio->kern_total_len = ctsio->kern_data_len;
9525 
9526 	/*
9527 	 * The control device is always connected.  The disk device, on the
9528 	 * other hand, may not be online all the time.
9529 	 */
9530 	if (lun != NULL)
9531 		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9532 				     lun->be_lun->lun_type;
9533 	else
9534 		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9535 	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9536 	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9537 	/*
9538 	 * We support head of queue, ordered and simple tags.
9539 	 */
9540 	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9541 	/*
9542 	 * Volatile cache supported.
9543 	 */
9544 	eid_ptr->flags3 = SVPD_EID_V_SUP;
9545 
9546 	/*
9547 	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9548 	 * attention for a particular IT nexus on all LUNs once we report
9549 	 * it to that nexus once.  This bit is required as of SPC-4.
9550 	 */
9551 	eid_ptr->flags4 = SVPD_EID_LUICLR;
9552 
9553 	/*
9554 	 * We support revert to defaults (RTD) bit in MODE SELECT.
9555 	 */
9556 	eid_ptr->flags5 = SVPD_EID_RTD_SUP;
9557 
9558 	/*
9559 	 * XXX KDM in order to correctly answer this, we would need
9560 	 * information from the SIM to determine how much sense data it
9561 	 * can send.  So this would really be a path inquiry field, most
9562 	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9563 	 * but the hardware may or may not be able to support that much.
9564 	 * 0 just means that the maximum sense data length is not reported.
9565 	 */
9566 	eid_ptr->max_sense_length = 0;
9567 
9568 	ctl_set_success(ctsio);
9569 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9570 	ctsio->be_move_done = ctl_config_move_done;
9571 	ctl_datamove((union ctl_io *)ctsio);
9572 	return (CTL_RETVAL_COMPLETE);
9573 }
9574 
9575 static int
ctl_inquiry_evpd_mpp(struct ctl_scsiio * ctsio,int alloc_len)9576 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9577 {
9578 	struct ctl_lun *lun = CTL_LUN(ctsio);
9579 	struct scsi_vpd_mode_page_policy *mpp_ptr;
9580 	int data_len;
9581 
9582 	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9583 	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9584 
9585 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9586 	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9587 	ctsio->kern_rel_offset = 0;
9588 	ctsio->kern_sg_entries = 0;
9589 	ctsio->kern_data_len = min(data_len, alloc_len);
9590 	ctsio->kern_total_len = ctsio->kern_data_len;
9591 
9592 	/*
9593 	 * The control device is always connected.  The disk device, on the
9594 	 * other hand, may not be online all the time.
9595 	 */
9596 	if (lun != NULL)
9597 		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9598 				     lun->be_lun->lun_type;
9599 	else
9600 		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9601 	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9602 	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9603 	mpp_ptr->descr[0].page_code = 0x3f;
9604 	mpp_ptr->descr[0].subpage_code = 0xff;
9605 	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9606 
9607 	ctl_set_success(ctsio);
9608 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9609 	ctsio->be_move_done = ctl_config_move_done;
9610 	ctl_datamove((union ctl_io *)ctsio);
9611 	return (CTL_RETVAL_COMPLETE);
9612 }
9613 
9614 /*
9615  * SCSI VPD page 0x83, the Device Identification page.
9616  */
9617 static int
ctl_inquiry_evpd_devid(struct ctl_scsiio * ctsio,int alloc_len)9618 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9619 {
9620 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9621 	struct ctl_port *port = CTL_PORT(ctsio);
9622 	struct ctl_lun *lun = CTL_LUN(ctsio);
9623 	struct scsi_vpd_device_id *devid_ptr;
9624 	struct scsi_vpd_id_descriptor *desc;
9625 	int data_len, g;
9626 	uint8_t proto;
9627 
9628 	data_len = sizeof(struct scsi_vpd_device_id) +
9629 	    sizeof(struct scsi_vpd_id_descriptor) +
9630 		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9631 	    sizeof(struct scsi_vpd_id_descriptor) +
9632 		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9633 	if (lun && lun->lun_devid)
9634 		data_len += lun->lun_devid->len;
9635 	if (port && port->port_devid)
9636 		data_len += port->port_devid->len;
9637 	if (port && port->target_devid)
9638 		data_len += port->target_devid->len;
9639 
9640 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9641 	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9642 	ctsio->kern_sg_entries = 0;
9643 	ctsio->kern_rel_offset = 0;
9644 	ctsio->kern_sg_entries = 0;
9645 	ctsio->kern_data_len = min(data_len, alloc_len);
9646 	ctsio->kern_total_len = ctsio->kern_data_len;
9647 
9648 	/*
9649 	 * The control device is always connected.  The disk device, on the
9650 	 * other hand, may not be online all the time.
9651 	 */
9652 	if (lun != NULL)
9653 		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9654 				     lun->be_lun->lun_type;
9655 	else
9656 		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9657 	devid_ptr->page_code = SVPD_DEVICE_ID;
9658 	scsi_ulto2b(data_len - 4, devid_ptr->length);
9659 
9660 	if (port && port->port_type == CTL_PORT_FC)
9661 		proto = SCSI_PROTO_FC << 4;
9662 	else if (port && port->port_type == CTL_PORT_SAS)
9663 		proto = SCSI_PROTO_SAS << 4;
9664 	else if (port && port->port_type == CTL_PORT_ISCSI)
9665 		proto = SCSI_PROTO_ISCSI << 4;
9666 	else
9667 		proto = SCSI_PROTO_SPI << 4;
9668 	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9669 
9670 	/*
9671 	 * We're using a LUN association here.  i.e., this device ID is a
9672 	 * per-LUN identifier.
9673 	 */
9674 	if (lun && lun->lun_devid) {
9675 		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9676 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9677 		    lun->lun_devid->len);
9678 	}
9679 
9680 	/*
9681 	 * This is for the WWPN which is a port association.
9682 	 */
9683 	if (port && port->port_devid) {
9684 		memcpy(desc, port->port_devid->data, port->port_devid->len);
9685 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9686 		    port->port_devid->len);
9687 	}
9688 
9689 	/*
9690 	 * This is for the Relative Target Port(type 4h) identifier
9691 	 */
9692 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9693 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9694 	    SVPD_ID_TYPE_RELTARG;
9695 	desc->length = 4;
9696 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9697 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9698 	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9699 
9700 	/*
9701 	 * This is for the Target Port Group(type 5h) identifier
9702 	 */
9703 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9704 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9705 	    SVPD_ID_TYPE_TPORTGRP;
9706 	desc->length = 4;
9707 	if (softc->is_single ||
9708 	    (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9709 		g = 1;
9710 	else
9711 		g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9712 	scsi_ulto2b(g, &desc->identifier[2]);
9713 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9714 	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9715 
9716 	/*
9717 	 * This is for the Target identifier
9718 	 */
9719 	if (port && port->target_devid) {
9720 		memcpy(desc, port->target_devid->data, port->target_devid->len);
9721 	}
9722 
9723 	ctl_set_success(ctsio);
9724 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9725 	ctsio->be_move_done = ctl_config_move_done;
9726 	ctl_datamove((union ctl_io *)ctsio);
9727 	return (CTL_RETVAL_COMPLETE);
9728 }
9729 
9730 static int
ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio * ctsio,int alloc_len)9731 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9732 {
9733 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9734 	struct ctl_lun *lun = CTL_LUN(ctsio);
9735 	struct scsi_vpd_scsi_ports *sp;
9736 	struct scsi_vpd_port_designation *pd;
9737 	struct scsi_vpd_port_designation_cont *pdc;
9738 	struct ctl_port *port;
9739 	int data_len, num_target_ports, iid_len, id_len;
9740 
9741 	num_target_ports = 0;
9742 	iid_len = 0;
9743 	id_len = 0;
9744 	mtx_lock(&softc->ctl_lock);
9745 	STAILQ_FOREACH(port, &softc->port_list, links) {
9746 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9747 			continue;
9748 		if (lun != NULL &&
9749 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9750 			continue;
9751 		num_target_ports++;
9752 		if (port->init_devid)
9753 			iid_len += port->init_devid->len;
9754 		if (port->port_devid)
9755 			id_len += port->port_devid->len;
9756 	}
9757 	mtx_unlock(&softc->ctl_lock);
9758 
9759 	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9760 	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9761 	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9762 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9763 	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9764 	ctsio->kern_sg_entries = 0;
9765 	ctsio->kern_rel_offset = 0;
9766 	ctsio->kern_sg_entries = 0;
9767 	ctsio->kern_data_len = min(data_len, alloc_len);
9768 	ctsio->kern_total_len = ctsio->kern_data_len;
9769 
9770 	/*
9771 	 * The control device is always connected.  The disk device, on the
9772 	 * other hand, may not be online all the time.  Need to change this
9773 	 * to figure out whether the disk device is actually online or not.
9774 	 */
9775 	if (lun != NULL)
9776 		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9777 				  lun->be_lun->lun_type;
9778 	else
9779 		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9780 
9781 	sp->page_code = SVPD_SCSI_PORTS;
9782 	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9783 	    sp->page_length);
9784 	pd = &sp->design[0];
9785 
9786 	mtx_lock(&softc->ctl_lock);
9787 	STAILQ_FOREACH(port, &softc->port_list, links) {
9788 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9789 			continue;
9790 		if (lun != NULL &&
9791 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9792 			continue;
9793 		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9794 		if (port->init_devid) {
9795 			iid_len = port->init_devid->len;
9796 			memcpy(pd->initiator_transportid,
9797 			    port->init_devid->data, port->init_devid->len);
9798 		} else
9799 			iid_len = 0;
9800 		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9801 		pdc = (struct scsi_vpd_port_designation_cont *)
9802 		    (&pd->initiator_transportid[iid_len]);
9803 		if (port->port_devid) {
9804 			id_len = port->port_devid->len;
9805 			memcpy(pdc->target_port_descriptors,
9806 			    port->port_devid->data, port->port_devid->len);
9807 		} else
9808 			id_len = 0;
9809 		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9810 		pd = (struct scsi_vpd_port_designation *)
9811 		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9812 	}
9813 	mtx_unlock(&softc->ctl_lock);
9814 
9815 	ctl_set_success(ctsio);
9816 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9817 	ctsio->be_move_done = ctl_config_move_done;
9818 	ctl_datamove((union ctl_io *)ctsio);
9819 	return (CTL_RETVAL_COMPLETE);
9820 }
9821 
9822 static int
ctl_inquiry_evpd_sfs(struct ctl_scsiio * ctsio,int alloc_len)9823 ctl_inquiry_evpd_sfs(struct ctl_scsiio *ctsio, int alloc_len)
9824 {
9825 	struct ctl_lun *lun = CTL_LUN(ctsio);
9826 	struct scsi_vpd_sfs *sfs_ptr;
9827 	int sfs_page_size, n;
9828 
9829 	sfs_page_size = sizeof(*sfs_ptr) + 5 * 2;
9830 	ctsio->kern_data_ptr = malloc(sfs_page_size, M_CTL, M_WAITOK | M_ZERO);
9831 	sfs_ptr = (struct scsi_vpd_sfs *)ctsio->kern_data_ptr;
9832 	ctsio->kern_sg_entries = 0;
9833 	ctsio->kern_rel_offset = 0;
9834 	ctsio->kern_sg_entries = 0;
9835 	ctsio->kern_data_len = min(sfs_page_size, alloc_len);
9836 	ctsio->kern_total_len = ctsio->kern_data_len;
9837 
9838 	/*
9839 	 * The control device is always connected.  The disk device, on the
9840 	 * other hand, may not be online all the time.  Need to change this
9841 	 * to figure out whether the disk device is actually online or not.
9842 	 */
9843 	if (lun != NULL)
9844 		sfs_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9845 				  lun->be_lun->lun_type;
9846 	else
9847 		sfs_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9848 
9849 	sfs_ptr->page_code = SVPD_SCSI_SFS;
9850 	n = 0;
9851 	/* Discovery 2016 */
9852 	scsi_ulto2b(0x0001, &sfs_ptr->codes[2 * n++]);
9853 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9854 		 /* SBC Base 2016 */
9855 		scsi_ulto2b(0x0101, &sfs_ptr->codes[2 * n++]);
9856 		 /* SBC Base 2010 */
9857 		scsi_ulto2b(0x0102, &sfs_ptr->codes[2 * n++]);
9858 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9859 			/* Basic Provisioning 2016 */
9860 			scsi_ulto2b(0x0103, &sfs_ptr->codes[2 * n++]);
9861 		}
9862 		/* Drive Maintenance 2016 */
9863 		//scsi_ulto2b(0x0104, &sfs_ptr->codes[2 * n++]);
9864 	}
9865 	scsi_ulto2b(4 + 2 * n, sfs_ptr->page_length);
9866 
9867 	ctl_set_success(ctsio);
9868 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9869 	ctsio->be_move_done = ctl_config_move_done;
9870 	ctl_datamove((union ctl_io *)ctsio);
9871 	return (CTL_RETVAL_COMPLETE);
9872 }
9873 
9874 static int
ctl_inquiry_evpd_block_limits(struct ctl_scsiio * ctsio,int alloc_len)9875 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9876 {
9877 	struct ctl_lun *lun = CTL_LUN(ctsio);
9878 	struct scsi_vpd_block_limits *bl_ptr;
9879 	const char *val;
9880 	uint64_t ival;
9881 
9882 	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9883 	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9884 	ctsio->kern_sg_entries = 0;
9885 	ctsio->kern_rel_offset = 0;
9886 	ctsio->kern_sg_entries = 0;
9887 	ctsio->kern_data_len = min(sizeof(*bl_ptr), alloc_len);
9888 	ctsio->kern_total_len = ctsio->kern_data_len;
9889 
9890 	/*
9891 	 * The control device is always connected.  The disk device, on the
9892 	 * other hand, may not be online all the time.  Need to change this
9893 	 * to figure out whether the disk device is actually online or not.
9894 	 */
9895 	if (lun != NULL)
9896 		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9897 				  lun->be_lun->lun_type;
9898 	else
9899 		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9900 
9901 	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9902 	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9903 	bl_ptr->max_cmp_write_len = 0xff;
9904 	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9905 	if (lun != NULL) {
9906 		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9907 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9908 			ival = 0xffffffff;
9909 			val = dnvlist_get_string(lun->be_lun->options,
9910 			    "unmap_max_lba", NULL);
9911 			if (val != NULL)
9912 				ctl_expand_number(val, &ival);
9913 			scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9914 			ival = 0xffffffff;
9915 			val = dnvlist_get_string(lun->be_lun->options,
9916 			    "unmap_max_descr", NULL);
9917 			if (val != NULL)
9918 				ctl_expand_number(val, &ival);
9919 			scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9920 			if (lun->be_lun->ublockexp != 0) {
9921 				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9922 				    bl_ptr->opt_unmap_grain);
9923 				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9924 				    bl_ptr->unmap_grain_align);
9925 			}
9926 		}
9927 		scsi_ulto4b(lun->be_lun->atomicblock,
9928 		    bl_ptr->max_atomic_transfer_length);
9929 		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9930 		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9931 		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9932 		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9933 		ival = UINT64_MAX;
9934 		val = dnvlist_get_string(lun->be_lun->options,
9935 		    "write_same_max_lba", NULL);
9936 		if (val != NULL)
9937 			ctl_expand_number(val, &ival);
9938 		scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9939 		if (lun->be_lun->maxlba + 1 > ival)
9940 			bl_ptr->flags |= SVPD_BL_WSNZ;
9941 	}
9942 
9943 	ctl_set_success(ctsio);
9944 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9945 	ctsio->be_move_done = ctl_config_move_done;
9946 	ctl_datamove((union ctl_io *)ctsio);
9947 	return (CTL_RETVAL_COMPLETE);
9948 }
9949 
9950 static int
ctl_inquiry_evpd_bdc(struct ctl_scsiio * ctsio,int alloc_len)9951 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9952 {
9953 	struct ctl_lun *lun = CTL_LUN(ctsio);
9954 	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9955 	const char *value;
9956 	u_int i;
9957 
9958 	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9959 	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9960 	ctsio->kern_sg_entries = 0;
9961 	ctsio->kern_rel_offset = 0;
9962 	ctsio->kern_data_len = min(sizeof(*bdc_ptr), alloc_len);
9963 	ctsio->kern_total_len = ctsio->kern_data_len;
9964 
9965 	/*
9966 	 * The control device is always connected.  The disk device, on the
9967 	 * other hand, may not be online all the time.  Need to change this
9968 	 * to figure out whether the disk device is actually online or not.
9969 	 */
9970 	if (lun != NULL)
9971 		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9972 				  lun->be_lun->lun_type;
9973 	else
9974 		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9975 	bdc_ptr->page_code = SVPD_BDC;
9976 	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9977 	if (lun != NULL &&
9978 	    (value = dnvlist_get_string(lun->be_lun->options, "rpm", NULL)) != NULL)
9979 		i = strtol(value, NULL, 0);
9980 	else
9981 		i = CTL_DEFAULT_ROTATION_RATE;
9982 	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9983 	if (lun != NULL &&
9984 	    (value = dnvlist_get_string(lun->be_lun->options, "formfactor", NULL)) != NULL)
9985 		i = strtol(value, NULL, 0);
9986 	else
9987 		i = 0;
9988 	bdc_ptr->wab_wac_ff = (i & 0x0f);
9989 	bdc_ptr->flags = SVPD_RBWZ | SVPD_FUAB | SVPD_VBULS;
9990 
9991 	ctl_set_success(ctsio);
9992 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9993 	ctsio->be_move_done = ctl_config_move_done;
9994 	ctl_datamove((union ctl_io *)ctsio);
9995 	return (CTL_RETVAL_COMPLETE);
9996 }
9997 
9998 static int
ctl_inquiry_evpd_lbp(struct ctl_scsiio * ctsio,int alloc_len)9999 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10000 {
10001 	struct ctl_lun *lun = CTL_LUN(ctsio);
10002 	struct scsi_vpd_logical_block_prov *lbp_ptr;
10003 	const char *value;
10004 
10005 	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10006 	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10007 	ctsio->kern_sg_entries = 0;
10008 	ctsio->kern_rel_offset = 0;
10009 	ctsio->kern_data_len = min(sizeof(*lbp_ptr), alloc_len);
10010 	ctsio->kern_total_len = ctsio->kern_data_len;
10011 
10012 	/*
10013 	 * The control device is always connected.  The disk device, on the
10014 	 * other hand, may not be online all the time.  Need to change this
10015 	 * to figure out whether the disk device is actually online or not.
10016 	 */
10017 	if (lun != NULL)
10018 		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10019 				  lun->be_lun->lun_type;
10020 	else
10021 		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10022 
10023 	lbp_ptr->page_code = SVPD_LBP;
10024 	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10025 	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10026 	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10027 		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10028 		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10029 		value = dnvlist_get_string(lun->be_lun->options,
10030 		    "provisioning_type", NULL);
10031 		if (value != NULL) {
10032 			if (strcmp(value, "resource") == 0)
10033 				lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10034 			else if (strcmp(value, "thin") == 0)
10035 				lbp_ptr->prov_type = SVPD_LBP_THIN;
10036 		} else
10037 			lbp_ptr->prov_type = SVPD_LBP_THIN;
10038 	}
10039 
10040 	ctl_set_success(ctsio);
10041 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10042 	ctsio->be_move_done = ctl_config_move_done;
10043 	ctl_datamove((union ctl_io *)ctsio);
10044 	return (CTL_RETVAL_COMPLETE);
10045 }
10046 
10047 /*
10048  * INQUIRY with the EVPD bit set.
10049  */
10050 static int
ctl_inquiry_evpd(struct ctl_scsiio * ctsio)10051 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10052 {
10053 	struct ctl_lun *lun = CTL_LUN(ctsio);
10054 	struct scsi_inquiry *cdb;
10055 	int alloc_len, retval;
10056 
10057 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10058 	alloc_len = scsi_2btoul(cdb->length);
10059 
10060 	switch (cdb->page_code) {
10061 	case SVPD_SUPPORTED_PAGES:
10062 		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10063 		break;
10064 	case SVPD_UNIT_SERIAL_NUMBER:
10065 		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10066 		break;
10067 	case SVPD_DEVICE_ID:
10068 		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10069 		break;
10070 	case SVPD_EXTENDED_INQUIRY_DATA:
10071 		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10072 		break;
10073 	case SVPD_MODE_PAGE_POLICY:
10074 		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10075 		break;
10076 	case SVPD_SCSI_PORTS:
10077 		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10078 		break;
10079 	case SVPD_SCSI_TPC:
10080 		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10081 		break;
10082 	case SVPD_SCSI_SFS:
10083 		retval = ctl_inquiry_evpd_sfs(ctsio, alloc_len);
10084 		break;
10085 	case SVPD_BLOCK_LIMITS:
10086 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10087 			goto err;
10088 		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10089 		break;
10090 	case SVPD_BDC:
10091 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10092 			goto err;
10093 		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10094 		break;
10095 	case SVPD_LBP:
10096 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10097 			goto err;
10098 		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10099 		break;
10100 	default:
10101 err:
10102 		ctl_set_invalid_field(ctsio,
10103 				      /*sks_valid*/ 1,
10104 				      /*command*/ 1,
10105 				      /*field*/ 2,
10106 				      /*bit_valid*/ 0,
10107 				      /*bit*/ 0);
10108 		ctl_done((union ctl_io *)ctsio);
10109 		retval = CTL_RETVAL_COMPLETE;
10110 		break;
10111 	}
10112 
10113 	return (retval);
10114 }
10115 
10116 /*
10117  * Standard INQUIRY data.
10118  */
10119 static int
ctl_inquiry_std(struct ctl_scsiio * ctsio)10120 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10121 {
10122 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
10123 	struct ctl_port *port = CTL_PORT(ctsio);
10124 	struct ctl_lun *lun = CTL_LUN(ctsio);
10125 	struct scsi_inquiry_data *inq_ptr;
10126 	struct scsi_inquiry *cdb;
10127 	const char *val;
10128 	uint32_t alloc_len, data_len;
10129 	ctl_port_type port_type;
10130 
10131 	port_type = port->port_type;
10132 	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10133 		port_type = CTL_PORT_SCSI;
10134 
10135 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10136 	alloc_len = scsi_2btoul(cdb->length);
10137 
10138 	/*
10139 	 * We malloc the full inquiry data size here and fill it
10140 	 * in.  If the user only asks for less, we'll give him
10141 	 * that much.
10142 	 */
10143 	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10144 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10145 	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10146 	ctsio->kern_sg_entries = 0;
10147 	ctsio->kern_rel_offset = 0;
10148 	ctsio->kern_data_len = min(data_len, alloc_len);
10149 	ctsio->kern_total_len = ctsio->kern_data_len;
10150 
10151 	if (lun != NULL) {
10152 		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10153 		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10154 			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10155 			    lun->be_lun->lun_type;
10156 		} else {
10157 			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10158 			    lun->be_lun->lun_type;
10159 		}
10160 		if (lun->flags & CTL_LUN_REMOVABLE)
10161 			inq_ptr->dev_qual2 |= SID_RMB;
10162 	} else
10163 		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10164 
10165 	/* RMB in byte 2 is 0 */
10166 	inq_ptr->version = SCSI_REV_SPC5;
10167 
10168 	/*
10169 	 * According to SAM-3, even if a device only supports a single
10170 	 * level of LUN addressing, it should still set the HISUP bit:
10171 	 *
10172 	 * 4.9.1 Logical unit numbers overview
10173 	 *
10174 	 * All logical unit number formats described in this standard are
10175 	 * hierarchical in structure even when only a single level in that
10176 	 * hierarchy is used. The HISUP bit shall be set to one in the
10177 	 * standard INQUIRY data (see SPC-2) when any logical unit number
10178 	 * format described in this standard is used.  Non-hierarchical
10179 	 * formats are outside the scope of this standard.
10180 	 *
10181 	 * Therefore we set the HiSup bit here.
10182 	 *
10183 	 * The response format is 2, per SPC-3.
10184 	 */
10185 	inq_ptr->response_format = SID_HiSup | 2;
10186 
10187 	inq_ptr->additional_length = data_len -
10188 	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10189 	CTL_DEBUG_PRINT(("additional_length = %d\n",
10190 			 inq_ptr->additional_length));
10191 
10192 	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10193 	if (port_type == CTL_PORT_SCSI)
10194 		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10195 	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10196 	inq_ptr->flags = SID_CmdQue;
10197 	if (port_type == CTL_PORT_SCSI)
10198 		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10199 
10200 	/*
10201 	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10202 	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10203 	 * name and 4 bytes for the revision.
10204 	 */
10205 	if (lun == NULL || (val = dnvlist_get_string(lun->be_lun->options,
10206 	    "vendor", NULL)) == NULL) {
10207 		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10208 	} else {
10209 		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10210 		strncpy(inq_ptr->vendor, val,
10211 		    min(sizeof(inq_ptr->vendor), strlen(val)));
10212 	}
10213 	if (lun == NULL) {
10214 		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10215 		    sizeof(inq_ptr->product));
10216 	} else if ((val = dnvlist_get_string(lun->be_lun->options, "product",
10217 	    NULL)) == NULL) {
10218 		switch (lun->be_lun->lun_type) {
10219 		case T_DIRECT:
10220 			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10221 			    sizeof(inq_ptr->product));
10222 			break;
10223 		case T_PROCESSOR:
10224 			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10225 			    sizeof(inq_ptr->product));
10226 			break;
10227 		case T_CDROM:
10228 			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10229 			    sizeof(inq_ptr->product));
10230 			break;
10231 		default:
10232 			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10233 			    sizeof(inq_ptr->product));
10234 			break;
10235 		}
10236 	} else {
10237 		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10238 		strncpy(inq_ptr->product, val,
10239 		    min(sizeof(inq_ptr->product), strlen(val)));
10240 	}
10241 
10242 	/*
10243 	 * XXX make this a macro somewhere so it automatically gets
10244 	 * incremented when we make changes.
10245 	 */
10246 	if (lun == NULL || (val = dnvlist_get_string(lun->be_lun->options,
10247 	    "revision", NULL)) == NULL) {
10248 		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10249 	} else {
10250 		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10251 		strncpy(inq_ptr->revision, val,
10252 		    min(sizeof(inq_ptr->revision), strlen(val)));
10253 	}
10254 
10255 	/*
10256 	 * For parallel SCSI, we support double transition and single
10257 	 * transition clocking.  We also support QAS (Quick Arbitration
10258 	 * and Selection) and Information Unit transfers on both the
10259 	 * control and array devices.
10260 	 */
10261 	if (port_type == CTL_PORT_SCSI)
10262 		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10263 				    SID_SPI_IUS;
10264 
10265 	/* SAM-6 (no version claimed) */
10266 	scsi_ulto2b(0x00C0, inq_ptr->version1);
10267 	/* SPC-5 (no version claimed) */
10268 	scsi_ulto2b(0x05C0, inq_ptr->version2);
10269 	if (port_type == CTL_PORT_FC) {
10270 		/* FCP-2 ANSI INCITS.350:2003 */
10271 		scsi_ulto2b(0x0917, inq_ptr->version3);
10272 	} else if (port_type == CTL_PORT_SCSI) {
10273 		/* SPI-4 ANSI INCITS.362:200x */
10274 		scsi_ulto2b(0x0B56, inq_ptr->version3);
10275 	} else if (port_type == CTL_PORT_ISCSI) {
10276 		/* iSCSI (no version claimed) */
10277 		scsi_ulto2b(0x0960, inq_ptr->version3);
10278 	} else if (port_type == CTL_PORT_SAS) {
10279 		/* SAS (no version claimed) */
10280 		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10281 	} else if (port_type == CTL_PORT_UMASS) {
10282 		/* USB Mass Storage Class Bulk-Only Transport, Revision 1.0 */
10283 		scsi_ulto2b(0x1730, inq_ptr->version3);
10284 	}
10285 
10286 	if (lun == NULL) {
10287 		/* SBC-4 (no version claimed) */
10288 		scsi_ulto2b(0x0600, inq_ptr->version4);
10289 	} else {
10290 		switch (lun->be_lun->lun_type) {
10291 		case T_DIRECT:
10292 			/* SBC-4 (no version claimed) */
10293 			scsi_ulto2b(0x0600, inq_ptr->version4);
10294 			break;
10295 		case T_PROCESSOR:
10296 			break;
10297 		case T_CDROM:
10298 			/* MMC-6 (no version claimed) */
10299 			scsi_ulto2b(0x04E0, inq_ptr->version4);
10300 			break;
10301 		default:
10302 			break;
10303 		}
10304 	}
10305 
10306 	ctl_set_success(ctsio);
10307 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10308 	ctsio->be_move_done = ctl_config_move_done;
10309 	ctl_datamove((union ctl_io *)ctsio);
10310 	return (CTL_RETVAL_COMPLETE);
10311 }
10312 
10313 int
ctl_inquiry(struct ctl_scsiio * ctsio)10314 ctl_inquiry(struct ctl_scsiio *ctsio)
10315 {
10316 	struct scsi_inquiry *cdb;
10317 	int retval;
10318 
10319 	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10320 
10321 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10322 	if (cdb->byte2 & SI_EVPD)
10323 		retval = ctl_inquiry_evpd(ctsio);
10324 	else if (cdb->page_code == 0)
10325 		retval = ctl_inquiry_std(ctsio);
10326 	else {
10327 		ctl_set_invalid_field(ctsio,
10328 				      /*sks_valid*/ 1,
10329 				      /*command*/ 1,
10330 				      /*field*/ 2,
10331 				      /*bit_valid*/ 0,
10332 				      /*bit*/ 0);
10333 		ctl_done((union ctl_io *)ctsio);
10334 		return (CTL_RETVAL_COMPLETE);
10335 	}
10336 
10337 	return (retval);
10338 }
10339 
10340 int
ctl_get_config(struct ctl_scsiio * ctsio)10341 ctl_get_config(struct ctl_scsiio *ctsio)
10342 {
10343 	struct ctl_lun *lun = CTL_LUN(ctsio);
10344 	struct scsi_get_config_header *hdr;
10345 	struct scsi_get_config_feature *feature;
10346 	struct scsi_get_config *cdb;
10347 	uint32_t alloc_len, data_len;
10348 	int rt, starting;
10349 
10350 	cdb = (struct scsi_get_config *)ctsio->cdb;
10351 	rt = (cdb->rt & SGC_RT_MASK);
10352 	starting = scsi_2btoul(cdb->starting_feature);
10353 	alloc_len = scsi_2btoul(cdb->length);
10354 
10355 	data_len = sizeof(struct scsi_get_config_header) +
10356 	    sizeof(struct scsi_get_config_feature) + 8 +
10357 	    sizeof(struct scsi_get_config_feature) + 8 +
10358 	    sizeof(struct scsi_get_config_feature) + 4 +
10359 	    sizeof(struct scsi_get_config_feature) + 4 +
10360 	    sizeof(struct scsi_get_config_feature) + 8 +
10361 	    sizeof(struct scsi_get_config_feature) +
10362 	    sizeof(struct scsi_get_config_feature) + 4 +
10363 	    sizeof(struct scsi_get_config_feature) + 4 +
10364 	    sizeof(struct scsi_get_config_feature) + 4 +
10365 	    sizeof(struct scsi_get_config_feature) + 4 +
10366 	    sizeof(struct scsi_get_config_feature) + 4 +
10367 	    sizeof(struct scsi_get_config_feature) + 4;
10368 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10369 	ctsio->kern_sg_entries = 0;
10370 	ctsio->kern_rel_offset = 0;
10371 
10372 	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10373 	if (lun->flags & CTL_LUN_NO_MEDIA)
10374 		scsi_ulto2b(0x0000, hdr->current_profile);
10375 	else
10376 		scsi_ulto2b(0x0010, hdr->current_profile);
10377 	feature = (struct scsi_get_config_feature *)(hdr + 1);
10378 
10379 	if (starting > 0x003b)
10380 		goto done;
10381 	if (starting > 0x003a)
10382 		goto f3b;
10383 	if (starting > 0x002b)
10384 		goto f3a;
10385 	if (starting > 0x002a)
10386 		goto f2b;
10387 	if (starting > 0x001f)
10388 		goto f2a;
10389 	if (starting > 0x001e)
10390 		goto f1f;
10391 	if (starting > 0x001d)
10392 		goto f1e;
10393 	if (starting > 0x0010)
10394 		goto f1d;
10395 	if (starting > 0x0003)
10396 		goto f10;
10397 	if (starting > 0x0002)
10398 		goto f3;
10399 	if (starting > 0x0001)
10400 		goto f2;
10401 	if (starting > 0x0000)
10402 		goto f1;
10403 
10404 	/* Profile List */
10405 	scsi_ulto2b(0x0000, feature->feature_code);
10406 	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10407 	feature->add_length = 8;
10408 	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10409 	feature->feature_data[2] = 0x00;
10410 	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10411 	feature->feature_data[6] = 0x01;
10412 	feature = (struct scsi_get_config_feature *)
10413 	    &feature->feature_data[feature->add_length];
10414 
10415 f1:	/* Core */
10416 	scsi_ulto2b(0x0001, feature->feature_code);
10417 	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10418 	feature->add_length = 8;
10419 	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10420 	feature->feature_data[4] = 0x03;
10421 	feature = (struct scsi_get_config_feature *)
10422 	    &feature->feature_data[feature->add_length];
10423 
10424 f2:	/* Morphing */
10425 	scsi_ulto2b(0x0002, feature->feature_code);
10426 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10427 	feature->add_length = 4;
10428 	feature->feature_data[0] = 0x02;
10429 	feature = (struct scsi_get_config_feature *)
10430 	    &feature->feature_data[feature->add_length];
10431 
10432 f3:	/* Removable Medium */
10433 	scsi_ulto2b(0x0003, feature->feature_code);
10434 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10435 	feature->add_length = 4;
10436 	feature->feature_data[0] = 0x39;
10437 	feature = (struct scsi_get_config_feature *)
10438 	    &feature->feature_data[feature->add_length];
10439 
10440 	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10441 		goto done;
10442 
10443 f10:	/* Random Read */
10444 	scsi_ulto2b(0x0010, feature->feature_code);
10445 	feature->flags = 0x00;
10446 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10447 		feature->flags |= SGC_F_CURRENT;
10448 	feature->add_length = 8;
10449 	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10450 	scsi_ulto2b(1, &feature->feature_data[4]);
10451 	feature->feature_data[6] = 0x00;
10452 	feature = (struct scsi_get_config_feature *)
10453 	    &feature->feature_data[feature->add_length];
10454 
10455 f1d:	/* Multi-Read */
10456 	scsi_ulto2b(0x001D, feature->feature_code);
10457 	feature->flags = 0x00;
10458 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10459 		feature->flags |= SGC_F_CURRENT;
10460 	feature->add_length = 0;
10461 	feature = (struct scsi_get_config_feature *)
10462 	    &feature->feature_data[feature->add_length];
10463 
10464 f1e:	/* CD Read */
10465 	scsi_ulto2b(0x001E, feature->feature_code);
10466 	feature->flags = 0x00;
10467 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10468 		feature->flags |= SGC_F_CURRENT;
10469 	feature->add_length = 4;
10470 	feature->feature_data[0] = 0x00;
10471 	feature = (struct scsi_get_config_feature *)
10472 	    &feature->feature_data[feature->add_length];
10473 
10474 f1f:	/* DVD Read */
10475 	scsi_ulto2b(0x001F, feature->feature_code);
10476 	feature->flags = 0x08;
10477 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10478 		feature->flags |= SGC_F_CURRENT;
10479 	feature->add_length = 4;
10480 	feature->feature_data[0] = 0x01;
10481 	feature->feature_data[2] = 0x03;
10482 	feature = (struct scsi_get_config_feature *)
10483 	    &feature->feature_data[feature->add_length];
10484 
10485 f2a:	/* DVD+RW */
10486 	scsi_ulto2b(0x002A, feature->feature_code);
10487 	feature->flags = 0x04;
10488 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10489 		feature->flags |= SGC_F_CURRENT;
10490 	feature->add_length = 4;
10491 	feature->feature_data[0] = 0x00;
10492 	feature->feature_data[1] = 0x00;
10493 	feature = (struct scsi_get_config_feature *)
10494 	    &feature->feature_data[feature->add_length];
10495 
10496 f2b:	/* DVD+R */
10497 	scsi_ulto2b(0x002B, feature->feature_code);
10498 	feature->flags = 0x00;
10499 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10500 		feature->flags |= SGC_F_CURRENT;
10501 	feature->add_length = 4;
10502 	feature->feature_data[0] = 0x00;
10503 	feature = (struct scsi_get_config_feature *)
10504 	    &feature->feature_data[feature->add_length];
10505 
10506 f3a:	/* DVD+RW Dual Layer */
10507 	scsi_ulto2b(0x003A, feature->feature_code);
10508 	feature->flags = 0x00;
10509 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10510 		feature->flags |= SGC_F_CURRENT;
10511 	feature->add_length = 4;
10512 	feature->feature_data[0] = 0x00;
10513 	feature->feature_data[1] = 0x00;
10514 	feature = (struct scsi_get_config_feature *)
10515 	    &feature->feature_data[feature->add_length];
10516 
10517 f3b:	/* DVD+R Dual Layer */
10518 	scsi_ulto2b(0x003B, feature->feature_code);
10519 	feature->flags = 0x00;
10520 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10521 		feature->flags |= SGC_F_CURRENT;
10522 	feature->add_length = 4;
10523 	feature->feature_data[0] = 0x00;
10524 	feature = (struct scsi_get_config_feature *)
10525 	    &feature->feature_data[feature->add_length];
10526 
10527 done:
10528 	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10529 	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10530 		feature = (struct scsi_get_config_feature *)(hdr + 1);
10531 		if (scsi_2btoul(feature->feature_code) == starting)
10532 			feature = (struct scsi_get_config_feature *)
10533 			    &feature->feature_data[feature->add_length];
10534 		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10535 	}
10536 	scsi_ulto4b(data_len - 4, hdr->data_length);
10537 	ctsio->kern_data_len = min(data_len, alloc_len);
10538 	ctsio->kern_total_len = ctsio->kern_data_len;
10539 
10540 	ctl_set_success(ctsio);
10541 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10542 	ctsio->be_move_done = ctl_config_move_done;
10543 	ctl_datamove((union ctl_io *)ctsio);
10544 	return (CTL_RETVAL_COMPLETE);
10545 }
10546 
10547 int
ctl_get_event_status(struct ctl_scsiio * ctsio)10548 ctl_get_event_status(struct ctl_scsiio *ctsio)
10549 {
10550 	struct scsi_get_event_status_header *hdr;
10551 	struct scsi_get_event_status *cdb;
10552 	uint32_t alloc_len, data_len;
10553 
10554 	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10555 	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10556 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10557 		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10558 		ctl_done((union ctl_io *)ctsio);
10559 		return (CTL_RETVAL_COMPLETE);
10560 	}
10561 	alloc_len = scsi_2btoul(cdb->length);
10562 
10563 	data_len = sizeof(struct scsi_get_event_status_header);
10564 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10565 	ctsio->kern_sg_entries = 0;
10566 	ctsio->kern_rel_offset = 0;
10567 	ctsio->kern_data_len = min(data_len, alloc_len);
10568 	ctsio->kern_total_len = ctsio->kern_data_len;
10569 
10570 	hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10571 	scsi_ulto2b(0, hdr->descr_length);
10572 	hdr->nea_class = SGESN_NEA;
10573 	hdr->supported_class = 0;
10574 
10575 	ctl_set_success(ctsio);
10576 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10577 	ctsio->be_move_done = ctl_config_move_done;
10578 	ctl_datamove((union ctl_io *)ctsio);
10579 	return (CTL_RETVAL_COMPLETE);
10580 }
10581 
10582 int
ctl_mechanism_status(struct ctl_scsiio * ctsio)10583 ctl_mechanism_status(struct ctl_scsiio *ctsio)
10584 {
10585 	struct scsi_mechanism_status_header *hdr;
10586 	struct scsi_mechanism_status *cdb;
10587 	uint32_t alloc_len, data_len;
10588 
10589 	cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10590 	alloc_len = scsi_2btoul(cdb->length);
10591 
10592 	data_len = sizeof(struct scsi_mechanism_status_header);
10593 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10594 	ctsio->kern_sg_entries = 0;
10595 	ctsio->kern_rel_offset = 0;
10596 	ctsio->kern_data_len = min(data_len, alloc_len);
10597 	ctsio->kern_total_len = ctsio->kern_data_len;
10598 
10599 	hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10600 	hdr->state1 = 0x00;
10601 	hdr->state2 = 0xe0;
10602 	scsi_ulto3b(0, hdr->lba);
10603 	hdr->slots_num = 0;
10604 	scsi_ulto2b(0, hdr->slots_length);
10605 
10606 	ctl_set_success(ctsio);
10607 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10608 	ctsio->be_move_done = ctl_config_move_done;
10609 	ctl_datamove((union ctl_io *)ctsio);
10610 	return (CTL_RETVAL_COMPLETE);
10611 }
10612 
10613 static void
ctl_ultomsf(uint32_t lba,uint8_t * buf)10614 ctl_ultomsf(uint32_t lba, uint8_t *buf)
10615 {
10616 
10617 	lba += 150;
10618 	buf[0] = 0;
10619 	buf[1] = bin2bcd((lba / 75) / 60);
10620 	buf[2] = bin2bcd((lba / 75) % 60);
10621 	buf[3] = bin2bcd(lba % 75);
10622 }
10623 
10624 int
ctl_read_toc(struct ctl_scsiio * ctsio)10625 ctl_read_toc(struct ctl_scsiio *ctsio)
10626 {
10627 	struct ctl_lun *lun = CTL_LUN(ctsio);
10628 	struct scsi_read_toc_hdr *hdr;
10629 	struct scsi_read_toc_type01_descr *descr;
10630 	struct scsi_read_toc *cdb;
10631 	uint32_t alloc_len, data_len;
10632 	int format, msf;
10633 
10634 	cdb = (struct scsi_read_toc *)ctsio->cdb;
10635 	msf = (cdb->byte2 & CD_MSF) != 0;
10636 	format = cdb->format;
10637 	alloc_len = scsi_2btoul(cdb->data_len);
10638 
10639 	data_len = sizeof(struct scsi_read_toc_hdr);
10640 	if (format == 0)
10641 		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10642 	else
10643 		data_len += sizeof(struct scsi_read_toc_type01_descr);
10644 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10645 	ctsio->kern_sg_entries = 0;
10646 	ctsio->kern_rel_offset = 0;
10647 	ctsio->kern_data_len = min(data_len, alloc_len);
10648 	ctsio->kern_total_len = ctsio->kern_data_len;
10649 
10650 	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10651 	if (format == 0) {
10652 		scsi_ulto2b(0x12, hdr->data_length);
10653 		hdr->first = 1;
10654 		hdr->last = 1;
10655 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10656 		descr->addr_ctl = 0x14;
10657 		descr->track_number = 1;
10658 		if (msf)
10659 			ctl_ultomsf(0, descr->track_start);
10660 		else
10661 			scsi_ulto4b(0, descr->track_start);
10662 		descr++;
10663 		descr->addr_ctl = 0x14;
10664 		descr->track_number = 0xaa;
10665 		if (msf)
10666 			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10667 		else
10668 			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10669 	} else {
10670 		scsi_ulto2b(0x0a, hdr->data_length);
10671 		hdr->first = 1;
10672 		hdr->last = 1;
10673 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10674 		descr->addr_ctl = 0x14;
10675 		descr->track_number = 1;
10676 		if (msf)
10677 			ctl_ultomsf(0, descr->track_start);
10678 		else
10679 			scsi_ulto4b(0, descr->track_start);
10680 	}
10681 
10682 	ctl_set_success(ctsio);
10683 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10684 	ctsio->be_move_done = ctl_config_move_done;
10685 	ctl_datamove((union ctl_io *)ctsio);
10686 	return (CTL_RETVAL_COMPLETE);
10687 }
10688 
10689 /*
10690  * For known CDB types, parse the LBA and length.
10691  */
10692 static int
ctl_get_lba_len(union ctl_io * io,uint64_t * lba,uint64_t * len)10693 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10694 {
10695 
10696 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
10697 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
10698 
10699 	switch (io->scsiio.cdb[0]) {
10700 	case COMPARE_AND_WRITE: {
10701 		struct scsi_compare_and_write *cdb;
10702 
10703 		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10704 
10705 		*lba = scsi_8btou64(cdb->addr);
10706 		*len = cdb->length;
10707 		break;
10708 	}
10709 	case READ_6:
10710 	case WRITE_6: {
10711 		struct scsi_rw_6 *cdb;
10712 
10713 		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10714 
10715 		*lba = scsi_3btoul(cdb->addr);
10716 		/* only 5 bits are valid in the most significant address byte */
10717 		*lba &= 0x1fffff;
10718 		*len = cdb->length;
10719 		break;
10720 	}
10721 	case READ_10:
10722 	case WRITE_10: {
10723 		struct scsi_rw_10 *cdb;
10724 
10725 		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10726 
10727 		*lba = scsi_4btoul(cdb->addr);
10728 		*len = scsi_2btoul(cdb->length);
10729 		break;
10730 	}
10731 	case WRITE_VERIFY_10: {
10732 		struct scsi_write_verify_10 *cdb;
10733 
10734 		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10735 
10736 		*lba = scsi_4btoul(cdb->addr);
10737 		*len = scsi_2btoul(cdb->length);
10738 		break;
10739 	}
10740 	case READ_12:
10741 	case WRITE_12: {
10742 		struct scsi_rw_12 *cdb;
10743 
10744 		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10745 
10746 		*lba = scsi_4btoul(cdb->addr);
10747 		*len = scsi_4btoul(cdb->length);
10748 		break;
10749 	}
10750 	case WRITE_VERIFY_12: {
10751 		struct scsi_write_verify_12 *cdb;
10752 
10753 		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10754 
10755 		*lba = scsi_4btoul(cdb->addr);
10756 		*len = scsi_4btoul(cdb->length);
10757 		break;
10758 	}
10759 	case READ_16:
10760 	case WRITE_16: {
10761 		struct scsi_rw_16 *cdb;
10762 
10763 		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10764 
10765 		*lba = scsi_8btou64(cdb->addr);
10766 		*len = scsi_4btoul(cdb->length);
10767 		break;
10768 	}
10769 	case WRITE_ATOMIC_16: {
10770 		struct scsi_write_atomic_16 *cdb;
10771 
10772 		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10773 
10774 		*lba = scsi_8btou64(cdb->addr);
10775 		*len = scsi_2btoul(cdb->length);
10776 		break;
10777 	}
10778 	case WRITE_VERIFY_16: {
10779 		struct scsi_write_verify_16 *cdb;
10780 
10781 		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10782 
10783 		*lba = scsi_8btou64(cdb->addr);
10784 		*len = scsi_4btoul(cdb->length);
10785 		break;
10786 	}
10787 	case WRITE_SAME_10: {
10788 		struct scsi_write_same_10 *cdb;
10789 
10790 		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10791 
10792 		*lba = scsi_4btoul(cdb->addr);
10793 		*len = scsi_2btoul(cdb->length);
10794 		break;
10795 	}
10796 	case WRITE_SAME_16: {
10797 		struct scsi_write_same_16 *cdb;
10798 
10799 		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10800 
10801 		*lba = scsi_8btou64(cdb->addr);
10802 		*len = scsi_4btoul(cdb->length);
10803 		break;
10804 	}
10805 	case VERIFY_10: {
10806 		struct scsi_verify_10 *cdb;
10807 
10808 		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10809 
10810 		*lba = scsi_4btoul(cdb->addr);
10811 		*len = scsi_2btoul(cdb->length);
10812 		break;
10813 	}
10814 	case VERIFY_12: {
10815 		struct scsi_verify_12 *cdb;
10816 
10817 		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10818 
10819 		*lba = scsi_4btoul(cdb->addr);
10820 		*len = scsi_4btoul(cdb->length);
10821 		break;
10822 	}
10823 	case VERIFY_16: {
10824 		struct scsi_verify_16 *cdb;
10825 
10826 		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10827 
10828 		*lba = scsi_8btou64(cdb->addr);
10829 		*len = scsi_4btoul(cdb->length);
10830 		break;
10831 	}
10832 	case UNMAP: {
10833 		*lba = 0;
10834 		*len = UINT64_MAX;
10835 		break;
10836 	}
10837 	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10838 		struct scsi_get_lba_status *cdb;
10839 
10840 		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10841 		*lba = scsi_8btou64(cdb->addr);
10842 		*len = UINT32_MAX;
10843 		break;
10844 	}
10845 	default:
10846 		*lba = 0;
10847 		*len = UINT64_MAX;
10848 		return (1);
10849 	}
10850 
10851 	return (0);
10852 }
10853 
10854 static ctl_action
ctl_extent_check_lba(uint64_t lba1,uint64_t len1,uint64_t lba2,uint64_t len2,bool seq)10855 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10856     bool seq)
10857 {
10858 	uint64_t endlba1, endlba2;
10859 
10860 	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10861 	endlba2 = lba2 + len2 - 1;
10862 
10863 	if ((endlba1 < lba2) || (endlba2 < lba1))
10864 		return (CTL_ACTION_PASS);
10865 	else
10866 		return (CTL_ACTION_BLOCK);
10867 }
10868 
10869 static int
ctl_extent_check_unmap(union ctl_io * io,uint64_t lba2,uint64_t len2)10870 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10871 {
10872 	struct ctl_ptr_len_flags *ptrlen;
10873 	struct scsi_unmap_desc *buf, *end, *range;
10874 	uint64_t lba;
10875 	uint32_t len;
10876 
10877 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
10878 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
10879 
10880 	/* If not UNMAP -- go other way. */
10881 	if (io->scsiio.cdb[0] != UNMAP)
10882 		return (CTL_ACTION_SKIP);
10883 
10884 	/* If UNMAP without data -- block and wait for data. */
10885 	ptrlen = (struct ctl_ptr_len_flags *)
10886 	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10887 	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10888 	    ptrlen->ptr == NULL)
10889 		return (CTL_ACTION_BLOCK);
10890 
10891 	/* UNMAP with data -- check for collision. */
10892 	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10893 	end = buf + ptrlen->len / sizeof(*buf);
10894 	for (range = buf; range < end; range++) {
10895 		lba = scsi_8btou64(range->lba);
10896 		len = scsi_4btoul(range->length);
10897 		if ((lba < lba2 + len2) && (lba + len > lba2))
10898 			return (CTL_ACTION_BLOCK);
10899 	}
10900 	return (CTL_ACTION_PASS);
10901 }
10902 
10903 static ctl_action
ctl_extent_check(union ctl_io * io1,union ctl_io * io2,bool seq)10904 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10905 {
10906 	uint64_t lba1, lba2;
10907 	uint64_t len1, len2;
10908 	int retval;
10909 
10910 	retval = ctl_get_lba_len(io2, &lba2, &len2);
10911 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
10912 
10913 	retval = ctl_extent_check_unmap(io1, lba2, len2);
10914 	if (retval != CTL_ACTION_SKIP)
10915 		return (retval);
10916 
10917 	retval = ctl_get_lba_len(io1, &lba1, &len1);
10918 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
10919 
10920 	if (seq && (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE))
10921 		seq = FALSE;
10922 	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10923 }
10924 
10925 static ctl_action
ctl_seq_check(union ctl_io * io1,union ctl_io * io2)10926 ctl_seq_check(union ctl_io *io1, union ctl_io *io2)
10927 {
10928 	uint64_t lba1, lba2;
10929 	uint64_t len1, len2;
10930 	int retval;
10931 
10932 	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10933 		return (CTL_ACTION_PASS);
10934 	retval = ctl_get_lba_len(io1, &lba1, &len1);
10935 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
10936 	retval = ctl_get_lba_len(io2, &lba2, &len2);
10937 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
10938 
10939 	if (lba1 + len1 == lba2)
10940 		return (CTL_ACTION_BLOCK);
10941 	return (CTL_ACTION_PASS);
10942 }
10943 
10944 static ctl_action
ctl_check_for_blockage(struct ctl_lun * lun,union ctl_io * pending_io,const uint8_t * serialize_row,union ctl_io * ooa_io)10945 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10946     const uint8_t *serialize_row, union ctl_io *ooa_io)
10947 {
10948 
10949 	/*
10950 	 * The initiator attempted multiple untagged commands at the same
10951 	 * time.  Can't do that.
10952 	 */
10953 	if (__predict_false(pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10954 	 && __predict_false(ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10955 	 && ((pending_io->io_hdr.nexus.targ_port ==
10956 	      ooa_io->io_hdr.nexus.targ_port)
10957 	  && (pending_io->io_hdr.nexus.initid ==
10958 	      ooa_io->io_hdr.nexus.initid))
10959 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10960 	      CTL_FLAG_STATUS_SENT)) == 0))
10961 		return (CTL_ACTION_OVERLAP);
10962 
10963 	/*
10964 	 * The initiator attempted to send multiple tagged commands with
10965 	 * the same ID.  (It's fine if different initiators have the same
10966 	 * tag ID.)
10967 	 *
10968 	 * Even if all of those conditions are true, we don't kill the I/O
10969 	 * if the command ahead of us has been aborted.  We won't end up
10970 	 * sending it to the FETD, and it's perfectly legal to resend a
10971 	 * command with the same tag number as long as the previous
10972 	 * instance of this tag number has been aborted somehow.
10973 	 */
10974 	if (__predict_true(pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10975 	 && __predict_true(ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10976 	 && __predict_false(pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10977 	 && ((pending_io->io_hdr.nexus.targ_port ==
10978 	      ooa_io->io_hdr.nexus.targ_port)
10979 	  && (pending_io->io_hdr.nexus.initid ==
10980 	      ooa_io->io_hdr.nexus.initid))
10981 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10982 	      CTL_FLAG_STATUS_SENT)) == 0))
10983 		return (CTL_ACTION_OVERLAP_TAG);
10984 
10985 	/*
10986 	 * If we get a head of queue tag, SAM-3 says that we should
10987 	 * immediately execute it.
10988 	 *
10989 	 * What happens if this command would normally block for some other
10990 	 * reason?  e.g. a request sense with a head of queue tag
10991 	 * immediately after a write.  Normally that would block, but this
10992 	 * will result in its getting executed immediately...
10993 	 *
10994 	 * We currently return "pass" instead of "skip", so we'll end up
10995 	 * going through the rest of the queue to check for overlapped tags.
10996 	 *
10997 	 * XXX KDM check for other types of blockage first??
10998 	 */
10999 	if (__predict_false(pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE))
11000 		return (CTL_ACTION_PASS);
11001 
11002 	/*
11003 	 * Simple tags get blocked until all head of queue and ordered tags
11004 	 * ahead of them have completed.  I'm lumping untagged commands in
11005 	 * with simple tags here.  XXX KDM is that the right thing to do?
11006 	 */
11007 	if (__predict_false(ooa_io->scsiio.tag_type == CTL_TAG_ORDERED) ||
11008 	    __predict_false(ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE))
11009 		return (CTL_ACTION_BLOCK);
11010 
11011 	/* Unsupported command in OOA queue. */
11012 	if (__predict_false(ooa_io->scsiio.seridx == CTL_SERIDX_INVLD))
11013 		return (CTL_ACTION_PASS);
11014 
11015 	switch (serialize_row[ooa_io->scsiio.seridx]) {
11016 	case CTL_SER_SEQ:
11017 		if (lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11018 			return (ctl_seq_check(ooa_io, pending_io));
11019 		/* FALLTHROUGH */
11020 	case CTL_SER_PASS:
11021 		return (CTL_ACTION_PASS);
11022 	case CTL_SER_EXTENTOPT:
11023 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) ==
11024 		    SCP_QUEUE_ALG_UNRESTRICTED)
11025 			return (CTL_ACTION_PASS);
11026 		/* FALLTHROUGH */
11027 	case CTL_SER_EXTENT:
11028 		return (ctl_extent_check(ooa_io, pending_io,
11029 		    (lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11030 	case CTL_SER_BLOCKOPT:
11031 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) ==
11032 		    SCP_QUEUE_ALG_UNRESTRICTED)
11033 			return (CTL_ACTION_PASS);
11034 		/* FALLTHROUGH */
11035 	case CTL_SER_BLOCK:
11036 		return (CTL_ACTION_BLOCK);
11037 	default:
11038 		__assert_unreachable();
11039 	}
11040 }
11041 
11042 /*
11043  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11044  * Assumptions:
11045  * - pending_io is generally either incoming, or on the blocked queue
11046  * - starting I/O is the I/O we want to start the check with.
11047  */
11048 static ctl_action
ctl_check_ooa(struct ctl_lun * lun,union ctl_io * pending_io,union ctl_io ** starting_io)11049 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11050 	      union ctl_io **starting_io)
11051 {
11052 	union ctl_io *ooa_io = *starting_io;
11053 	const uint8_t *serialize_row;
11054 	ctl_action action;
11055 
11056 	mtx_assert(&lun->lun_lock, MA_OWNED);
11057 
11058 	/*
11059 	 * Aborted commands are not going to be executed and may even
11060 	 * not report completion, so we don't care about their order.
11061 	 * Let them complete ASAP to clean the OOA queue.
11062 	 */
11063 	if (__predict_false(pending_io->io_hdr.flags & CTL_FLAG_ABORT))
11064 		return (CTL_ACTION_SKIP);
11065 
11066 	/*
11067 	 * Ordered tags have to block until all items ahead of them have
11068 	 * completed.  If we get called with an ordered tag, we always
11069 	 * block, if something else is ahead of us in the queue.
11070 	 */
11071 	if ((pending_io->scsiio.tag_type == CTL_TAG_ORDERED) &&
11072 	    (ooa_io != NULL))
11073 		return (CTL_ACTION_BLOCK);
11074 
11075 	serialize_row = ctl_serialize_table[pending_io->scsiio.seridx];
11076 
11077 	/*
11078 	 * Run back along the OOA queue, starting with the current
11079 	 * blocked I/O and going through every I/O before it on the
11080 	 * queue.  If starting_io is NULL, we'll just end up returning
11081 	 * CTL_ACTION_PASS.
11082 	 */
11083 	for (; ooa_io != NULL;
11084 	     ooa_io = (union ctl_io *)LIST_NEXT(&ooa_io->io_hdr, ooa_links)) {
11085 		action = ctl_check_for_blockage(lun, pending_io, serialize_row,
11086 		    ooa_io);
11087 		if (action != CTL_ACTION_PASS) {
11088 			*starting_io = ooa_io;
11089 			return (action);
11090 		}
11091 	}
11092 
11093 	*starting_io = NULL;
11094 	return (CTL_ACTION_PASS);
11095 }
11096 
11097 /*
11098  * Try to unblock the specified I/O.
11099  *
11100  * skip parameter allows explicitly skip present blocker of the I/O,
11101  * starting from the previous one on OOA queue.  It can be used when
11102  * we know for sure that the blocker I/O does no longer count.
11103  */
11104 static void
ctl_try_unblock_io(struct ctl_lun * lun,union ctl_io * io,bool skip)11105 ctl_try_unblock_io(struct ctl_lun *lun, union ctl_io *io, bool skip)
11106 {
11107 	struct ctl_softc *softc = lun->ctl_softc;
11108 	union ctl_io *bio, *obio;
11109 	const struct ctl_cmd_entry *entry;
11110 	union ctl_ha_msg msg_info;
11111 	ctl_action action;
11112 
11113 	mtx_assert(&lun->lun_lock, MA_OWNED);
11114 
11115 	if (io->io_hdr.blocker == NULL)
11116 		return;
11117 
11118 	obio = bio = io->io_hdr.blocker;
11119 	if (skip)
11120 		bio = (union ctl_io *)LIST_NEXT(&bio->io_hdr, ooa_links);
11121 	action = ctl_check_ooa(lun, io, &bio);
11122 	if (action == CTL_ACTION_BLOCK) {
11123 		/* Still blocked, but may be by different I/O now. */
11124 		if (bio != obio) {
11125 			TAILQ_REMOVE(&obio->io_hdr.blocked_queue,
11126 			    &io->io_hdr, blocked_links);
11127 			TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue,
11128 			    &io->io_hdr, blocked_links);
11129 			io->io_hdr.blocker = bio;
11130 		}
11131 		return;
11132 	}
11133 
11134 	/* No longer blocked, one way or another. */
11135 	TAILQ_REMOVE(&obio->io_hdr.blocked_queue, &io->io_hdr, blocked_links);
11136 	io->io_hdr.blocker = NULL;
11137 
11138 	switch (action) {
11139 	case CTL_ACTION_PASS:
11140 	case CTL_ACTION_SKIP:
11141 
11142 		/* Serializing commands from the other SC retire there. */
11143 		if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) &&
11144 		    (softc->ha_mode != CTL_HA_MODE_XFER)) {
11145 			io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11146 			msg_info.hdr.original_sc = io->io_hdr.remote_io;
11147 			msg_info.hdr.serializing_sc = io;
11148 			msg_info.hdr.msg_type = CTL_MSG_R2R;
11149 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11150 			    sizeof(msg_info.hdr), M_NOWAIT);
11151 			break;
11152 		}
11153 
11154 		/*
11155 		 * Check this I/O for LUN state changes that may have happened
11156 		 * while this command was blocked. The LUN state may have been
11157 		 * changed by a command ahead of us in the queue.
11158 		 */
11159 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
11160 		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
11161 			ctl_done(io);
11162 			break;
11163 		}
11164 
11165 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11166 		ctl_enqueue_rtr(io);
11167 		break;
11168 	default:
11169 		__assert_unreachable();
11170 	case CTL_ACTION_OVERLAP:
11171 		ctl_set_overlapped_cmd(&io->scsiio);
11172 		goto error;
11173 	case CTL_ACTION_OVERLAP_TAG:
11174 		ctl_set_overlapped_tag(&io->scsiio,
11175 		    io->scsiio.tag_num & 0xff);
11176 error:
11177 		/* Serializing commands from the other SC are done here. */
11178 		if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) &&
11179 		    (softc->ha_mode != CTL_HA_MODE_XFER)) {
11180 			ctl_try_unblock_others(lun, io, TRUE);
11181 			LIST_REMOVE(&io->io_hdr, ooa_links);
11182 
11183 			ctl_copy_sense_data_back(io, &msg_info);
11184 			msg_info.hdr.original_sc = io->io_hdr.remote_io;
11185 			msg_info.hdr.serializing_sc = NULL;
11186 			msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
11187 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11188 			    sizeof(msg_info.scsi), M_WAITOK);
11189 			ctl_free_io(io);
11190 			break;
11191 		}
11192 
11193 		ctl_done(io);
11194 		break;
11195 	}
11196 }
11197 
11198 /*
11199  * Try to unblock I/Os blocked by the specified I/O.
11200  *
11201  * skip parameter allows explicitly skip the specified I/O as blocker,
11202  * starting from the previous one on the OOA queue.  It can be used when
11203  * we know for sure that the specified I/O does no longer count (done).
11204  * It has to be still on OOA queue though so that we know where to start.
11205  */
11206 static void
ctl_try_unblock_others(struct ctl_lun * lun,union ctl_io * bio,bool skip)11207 ctl_try_unblock_others(struct ctl_lun *lun, union ctl_io *bio, bool skip)
11208 {
11209 	union ctl_io *io, *next_io;
11210 
11211 	mtx_assert(&lun->lun_lock, MA_OWNED);
11212 
11213 	for (io = (union ctl_io *)TAILQ_FIRST(&bio->io_hdr.blocked_queue);
11214 	     io != NULL; io = next_io) {
11215 		next_io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr, blocked_links);
11216 
11217 		KASSERT(io->io_hdr.blocker != NULL,
11218 		    ("I/O %p on blocked list without blocker", io));
11219 		ctl_try_unblock_io(lun, io, skip);
11220 	}
11221 	KASSERT(!skip || TAILQ_EMPTY(&bio->io_hdr.blocked_queue),
11222 	    ("blocked_queue is not empty after skipping %p", bio));
11223 }
11224 
11225 /*
11226  * This routine (with one exception) checks LUN flags that can be set by
11227  * commands ahead of us in the OOA queue.  These flags have to be checked
11228  * when a command initially comes in, and when we pull a command off the
11229  * blocked queue and are preparing to execute it.  The reason we have to
11230  * check these flags for commands on the blocked queue is that the LUN
11231  * state may have been changed by a command ahead of us while we're on the
11232  * blocked queue.
11233  *
11234  * Ordering is somewhat important with these checks, so please pay
11235  * careful attention to the placement of any new checks.
11236  */
11237 static int
ctl_scsiio_lun_check(struct ctl_lun * lun,const struct ctl_cmd_entry * entry,struct ctl_scsiio * ctsio)11238 ctl_scsiio_lun_check(struct ctl_lun *lun,
11239     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11240 {
11241 	struct ctl_softc *softc = lun->ctl_softc;
11242 	int retval;
11243 	uint32_t residx;
11244 
11245 	retval = 0;
11246 
11247 	mtx_assert(&lun->lun_lock, MA_OWNED);
11248 
11249 	/*
11250 	 * If this shelf is a secondary shelf controller, we may have to
11251 	 * reject some commands disallowed by HA mode and link state.
11252 	 */
11253 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11254 		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11255 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11256 			ctl_set_lun_unavail(ctsio);
11257 			retval = 1;
11258 			goto bailout;
11259 		}
11260 		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11261 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11262 			ctl_set_lun_transit(ctsio);
11263 			retval = 1;
11264 			goto bailout;
11265 		}
11266 		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11267 		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11268 			ctl_set_lun_standby(ctsio);
11269 			retval = 1;
11270 			goto bailout;
11271 		}
11272 
11273 		/* The rest of checks are only done on executing side */
11274 		if (softc->ha_mode == CTL_HA_MODE_XFER)
11275 			goto bailout;
11276 	}
11277 
11278 	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11279 		if (lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11280 			ctl_set_hw_write_protected(ctsio);
11281 			retval = 1;
11282 			goto bailout;
11283 		}
11284 		if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11285 			ctl_set_sense(ctsio, /*current_error*/ 1,
11286 			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11287 			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11288 			retval = 1;
11289 			goto bailout;
11290 		}
11291 	}
11292 
11293 	/*
11294 	 * Check for a reservation conflict.  If this command isn't allowed
11295 	 * even on reserved LUNs, and if this initiator isn't the one who
11296 	 * reserved us, reject the command with a reservation conflict.
11297 	 */
11298 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11299 	if ((lun->flags & CTL_LUN_RESERVED)
11300 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11301 		if (lun->res_idx != residx) {
11302 			ctl_set_reservation_conflict(ctsio);
11303 			retval = 1;
11304 			goto bailout;
11305 		}
11306 	}
11307 
11308 	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11309 	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11310 		/* No reservation or command is allowed. */;
11311 	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11312 	    (lun->pr_res_type == SPR_TYPE_WR_EX ||
11313 	     lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11314 	     lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11315 		/* The command is allowed for Write Exclusive resv. */;
11316 	} else {
11317 		/*
11318 		 * if we aren't registered or it's a res holder type
11319 		 * reservation and this isn't the res holder then set a
11320 		 * conflict.
11321 		 */
11322 		if (ctl_get_prkey(lun, residx) == 0 ||
11323 		    (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11324 			ctl_set_reservation_conflict(ctsio);
11325 			retval = 1;
11326 			goto bailout;
11327 		}
11328 	}
11329 
11330 	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11331 		if (lun->flags & CTL_LUN_EJECTED)
11332 			ctl_set_lun_ejected(ctsio);
11333 		else if (lun->flags & CTL_LUN_NO_MEDIA) {
11334 			if (lun->flags & CTL_LUN_REMOVABLE)
11335 				ctl_set_lun_no_media(ctsio);
11336 			else
11337 				ctl_set_lun_int_reqd(ctsio);
11338 		} else if (lun->flags & CTL_LUN_STOPPED)
11339 			ctl_set_lun_stopped(ctsio);
11340 		else
11341 			goto bailout;
11342 		retval = 1;
11343 		goto bailout;
11344 	}
11345 
11346 bailout:
11347 	return (retval);
11348 }
11349 
11350 static void
ctl_failover_io(union ctl_io * io,int have_lock)11351 ctl_failover_io(union ctl_io *io, int have_lock)
11352 {
11353 	ctl_set_busy(&io->scsiio);
11354 	ctl_done(io);
11355 }
11356 
11357 static void
ctl_failover_lun(union ctl_io * rio)11358 ctl_failover_lun(union ctl_io *rio)
11359 {
11360 	struct ctl_softc *softc = CTL_SOFTC(rio);
11361 	struct ctl_lun *lun;
11362 	struct ctl_io_hdr *io, *next_io;
11363 	uint32_t targ_lun;
11364 
11365 	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11366 	CTL_DEBUG_PRINT(("FAILOVER for lun %u\n", targ_lun));
11367 
11368 	/* Find and lock the LUN. */
11369 	mtx_lock(&softc->ctl_lock);
11370 	if (targ_lun > ctl_max_luns ||
11371 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11372 		mtx_unlock(&softc->ctl_lock);
11373 		return;
11374 	}
11375 	mtx_lock(&lun->lun_lock);
11376 	mtx_unlock(&softc->ctl_lock);
11377 	if (lun->flags & CTL_LUN_DISABLED) {
11378 		mtx_unlock(&lun->lun_lock);
11379 		return;
11380 	}
11381 
11382 	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11383 		LIST_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11384 			/* We are master */
11385 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11386 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11387 					io->flags |= CTL_FLAG_ABORT |
11388 					    CTL_FLAG_FAILOVER;
11389 					ctl_try_unblock_io(lun,
11390 					    (union ctl_io *)io, FALSE);
11391 				} else { /* This can be only due to DATAMOVE */
11392 					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11393 					io->flags &= ~CTL_FLAG_DMA_INPROG;
11394 					io->flags |= CTL_FLAG_IO_ACTIVE;
11395 					io->port_status = 31340;
11396 					ctl_enqueue_isc((union ctl_io *)io);
11397 				}
11398 			} else
11399 			/* We are slave */
11400 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11401 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11402 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11403 					io->flags |= CTL_FLAG_FAILOVER;
11404 				} else {
11405 					ctl_set_busy(&((union ctl_io *)io)->
11406 					    scsiio);
11407 					ctl_done((union ctl_io *)io);
11408 				}
11409 			}
11410 		}
11411 	} else { /* SERIALIZE modes */
11412 		LIST_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11413 			/* We are master */
11414 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11415 				if (io->blocker != NULL) {
11416 					TAILQ_REMOVE(&io->blocker->io_hdr.blocked_queue,
11417 					    io, blocked_links);
11418 					io->blocker = NULL;
11419 				}
11420 				ctl_try_unblock_others(lun, (union ctl_io *)io,
11421 				    TRUE);
11422 				LIST_REMOVE(io, ooa_links);
11423 				ctl_free_io((union ctl_io *)io);
11424 			} else
11425 			/* We are slave */
11426 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11427 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11428 				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11429 					ctl_set_busy(&((union ctl_io *)io)->
11430 					    scsiio);
11431 					ctl_done((union ctl_io *)io);
11432 				}
11433 			}
11434 		}
11435 	}
11436 	mtx_unlock(&lun->lun_lock);
11437 }
11438 
11439 static void
ctl_scsiio_precheck(struct ctl_scsiio * ctsio)11440 ctl_scsiio_precheck(struct ctl_scsiio *ctsio)
11441 {
11442 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
11443 	struct ctl_lun *lun;
11444 	const struct ctl_cmd_entry *entry;
11445 	union ctl_io *bio;
11446 	uint32_t initidx, targ_lun;
11447 
11448 	lun = NULL;
11449 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11450 	if (targ_lun < ctl_max_luns)
11451 		lun = softc->ctl_luns[targ_lun];
11452 	if (lun) {
11453 		/*
11454 		 * If the LUN is invalid, pretend that it doesn't exist.
11455 		 * It will go away as soon as all pending I/O has been
11456 		 * completed.
11457 		 */
11458 		mtx_lock(&lun->lun_lock);
11459 		if (lun->flags & CTL_LUN_DISABLED) {
11460 			mtx_unlock(&lun->lun_lock);
11461 			lun = NULL;
11462 		}
11463 	}
11464 	CTL_LUN(ctsio) = lun;
11465 	if (lun) {
11466 		CTL_BACKEND_LUN(ctsio) = lun->be_lun;
11467 
11468 		/*
11469 		 * Every I/O goes into the OOA queue for a particular LUN,
11470 		 * and stays there until completion.
11471 		 */
11472 #ifdef CTL_TIME_IO
11473 		if (LIST_EMPTY(&lun->ooa_queue))
11474 			lun->idle_time += getsbinuptime() - lun->last_busy;
11475 #endif
11476 		LIST_INSERT_HEAD(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
11477 	}
11478 
11479 	/* Get command entry and return error if it is unsuppotyed. */
11480 	entry = ctl_validate_command(ctsio);
11481 	if (entry == NULL) {
11482 		if (lun)
11483 			mtx_unlock(&lun->lun_lock);
11484 		return;
11485 	}
11486 
11487 	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11488 	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11489 
11490 	/*
11491 	 * Check to see whether we can send this command to LUNs that don't
11492 	 * exist.  This should pretty much only be the case for inquiry
11493 	 * and request sense.  Further checks, below, really require having
11494 	 * a LUN, so we can't really check the command anymore.  Just put
11495 	 * it on the rtr queue.
11496 	 */
11497 	if (lun == NULL) {
11498 		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11499 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11500 			ctl_enqueue_rtr((union ctl_io *)ctsio);
11501 			return;
11502 		}
11503 
11504 		ctl_set_unsupported_lun(ctsio);
11505 		ctl_done((union ctl_io *)ctsio);
11506 		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11507 		return;
11508 	} else {
11509 		/*
11510 		 * Make sure we support this particular command on this LUN.
11511 		 * e.g., we don't support writes to the control LUN.
11512 		 */
11513 		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11514 			mtx_unlock(&lun->lun_lock);
11515 			ctl_set_invalid_opcode(ctsio);
11516 			ctl_done((union ctl_io *)ctsio);
11517 			return;
11518 		}
11519 	}
11520 
11521 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11522 
11523 	/*
11524 	 * If we've got a request sense, it'll clear the contingent
11525 	 * allegiance condition.  Otherwise, if we have a CA condition for
11526 	 * this initiator, clear it, because it sent down a command other
11527 	 * than request sense.
11528 	 */
11529 	if (ctsio->cdb[0] != REQUEST_SENSE) {
11530 		struct scsi_sense_data *ps;
11531 
11532 		ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
11533 		if (ps != NULL)
11534 			ps[initidx % CTL_MAX_INIT_PER_PORT].error_code = 0;
11535 	}
11536 
11537 	/*
11538 	 * If the command has this flag set, it handles its own unit
11539 	 * attention reporting, we shouldn't do anything.  Otherwise we
11540 	 * check for any pending unit attentions, and send them back to the
11541 	 * initiator.  We only do this when a command initially comes in,
11542 	 * not when we pull it off the blocked queue.
11543 	 *
11544 	 * According to SAM-3, section 5.3.2, the order that things get
11545 	 * presented back to the host is basically unit attentions caused
11546 	 * by some sort of reset event, busy status, reservation conflicts
11547 	 * or task set full, and finally any other status.
11548 	 *
11549 	 * One issue here is that some of the unit attentions we report
11550 	 * don't fall into the "reset" category (e.g. "reported luns data
11551 	 * has changed").  So reporting it here, before the reservation
11552 	 * check, may be technically wrong.  I guess the only thing to do
11553 	 * would be to check for and report the reset events here, and then
11554 	 * check for the other unit attention types after we check for a
11555 	 * reservation conflict.
11556 	 *
11557 	 * XXX KDM need to fix this
11558 	 */
11559 	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11560 		ctl_ua_type ua_type;
11561 		u_int sense_len = 0;
11562 
11563 		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11564 		    &sense_len, SSD_TYPE_NONE);
11565 		if (ua_type != CTL_UA_NONE) {
11566 			mtx_unlock(&lun->lun_lock);
11567 			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11568 			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11569 			ctsio->sense_len = sense_len;
11570 			ctl_done((union ctl_io *)ctsio);
11571 			return;
11572 		}
11573 	}
11574 
11575 
11576 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11577 		mtx_unlock(&lun->lun_lock);
11578 		ctl_done((union ctl_io *)ctsio);
11579 		return;
11580 	}
11581 
11582 	/*
11583 	 * XXX CHD this is where we want to send IO to other side if
11584 	 * this LUN is secondary on this SC. We will need to make a copy
11585 	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11586 	 * the copy we send as FROM_OTHER.
11587 	 * We also need to stuff the address of the original IO so we can
11588 	 * find it easily. Something similar will need be done on the other
11589 	 * side so when we are done we can find the copy.
11590 	 */
11591 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11592 	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11593 	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11594 		union ctl_ha_msg msg_info;
11595 		int isc_retval;
11596 
11597 		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11598 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11599 		mtx_unlock(&lun->lun_lock);
11600 
11601 		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11602 		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11603 		msg_info.hdr.serializing_sc = NULL;
11604 		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11605 		msg_info.scsi.tag_num = ctsio->tag_num;
11606 		msg_info.scsi.tag_type = ctsio->tag_type;
11607 		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11608 		msg_info.scsi.cdb_len = ctsio->cdb_len;
11609 		msg_info.scsi.priority = ctsio->priority;
11610 
11611 		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11612 		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11613 		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11614 			ctsio->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11615 			ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
11616 			ctl_set_busy(ctsio);
11617 			ctl_done((union ctl_io *)ctsio);
11618 			return;
11619 		}
11620 		return;
11621 	}
11622 
11623 	bio = (union ctl_io *)LIST_NEXT(&ctsio->io_hdr, ooa_links);
11624 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio, &bio)) {
11625 	case CTL_ACTION_PASS:
11626 	case CTL_ACTION_SKIP:
11627 		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11628 		mtx_unlock(&lun->lun_lock);
11629 		ctl_enqueue_rtr((union ctl_io *)ctsio);
11630 		break;
11631 	case CTL_ACTION_BLOCK:
11632 		ctsio->io_hdr.blocker = bio;
11633 		TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue, &ctsio->io_hdr,
11634 				  blocked_links);
11635 		mtx_unlock(&lun->lun_lock);
11636 		break;
11637 	case CTL_ACTION_OVERLAP:
11638 		mtx_unlock(&lun->lun_lock);
11639 		ctl_set_overlapped_cmd(ctsio);
11640 		ctl_done((union ctl_io *)ctsio);
11641 		break;
11642 	case CTL_ACTION_OVERLAP_TAG:
11643 		mtx_unlock(&lun->lun_lock);
11644 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11645 		ctl_done((union ctl_io *)ctsio);
11646 		break;
11647 	default:
11648 		__assert_unreachable();
11649 	}
11650 }
11651 
11652 const struct ctl_cmd_entry *
ctl_get_cmd_entry(struct ctl_scsiio * ctsio,int * sa)11653 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11654 {
11655 	const struct ctl_cmd_entry *entry;
11656 	int service_action;
11657 
11658 	entry = &ctl_cmd_table[ctsio->cdb[0]];
11659 	if (sa)
11660 		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11661 	if (entry->flags & CTL_CMD_FLAG_SA5) {
11662 		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11663 		entry = &((const struct ctl_cmd_entry *)
11664 		    entry->execute)[service_action];
11665 	}
11666 	return (entry);
11667 }
11668 
11669 const struct ctl_cmd_entry *
ctl_validate_command(struct ctl_scsiio * ctsio)11670 ctl_validate_command(struct ctl_scsiio *ctsio)
11671 {
11672 	const struct ctl_cmd_entry *entry;
11673 	int i, sa;
11674 	uint8_t diff;
11675 
11676 	entry = ctl_get_cmd_entry(ctsio, &sa);
11677 	ctsio->seridx = entry->seridx;
11678 	if (entry->execute == NULL) {
11679 		if (sa)
11680 			ctl_set_invalid_field(ctsio,
11681 					      /*sks_valid*/ 1,
11682 					      /*command*/ 1,
11683 					      /*field*/ 1,
11684 					      /*bit_valid*/ 1,
11685 					      /*bit*/ 4);
11686 		else
11687 			ctl_set_invalid_opcode(ctsio);
11688 		ctl_done((union ctl_io *)ctsio);
11689 		return (NULL);
11690 	}
11691 	KASSERT(entry->length > 0,
11692 	    ("Not defined length for command 0x%02x/0x%02x",
11693 	     ctsio->cdb[0], ctsio->cdb[1]));
11694 	for (i = 1; i < entry->length; i++) {
11695 		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11696 		if (diff == 0)
11697 			continue;
11698 		ctl_set_invalid_field(ctsio,
11699 				      /*sks_valid*/ 1,
11700 				      /*command*/ 1,
11701 				      /*field*/ i,
11702 				      /*bit_valid*/ 1,
11703 				      /*bit*/ fls(diff) - 1);
11704 		ctl_done((union ctl_io *)ctsio);
11705 		return (NULL);
11706 	}
11707 	return (entry);
11708 }
11709 
11710 static int
ctl_cmd_applicable(uint8_t lun_type,const struct ctl_cmd_entry * entry)11711 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11712 {
11713 
11714 	switch (lun_type) {
11715 	case T_DIRECT:
11716 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11717 			return (0);
11718 		break;
11719 	case T_PROCESSOR:
11720 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11721 			return (0);
11722 		break;
11723 	case T_CDROM:
11724 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11725 			return (0);
11726 		break;
11727 	default:
11728 		return (0);
11729 	}
11730 	return (1);
11731 }
11732 
11733 static int
ctl_scsiio(struct ctl_scsiio * ctsio)11734 ctl_scsiio(struct ctl_scsiio *ctsio)
11735 {
11736 	int retval;
11737 	const struct ctl_cmd_entry *entry;
11738 
11739 	retval = CTL_RETVAL_COMPLETE;
11740 
11741 	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11742 
11743 	entry = ctl_get_cmd_entry(ctsio, NULL);
11744 
11745 	/*
11746 	 * If this I/O has been aborted, just send it straight to
11747 	 * ctl_done() without executing it.
11748 	 */
11749 	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11750 		ctl_done((union ctl_io *)ctsio);
11751 		goto bailout;
11752 	}
11753 
11754 	/*
11755 	 * All the checks should have been handled by ctl_scsiio_precheck().
11756 	 * We should be clear now to just execute the I/O.
11757 	 */
11758 	retval = entry->execute(ctsio);
11759 
11760 bailout:
11761 	return (retval);
11762 }
11763 
11764 static int
ctl_target_reset(union ctl_io * io)11765 ctl_target_reset(union ctl_io *io)
11766 {
11767 	struct ctl_softc *softc = CTL_SOFTC(io);
11768 	struct ctl_port *port = CTL_PORT(io);
11769 	struct ctl_lun *lun;
11770 	uint32_t initidx;
11771 	ctl_ua_type ua_type;
11772 
11773 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11774 		union ctl_ha_msg msg_info;
11775 
11776 		msg_info.hdr.nexus = io->io_hdr.nexus;
11777 		msg_info.task.task_action = io->taskio.task_action;
11778 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11779 		msg_info.hdr.original_sc = NULL;
11780 		msg_info.hdr.serializing_sc = NULL;
11781 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11782 		    sizeof(msg_info.task), M_WAITOK);
11783 	}
11784 
11785 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11786 	if (io->taskio.task_action == CTL_TASK_TARGET_RESET)
11787 		ua_type = CTL_UA_TARG_RESET;
11788 	else
11789 		ua_type = CTL_UA_BUS_RESET;
11790 	mtx_lock(&softc->ctl_lock);
11791 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11792 		if (port != NULL &&
11793 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
11794 			continue;
11795 		ctl_do_lun_reset(lun, initidx, ua_type);
11796 	}
11797 	mtx_unlock(&softc->ctl_lock);
11798 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11799 	return (0);
11800 }
11801 
11802 /*
11803  * The LUN should always be set.  The I/O is optional, and is used to
11804  * distinguish between I/Os sent by this initiator, and by other
11805  * initiators.  We set unit attention for initiators other than this one.
11806  * SAM-3 is vague on this point.  It does say that a unit attention should
11807  * be established for other initiators when a LUN is reset (see section
11808  * 5.7.3), but it doesn't specifically say that the unit attention should
11809  * be established for this particular initiator when a LUN is reset.  Here
11810  * is the relevant text, from SAM-3 rev 8:
11811  *
11812  * 5.7.2 When a SCSI initiator port aborts its own tasks
11813  *
11814  * When a SCSI initiator port causes its own task(s) to be aborted, no
11815  * notification that the task(s) have been aborted shall be returned to
11816  * the SCSI initiator port other than the completion response for the
11817  * command or task management function action that caused the task(s) to
11818  * be aborted and notification(s) associated with related effects of the
11819  * action (e.g., a reset unit attention condition).
11820  *
11821  * XXX KDM for now, we're setting unit attention for all initiators.
11822  */
11823 static void
ctl_do_lun_reset(struct ctl_lun * lun,uint32_t initidx,ctl_ua_type ua_type)11824 ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua_type)
11825 {
11826 	struct ctl_io_hdr *xioh;
11827 	int i;
11828 
11829 	mtx_lock(&lun->lun_lock);
11830 	/* Abort tasks. */
11831 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
11832 		xioh->flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11833 		ctl_try_unblock_io(lun, (union ctl_io *)xioh, FALSE);
11834 	}
11835 	/* Clear CA. */
11836 	for (i = 0; i < ctl_max_ports; i++) {
11837 		free(lun->pending_sense[i], M_CTL);
11838 		lun->pending_sense[i] = NULL;
11839 	}
11840 	/* Clear reservation. */
11841 	lun->flags &= ~CTL_LUN_RESERVED;
11842 	/* Clear prevent media removal. */
11843 	if (lun->prevent) {
11844 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
11845 			ctl_clear_mask(lun->prevent, i);
11846 		lun->prevent_count = 0;
11847 	}
11848 	/* Clear TPC status */
11849 	ctl_tpc_lun_clear(lun, -1);
11850 	/* Establish UA. */
11851 #if 0
11852 	ctl_est_ua_all(lun, initidx, ua_type);
11853 #else
11854 	ctl_est_ua_all(lun, -1, ua_type);
11855 #endif
11856 	mtx_unlock(&lun->lun_lock);
11857 }
11858 
11859 static int
ctl_lun_reset(union ctl_io * io)11860 ctl_lun_reset(union ctl_io *io)
11861 {
11862 	struct ctl_softc *softc = CTL_SOFTC(io);
11863 	struct ctl_lun *lun;
11864 	uint32_t targ_lun, initidx;
11865 
11866 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11867 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11868 	mtx_lock(&softc->ctl_lock);
11869 	if (targ_lun >= ctl_max_luns ||
11870 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11871 		mtx_unlock(&softc->ctl_lock);
11872 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11873 		return (1);
11874 	}
11875 	ctl_do_lun_reset(lun, initidx, CTL_UA_LUN_RESET);
11876 	mtx_unlock(&softc->ctl_lock);
11877 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11878 
11879 	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11880 		union ctl_ha_msg msg_info;
11881 
11882 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11883 		msg_info.hdr.nexus = io->io_hdr.nexus;
11884 		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11885 		msg_info.hdr.original_sc = NULL;
11886 		msg_info.hdr.serializing_sc = NULL;
11887 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11888 		    sizeof(msg_info.task), M_WAITOK);
11889 	}
11890 	return (0);
11891 }
11892 
11893 static void
ctl_abort_tasks_lun(struct ctl_lun * lun,uint32_t targ_port,uint32_t init_id,int other_sc)11894 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11895     int other_sc)
11896 {
11897 	struct ctl_io_hdr *xioh;
11898 
11899 	mtx_assert(&lun->lun_lock, MA_OWNED);
11900 
11901 	/*
11902 	 * Run through the OOA queue and attempt to find the given I/O.
11903 	 * The target port, initiator ID, tag type and tag number have to
11904 	 * match the values that we got from the initiator.  If we have an
11905 	 * untagged command to abort, simply abort the first untagged command
11906 	 * we come to.  We only allow one untagged command at a time of course.
11907 	 */
11908 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
11909 		union ctl_io *xio = (union ctl_io *)xioh;
11910 		if ((targ_port == UINT32_MAX ||
11911 		     targ_port == xioh->nexus.targ_port) &&
11912 		    (init_id == UINT32_MAX ||
11913 		     init_id == xioh->nexus.initid)) {
11914 			if (targ_port != xioh->nexus.targ_port ||
11915 			    init_id != xioh->nexus.initid)
11916 				xioh->flags |= CTL_FLAG_ABORT_STATUS;
11917 			xioh->flags |= CTL_FLAG_ABORT;
11918 			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11919 				union ctl_ha_msg msg_info;
11920 
11921 				msg_info.hdr.nexus = xioh->nexus;
11922 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11923 				msg_info.task.tag_num = xio->scsiio.tag_num;
11924 				msg_info.task.tag_type = xio->scsiio.tag_type;
11925 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11926 				msg_info.hdr.original_sc = NULL;
11927 				msg_info.hdr.serializing_sc = NULL;
11928 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11929 				    sizeof(msg_info.task), M_NOWAIT);
11930 			}
11931 			ctl_try_unblock_io(lun, xio, FALSE);
11932 		}
11933 	}
11934 }
11935 
11936 static int
ctl_abort_task_set(union ctl_io * io)11937 ctl_abort_task_set(union ctl_io *io)
11938 {
11939 	struct ctl_softc *softc = CTL_SOFTC(io);
11940 	struct ctl_lun *lun;
11941 	uint32_t targ_lun;
11942 
11943 	/*
11944 	 * Look up the LUN.
11945 	 */
11946 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11947 	mtx_lock(&softc->ctl_lock);
11948 	if (targ_lun >= ctl_max_luns ||
11949 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11950 		mtx_unlock(&softc->ctl_lock);
11951 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11952 		return (1);
11953 	}
11954 
11955 	mtx_lock(&lun->lun_lock);
11956 	mtx_unlock(&softc->ctl_lock);
11957 	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11958 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11959 		    io->io_hdr.nexus.initid,
11960 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11961 	} else { /* CTL_TASK_CLEAR_TASK_SET */
11962 		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11963 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11964 	}
11965 	mtx_unlock(&lun->lun_lock);
11966 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11967 	return (0);
11968 }
11969 
11970 static void
ctl_i_t_nexus_loss(struct ctl_softc * softc,uint32_t initidx,ctl_ua_type ua_type)11971 ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
11972     ctl_ua_type ua_type)
11973 {
11974 	struct ctl_lun *lun;
11975 	struct scsi_sense_data *ps;
11976 	uint32_t p, i;
11977 
11978 	p = initidx / CTL_MAX_INIT_PER_PORT;
11979 	i = initidx % CTL_MAX_INIT_PER_PORT;
11980 	mtx_lock(&softc->ctl_lock);
11981 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11982 		mtx_lock(&lun->lun_lock);
11983 		/* Abort tasks. */
11984 		ctl_abort_tasks_lun(lun, p, i, 1);
11985 		/* Clear CA. */
11986 		ps = lun->pending_sense[p];
11987 		if (ps != NULL)
11988 			ps[i].error_code = 0;
11989 		/* Clear reservation. */
11990 		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
11991 			lun->flags &= ~CTL_LUN_RESERVED;
11992 		/* Clear prevent media removal. */
11993 		if (lun->prevent && ctl_is_set(lun->prevent, initidx)) {
11994 			ctl_clear_mask(lun->prevent, initidx);
11995 			lun->prevent_count--;
11996 		}
11997 		/* Clear TPC status */
11998 		ctl_tpc_lun_clear(lun, initidx);
11999 		/* Establish UA. */
12000 		ctl_est_ua(lun, initidx, ua_type);
12001 		mtx_unlock(&lun->lun_lock);
12002 	}
12003 	mtx_unlock(&softc->ctl_lock);
12004 }
12005 
12006 static int
ctl_i_t_nexus_reset(union ctl_io * io)12007 ctl_i_t_nexus_reset(union ctl_io *io)
12008 {
12009 	struct ctl_softc *softc = CTL_SOFTC(io);
12010 	uint32_t initidx;
12011 
12012 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12013 		union ctl_ha_msg msg_info;
12014 
12015 		msg_info.hdr.nexus = io->io_hdr.nexus;
12016 		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
12017 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12018 		msg_info.hdr.original_sc = NULL;
12019 		msg_info.hdr.serializing_sc = NULL;
12020 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12021 		    sizeof(msg_info.task), M_WAITOK);
12022 	}
12023 
12024 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12025 	ctl_i_t_nexus_loss(softc, initidx, CTL_UA_I_T_NEXUS_LOSS);
12026 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12027 	return (0);
12028 }
12029 
12030 static int
ctl_abort_task(union ctl_io * io)12031 ctl_abort_task(union ctl_io *io)
12032 {
12033 	struct ctl_softc *softc = CTL_SOFTC(io);
12034 	struct ctl_io_hdr *xioh;
12035 	struct ctl_lun *lun;
12036 	uint32_t targ_lun;
12037 
12038 	/*
12039 	 * Look up the LUN.
12040 	 */
12041 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12042 	mtx_lock(&softc->ctl_lock);
12043 	if (targ_lun >= ctl_max_luns ||
12044 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12045 		mtx_unlock(&softc->ctl_lock);
12046 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12047 		return (1);
12048 	}
12049 
12050 	mtx_lock(&lun->lun_lock);
12051 	mtx_unlock(&softc->ctl_lock);
12052 	/*
12053 	 * Run through the OOA queue and attempt to find the given I/O.
12054 	 * The target port, initiator ID, tag type and tag number have to
12055 	 * match the values that we got from the initiator.  If we have an
12056 	 * untagged command to abort, simply abort the first untagged command
12057 	 * we come to.  We only allow one untagged command at a time of course.
12058 	 */
12059 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
12060 		union ctl_io *xio = (union ctl_io *)xioh;
12061 		if ((xioh->nexus.targ_port != io->io_hdr.nexus.targ_port)
12062 		 || (xioh->nexus.initid != io->io_hdr.nexus.initid)
12063 		 || (xioh->flags & CTL_FLAG_ABORT))
12064 			continue;
12065 
12066 		/*
12067 		 * If the abort says that the task is untagged, the
12068 		 * task in the queue must be untagged.  Otherwise,
12069 		 * we just check to see whether the tag numbers
12070 		 * match.  This is because the QLogic firmware
12071 		 * doesn't pass back the tag type in an abort
12072 		 * request.
12073 		 */
12074 #if 0
12075 		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12076 		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12077 		 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12078 #else
12079 		/*
12080 		 * XXX KDM we've got problems with FC, because it
12081 		 * doesn't send down a tag type with aborts.  So we
12082 		 * can only really go by the tag number...
12083 		 * This may cause problems with parallel SCSI.
12084 		 * Need to figure that out!!
12085 		 */
12086 		if (xio->scsiio.tag_num == io->taskio.tag_num) {
12087 #endif
12088 			xioh->flags |= CTL_FLAG_ABORT;
12089 			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12090 			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12091 				union ctl_ha_msg msg_info;
12092 
12093 				msg_info.hdr.nexus = io->io_hdr.nexus;
12094 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12095 				msg_info.task.tag_num = io->taskio.tag_num;
12096 				msg_info.task.tag_type = io->taskio.tag_type;
12097 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12098 				msg_info.hdr.original_sc = NULL;
12099 				msg_info.hdr.serializing_sc = NULL;
12100 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12101 				    sizeof(msg_info.task), M_NOWAIT);
12102 			}
12103 			ctl_try_unblock_io(lun, xio, FALSE);
12104 		}
12105 	}
12106 	mtx_unlock(&lun->lun_lock);
12107 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12108 	return (0);
12109 }
12110 
12111 static int
12112 ctl_query_task(union ctl_io *io, int task_set)
12113 {
12114 	struct ctl_softc *softc = CTL_SOFTC(io);
12115 	struct ctl_io_hdr *xioh;
12116 	struct ctl_lun *lun;
12117 	int found = 0;
12118 	uint32_t targ_lun;
12119 
12120 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12121 	mtx_lock(&softc->ctl_lock);
12122 	if (targ_lun >= ctl_max_luns ||
12123 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12124 		mtx_unlock(&softc->ctl_lock);
12125 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12126 		return (1);
12127 	}
12128 	mtx_lock(&lun->lun_lock);
12129 	mtx_unlock(&softc->ctl_lock);
12130 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
12131 		union ctl_io *xio = (union ctl_io *)xioh;
12132 		if ((xioh->nexus.targ_port != io->io_hdr.nexus.targ_port)
12133 		 || (xioh->nexus.initid != io->io_hdr.nexus.initid)
12134 		 || (xioh->flags & CTL_FLAG_ABORT))
12135 			continue;
12136 
12137 		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12138 			found = 1;
12139 			break;
12140 		}
12141 	}
12142 	mtx_unlock(&lun->lun_lock);
12143 	if (found)
12144 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12145 	else
12146 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12147 	return (0);
12148 }
12149 
12150 static int
12151 ctl_query_async_event(union ctl_io *io)
12152 {
12153 	struct ctl_softc *softc = CTL_SOFTC(io);
12154 	struct ctl_lun *lun;
12155 	ctl_ua_type ua;
12156 	uint32_t targ_lun, initidx;
12157 
12158 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12159 	mtx_lock(&softc->ctl_lock);
12160 	if (targ_lun >= ctl_max_luns ||
12161 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12162 		mtx_unlock(&softc->ctl_lock);
12163 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12164 		return (1);
12165 	}
12166 	mtx_lock(&lun->lun_lock);
12167 	mtx_unlock(&softc->ctl_lock);
12168 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12169 	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12170 	mtx_unlock(&lun->lun_lock);
12171 	if (ua != CTL_UA_NONE)
12172 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12173 	else
12174 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12175 	return (0);
12176 }
12177 
12178 static void
12179 ctl_run_task(union ctl_io *io)
12180 {
12181 	int retval = 1;
12182 
12183 	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12184 	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12185 	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12186 	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12187 	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12188 	switch (io->taskio.task_action) {
12189 	case CTL_TASK_ABORT_TASK:
12190 		retval = ctl_abort_task(io);
12191 		break;
12192 	case CTL_TASK_ABORT_TASK_SET:
12193 	case CTL_TASK_CLEAR_TASK_SET:
12194 		retval = ctl_abort_task_set(io);
12195 		break;
12196 	case CTL_TASK_CLEAR_ACA:
12197 		break;
12198 	case CTL_TASK_I_T_NEXUS_RESET:
12199 		retval = ctl_i_t_nexus_reset(io);
12200 		break;
12201 	case CTL_TASK_LUN_RESET:
12202 		retval = ctl_lun_reset(io);
12203 		break;
12204 	case CTL_TASK_TARGET_RESET:
12205 	case CTL_TASK_BUS_RESET:
12206 		retval = ctl_target_reset(io);
12207 		break;
12208 	case CTL_TASK_PORT_LOGIN:
12209 		break;
12210 	case CTL_TASK_PORT_LOGOUT:
12211 		break;
12212 	case CTL_TASK_QUERY_TASK:
12213 		retval = ctl_query_task(io, 0);
12214 		break;
12215 	case CTL_TASK_QUERY_TASK_SET:
12216 		retval = ctl_query_task(io, 1);
12217 		break;
12218 	case CTL_TASK_QUERY_ASYNC_EVENT:
12219 		retval = ctl_query_async_event(io);
12220 		break;
12221 	default:
12222 		printf("%s: got unknown task management event %d\n",
12223 		       __func__, io->taskio.task_action);
12224 		break;
12225 	}
12226 	if (retval == 0)
12227 		io->io_hdr.status = CTL_SUCCESS;
12228 	else
12229 		io->io_hdr.status = CTL_ERROR;
12230 	ctl_done(io);
12231 }
12232 
12233 /*
12234  * For HA operation.  Handle commands that come in from the other
12235  * controller.
12236  */
12237 static void
12238 ctl_handle_isc(union ctl_io *io)
12239 {
12240 	struct ctl_softc *softc = CTL_SOFTC(io);
12241 	struct ctl_lun *lun;
12242 	const struct ctl_cmd_entry *entry;
12243 	uint32_t targ_lun;
12244 
12245 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12246 	switch (io->io_hdr.msg_type) {
12247 	case CTL_MSG_SERIALIZE:
12248 		ctl_serialize_other_sc_cmd(&io->scsiio);
12249 		break;
12250 	case CTL_MSG_R2R:		/* Only used in SER_ONLY mode. */
12251 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12252 		if (targ_lun >= ctl_max_luns ||
12253 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12254 			ctl_done(io);
12255 			break;
12256 		}
12257 		mtx_lock(&lun->lun_lock);
12258 		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
12259 			mtx_unlock(&lun->lun_lock);
12260 			ctl_done(io);
12261 			break;
12262 		}
12263 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12264 		mtx_unlock(&lun->lun_lock);
12265 		ctl_enqueue_rtr(io);
12266 		break;
12267 	case CTL_MSG_FINISH_IO:
12268 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12269 			ctl_done(io);
12270 			break;
12271 		}
12272 		if (targ_lun >= ctl_max_luns ||
12273 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12274 			ctl_free_io(io);
12275 			break;
12276 		}
12277 		mtx_lock(&lun->lun_lock);
12278 		ctl_try_unblock_others(lun, io, TRUE);
12279 		LIST_REMOVE(&io->io_hdr, ooa_links);
12280 		mtx_unlock(&lun->lun_lock);
12281 		ctl_free_io(io);
12282 		break;
12283 	case CTL_MSG_PERS_ACTION:
12284 		ctl_hndl_per_res_out_on_other_sc(io);
12285 		ctl_free_io(io);
12286 		break;
12287 	case CTL_MSG_BAD_JUJU:
12288 		ctl_done(io);
12289 		break;
12290 	case CTL_MSG_DATAMOVE:		/* Only used in XFER mode */
12291 		ctl_datamove_remote(io);
12292 		break;
12293 	case CTL_MSG_DATAMOVE_DONE:	/* Only used in XFER mode */
12294 		ctl_datamove_done(io, false);
12295 		break;
12296 	case CTL_MSG_FAILOVER:
12297 		ctl_failover_lun(io);
12298 		ctl_free_io(io);
12299 		break;
12300 	default:
12301 		printf("%s: Invalid message type %d\n",
12302 		       __func__, io->io_hdr.msg_type);
12303 		ctl_free_io(io);
12304 		break;
12305 	}
12306 
12307 }
12308 
12309 
12310 /*
12311  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12312  * there is no match.
12313  */
12314 static ctl_lun_error_pattern
12315 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12316 {
12317 	const struct ctl_cmd_entry *entry;
12318 	ctl_lun_error_pattern filtered_pattern, pattern;
12319 
12320 	pattern = desc->error_pattern;
12321 
12322 	/*
12323 	 * XXX KDM we need more data passed into this function to match a
12324 	 * custom pattern, and we actually need to implement custom pattern
12325 	 * matching.
12326 	 */
12327 	if (pattern & CTL_LUN_PAT_CMD)
12328 		return (CTL_LUN_PAT_CMD);
12329 
12330 	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12331 		return (CTL_LUN_PAT_ANY);
12332 
12333 	entry = ctl_get_cmd_entry(ctsio, NULL);
12334 
12335 	filtered_pattern = entry->pattern & pattern;
12336 
12337 	/*
12338 	 * If the user requested specific flags in the pattern (e.g.
12339 	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12340 	 * flags.
12341 	 *
12342 	 * If the user did not specify any flags, it doesn't matter whether
12343 	 * or not the command supports the flags.
12344 	 */
12345 	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12346 	     (pattern & ~CTL_LUN_PAT_MASK))
12347 		return (CTL_LUN_PAT_NONE);
12348 
12349 	/*
12350 	 * If the user asked for a range check, see if the requested LBA
12351 	 * range overlaps with this command's LBA range.
12352 	 */
12353 	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12354 		uint64_t lba1;
12355 		uint64_t len1;
12356 		ctl_action action;
12357 		int retval;
12358 
12359 		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12360 		if (retval != 0)
12361 			return (CTL_LUN_PAT_NONE);
12362 
12363 		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12364 					      desc->lba_range.len, FALSE);
12365 		/*
12366 		 * A "pass" means that the LBA ranges don't overlap, so
12367 		 * this doesn't match the user's range criteria.
12368 		 */
12369 		if (action == CTL_ACTION_PASS)
12370 			return (CTL_LUN_PAT_NONE);
12371 	}
12372 
12373 	return (filtered_pattern);
12374 }
12375 
12376 static void
12377 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12378 {
12379 	struct ctl_error_desc *desc, *desc2;
12380 
12381 	mtx_assert(&lun->lun_lock, MA_OWNED);
12382 
12383 	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12384 		ctl_lun_error_pattern pattern;
12385 		/*
12386 		 * Check to see whether this particular command matches
12387 		 * the pattern in the descriptor.
12388 		 */
12389 		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12390 		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12391 			continue;
12392 
12393 		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12394 		case CTL_LUN_INJ_ABORTED:
12395 			ctl_set_aborted(&io->scsiio);
12396 			break;
12397 		case CTL_LUN_INJ_MEDIUM_ERR:
12398 			ctl_set_medium_error(&io->scsiio,
12399 			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12400 			     CTL_FLAG_DATA_OUT);
12401 			break;
12402 		case CTL_LUN_INJ_UA:
12403 			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12404 			 * OCCURRED */
12405 			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12406 			break;
12407 		case CTL_LUN_INJ_CUSTOM:
12408 			/*
12409 			 * We're assuming the user knows what he is doing.
12410 			 * Just copy the sense information without doing
12411 			 * checks.
12412 			 */
12413 			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12414 			      MIN(sizeof(desc->custom_sense),
12415 				  sizeof(io->scsiio.sense_data)));
12416 			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12417 			io->scsiio.sense_len = SSD_FULL_SIZE;
12418 			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12419 			break;
12420 		case CTL_LUN_INJ_NONE:
12421 		default:
12422 			/*
12423 			 * If this is an error injection type we don't know
12424 			 * about, clear the continuous flag (if it is set)
12425 			 * so it will get deleted below.
12426 			 */
12427 			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12428 			break;
12429 		}
12430 		/*
12431 		 * By default, each error injection action is a one-shot
12432 		 */
12433 		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12434 			continue;
12435 
12436 		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12437 
12438 		free(desc, M_CTL);
12439 	}
12440 }
12441 
12442 #ifdef CTL_IO_DELAY
12443 static void
12444 ctl_datamove_timer_wakeup(void *arg)
12445 {
12446 	union ctl_io *io;
12447 
12448 	io = (union ctl_io *)arg;
12449 
12450 	ctl_datamove(io);
12451 }
12452 #endif /* CTL_IO_DELAY */
12453 
12454 static void
12455 ctl_datamove_done_process(union ctl_io *io)
12456 {
12457 #ifdef CTL_TIME_IO
12458 	struct bintime cur_bt;
12459 #endif
12460 
12461 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
12462 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
12463 
12464 #ifdef CTL_TIME_IO
12465 	getbinuptime(&cur_bt);
12466 	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12467 	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12468 #endif
12469 	io->io_hdr.num_dmas++;
12470 
12471 	if ((io->io_hdr.port_status != 0) &&
12472 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
12473 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
12474 		ctl_set_internal_failure(&io->scsiio, /*sks_valid*/ 1,
12475 		    /*retry_count*/ io->io_hdr.port_status);
12476 	} else if (io->scsiio.kern_data_resid != 0 &&
12477 	    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT &&
12478 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
12479 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
12480 		ctl_set_invalid_field_ciu(&io->scsiio);
12481 	} else if (ctl_debug & CTL_DEBUG_CDB_DATA)
12482 		ctl_data_print(io);
12483 }
12484 
12485 void
12486 ctl_datamove_done(union ctl_io *io, bool samethr)
12487 {
12488 
12489 	ctl_datamove_done_process(io);
12490 	io->scsiio.be_move_done(io, samethr);
12491 }
12492 
12493 void
12494 ctl_datamove(union ctl_io *io)
12495 {
12496 	void (*fe_datamove)(union ctl_io *io);
12497 
12498 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12499 
12500 	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12501 
12502 	/* No data transferred yet.  Frontend must update this when done. */
12503 	io->scsiio.kern_data_resid = io->scsiio.kern_data_len;
12504 
12505 #ifdef CTL_TIME_IO
12506 	getbinuptime(&io->io_hdr.dma_start_bt);
12507 #endif /* CTL_TIME_IO */
12508 
12509 #ifdef CTL_IO_DELAY
12510 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12511 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12512 	} else {
12513 		struct ctl_lun *lun;
12514 
12515 		lun = CTL_LUN(io);
12516 		if ((lun != NULL)
12517 		 && (lun->delay_info.datamove_delay > 0)) {
12518 
12519 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12520 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12521 			callout_reset(&io->io_hdr.delay_callout,
12522 				      lun->delay_info.datamove_delay * hz,
12523 				      ctl_datamove_timer_wakeup, io);
12524 			if (lun->delay_info.datamove_type ==
12525 			    CTL_DELAY_TYPE_ONESHOT)
12526 				lun->delay_info.datamove_delay = 0;
12527 			return;
12528 		}
12529 	}
12530 #endif
12531 
12532 	/*
12533 	 * This command has been aborted.  Set the port status, so we fail
12534 	 * the data move.
12535 	 */
12536 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12537 		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12538 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12539 		       io->io_hdr.nexus.targ_port,
12540 		       io->io_hdr.nexus.targ_lun);
12541 		io->io_hdr.port_status = 31337;
12542 		ctl_datamove_done_process(io);
12543 		io->scsiio.be_move_done(io, true);
12544 		return;
12545 	}
12546 
12547 	/* Don't confuse frontend with zero length data move. */
12548 	if (io->scsiio.kern_data_len == 0) {
12549 		ctl_datamove_done_process(io);
12550 		io->scsiio.be_move_done(io, true);
12551 		return;
12552 	}
12553 
12554 	fe_datamove = CTL_PORT(io)->fe_datamove;
12555 	fe_datamove(io);
12556 }
12557 
12558 static void
12559 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12560 {
12561 	union ctl_ha_msg msg;
12562 #ifdef CTL_TIME_IO
12563 	struct bintime cur_bt;
12564 #endif
12565 
12566 	memset(&msg, 0, sizeof(msg));
12567 	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12568 	msg.hdr.original_sc = io;
12569 	msg.hdr.serializing_sc = io->io_hdr.remote_io;
12570 	msg.hdr.nexus = io->io_hdr.nexus;
12571 	msg.hdr.status = io->io_hdr.status;
12572 	msg.scsi.kern_data_resid = io->scsiio.kern_data_resid;
12573 	msg.scsi.tag_num = io->scsiio.tag_num;
12574 	msg.scsi.tag_type = io->scsiio.tag_type;
12575 	msg.scsi.scsi_status = io->scsiio.scsi_status;
12576 	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12577 	       io->scsiio.sense_len);
12578 	msg.scsi.sense_len = io->scsiio.sense_len;
12579 	msg.scsi.port_status = io->io_hdr.port_status;
12580 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12581 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12582 		ctl_failover_io(io, /*have_lock*/ have_lock);
12583 		return;
12584 	}
12585 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12586 	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12587 	    msg.scsi.sense_len, M_WAITOK);
12588 
12589 #ifdef CTL_TIME_IO
12590 	getbinuptime(&cur_bt);
12591 	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12592 	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12593 #endif
12594 	io->io_hdr.num_dmas++;
12595 }
12596 
12597 /*
12598  * The DMA to the remote side is done, now we need to tell the other side
12599  * we're done so it can continue with its data movement.
12600  */
12601 static void
12602 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12603 {
12604 	union ctl_io *io;
12605 	uint32_t i;
12606 
12607 	io = rq->context;
12608 
12609 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12610 		printf("%s: ISC DMA write failed with error %d", __func__,
12611 		       rq->ret);
12612 		ctl_set_internal_failure(&io->scsiio,
12613 					 /*sks_valid*/ 1,
12614 					 /*retry_count*/ rq->ret);
12615 	}
12616 
12617 	ctl_dt_req_free(rq);
12618 
12619 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12620 		free(CTL_LSGLT(io)[i].addr, M_CTL);
12621 	free(CTL_RSGL(io), M_CTL);
12622 	CTL_RSGL(io) = NULL;
12623 	CTL_LSGL(io) = NULL;
12624 
12625 	/*
12626 	 * The data is in local and remote memory, so now we need to send
12627 	 * status (good or back) back to the other side.
12628 	 */
12629 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12630 }
12631 
12632 /*
12633  * We've moved the data from the host/controller into local memory.  Now we
12634  * need to push it over to the remote controller's memory.
12635  */
12636 static int
12637 ctl_datamove_remote_dm_write_cb(union ctl_io *io, bool samethr)
12638 {
12639 	int retval;
12640 
12641 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12642 					  ctl_datamove_remote_write_cb);
12643 	return (retval);
12644 }
12645 
12646 static void
12647 ctl_datamove_remote_write(union ctl_io *io)
12648 {
12649 	int retval;
12650 	void (*fe_datamove)(union ctl_io *io);
12651 
12652 	/*
12653 	 * - Get the data from the host/HBA into local memory.
12654 	 * - DMA memory from the local controller to the remote controller.
12655 	 * - Send status back to the remote controller.
12656 	 */
12657 
12658 	retval = ctl_datamove_remote_sgl_setup(io);
12659 	if (retval != 0)
12660 		return;
12661 
12662 	/* Switch the pointer over so the FETD knows what to do */
12663 	io->scsiio.kern_data_ptr = (uint8_t *)CTL_LSGL(io);
12664 
12665 	/*
12666 	 * Use a custom move done callback, since we need to send completion
12667 	 * back to the other controller, not to the backend on this side.
12668 	 */
12669 	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12670 
12671 	fe_datamove = CTL_PORT(io)->fe_datamove;
12672 	fe_datamove(io);
12673 }
12674 
12675 static int
12676 ctl_datamove_remote_dm_read_cb(union ctl_io *io, bool samethr)
12677 {
12678 	uint32_t i;
12679 
12680 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12681 		free(CTL_LSGLT(io)[i].addr, M_CTL);
12682 	free(CTL_RSGL(io), M_CTL);
12683 	CTL_RSGL(io) = NULL;
12684 	CTL_LSGL(io) = NULL;
12685 
12686 	/*
12687 	 * The read is done, now we need to send status (good or bad) back
12688 	 * to the other side.
12689 	 */
12690 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12691 
12692 	return (0);
12693 }
12694 
12695 static void
12696 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12697 {
12698 	union ctl_io *io;
12699 	void (*fe_datamove)(union ctl_io *io);
12700 
12701 	io = rq->context;
12702 
12703 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12704 		printf("%s: ISC DMA read failed with error %d\n", __func__,
12705 		       rq->ret);
12706 		ctl_set_internal_failure(&io->scsiio,
12707 					 /*sks_valid*/ 1,
12708 					 /*retry_count*/ rq->ret);
12709 	}
12710 
12711 	ctl_dt_req_free(rq);
12712 
12713 	/* Switch the pointer over so the FETD knows what to do */
12714 	io->scsiio.kern_data_ptr = (uint8_t *)CTL_LSGL(io);
12715 
12716 	/*
12717 	 * Use a custom move done callback, since we need to send completion
12718 	 * back to the other controller, not to the backend on this side.
12719 	 */
12720 	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12721 
12722 	/* XXX KDM add checks like the ones in ctl_datamove? */
12723 
12724 	fe_datamove = CTL_PORT(io)->fe_datamove;
12725 	fe_datamove(io);
12726 }
12727 
12728 static int
12729 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12730 {
12731 	struct ctl_sg_entry *local_sglist;
12732 	uint32_t len_to_go;
12733 	int retval;
12734 	int i;
12735 
12736 	retval = 0;
12737 	local_sglist = CTL_LSGL(io);
12738 	len_to_go = io->scsiio.kern_data_len;
12739 
12740 	/*
12741 	 * The difficult thing here is that the size of the various
12742 	 * S/G segments may be different than the size from the
12743 	 * remote controller.  That'll make it harder when DMAing
12744 	 * the data back to the other side.
12745 	 */
12746 	for (i = 0; len_to_go > 0; i++) {
12747 		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12748 		local_sglist[i].addr =
12749 		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12750 
12751 		len_to_go -= local_sglist[i].len;
12752 	}
12753 	/*
12754 	 * Reset the number of S/G entries accordingly.  The original
12755 	 * number of S/G entries is available in rem_sg_entries.
12756 	 */
12757 	io->scsiio.kern_sg_entries = i;
12758 
12759 	return (retval);
12760 }
12761 
12762 static int
12763 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12764 			 ctl_ha_dt_cb callback)
12765 {
12766 	struct ctl_ha_dt_req *rq;
12767 	struct ctl_sg_entry *remote_sglist, *local_sglist;
12768 	uint32_t local_used, remote_used, total_used;
12769 	int i, j, isc_ret;
12770 
12771 	rq = ctl_dt_req_alloc();
12772 
12773 	/*
12774 	 * If we failed to allocate the request, and if the DMA didn't fail
12775 	 * anyway, set busy status.  This is just a resource allocation
12776 	 * failure.
12777 	 */
12778 	if ((rq == NULL)
12779 	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12780 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12781 		ctl_set_busy(&io->scsiio);
12782 
12783 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12784 	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12785 
12786 		if (rq != NULL)
12787 			ctl_dt_req_free(rq);
12788 
12789 		/*
12790 		 * The data move failed.  We need to return status back
12791 		 * to the other controller.  No point in trying to DMA
12792 		 * data to the remote controller.
12793 		 */
12794 
12795 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12796 
12797 		return (1);
12798 	}
12799 
12800 	local_sglist = CTL_LSGL(io);
12801 	remote_sglist = CTL_RSGL(io);
12802 	local_used = 0;
12803 	remote_used = 0;
12804 	total_used = 0;
12805 
12806 	/*
12807 	 * Pull/push the data over the wire from/to the other controller.
12808 	 * This takes into account the possibility that the local and
12809 	 * remote sglists may not be identical in terms of the size of
12810 	 * the elements and the number of elements.
12811 	 *
12812 	 * One fundamental assumption here is that the length allocated for
12813 	 * both the local and remote sglists is identical.  Otherwise, we've
12814 	 * essentially got a coding error of some sort.
12815 	 */
12816 	isc_ret = CTL_HA_STATUS_SUCCESS;
12817 	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12818 		uint32_t cur_len;
12819 		uint8_t *tmp_ptr;
12820 
12821 		rq->command = command;
12822 		rq->context = io;
12823 
12824 		/*
12825 		 * Both pointers should be aligned.  But it is possible
12826 		 * that the allocation length is not.  They should both
12827 		 * also have enough slack left over at the end, though,
12828 		 * to round up to the next 8 byte boundary.
12829 		 */
12830 		cur_len = MIN(local_sglist[i].len - local_used,
12831 			      remote_sglist[j].len - remote_used);
12832 		rq->size = cur_len;
12833 
12834 		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12835 		tmp_ptr += local_used;
12836 
12837 #if 0
12838 		/* Use physical addresses when talking to ISC hardware */
12839 		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12840 			/* XXX KDM use busdma */
12841 			rq->local = vtophys(tmp_ptr);
12842 		} else
12843 			rq->local = tmp_ptr;
12844 #else
12845 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12846 		    ("HA does not support BUS_ADDR"));
12847 		rq->local = tmp_ptr;
12848 #endif
12849 
12850 		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12851 		tmp_ptr += remote_used;
12852 		rq->remote = tmp_ptr;
12853 
12854 		rq->callback = NULL;
12855 
12856 		local_used += cur_len;
12857 		if (local_used >= local_sglist[i].len) {
12858 			i++;
12859 			local_used = 0;
12860 		}
12861 
12862 		remote_used += cur_len;
12863 		if (remote_used >= remote_sglist[j].len) {
12864 			j++;
12865 			remote_used = 0;
12866 		}
12867 		total_used += cur_len;
12868 
12869 		if (total_used >= io->scsiio.kern_data_len)
12870 			rq->callback = callback;
12871 
12872 		isc_ret = ctl_dt_single(rq);
12873 		if (isc_ret > CTL_HA_STATUS_SUCCESS)
12874 			break;
12875 	}
12876 	if (isc_ret != CTL_HA_STATUS_WAIT) {
12877 		rq->ret = isc_ret;
12878 		callback(rq);
12879 	}
12880 
12881 	return (0);
12882 }
12883 
12884 static void
12885 ctl_datamove_remote_read(union ctl_io *io)
12886 {
12887 	int retval;
12888 	uint32_t i;
12889 
12890 	/*
12891 	 * This will send an error to the other controller in the case of a
12892 	 * failure.
12893 	 */
12894 	retval = ctl_datamove_remote_sgl_setup(io);
12895 	if (retval != 0)
12896 		return;
12897 
12898 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12899 					  ctl_datamove_remote_read_cb);
12900 	if (retval != 0) {
12901 		/*
12902 		 * Make sure we free memory if there was an error..  The
12903 		 * ctl_datamove_remote_xfer() function will send the
12904 		 * datamove done message, or call the callback with an
12905 		 * error if there is a problem.
12906 		 */
12907 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12908 			free(CTL_LSGLT(io)[i].addr, M_CTL);
12909 		free(CTL_RSGL(io), M_CTL);
12910 		CTL_RSGL(io) = NULL;
12911 		CTL_LSGL(io) = NULL;
12912 	}
12913 }
12914 
12915 /*
12916  * Process a datamove request from the other controller.  This is used for
12917  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12918  * first.  Once that is complete, the data gets DMAed into the remote
12919  * controller's memory.  For reads, we DMA from the remote controller's
12920  * memory into our memory first, and then move it out to the FETD.
12921  */
12922 static void
12923 ctl_datamove_remote(union ctl_io *io)
12924 {
12925 
12926 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12927 
12928 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12929 		ctl_failover_io(io, /*have_lock*/ 0);
12930 		return;
12931 	}
12932 
12933 	/*
12934 	 * Note that we look for an aborted I/O here, but don't do some of
12935 	 * the other checks that ctl_datamove() normally does.
12936 	 * We don't need to run the datamove delay code, since that should
12937 	 * have been done if need be on the other controller.
12938 	 */
12939 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12940 		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
12941 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12942 		       io->io_hdr.nexus.targ_port,
12943 		       io->io_hdr.nexus.targ_lun);
12944 		io->io_hdr.port_status = 31338;
12945 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12946 		return;
12947 	}
12948 
12949 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
12950 		ctl_datamove_remote_write(io);
12951 	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
12952 		ctl_datamove_remote_read(io);
12953 	else {
12954 		io->io_hdr.port_status = 31339;
12955 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12956 	}
12957 }
12958 
12959 static void
12960 ctl_process_done(union ctl_io *io)
12961 {
12962 	struct ctl_softc *softc = CTL_SOFTC(io);
12963 	struct ctl_port *port = CTL_PORT(io);
12964 	struct ctl_lun *lun = CTL_LUN(io);
12965 	void (*fe_done)(union ctl_io *io);
12966 	union ctl_ha_msg msg;
12967 
12968 	CTL_DEBUG_PRINT(("ctl_process_done\n"));
12969 	fe_done = port->fe_done;
12970 
12971 #ifdef CTL_TIME_IO
12972 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12973 		char str[256];
12974 		char path_str[64];
12975 		struct sbuf sb;
12976 
12977 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12978 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12979 
12980 		sbuf_cat(&sb, path_str);
12981 		switch (io->io_hdr.io_type) {
12982 		case CTL_IO_SCSI:
12983 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12984 			sbuf_printf(&sb, "\n");
12985 			sbuf_cat(&sb, path_str);
12986 			sbuf_printf(&sb, "Tag: 0x%04x/%d, Prio: %d\n",
12987 				    io->scsiio.tag_num, io->scsiio.tag_type,
12988 				    io->scsiio.priority);
12989 			break;
12990 		case CTL_IO_TASK:
12991 			sbuf_printf(&sb, "Task Action: %d Tag: 0x%04x/%d\n",
12992 				    io->taskio.task_action,
12993 				    io->taskio.tag_num, io->taskio.tag_type);
12994 			break;
12995 		default:
12996 			panic("%s: Invalid CTL I/O type %d\n",
12997 			    __func__, io->io_hdr.io_type);
12998 		}
12999 		sbuf_cat(&sb, path_str);
13000 		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13001 			    (intmax_t)time_uptime - io->io_hdr.start_time);
13002 		sbuf_finish(&sb);
13003 		printf("%s", sbuf_data(&sb));
13004 	}
13005 #endif /* CTL_TIME_IO */
13006 
13007 	switch (io->io_hdr.io_type) {
13008 	case CTL_IO_SCSI:
13009 		break;
13010 	case CTL_IO_TASK:
13011 		if (ctl_debug & CTL_DEBUG_INFO)
13012 			ctl_io_error_print(io, NULL);
13013 		fe_done(io);
13014 		return;
13015 	default:
13016 		panic("%s: Invalid CTL I/O type %d\n",
13017 		    __func__, io->io_hdr.io_type);
13018 	}
13019 
13020 	if (lun == NULL) {
13021 		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13022 				 io->io_hdr.nexus.targ_mapped_lun));
13023 		goto bailout;
13024 	}
13025 
13026 	mtx_lock(&lun->lun_lock);
13027 
13028 	/*
13029 	 * Check to see if we have any informational exception and status
13030 	 * of this command can be modified to report it in form of either
13031 	 * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
13032 	 */
13033 	if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
13034 	    io->io_hdr.status == CTL_SUCCESS &&
13035 	    (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
13036 		uint8_t mrie = lun->MODE_IE.mrie;
13037 		uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
13038 		    (lun->MODE_VER.byte3 & SMS_VER_PER));
13039 		if (((mrie == SIEP_MRIE_REC_COND && per) ||
13040 		     mrie == SIEP_MRIE_REC_UNCOND ||
13041 		     mrie == SIEP_MRIE_NO_SENSE) &&
13042 		    (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
13043 		     CTL_CMD_FLAG_NO_SENSE) == 0) {
13044 			ctl_set_sense(&io->scsiio,
13045 			      /*current_error*/ 1,
13046 			      /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
13047 			        SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
13048 			      /*asc*/ lun->ie_asc,
13049 			      /*ascq*/ lun->ie_ascq,
13050 			      SSD_ELEM_NONE);
13051 			lun->ie_reported = 1;
13052 		}
13053 	} else if (lun->ie_reported < 0)
13054 		lun->ie_reported = 0;
13055 
13056 	/*
13057 	 * Check to see if we have any errors to inject here.  We only
13058 	 * inject errors for commands that don't already have errors set.
13059 	 */
13060 	if (!STAILQ_EMPTY(&lun->error_list) &&
13061 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13062 	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13063 		ctl_inject_error(lun, io);
13064 
13065 	/*
13066 	 * XXX KDM how do we treat commands that aren't completed
13067 	 * successfully?
13068 	 *
13069 	 * XXX KDM should we also track I/O latency?
13070 	 */
13071 	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13072 	    io->io_hdr.io_type == CTL_IO_SCSI) {
13073 		int type;
13074 #ifdef CTL_TIME_IO
13075 		struct bintime bt;
13076 
13077 		getbinuptime(&bt);
13078 		bintime_sub(&bt, &io->io_hdr.start_bt);
13079 #endif
13080 		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13081 		    CTL_FLAG_DATA_IN)
13082 			type = CTL_STATS_READ;
13083 		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13084 		    CTL_FLAG_DATA_OUT)
13085 			type = CTL_STATS_WRITE;
13086 		else
13087 			type = CTL_STATS_NO_IO;
13088 
13089 		lun->stats.bytes[type] += io->scsiio.kern_total_len;
13090 		lun->stats.operations[type] ++;
13091 		lun->stats.dmas[type] += io->io_hdr.num_dmas;
13092 #ifdef CTL_TIME_IO
13093 		bintime_add(&lun->stats.dma_time[type], &io->io_hdr.dma_bt);
13094 		bintime_add(&lun->stats.time[type], &bt);
13095 #endif
13096 
13097 		mtx_lock(&port->port_lock);
13098 		port->stats.bytes[type] += io->scsiio.kern_total_len;
13099 		port->stats.operations[type] ++;
13100 		port->stats.dmas[type] += io->io_hdr.num_dmas;
13101 #ifdef CTL_TIME_IO
13102 		bintime_add(&port->stats.dma_time[type], &io->io_hdr.dma_bt);
13103 		bintime_add(&port->stats.time[type], &bt);
13104 #endif
13105 		mtx_unlock(&port->port_lock);
13106 	}
13107 
13108 	/*
13109 	 * Run through the blocked queue of this I/O and see if anything
13110 	 * can be unblocked, now that this I/O is done and will be removed.
13111 	 * We need to do it before removal to have OOA position to start.
13112 	 */
13113 	ctl_try_unblock_others(lun, io, TRUE);
13114 
13115 	/*
13116 	 * Remove this from the OOA queue.
13117 	 */
13118 	LIST_REMOVE(&io->io_hdr, ooa_links);
13119 #ifdef CTL_TIME_IO
13120 	if (LIST_EMPTY(&lun->ooa_queue))
13121 		lun->last_busy = getsbinuptime();
13122 #endif
13123 
13124 	/*
13125 	 * If the LUN has been invalidated, free it if there is nothing
13126 	 * left on its OOA queue.
13127 	 */
13128 	if ((lun->flags & CTL_LUN_INVALID)
13129 	 && LIST_EMPTY(&lun->ooa_queue)) {
13130 		mtx_unlock(&lun->lun_lock);
13131 		ctl_free_lun(lun);
13132 	} else
13133 		mtx_unlock(&lun->lun_lock);
13134 
13135 bailout:
13136 
13137 	/*
13138 	 * If this command has been aborted, make sure we set the status
13139 	 * properly.  The FETD is responsible for freeing the I/O and doing
13140 	 * whatever it needs to do to clean up its state.
13141 	 */
13142 	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13143 		ctl_set_task_aborted(&io->scsiio);
13144 
13145 	/*
13146 	 * If enabled, print command error status.
13147 	 */
13148 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13149 	    (ctl_debug & CTL_DEBUG_INFO) != 0)
13150 		ctl_io_error_print(io, NULL);
13151 
13152 	/*
13153 	 * Tell the FETD or the other shelf controller we're done with this
13154 	 * command.  Note that only SCSI commands get to this point.  Task
13155 	 * management commands are completed above.
13156 	 */
13157 	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13158 	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13159 		memset(&msg, 0, sizeof(msg));
13160 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13161 		msg.hdr.serializing_sc = io->io_hdr.remote_io;
13162 		msg.hdr.nexus = io->io_hdr.nexus;
13163 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13164 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13165 		    M_WAITOK);
13166 	}
13167 
13168 	fe_done(io);
13169 }
13170 
13171 /*
13172  * Front end should call this if it doesn't do autosense.  When the request
13173  * sense comes back in from the initiator, we'll dequeue this and send it.
13174  */
13175 int
13176 ctl_queue_sense(union ctl_io *io)
13177 {
13178 	struct ctl_softc *softc = CTL_SOFTC(io);
13179 	struct ctl_port *port = CTL_PORT(io);
13180 	struct ctl_lun *lun;
13181 	struct scsi_sense_data *ps;
13182 	uint32_t initidx, p, targ_lun;
13183 
13184 	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13185 
13186 	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13187 
13188 	/*
13189 	 * LUN lookup will likely move to the ctl_work_thread() once we
13190 	 * have our new queueing infrastructure (that doesn't put things on
13191 	 * a per-LUN queue initially).  That is so that we can handle
13192 	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13193 	 * can't deal with that right now.
13194 	 * If we don't have a LUN for this, just toss the sense information.
13195 	 */
13196 	mtx_lock(&softc->ctl_lock);
13197 	if (targ_lun >= ctl_max_luns ||
13198 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
13199 		mtx_unlock(&softc->ctl_lock);
13200 		goto bailout;
13201 	}
13202 	mtx_lock(&lun->lun_lock);
13203 	mtx_unlock(&softc->ctl_lock);
13204 
13205 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13206 	p = initidx / CTL_MAX_INIT_PER_PORT;
13207 	if (lun->pending_sense[p] == NULL) {
13208 		lun->pending_sense[p] = malloc(sizeof(*ps) * CTL_MAX_INIT_PER_PORT,
13209 		    M_CTL, M_NOWAIT | M_ZERO);
13210 	}
13211 	if ((ps = lun->pending_sense[p]) != NULL) {
13212 		ps += initidx % CTL_MAX_INIT_PER_PORT;
13213 		memset(ps, 0, sizeof(*ps));
13214 		memcpy(ps, &io->scsiio.sense_data, io->scsiio.sense_len);
13215 	}
13216 	mtx_unlock(&lun->lun_lock);
13217 
13218 bailout:
13219 	ctl_free_io(io);
13220 	return (CTL_RETVAL_COMPLETE);
13221 }
13222 
13223 /*
13224  * Primary command inlet from frontend ports.  All SCSI and task I/O
13225  * requests must go through this function.
13226  */
13227 int
13228 ctl_queue(union ctl_io *io)
13229 {
13230 	struct ctl_port *port = CTL_PORT(io);
13231 
13232 	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13233 
13234 #ifdef CTL_TIME_IO
13235 	io->io_hdr.start_time = time_uptime;
13236 	getbinuptime(&io->io_hdr.start_bt);
13237 #endif /* CTL_TIME_IO */
13238 
13239 	/* Map FE-specific LUN ID into global one. */
13240 	io->io_hdr.nexus.targ_mapped_lun =
13241 	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13242 
13243 	switch (io->io_hdr.io_type) {
13244 	case CTL_IO_SCSI:
13245 	case CTL_IO_TASK:
13246 		if (ctl_debug & CTL_DEBUG_CDB)
13247 			ctl_io_print(io);
13248 		ctl_enqueue_incoming(io);
13249 		break;
13250 	default:
13251 		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13252 		return (EINVAL);
13253 	}
13254 
13255 	return (CTL_RETVAL_COMPLETE);
13256 }
13257 
13258 int
13259 ctl_run(union ctl_io *io)
13260 {
13261 	struct ctl_port *port = CTL_PORT(io);
13262 
13263 	CTL_DEBUG_PRINT(("ctl_run cdb[0]=%02X\n", io->scsiio.cdb[0]));
13264 
13265 #ifdef CTL_TIME_IO
13266 	io->io_hdr.start_time = time_uptime;
13267 	getbinuptime(&io->io_hdr.start_bt);
13268 #endif /* CTL_TIME_IO */
13269 
13270 	/* Map FE-specific LUN ID into global one. */
13271 	io->io_hdr.nexus.targ_mapped_lun =
13272 	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13273 
13274 	switch (io->io_hdr.io_type) {
13275 	case CTL_IO_SCSI:
13276 		if (ctl_debug & CTL_DEBUG_CDB)
13277 			ctl_io_print(io);
13278 		ctl_scsiio_precheck(&io->scsiio);
13279 		break;
13280 	case CTL_IO_TASK:
13281 		if (ctl_debug & CTL_DEBUG_CDB)
13282 			ctl_io_print(io);
13283 		ctl_run_task(io);
13284 		break;
13285 	default:
13286 		printf("ctl_run: unknown I/O type %d\n", io->io_hdr.io_type);
13287 		return (EINVAL);
13288 	}
13289 
13290 	return (CTL_RETVAL_COMPLETE);
13291 }
13292 
13293 #ifdef CTL_IO_DELAY
13294 static void
13295 ctl_done_timer_wakeup(void *arg)
13296 {
13297 	union ctl_io *io;
13298 
13299 	io = (union ctl_io *)arg;
13300 	ctl_done(io);
13301 }
13302 #endif /* CTL_IO_DELAY */
13303 
13304 void
13305 ctl_serseq_done(union ctl_io *io)
13306 {
13307 	struct ctl_lun *lun = CTL_LUN(io);;
13308 
13309 	if (lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13310 		return;
13311 
13312 	/* This is racy, but should not be a problem. */
13313 	if (!TAILQ_EMPTY(&io->io_hdr.blocked_queue)) {
13314 		mtx_lock(&lun->lun_lock);
13315 		io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13316 		ctl_try_unblock_others(lun, io, FALSE);
13317 		mtx_unlock(&lun->lun_lock);
13318 	} else
13319 		io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13320 }
13321 
13322 void
13323 ctl_done(union ctl_io *io)
13324 {
13325 
13326 	/*
13327 	 * Enable this to catch duplicate completion issues.
13328 	 */
13329 #if 0
13330 	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13331 		printf("%s: type %d msg %d cdb %x iptl: "
13332 		       "%u:%u:%u tag 0x%04x "
13333 		       "flag %#x status %x\n",
13334 			__func__,
13335 			io->io_hdr.io_type,
13336 			io->io_hdr.msg_type,
13337 			io->scsiio.cdb[0],
13338 			io->io_hdr.nexus.initid,
13339 			io->io_hdr.nexus.targ_port,
13340 			io->io_hdr.nexus.targ_lun,
13341 			(io->io_hdr.io_type ==
13342 			CTL_IO_TASK) ?
13343 			io->taskio.tag_num :
13344 			io->scsiio.tag_num,
13345 		        io->io_hdr.flags,
13346 			io->io_hdr.status);
13347 	} else
13348 		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13349 #endif
13350 
13351 	/*
13352 	 * This is an internal copy of an I/O, and should not go through
13353 	 * the normal done processing logic.
13354 	 */
13355 	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13356 		return;
13357 
13358 #ifdef CTL_IO_DELAY
13359 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13360 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13361 	} else {
13362 		struct ctl_lun *lun = CTL_LUN(io);
13363 
13364 		if ((lun != NULL)
13365 		 && (lun->delay_info.done_delay > 0)) {
13366 
13367 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13368 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13369 			callout_reset(&io->io_hdr.delay_callout,
13370 				      lun->delay_info.done_delay * hz,
13371 				      ctl_done_timer_wakeup, io);
13372 			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13373 				lun->delay_info.done_delay = 0;
13374 			return;
13375 		}
13376 	}
13377 #endif /* CTL_IO_DELAY */
13378 
13379 	ctl_enqueue_done(io);
13380 }
13381 
13382 static void
13383 ctl_work_thread(void *arg)
13384 {
13385 	struct ctl_thread *thr = (struct ctl_thread *)arg;
13386 	struct ctl_softc *softc = thr->ctl_softc;
13387 	union ctl_io *io;
13388 	int retval;
13389 
13390 	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13391 	thread_lock(curthread);
13392 	sched_prio(curthread, PUSER - 1);
13393 	thread_unlock(curthread);
13394 
13395 	while (!softc->shutdown) {
13396 		/*
13397 		 * We handle the queues in this order:
13398 		 * - ISC
13399 		 * - done queue (to free up resources, unblock other commands)
13400 		 * - incoming queue
13401 		 * - RtR queue
13402 		 *
13403 		 * If those queues are empty, we break out of the loop and
13404 		 * go to sleep.
13405 		 */
13406 		mtx_lock(&thr->queue_lock);
13407 		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13408 		if (io != NULL) {
13409 			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13410 			mtx_unlock(&thr->queue_lock);
13411 			ctl_handle_isc(io);
13412 			continue;
13413 		}
13414 		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13415 		if (io != NULL) {
13416 			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13417 			/* clear any blocked commands, call fe_done */
13418 			mtx_unlock(&thr->queue_lock);
13419 			ctl_process_done(io);
13420 			continue;
13421 		}
13422 		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13423 		if (io != NULL) {
13424 			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13425 			mtx_unlock(&thr->queue_lock);
13426 			if (io->io_hdr.io_type == CTL_IO_TASK)
13427 				ctl_run_task(io);
13428 			else
13429 				ctl_scsiio_precheck(&io->scsiio);
13430 			continue;
13431 		}
13432 		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13433 		if (io != NULL) {
13434 			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13435 			mtx_unlock(&thr->queue_lock);
13436 			retval = ctl_scsiio(&io->scsiio);
13437 			if (retval != CTL_RETVAL_COMPLETE)
13438 				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13439 			continue;
13440 		}
13441 
13442 		/* Sleep until we have something to do. */
13443 		mtx_sleep(thr, &thr->queue_lock, PDROP, "-", 0);
13444 	}
13445 	thr->thread = NULL;
13446 	kthread_exit();
13447 }
13448 
13449 static void
13450 ctl_thresh_thread(void *arg)
13451 {
13452 	struct ctl_softc *softc = (struct ctl_softc *)arg;
13453 	struct ctl_lun *lun;
13454 	struct ctl_logical_block_provisioning_page *page;
13455 	const char *attr;
13456 	union ctl_ha_msg msg;
13457 	uint64_t thres, val;
13458 	int i, e, set;
13459 
13460 	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13461 	thread_lock(curthread);
13462 	sched_prio(curthread, PUSER - 1);
13463 	thread_unlock(curthread);
13464 
13465 	while (!softc->shutdown) {
13466 		mtx_lock(&softc->ctl_lock);
13467 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13468 			if ((lun->flags & CTL_LUN_DISABLED) ||
13469 			    (lun->flags & CTL_LUN_NO_MEDIA) ||
13470 			    lun->backend->lun_attr == NULL)
13471 				continue;
13472 			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13473 			    softc->ha_mode == CTL_HA_MODE_XFER)
13474 				continue;
13475 			if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13476 				continue;
13477 			e = 0;
13478 			page = &lun->MODE_LBP;
13479 			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13480 				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13481 					continue;
13482 				thres = scsi_4btoul(page->descr[i].count);
13483 				thres <<= CTL_LBP_EXPONENT;
13484 				switch (page->descr[i].resource) {
13485 				case 0x01:
13486 					attr = "blocksavail";
13487 					break;
13488 				case 0x02:
13489 					attr = "blocksused";
13490 					break;
13491 				case 0xf1:
13492 					attr = "poolblocksavail";
13493 					break;
13494 				case 0xf2:
13495 					attr = "poolblocksused";
13496 					break;
13497 				default:
13498 					continue;
13499 				}
13500 				mtx_unlock(&softc->ctl_lock); // XXX
13501 				val = lun->backend->lun_attr(lun->be_lun, attr);
13502 				mtx_lock(&softc->ctl_lock);
13503 				if (val == UINT64_MAX)
13504 					continue;
13505 				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13506 				    == SLBPPD_ARMING_INC)
13507 					e = (val >= thres);
13508 				else
13509 					e = (val <= thres);
13510 				if (e)
13511 					break;
13512 			}
13513 			mtx_lock(&lun->lun_lock);
13514 			if (e) {
13515 				scsi_u64to8b((uint8_t *)&page->descr[i] -
13516 				    (uint8_t *)page, lun->ua_tpt_info);
13517 				if (lun->lasttpt == 0 ||
13518 				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13519 					lun->lasttpt = time_uptime;
13520 					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13521 					set = 1;
13522 				} else
13523 					set = 0;
13524 			} else {
13525 				lun->lasttpt = 0;
13526 				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13527 				set = -1;
13528 			}
13529 			mtx_unlock(&lun->lun_lock);
13530 			if (set != 0 &&
13531 			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13532 				/* Send msg to other side. */
13533 				bzero(&msg.ua, sizeof(msg.ua));
13534 				msg.hdr.msg_type = CTL_MSG_UA;
13535 				msg.hdr.nexus.initid = -1;
13536 				msg.hdr.nexus.targ_port = -1;
13537 				msg.hdr.nexus.targ_lun = lun->lun;
13538 				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13539 				msg.ua.ua_all = 1;
13540 				msg.ua.ua_set = (set > 0);
13541 				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13542 				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13543 				mtx_unlock(&softc->ctl_lock); // XXX
13544 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13545 				    sizeof(msg.ua), M_WAITOK);
13546 				mtx_lock(&softc->ctl_lock);
13547 			}
13548 		}
13549 		mtx_sleep(&softc->thresh_thread, &softc->ctl_lock,
13550 		    PDROP, "-", CTL_LBP_PERIOD * hz);
13551 	}
13552 	softc->thresh_thread = NULL;
13553 	kthread_exit();
13554 }
13555 
13556 static void
13557 ctl_enqueue_incoming(union ctl_io *io)
13558 {
13559 	struct ctl_softc *softc = CTL_SOFTC(io);
13560 	struct ctl_thread *thr;
13561 	u_int idx;
13562 
13563 	idx = (io->io_hdr.nexus.targ_port * 127 +
13564 	       io->io_hdr.nexus.initid) % worker_threads;
13565 	thr = &softc->threads[idx];
13566 	mtx_lock(&thr->queue_lock);
13567 	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13568 	mtx_unlock(&thr->queue_lock);
13569 	wakeup(thr);
13570 }
13571 
13572 static void
13573 ctl_enqueue_rtr(union ctl_io *io)
13574 {
13575 	struct ctl_softc *softc = CTL_SOFTC(io);
13576 	struct ctl_thread *thr;
13577 
13578 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13579 	mtx_lock(&thr->queue_lock);
13580 	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13581 	mtx_unlock(&thr->queue_lock);
13582 	wakeup(thr);
13583 }
13584 
13585 static void
13586 ctl_enqueue_done(union ctl_io *io)
13587 {
13588 	struct ctl_softc *softc = CTL_SOFTC(io);
13589 	struct ctl_thread *thr;
13590 
13591 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13592 	mtx_lock(&thr->queue_lock);
13593 	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13594 	mtx_unlock(&thr->queue_lock);
13595 	wakeup(thr);
13596 }
13597 
13598 static void
13599 ctl_enqueue_isc(union ctl_io *io)
13600 {
13601 	struct ctl_softc *softc = CTL_SOFTC(io);
13602 	struct ctl_thread *thr;
13603 
13604 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13605 	mtx_lock(&thr->queue_lock);
13606 	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13607 	mtx_unlock(&thr->queue_lock);
13608 	wakeup(thr);
13609 }
13610 
13611 /*
13612  *  vim: ts=8
13613  */
13614