xref: /freebsd/sys/cam/cam_xpt.c (revision 5a656ef632de2f363f37484b0128aa60b688bf32)
1 /*-
2  * Implementation of the Common Access Method Transport (XPT) layer.
3  *
4  * SPDX-License-Identifier: BSD-2-Clause
5  *
6  * Copyright (c) 1997, 1998, 1999 Justin T. Gibbs.
7  * Copyright (c) 1997, 1998, 1999 Kenneth D. Merry.
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions, and the following disclaimer,
15  *    without modification, immediately at the beginning of the file.
16  * 2. The name of the author may not be used to endorse or promote products
17  *    derived from this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
23  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include "opt_printf.h"
33 
34 #include <sys/param.h>
35 #include <sys/bio.h>
36 #include <sys/bus.h>
37 #include <sys/systm.h>
38 #include <sys/types.h>
39 #include <sys/malloc.h>
40 #include <sys/kernel.h>
41 #include <sys/time.h>
42 #include <sys/conf.h>
43 #include <sys/fcntl.h>
44 #include <sys/proc.h>
45 #include <sys/sbuf.h>
46 #include <sys/smp.h>
47 #include <sys/stdarg.h>
48 #include <sys/taskqueue.h>
49 
50 #include <sys/lock.h>
51 #include <sys/mutex.h>
52 #include <sys/sysctl.h>
53 #include <sys/kthread.h>
54 
55 #include <cam/cam.h>
56 #include <cam/cam_ccb.h>
57 #include <cam/cam_iosched.h>
58 #include <cam/cam_periph.h>
59 #include <cam/cam_queue.h>
60 #include <cam/cam_sim.h>
61 #include <cam/cam_xpt.h>
62 #include <cam/cam_xpt_sim.h>
63 #include <cam/cam_xpt_periph.h>
64 #include <cam/cam_xpt_internal.h>
65 #include <cam/cam_debug.h>
66 #include <cam/cam_compat.h>
67 
68 #include <cam/scsi/scsi_all.h>
69 #include <cam/scsi/scsi_message.h>
70 #include <cam/scsi/scsi_pass.h>
71 
72 
73 /* Wild guess based on not wanting to grow the stack too much */
74 #define XPT_PRINT_MAXLEN	512
75 #ifdef PRINTF_BUFR_SIZE
76 #define XPT_PRINT_LEN	PRINTF_BUFR_SIZE
77 #else
78 #define XPT_PRINT_LEN	128
79 #endif
80 _Static_assert(XPT_PRINT_LEN <= XPT_PRINT_MAXLEN, "XPT_PRINT_LEN is too large");
81 
82 /*
83  * This is the maximum number of high powered commands (e.g. start unit)
84  * that can be outstanding at a particular time.
85  */
86 #ifndef CAM_MAX_HIGHPOWER
87 #define CAM_MAX_HIGHPOWER  4
88 #endif
89 
90 /* Datastructures internal to the xpt layer */
91 MALLOC_DEFINE(M_CAMXPT, "CAM XPT", "CAM XPT buffers");
92 MALLOC_DEFINE(M_CAMDEV, "CAM DEV", "CAM devices");
93 MALLOC_DEFINE(M_CAMCCB, "CAM CCB", "CAM CCBs");
94 MALLOC_DEFINE(M_CAMPATH, "CAM path", "CAM paths");
95 
96 struct xpt_softc {
97 	uint32_t		xpt_generation;
98 
99 	/* number of high powered commands that can go through right now */
100 	struct mtx		xpt_highpower_lock;
101 	STAILQ_HEAD(highpowerlist, cam_ed)	highpowerq;
102 	int			num_highpower;
103 
104 	/* queue for handling async rescan requests. */
105 	TAILQ_HEAD(, ccb_hdr) ccb_scanq;
106 	int buses_to_config;
107 	int buses_config_done;
108 
109 	/*
110 	 * Registered buses
111 	 *
112 	 * N.B., "busses" is an archaic spelling of "buses".  In new code
113 	 * "buses" is preferred.
114 	 */
115 	TAILQ_HEAD(,cam_eb)	xpt_busses;
116 	u_int			bus_generation;
117 
118 	int			boot_delay;
119 	struct callout 		boot_callout;
120 	struct task		boot_task;
121 	struct root_hold_token	xpt_rootmount;
122 
123 	struct mtx		xpt_topo_lock;
124 	struct taskqueue	*xpt_taskq;
125 };
126 
127 typedef enum {
128 	DM_RET_COPY		= 0x01,
129 	DM_RET_FLAG_MASK	= 0x0f,
130 	DM_RET_NONE		= 0x00,
131 	DM_RET_STOP		= 0x10,
132 	DM_RET_DESCEND		= 0x20,
133 	DM_RET_ERROR		= 0x30,
134 	DM_RET_ACTION_MASK	= 0xf0
135 } dev_match_ret;
136 
137 typedef enum {
138 	XPT_DEPTH_BUS,
139 	XPT_DEPTH_TARGET,
140 	XPT_DEPTH_DEVICE,
141 	XPT_DEPTH_PERIPH
142 } xpt_traverse_depth;
143 
144 struct xpt_traverse_config {
145 	xpt_traverse_depth	depth;
146 	void			*tr_func;
147 	void			*tr_arg;
148 };
149 
150 typedef	int	xpt_busfunc_t (struct cam_eb *bus, void *arg);
151 typedef	int	xpt_targetfunc_t (struct cam_et *target, void *arg);
152 typedef	int	xpt_devicefunc_t (struct cam_ed *device, void *arg);
153 typedef	int	xpt_periphfunc_t (struct cam_periph *periph, void *arg);
154 typedef int	xpt_pdrvfunc_t (struct periph_driver **pdrv, void *arg);
155 
156 /* Transport layer configuration information */
157 static struct xpt_softc xsoftc;
158 
159 MTX_SYSINIT(xpt_topo_init, &xsoftc.xpt_topo_lock, "XPT topology lock", MTX_DEF);
160 
161 SYSCTL_INT(_kern_cam, OID_AUTO, boot_delay, CTLFLAG_RDTUN,
162            &xsoftc.boot_delay, 0, "Bus registration wait time");
163 SYSCTL_UINT(_kern_cam, OID_AUTO, xpt_generation, CTLFLAG_RD,
164 	    &xsoftc.xpt_generation, 0, "CAM peripheral generation count");
165 
166 struct cam_doneq {
167 	struct mtx_padalign	cam_doneq_mtx;
168 	STAILQ_HEAD(, ccb_hdr)	cam_doneq;
169 	int			cam_doneq_sleep;
170 };
171 
172 static struct cam_doneq cam_doneqs[MAXCPU];
173 static u_int __read_mostly cam_num_doneqs;
174 static struct proc *cam_proc;
175 static struct cam_doneq cam_async;
176 
177 SYSCTL_INT(_kern_cam, OID_AUTO, num_doneqs, CTLFLAG_RDTUN,
178            &cam_num_doneqs, 0, "Number of completion queues/threads");
179 
180 struct cam_periph *xpt_periph;
181 
182 static periph_init_t xpt_periph_init;
183 
184 static struct periph_driver xpt_driver =
185 {
186 	xpt_periph_init, "xpt",
187 	TAILQ_HEAD_INITIALIZER(xpt_driver.units), /* generation */ 0,
188 	CAM_PERIPH_DRV_EARLY
189 };
190 
191 PERIPHDRIVER_DECLARE(xpt, xpt_driver);
192 
193 static d_open_t xptopen;
194 static d_close_t xptclose;
195 static d_ioctl_t xptioctl;
196 static d_ioctl_t xptdoioctl;
197 
198 static struct cdevsw xpt_cdevsw = {
199 	.d_version =	D_VERSION,
200 	.d_flags =	0,
201 	.d_open =	xptopen,
202 	.d_close =	xptclose,
203 	.d_ioctl =	xptioctl,
204 	.d_name =	"xpt",
205 };
206 
207 /* Storage for debugging datastructures */
208 struct cam_path *cam_dpath;
209 uint32_t __read_mostly cam_dflags = CAM_DEBUG_FLAGS;
210 SYSCTL_UINT(_kern_cam, OID_AUTO, dflags, CTLFLAG_RWTUN,
211 	&cam_dflags, 0, "Enabled debug flags");
212 uint32_t cam_debug_delay = CAM_DEBUG_DELAY;
213 SYSCTL_UINT(_kern_cam, OID_AUTO, debug_delay, CTLFLAG_RWTUN,
214 	&cam_debug_delay, 0, "Delay in us after each debug message");
215 
216 /* Our boot-time initialization hook */
217 static int cam_module_event_handler(module_t, int /*modeventtype_t*/, void *);
218 
219 static moduledata_t cam_moduledata = {
220 	"cam",
221 	cam_module_event_handler,
222 	NULL
223 };
224 
225 static int	xpt_init(void *);
226 
227 DECLARE_MODULE(cam, cam_moduledata, SI_SUB_CONFIGURE, SI_ORDER_SECOND);
228 MODULE_VERSION(cam, 1);
229 
230 static void		xpt_async_bcast(struct async_list *async_head,
231 					uint32_t async_code,
232 					struct cam_path *path,
233 					void *async_arg);
234 static path_id_t xptnextfreepathid(void);
235 static path_id_t xptpathid(const char *sim_name, int sim_unit, int sim_bus);
236 static union ccb *xpt_get_ccb(struct cam_periph *periph);
237 static union ccb *xpt_get_ccb_nowait(struct cam_periph *periph);
238 static void	 xpt_run_allocq(struct cam_periph *periph, int sleep);
239 static void	 xpt_run_allocq_task(void *context, int pending);
240 static void	 xpt_run_devq(struct cam_devq *devq);
241 static callout_func_t xpt_release_devq_timeout;
242 static void	 xpt_acquire_bus(struct cam_eb *bus);
243 static void	 xpt_release_bus(struct cam_eb *bus);
244 static uint32_t	 xpt_freeze_devq_device(struct cam_ed *dev, u_int count);
245 static int	 xpt_release_devq_device(struct cam_ed *dev, u_int count,
246 		    int run_queue);
247 static struct cam_et*
248 		 xpt_alloc_target(struct cam_eb *bus, target_id_t target_id);
249 static void	 xpt_acquire_target(struct cam_et *target);
250 static void	 xpt_release_target(struct cam_et *target);
251 static struct cam_eb*
252 		 xpt_find_bus(path_id_t path_id);
253 static struct cam_et*
254 		 xpt_find_target(struct cam_eb *bus, target_id_t target_id);
255 static struct cam_ed*
256 		 xpt_find_device(struct cam_et *target, lun_id_t lun_id);
257 static void	 xpt_config(void *arg);
258 static void	 xpt_hold_boot_locked(void);
259 static int	 xpt_schedule_dev(struct camq *queue, cam_pinfo *dev_pinfo,
260 				 uint32_t new_priority);
261 static xpt_devicefunc_t xptpassannouncefunc;
262 static void	 xptaction(struct cam_sim *sim, union ccb *work_ccb);
263 static void	 xptpoll(struct cam_sim *sim);
264 static void	 camisr_runqueue(void);
265 static void	 xpt_done_process(struct ccb_hdr *ccb_h);
266 static void	 xpt_done_td(void *);
267 static void	 xpt_async_td(void *);
268 static dev_match_ret	xptbusmatch(struct dev_match_pattern *patterns,
269 				    u_int num_patterns, struct cam_eb *bus);
270 static dev_match_ret	xptdevicematch(struct dev_match_pattern *patterns,
271 				       u_int num_patterns,
272 				       struct cam_ed *device);
273 static dev_match_ret	xptperiphmatch(struct dev_match_pattern *patterns,
274 				       u_int num_patterns,
275 				       struct cam_periph *periph);
276 static xpt_busfunc_t	xptedtbusfunc;
277 static xpt_targetfunc_t	xptedttargetfunc;
278 static xpt_devicefunc_t	xptedtdevicefunc;
279 static xpt_periphfunc_t	xptedtperiphfunc;
280 static xpt_pdrvfunc_t	xptplistpdrvfunc;
281 static xpt_periphfunc_t	xptplistperiphfunc;
282 static int		xptedtmatch(struct ccb_dev_match *cdm);
283 static int		xptperiphlistmatch(struct ccb_dev_match *cdm);
284 static int		xptbustraverse(struct cam_eb *start_bus,
285 				       xpt_busfunc_t *tr_func, void *arg);
286 static int		xpttargettraverse(struct cam_eb *bus,
287 					  struct cam_et *start_target,
288 					  xpt_targetfunc_t *tr_func, void *arg);
289 static int		xptdevicetraverse(struct cam_et *target,
290 					  struct cam_ed *start_device,
291 					  xpt_devicefunc_t *tr_func, void *arg);
292 static int		xptperiphtraverse(struct cam_ed *device,
293 					  struct cam_periph *start_periph,
294 					  xpt_periphfunc_t *tr_func, void *arg);
295 static int		xptpdrvtraverse(struct periph_driver **start_pdrv,
296 					xpt_pdrvfunc_t *tr_func, void *arg);
297 static int		xptpdperiphtraverse(struct periph_driver **pdrv,
298 					    struct cam_periph *start_periph,
299 					    xpt_periphfunc_t *tr_func,
300 					    void *arg);
301 static xpt_busfunc_t	xptdefbusfunc;
302 static xpt_targetfunc_t	xptdeftargetfunc;
303 static xpt_devicefunc_t	xptdefdevicefunc;
304 static xpt_periphfunc_t	xptdefperiphfunc;
305 static void		xpt_finishconfig_task(void *context, int pending);
306 static void		xpt_dev_async_default(uint32_t async_code,
307 					      struct cam_eb *bus,
308 					      struct cam_et *target,
309 					      struct cam_ed *device,
310 					      void *async_arg);
311 static struct cam_ed *	xpt_alloc_device_default(struct cam_eb *bus,
312 						 struct cam_et *target,
313 						 lun_id_t lun_id);
314 static xpt_devicefunc_t	xptsetasyncfunc;
315 static xpt_busfunc_t	xptsetasyncbusfunc;
316 static cam_status	xptregister(struct cam_periph *periph,
317 				    void *arg);
318 
319 static __inline int
xpt_schedule_devq(struct cam_devq * devq,struct cam_ed * dev)320 xpt_schedule_devq(struct cam_devq *devq, struct cam_ed *dev)
321 {
322 	int	retval;
323 
324 	mtx_assert(&devq->send_mtx, MA_OWNED);
325 	if ((dev->ccbq.queue.entries > 0) &&
326 	    (dev->ccbq.dev_openings > 0) &&
327 	    (dev->ccbq.queue.qfrozen_cnt == 0)) {
328 		/*
329 		 * The priority of a device waiting for controller
330 		 * resources is that of the highest priority CCB
331 		 * enqueued.
332 		 */
333 		retval =
334 		    xpt_schedule_dev(&devq->send_queue,
335 				     &dev->devq_entry,
336 				     CAMQ_GET_PRIO(&dev->ccbq.queue));
337 	} else {
338 		retval = 0;
339 	}
340 	return (retval);
341 }
342 
343 static __inline int
device_is_queued(struct cam_ed * device)344 device_is_queued(struct cam_ed *device)
345 {
346 	return (device->devq_entry.index != CAM_UNQUEUED_INDEX);
347 }
348 
349 static void
xpt_periph_init(void)350 xpt_periph_init(void)
351 {
352 	make_dev(&xpt_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600, "xpt0");
353 }
354 
355 static int
xptopen(struct cdev * dev,int flags,int fmt,struct thread * td)356 xptopen(struct cdev *dev, int flags, int fmt, struct thread *td)
357 {
358 
359 	/*
360 	 * Only allow read-write access.
361 	 */
362 	if (((flags & FWRITE) == 0) || ((flags & FREAD) == 0))
363 		return(EPERM);
364 
365 	/*
366 	 * We don't allow nonblocking access.
367 	 */
368 	if ((flags & O_NONBLOCK) != 0) {
369 		printf("%s: can't do nonblocking access\n", devtoname(dev));
370 		return(ENODEV);
371 	}
372 
373 	return(0);
374 }
375 
376 static int
xptclose(struct cdev * dev,int flag,int fmt,struct thread * td)377 xptclose(struct cdev *dev, int flag, int fmt, struct thread *td)
378 {
379 
380 	return(0);
381 }
382 
383 /*
384  * Don't automatically grab the xpt softc lock here even though this is going
385  * through the xpt device.  The xpt device is really just a back door for
386  * accessing other devices and SIMs, so the right thing to do is to grab
387  * the appropriate SIM lock once the bus/SIM is located.
388  */
389 static int
xptioctl(struct cdev * dev,u_long cmd,caddr_t addr,int flag,struct thread * td)390 xptioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
391 {
392 	int error;
393 
394 	if ((error = xptdoioctl(dev, cmd, addr, flag, td)) == ENOTTY) {
395 		error = cam_compat_ioctl(dev, cmd, addr, flag, td, xptdoioctl);
396 	}
397 	return (error);
398 }
399 
400 static int
xptdoioctl(struct cdev * dev,u_long cmd,caddr_t addr,int flag,struct thread * td)401 xptdoioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
402 {
403 	int error;
404 
405 	error = 0;
406 
407 	switch(cmd) {
408 	/*
409 	 * For the transport layer CAMIOCOMMAND ioctl, we really only want
410 	 * to accept CCB types that don't quite make sense to send through a
411 	 * passthrough driver. XPT_PATH_INQ is an exception to this, as stated
412 	 * in the CAM spec.
413 	 */
414 	case CAMIOCOMMAND: {
415 		union ccb *ccb;
416 		union ccb *inccb;
417 		struct cam_eb *bus;
418 
419 		inccb = (union ccb *)addr;
420 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
421 		if (inccb->ccb_h.func_code == XPT_SCSI_IO)
422 			inccb->csio.bio = NULL;
423 #endif
424 
425 		if (inccb->ccb_h.flags & CAM_UNLOCKED)
426 			return (EINVAL);
427 
428 		bus = xpt_find_bus(inccb->ccb_h.path_id);
429 		if (bus == NULL)
430 			return (EINVAL);
431 
432 		switch (inccb->ccb_h.func_code) {
433 		case XPT_SCAN_BUS:
434 		case XPT_RESET_BUS:
435 			if (inccb->ccb_h.target_id != CAM_TARGET_WILDCARD ||
436 			    inccb->ccb_h.target_lun != CAM_LUN_WILDCARD) {
437 				xpt_release_bus(bus);
438 				return (EINVAL);
439 			}
440 			break;
441 		case XPT_SCAN_TGT:
442 			if (inccb->ccb_h.target_id == CAM_TARGET_WILDCARD ||
443 			    inccb->ccb_h.target_lun != CAM_LUN_WILDCARD) {
444 				xpt_release_bus(bus);
445 				return (EINVAL);
446 			}
447 			break;
448 		default:
449 			break;
450 		}
451 
452 		switch(inccb->ccb_h.func_code) {
453 		case XPT_SCAN_BUS:
454 		case XPT_RESET_BUS:
455 		case XPT_PATH_INQ:
456 		case XPT_ENG_INQ:
457 		case XPT_SCAN_LUN:
458 		case XPT_SCAN_TGT:
459 
460 			ccb = xpt_alloc_ccb();
461 
462 			/*
463 			 * Create a path using the bus, target, and lun the
464 			 * user passed in.
465 			 */
466 			if (xpt_create_path(&ccb->ccb_h.path, NULL,
467 					    inccb->ccb_h.path_id,
468 					    inccb->ccb_h.target_id,
469 					    inccb->ccb_h.target_lun) !=
470 					    CAM_REQ_CMP){
471 				error = EINVAL;
472 				xpt_free_ccb(ccb);
473 				break;
474 			}
475 			/* Ensure all of our fields are correct */
476 			xpt_setup_ccb(&ccb->ccb_h, ccb->ccb_h.path,
477 				      inccb->ccb_h.pinfo.priority);
478 			xpt_merge_ccb(ccb, inccb);
479 			xpt_path_lock(ccb->ccb_h.path);
480 			cam_periph_runccb(ccb, NULL, 0, 0, NULL);
481 			xpt_path_unlock(ccb->ccb_h.path);
482 			bcopy(ccb, inccb, sizeof(union ccb));
483 			xpt_free_path(ccb->ccb_h.path);
484 			xpt_free_ccb(ccb);
485 			break;
486 
487 		case XPT_DEBUG: {
488 			union ccb ccb;
489 
490 			/*
491 			 * This is an immediate CCB, so it's okay to
492 			 * allocate it on the stack.
493 			 */
494 			memset(&ccb, 0, sizeof(ccb));
495 
496 			/*
497 			 * Create a path using the bus, target, and lun the
498 			 * user passed in.
499 			 */
500 			if (xpt_create_path(&ccb.ccb_h.path, NULL,
501 					    inccb->ccb_h.path_id,
502 					    inccb->ccb_h.target_id,
503 					    inccb->ccb_h.target_lun) !=
504 					    CAM_REQ_CMP){
505 				error = EINVAL;
506 				break;
507 			}
508 			/* Ensure all of our fields are correct */
509 			xpt_setup_ccb(&ccb.ccb_h, ccb.ccb_h.path,
510 				      inccb->ccb_h.pinfo.priority);
511 			xpt_merge_ccb(&ccb, inccb);
512 			xpt_action(&ccb);
513 			bcopy(&ccb, inccb, sizeof(union ccb));
514 			xpt_free_path(ccb.ccb_h.path);
515 			break;
516 		}
517 		case XPT_DEV_MATCH: {
518 			struct cam_periph_map_info mapinfo;
519 			struct cam_path *old_path;
520 
521 			/*
522 			 * We can't deal with physical addresses for this
523 			 * type of transaction.
524 			 */
525 			if ((inccb->ccb_h.flags & CAM_DATA_MASK) !=
526 			    CAM_DATA_VADDR) {
527 				error = EINVAL;
528 				break;
529 			}
530 
531 			/*
532 			 * Save this in case the caller had it set to
533 			 * something in particular.
534 			 */
535 			old_path = inccb->ccb_h.path;
536 
537 			/*
538 			 * We really don't need a path for the matching
539 			 * code.  The path is needed because of the
540 			 * debugging statements in xpt_action().  They
541 			 * assume that the CCB has a valid path.
542 			 */
543 			inccb->ccb_h.path = xpt_periph->path;
544 
545 			bzero(&mapinfo, sizeof(mapinfo));
546 
547 			/*
548 			 * Map the pattern and match buffers into kernel
549 			 * virtual address space.
550 			 */
551 			error = cam_periph_mapmem(inccb, &mapinfo, maxphys);
552 
553 			if (error) {
554 				inccb->ccb_h.path = old_path;
555 				break;
556 			}
557 
558 			/*
559 			 * This is an immediate CCB, we can send it on directly.
560 			 */
561 			xpt_action(inccb);
562 
563 			/*
564 			 * Map the buffers back into user space.
565 			 */
566 			error = cam_periph_unmapmem(inccb, &mapinfo);
567 
568 			inccb->ccb_h.path = old_path;
569 			break;
570 		}
571 		default:
572 			error = ENOTSUP;
573 			break;
574 		}
575 		xpt_release_bus(bus);
576 		break;
577 	}
578 	/*
579 	 * This is the getpassthru ioctl. It takes a XPT_GDEVLIST ccb as input,
580 	 * with the periphal driver name and unit name filled in.  The other
581 	 * fields don't really matter as input.  The passthrough driver name
582 	 * ("pass"), and unit number are passed back in the ccb.  The current
583 	 * device generation number, and the index into the device peripheral
584 	 * driver list, and the status are also passed back.  Note that
585 	 * since we do everything in one pass, unlike the XPT_GDEVLIST ccb,
586 	 * we never return a status of CAM_GDEVLIST_LIST_CHANGED.  It is
587 	 * (or rather should be) impossible for the device peripheral driver
588 	 * list to change since we look at the whole thing in one pass, and
589 	 * we do it with lock protection.
590 	 *
591 	 */
592 	case CAMGETPASSTHRU: {
593 		union ccb *ccb;
594 		struct cam_periph *periph;
595 		struct periph_driver **p_drv;
596 		char   *name;
597 		u_int unit;
598 		bool base_periph_found;
599 
600 		ccb = (union ccb *)addr;
601 		unit = ccb->cgdl.unit_number;
602 		name = ccb->cgdl.periph_name;
603 		base_periph_found = false;
604 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
605 		if (ccb->ccb_h.func_code == XPT_SCSI_IO)
606 			ccb->csio.bio = NULL;
607 #endif
608 
609 		/*
610 		 * Sanity check -- make sure we don't get a null peripheral
611 		 * driver name.
612 		 */
613 		if (*ccb->cgdl.periph_name == '\0') {
614 			error = EINVAL;
615 			break;
616 		}
617 
618 		/* Keep the list from changing while we traverse it */
619 		xpt_lock_buses();
620 
621 		/* first find our driver in the list of drivers */
622 		for (p_drv = periph_drivers; *p_drv != NULL; p_drv++)
623 			if (strcmp((*p_drv)->driver_name, name) == 0)
624 				break;
625 
626 		if (*p_drv == NULL) {
627 			xpt_unlock_buses();
628 			ccb->ccb_h.status = CAM_REQ_CMP_ERR;
629 			ccb->cgdl.status = CAM_GDEVLIST_ERROR;
630 			*ccb->cgdl.periph_name = '\0';
631 			ccb->cgdl.unit_number = 0;
632 			error = ENOENT;
633 			break;
634 		}
635 
636 		/*
637 		 * Run through every peripheral instance of this driver
638 		 * and check to see whether it matches the unit passed
639 		 * in by the user.  If it does, get out of the loops and
640 		 * find the passthrough driver associated with that
641 		 * peripheral driver.
642 		 */
643 		for (periph = TAILQ_FIRST(&(*p_drv)->units); periph != NULL;
644 		     periph = TAILQ_NEXT(periph, unit_links)) {
645 			if (periph->unit_number == unit)
646 				break;
647 		}
648 		/*
649 		 * If we found the peripheral driver that the user passed
650 		 * in, go through all of the peripheral drivers for that
651 		 * particular device and look for a passthrough driver.
652 		 */
653 		if (periph != NULL) {
654 			struct cam_ed *device;
655 			int i;
656 
657 			base_periph_found = true;
658 			device = periph->path->device;
659 			for (i = 0, periph = SLIST_FIRST(&device->periphs);
660 			     periph != NULL;
661 			     periph = SLIST_NEXT(periph, periph_links), i++) {
662 				/*
663 				 * Check to see whether we have a
664 				 * passthrough device or not.
665 				 */
666 				if (strcmp(periph->periph_name, "pass") == 0) {
667 					/*
668 					 * Fill in the getdevlist fields.
669 					 */
670 					strlcpy(ccb->cgdl.periph_name,
671 					       periph->periph_name,
672 					       sizeof(ccb->cgdl.periph_name));
673 					ccb->cgdl.unit_number =
674 						periph->unit_number;
675 					if (SLIST_NEXT(periph, periph_links))
676 						ccb->cgdl.status =
677 							CAM_GDEVLIST_MORE_DEVS;
678 					else
679 						ccb->cgdl.status =
680 						       CAM_GDEVLIST_LAST_DEVICE;
681 					ccb->cgdl.generation =
682 						device->generation;
683 					ccb->cgdl.index = i;
684 					/*
685 					 * Fill in some CCB header fields
686 					 * that the user may want.
687 					 */
688 					ccb->ccb_h.path_id =
689 						periph->path->bus->path_id;
690 					ccb->ccb_h.target_id =
691 						periph->path->target->target_id;
692 					ccb->ccb_h.target_lun =
693 						periph->path->device->lun_id;
694 					ccb->ccb_h.status = CAM_REQ_CMP;
695 					break;
696 				}
697 			}
698 		}
699 
700 		/*
701 		 * If the periph is null here, one of two things has
702 		 * happened.  The first possibility is that we couldn't
703 		 * find the unit number of the particular peripheral driver
704 		 * that the user is asking about.  e.g. the user asks for
705 		 * the passthrough driver for "da11".  We find the list of
706 		 * "da" peripherals all right, but there is no unit 11.
707 		 * The other possibility is that we went through the list
708 		 * of peripheral drivers attached to the device structure,
709 		 * but didn't find one with the name "pass".  Either way,
710 		 * we return ENOENT, since we couldn't find something.
711 		 */
712 		if (periph == NULL) {
713 			ccb->ccb_h.status = CAM_REQ_CMP_ERR;
714 			ccb->cgdl.status = CAM_GDEVLIST_ERROR;
715 			*ccb->cgdl.periph_name = '\0';
716 			ccb->cgdl.unit_number = 0;
717 			error = ENOENT;
718 			/*
719 			 * It is unfortunate that this is even necessary,
720 			 * but there are many, many clueless users out there.
721 			 * If this is true, the user is looking for the
722 			 * passthrough driver, but doesn't have one in his
723 			 * kernel.
724 			 */
725 			if (base_periph_found) {
726 				printf(
727 		"xptioctl: pass driver is not in the kernel\n"
728 		"xptioctl: put \"device pass\" in your kernel config file\n");
729 			}
730 		}
731 		xpt_unlock_buses();
732 		break;
733 		}
734 	default:
735 		error = ENOTTY;
736 		break;
737 	}
738 
739 	return(error);
740 }
741 
742 static int
cam_module_event_handler(module_t mod,int what,void * arg)743 cam_module_event_handler(module_t mod, int what, void *arg)
744 {
745 	int error;
746 
747 	switch (what) {
748 	case MOD_LOAD:
749 		if ((error = xpt_init(NULL)) != 0)
750 			return (error);
751 		break;
752 	case MOD_UNLOAD:
753 		return EBUSY;
754 	default:
755 		return EOPNOTSUPP;
756 	}
757 
758 	return 0;
759 }
760 
761 static struct xpt_proto *
xpt_proto_find(cam_proto proto)762 xpt_proto_find(cam_proto proto)
763 {
764 	struct xpt_proto **pp;
765 
766 	SET_FOREACH(pp, cam_xpt_proto_set) {
767 		if ((*pp)->proto == proto)
768 			return *pp;
769 	}
770 
771 	return NULL;
772 }
773 
774 static void
xpt_rescan_done(struct cam_periph * periph,union ccb * done_ccb)775 xpt_rescan_done(struct cam_periph *periph, union ccb *done_ccb)
776 {
777 
778 	if (done_ccb->ccb_h.ppriv_ptr1 == NULL) {
779 		xpt_free_path(done_ccb->ccb_h.path);
780 		xpt_free_ccb(done_ccb);
781 	} else {
782 		done_ccb->ccb_h.cbfcnp = done_ccb->ccb_h.ppriv_ptr1;
783 		(*done_ccb->ccb_h.cbfcnp)(periph, done_ccb);
784 	}
785 	xpt_release_boot();
786 }
787 
788 /* thread to handle bus rescans */
789 static void
xpt_scanner_thread(void * dummy)790 xpt_scanner_thread(void *dummy)
791 {
792 	union ccb	*ccb;
793 	struct mtx	*mtx;
794 	struct cam_ed	*device;
795 
796 	xpt_lock_buses();
797 	for (;;) {
798 		if (TAILQ_EMPTY(&xsoftc.ccb_scanq))
799 			msleep(&xsoftc.ccb_scanq, &xsoftc.xpt_topo_lock, PRIBIO,
800 			       "-", 0);
801 		if ((ccb = (union ccb *)TAILQ_FIRST(&xsoftc.ccb_scanq)) != NULL) {
802 			TAILQ_REMOVE(&xsoftc.ccb_scanq, &ccb->ccb_h, sim_links.tqe);
803 			xpt_unlock_buses();
804 
805 			/*
806 			 * We need to lock the device's mutex which we use as
807 			 * the path mutex. We can't do it directly because the
808 			 * cam_path in the ccb may wind up going away because
809 			 * the path lock may be dropped and the path retired in
810 			 * the completion callback. We do this directly to keep
811 			 * the reference counts in cam_path sane. We also have
812 			 * to copy the device pointer because ccb_h.path may
813 			 * be freed in the callback.
814 			 */
815 			mtx = xpt_path_mtx(ccb->ccb_h.path);
816 			device = ccb->ccb_h.path->device;
817 			xpt_acquire_device(device);
818 			mtx_lock(mtx);
819 			xpt_action(ccb);
820 			mtx_unlock(mtx);
821 			xpt_release_device(device);
822 
823 			xpt_lock_buses();
824 		}
825 	}
826 }
827 
828 void
xpt_rescan(union ccb * ccb)829 xpt_rescan(union ccb *ccb)
830 {
831 	struct ccb_hdr *hdr;
832 
833 	/* Prepare request */
834 	if (ccb->ccb_h.path->target->target_id == CAM_TARGET_WILDCARD &&
835 	    ccb->ccb_h.path->device->lun_id == CAM_LUN_WILDCARD)
836 		ccb->ccb_h.func_code = XPT_SCAN_BUS;
837 	else if (ccb->ccb_h.path->target->target_id != CAM_TARGET_WILDCARD &&
838 	    ccb->ccb_h.path->device->lun_id == CAM_LUN_WILDCARD)
839 		ccb->ccb_h.func_code = XPT_SCAN_TGT;
840 	else if (ccb->ccb_h.path->target->target_id != CAM_TARGET_WILDCARD &&
841 	    ccb->ccb_h.path->device->lun_id != CAM_LUN_WILDCARD)
842 		ccb->ccb_h.func_code = XPT_SCAN_LUN;
843 	else {
844 		xpt_print(ccb->ccb_h.path, "illegal scan path\n");
845 		xpt_free_path(ccb->ccb_h.path);
846 		xpt_free_ccb(ccb);
847 		return;
848 	}
849 	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE,
850 	    ("xpt_rescan: func %#x %s\n", ccb->ccb_h.func_code,
851  		xpt_action_name(ccb->ccb_h.func_code)));
852 
853 	ccb->ccb_h.ppriv_ptr1 = ccb->ccb_h.cbfcnp;
854 	ccb->ccb_h.cbfcnp = xpt_rescan_done;
855 	xpt_setup_ccb(&ccb->ccb_h, ccb->ccb_h.path, CAM_PRIORITY_XPT);
856 	/* Don't make duplicate entries for the same paths. */
857 	xpt_lock_buses();
858 	if (ccb->ccb_h.ppriv_ptr1 == NULL) {
859 		TAILQ_FOREACH(hdr, &xsoftc.ccb_scanq, sim_links.tqe) {
860 			if (xpt_path_comp(hdr->path, ccb->ccb_h.path) == 0) {
861 				wakeup(&xsoftc.ccb_scanq);
862 				xpt_unlock_buses();
863 				xpt_print(ccb->ccb_h.path, "rescan already queued\n");
864 				xpt_free_path(ccb->ccb_h.path);
865 				xpt_free_ccb(ccb);
866 				return;
867 			}
868 		}
869 	}
870 	TAILQ_INSERT_TAIL(&xsoftc.ccb_scanq, &ccb->ccb_h, sim_links.tqe);
871 	xpt_hold_boot_locked();
872 	wakeup(&xsoftc.ccb_scanq);
873 	xpt_unlock_buses();
874 }
875 
876 /* Functions accessed by the peripheral drivers */
877 static int
xpt_init(void * dummy)878 xpt_init(void *dummy)
879 {
880 	struct cam_sim *xpt_sim;
881 	struct cam_path *path;
882 	struct cam_devq *devq;
883 	cam_status status;
884 	int error, i;
885 
886 	TAILQ_INIT(&xsoftc.xpt_busses);
887 	TAILQ_INIT(&xsoftc.ccb_scanq);
888 	STAILQ_INIT(&xsoftc.highpowerq);
889 	xsoftc.num_highpower = CAM_MAX_HIGHPOWER;
890 
891 	mtx_init(&xsoftc.xpt_highpower_lock, "XPT highpower lock", NULL, MTX_DEF);
892 	xsoftc.xpt_taskq = taskqueue_create("CAM XPT task", M_WAITOK,
893 	    taskqueue_thread_enqueue, /*context*/&xsoftc.xpt_taskq);
894 
895 #ifdef CAM_BOOT_DELAY
896 	/*
897 	 * Override this value at compile time to assist our users
898 	 * who don't use loader to boot a kernel.
899 	 */
900 	xsoftc.boot_delay = CAM_BOOT_DELAY;
901 #endif
902 
903 	/*
904 	 * The xpt layer is, itself, the equivalent of a SIM.
905 	 * Allow 16 ccbs in the ccb pool for it.  This should
906 	 * give decent parallelism when we probe buses and
907 	 * perform other XPT functions.
908 	 */
909 	devq = cam_simq_alloc(16);
910 	if (devq == NULL)
911 		return (ENOMEM);
912 	xpt_sim = cam_sim_alloc(xptaction,
913 				xptpoll,
914 				"xpt",
915 				/*softc*/NULL,
916 				/*unit*/0,
917 				/*mtx*/NULL,
918 				/*max_dev_transactions*/0,
919 				/*max_tagged_dev_transactions*/0,
920 				devq);
921 	if (xpt_sim == NULL)
922 		return (ENOMEM);
923 
924 	if ((error = xpt_bus_register(xpt_sim, NULL, 0)) != CAM_SUCCESS) {
925 		printf(
926 		    "xpt_init: xpt_bus_register failed with errno %d, failing attach\n",
927 		    error);
928 		return (EINVAL);
929 	}
930 
931 	/*
932 	 * Looking at the XPT from the SIM layer, the XPT is
933 	 * the equivalent of a peripheral driver.  Allocate
934 	 * a peripheral driver entry for us.
935 	 */
936 	if ((status = xpt_create_path(&path, NULL, CAM_XPT_PATH_ID,
937 				      CAM_TARGET_WILDCARD,
938 				      CAM_LUN_WILDCARD)) != CAM_REQ_CMP) {
939 		printf(
940 	"xpt_init: xpt_create_path failed with status %#x, failing attach\n",
941 		    status);
942 		return (EINVAL);
943 	}
944 	xpt_path_lock(path);
945 	cam_periph_alloc(xptregister, NULL, NULL, NULL, "xpt", CAM_PERIPH_BIO,
946 			 path, NULL, 0, xpt_sim);
947 	xpt_path_unlock(path);
948 	xpt_free_path(path);
949 
950 	if (cam_num_doneqs < 1)
951 		cam_num_doneqs = 1 + mp_ncpus / 6;
952 	else if (cam_num_doneqs > MAXCPU)
953 		cam_num_doneqs = MAXCPU;
954 	for (i = 0; i < cam_num_doneqs; i++) {
955 		mtx_init(&cam_doneqs[i].cam_doneq_mtx, "CAM doneq", NULL,
956 		    MTX_DEF);
957 		STAILQ_INIT(&cam_doneqs[i].cam_doneq);
958 		error = kproc_kthread_add(xpt_done_td, &cam_doneqs[i],
959 		    &cam_proc, NULL, 0, 0, "cam", "doneq%d", i);
960 		if (error != 0) {
961 			cam_num_doneqs = i;
962 			break;
963 		}
964 	}
965 	if (cam_num_doneqs < 1) {
966 		printf("xpt_init: Cannot init completion queues - failing attach\n");
967 		return (ENOMEM);
968 	}
969 
970 	mtx_init(&cam_async.cam_doneq_mtx, "CAM async", NULL, MTX_DEF);
971 	STAILQ_INIT(&cam_async.cam_doneq);
972 	if (kproc_kthread_add(xpt_async_td, &cam_async,
973 		&cam_proc, NULL, 0, 0, "cam", "async") != 0) {
974 		printf("xpt_init: Cannot init async thread - failing attach\n");
975 		return (ENOMEM);
976 	}
977 
978 	/*
979 	 * Register a callback for when interrupts are enabled.
980 	 */
981 	config_intrhook_oneshot(xpt_config, NULL);
982 
983 	return (0);
984 }
985 
986 static cam_status
xptregister(struct cam_periph * periph,void * arg)987 xptregister(struct cam_periph *periph, void *arg)
988 {
989 	struct cam_sim *xpt_sim;
990 
991 	if (periph == NULL) {
992 		printf("xptregister: periph was NULL!!\n");
993 		return(CAM_REQ_CMP_ERR);
994 	}
995 
996 	xpt_sim = (struct cam_sim *)arg;
997 	xpt_sim->softc = periph;
998 	xpt_periph = periph;
999 	periph->softc = NULL;
1000 
1001 	return(CAM_REQ_CMP);
1002 }
1003 
1004 int32_t
xpt_add_periph(struct cam_periph * periph)1005 xpt_add_periph(struct cam_periph *periph)
1006 {
1007 	struct cam_ed *device;
1008 	int32_t	 status;
1009 
1010 	TASK_INIT(&periph->periph_run_task, 0, xpt_run_allocq_task, periph);
1011 	device = periph->path->device;
1012 	status = CAM_REQ_CMP;
1013 	if (device != NULL) {
1014 		mtx_lock(&device->target->bus->eb_mtx);
1015 		device->generation++;
1016 		SLIST_INSERT_HEAD(&device->periphs, periph, periph_links);
1017 		mtx_unlock(&device->target->bus->eb_mtx);
1018 		atomic_add_32(&xsoftc.xpt_generation, 1);
1019 	}
1020 
1021 	return (status);
1022 }
1023 
1024 void
xpt_remove_periph(struct cam_periph * periph)1025 xpt_remove_periph(struct cam_periph *periph)
1026 {
1027 	struct cam_ed *device;
1028 
1029 	device = periph->path->device;
1030 	if (device != NULL) {
1031 		mtx_lock(&device->target->bus->eb_mtx);
1032 		device->generation++;
1033 		SLIST_REMOVE(&device->periphs, periph, cam_periph, periph_links);
1034 		mtx_unlock(&device->target->bus->eb_mtx);
1035 		atomic_add_32(&xsoftc.xpt_generation, 1);
1036 	}
1037 }
1038 
1039 void
xpt_announce_periph(struct cam_periph * periph,char * announce_string)1040 xpt_announce_periph(struct cam_periph *periph, char *announce_string)
1041 {
1042 	char buf[128];
1043 	struct sbuf sb;
1044 
1045 	(void)sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN | SBUF_INCLUDENUL);
1046 	sbuf_set_drain(&sb, sbuf_printf_drain, NULL);
1047 	xpt_announce_periph_sbuf(periph, &sb, announce_string);
1048 	(void)sbuf_finish(&sb);
1049 }
1050 
1051 void
xpt_announce_periph_sbuf(struct cam_periph * periph,struct sbuf * sb,char * announce_string)1052 xpt_announce_periph_sbuf(struct cam_periph *periph, struct sbuf *sb,
1053     char *announce_string)
1054 {
1055 	struct	cam_path *path = periph->path;
1056 	struct  xpt_proto *proto;
1057 
1058 	cam_periph_assert(periph, MA_OWNED);
1059 	periph->flags |= CAM_PERIPH_ANNOUNCED;
1060 
1061 	sbuf_printf(sb, "%s%d at %s%d bus %d scbus%d target %d lun %jx\n",
1062 	    periph->periph_name, periph->unit_number,
1063 	    path->bus->sim->sim_name,
1064 	    path->bus->sim->unit_number,
1065 	    path->bus->sim->bus_id,
1066 	    path->bus->path_id,
1067 	    path->target->target_id,
1068 	    (uintmax_t)path->device->lun_id);
1069 	sbuf_printf(sb, "%s%d: ", periph->periph_name, periph->unit_number);
1070 	proto = xpt_proto_find(path->device->protocol);
1071 	if (proto)
1072 		proto->ops->announce_sbuf(path->device, sb);
1073 	else
1074 		sbuf_printf(sb, "Unknown protocol device %d\n",
1075 		    path->device->protocol);
1076 	if (path->device->serial_num_len > 0) {
1077 		/* Don't wrap the screen  - print only the first 60 chars */
1078 		sbuf_printf(sb, "%s%d: Serial Number %.60s\n",
1079 		    periph->periph_name, periph->unit_number,
1080 		    path->device->serial_num);
1081 	}
1082 	/* Announce transport details. */
1083 	path->bus->xport->ops->announce_sbuf(periph, sb);
1084 	/* Announce command queueing. */
1085 	if (path->device->inq_flags & SID_CmdQue
1086 	 || path->device->flags & CAM_DEV_TAG_AFTER_COUNT) {
1087 		sbuf_printf(sb, "%s%d: Command Queueing enabled\n",
1088 		    periph->periph_name, periph->unit_number);
1089 	}
1090 	/* Announce caller's details if they've passed in. */
1091 	if (announce_string != NULL)
1092 		sbuf_printf(sb, "%s%d: %s\n", periph->periph_name,
1093 		    periph->unit_number, announce_string);
1094 }
1095 
1096 void
xpt_announce_quirks(struct cam_periph * periph,int quirks,char * bit_string)1097 xpt_announce_quirks(struct cam_periph *periph, int quirks, char *bit_string)
1098 {
1099 	if (quirks != 0) {
1100 		printf("%s%d: quirks=0x%b\n", periph->periph_name,
1101 		    periph->unit_number, quirks, bit_string);
1102 	}
1103 }
1104 
1105 void
xpt_announce_quirks_sbuf(struct cam_periph * periph,struct sbuf * sb,int quirks,char * bit_string)1106 xpt_announce_quirks_sbuf(struct cam_periph *periph, struct sbuf *sb,
1107 			 int quirks, char *bit_string)
1108 {
1109 	if (quirks != 0) {
1110 		sbuf_printf(sb, "%s%d: quirks=0x%b\n", periph->periph_name,
1111 		    periph->unit_number, quirks, bit_string);
1112 	}
1113 }
1114 
1115 void
xpt_denounce_periph(struct cam_periph * periph)1116 xpt_denounce_periph(struct cam_periph *periph)
1117 {
1118 	char buf[128];
1119 	struct sbuf sb;
1120 
1121 	(void)sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN | SBUF_INCLUDENUL);
1122 	sbuf_set_drain(&sb, sbuf_printf_drain, NULL);
1123 	xpt_denounce_periph_sbuf(periph, &sb);
1124 	(void)sbuf_finish(&sb);
1125 }
1126 
1127 void
xpt_denounce_periph_sbuf(struct cam_periph * periph,struct sbuf * sb)1128 xpt_denounce_periph_sbuf(struct cam_periph *periph, struct sbuf *sb)
1129 {
1130 	struct cam_path *path = periph->path;
1131 	struct xpt_proto *proto;
1132 
1133 	cam_periph_assert(periph, MA_OWNED);
1134 
1135 	sbuf_printf(sb, "%s%d at %s%d bus %d scbus%d target %d lun %jx\n",
1136 	    periph->periph_name, periph->unit_number,
1137 	    path->bus->sim->sim_name,
1138 	    path->bus->sim->unit_number,
1139 	    path->bus->sim->bus_id,
1140 	    path->bus->path_id,
1141 	    path->target->target_id,
1142 	    (uintmax_t)path->device->lun_id);
1143 	sbuf_printf(sb, "%s%d: ", periph->periph_name, periph->unit_number);
1144 	proto = xpt_proto_find(path->device->protocol);
1145 	if (proto)
1146 		proto->ops->denounce_sbuf(path->device, sb);
1147 	else
1148 		sbuf_printf(sb, "Unknown protocol device %d",
1149 		    path->device->protocol);
1150 	if (path->device->serial_num_len > 0)
1151 		sbuf_printf(sb, " s/n %.60s", path->device->serial_num);
1152 	sbuf_cat(sb, " detached\n");
1153 }
1154 
1155 int
xpt_getattr(char * buf,size_t len,const char * attr,struct cam_path * path)1156 xpt_getattr(char *buf, size_t len, const char *attr, struct cam_path *path)
1157 {
1158 	int ret = -1, l, o;
1159 	struct ccb_dev_advinfo cdai;
1160 	struct scsi_vpd_device_id *did;
1161 	struct scsi_vpd_id_descriptor *idd;
1162 
1163 	xpt_path_assert(path, MA_OWNED);
1164 
1165 	memset(&cdai, 0, sizeof(cdai));
1166 	xpt_setup_ccb(&cdai.ccb_h, path, CAM_PRIORITY_NORMAL);
1167 	cdai.ccb_h.func_code = XPT_DEV_ADVINFO;
1168 	cdai.flags = CDAI_FLAG_NONE;
1169 	cdai.bufsiz = len;
1170 	cdai.buf = buf;
1171 
1172 	if (!strcmp(attr, "GEOM::ident"))
1173 		cdai.buftype = CDAI_TYPE_SERIAL_NUM;
1174 	else if (!strcmp(attr, "GEOM::physpath"))
1175 		cdai.buftype = CDAI_TYPE_PHYS_PATH;
1176 	else if (strcmp(attr, "GEOM::lunid") == 0 ||
1177 		 strcmp(attr, "GEOM::lunname") == 0) {
1178 		cdai.buftype = CDAI_TYPE_SCSI_DEVID;
1179 		cdai.bufsiz = CAM_SCSI_DEVID_MAXLEN;
1180 		cdai.buf = malloc(cdai.bufsiz, M_CAMXPT, M_NOWAIT);
1181 		if (cdai.buf == NULL) {
1182 			ret = ENOMEM;
1183 			goto out;
1184 		}
1185 	} else
1186 		goto out;
1187 
1188 	xpt_action((union ccb *)&cdai); /* can only be synchronous */
1189 	if ((cdai.ccb_h.status & CAM_DEV_QFRZN) != 0)
1190 		cam_release_devq(cdai.ccb_h.path, 0, 0, 0, FALSE);
1191 	if (cdai.provsiz == 0)
1192 		goto out;
1193 	switch(cdai.buftype) {
1194 	case CDAI_TYPE_SCSI_DEVID:
1195 		did = (struct scsi_vpd_device_id *)cdai.buf;
1196 		if (strcmp(attr, "GEOM::lunid") == 0) {
1197 			idd = scsi_get_devid(did, cdai.provsiz,
1198 			    scsi_devid_is_lun_naa);
1199 			if (idd == NULL)
1200 				idd = scsi_get_devid(did, cdai.provsiz,
1201 				    scsi_devid_is_lun_eui64);
1202 			if (idd == NULL)
1203 				idd = scsi_get_devid(did, cdai.provsiz,
1204 				    scsi_devid_is_lun_uuid);
1205 			if (idd == NULL)
1206 				idd = scsi_get_devid(did, cdai.provsiz,
1207 				    scsi_devid_is_lun_md5);
1208 		} else
1209 			idd = NULL;
1210 
1211 		if (idd == NULL)
1212 			idd = scsi_get_devid(did, cdai.provsiz,
1213 			    scsi_devid_is_lun_t10);
1214 		if (idd == NULL)
1215 			idd = scsi_get_devid(did, cdai.provsiz,
1216 			    scsi_devid_is_lun_name);
1217 		if (idd == NULL)
1218 			break;
1219 
1220 		ret = 0;
1221 		if ((idd->proto_codeset & SVPD_ID_CODESET_MASK) ==
1222 		    SVPD_ID_CODESET_ASCII) {
1223 			if (idd->length < len) {
1224 				for (l = 0; l < idd->length; l++)
1225 					buf[l] = idd->identifier[l] ?
1226 					    idd->identifier[l] : ' ';
1227 				buf[l] = 0;
1228 			} else
1229 				ret = EFAULT;
1230 			break;
1231 		}
1232 		if ((idd->proto_codeset & SVPD_ID_CODESET_MASK) ==
1233 		    SVPD_ID_CODESET_UTF8) {
1234 			l = strnlen(idd->identifier, idd->length);
1235 			if (l < len) {
1236 				bcopy(idd->identifier, buf, l);
1237 				buf[l] = 0;
1238 			} else
1239 				ret = EFAULT;
1240 			break;
1241 		}
1242 		if ((idd->id_type & SVPD_ID_TYPE_MASK) ==
1243 		    SVPD_ID_TYPE_UUID && idd->identifier[0] == 0x10) {
1244 			if ((idd->length - 2) * 2 + 4 >= len) {
1245 				ret = EFAULT;
1246 				break;
1247 			}
1248 			for (l = 2, o = 0; l < idd->length; l++) {
1249 				if (l == 6 || l == 8 || l == 10 || l == 12)
1250 				    o += sprintf(buf + o, "-");
1251 				o += sprintf(buf + o, "%02x",
1252 				    idd->identifier[l]);
1253 			}
1254 			break;
1255 		}
1256 		if (idd->length * 2 < len) {
1257 			for (l = 0; l < idd->length; l++)
1258 				sprintf(buf + l * 2, "%02x",
1259 				    idd->identifier[l]);
1260 		} else
1261 				ret = EFAULT;
1262 		break;
1263 	default:
1264 		if (cdai.provsiz < len) {
1265 			cdai.buf[cdai.provsiz] = 0;
1266 			ret = 0;
1267 		} else
1268 			ret = EFAULT;
1269 		break;
1270 	}
1271 
1272 out:
1273 	if ((char *)cdai.buf != buf)
1274 		free(cdai.buf, M_CAMXPT);
1275 	return ret;
1276 }
1277 
1278 static dev_match_ret
xptbusmatch(struct dev_match_pattern * patterns,u_int num_patterns,struct cam_eb * bus)1279 xptbusmatch(struct dev_match_pattern *patterns, u_int num_patterns,
1280 	    struct cam_eb *bus)
1281 {
1282 	dev_match_ret retval;
1283 	u_int i;
1284 
1285 	retval = DM_RET_NONE;
1286 
1287 	/*
1288 	 * If we aren't given something to match against, that's an error.
1289 	 */
1290 	if (bus == NULL)
1291 		return(DM_RET_ERROR);
1292 
1293 	/*
1294 	 * If there are no match entries, then this bus matches no
1295 	 * matter what.
1296 	 */
1297 	if ((patterns == NULL) || (num_patterns == 0))
1298 		return(DM_RET_DESCEND | DM_RET_COPY);
1299 
1300 	for (i = 0; i < num_patterns; i++) {
1301 		struct bus_match_pattern *cur_pattern;
1302 		struct device_match_pattern *dp = &patterns[i].pattern.device_pattern;
1303 		struct periph_match_pattern *pp = &patterns[i].pattern.periph_pattern;
1304 
1305 		/*
1306 		 * If the pattern in question isn't for a bus node, we
1307 		 * aren't interested.  However, we do indicate to the
1308 		 * calling routine that we should continue descending the
1309 		 * tree, since the user wants to match against lower-level
1310 		 * EDT elements.
1311 		 */
1312 		if (patterns[i].type == DEV_MATCH_DEVICE &&
1313 		    (dp->flags & DEV_MATCH_PATH) != 0 &&
1314 		    dp->path_id != bus->path_id)
1315 			continue;
1316 		if (patterns[i].type == DEV_MATCH_PERIPH &&
1317 		    (pp->flags & PERIPH_MATCH_PATH) != 0 &&
1318 		    pp->path_id != bus->path_id)
1319 			continue;
1320 		if (patterns[i].type != DEV_MATCH_BUS) {
1321 			if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1322 				retval |= DM_RET_DESCEND;
1323 			continue;
1324 		}
1325 
1326 		cur_pattern = &patterns[i].pattern.bus_pattern;
1327 
1328 		if (((cur_pattern->flags & BUS_MATCH_PATH) != 0)
1329 		 && (cur_pattern->path_id != bus->path_id))
1330 			continue;
1331 
1332 		if (((cur_pattern->flags & BUS_MATCH_BUS_ID) != 0)
1333 		 && (cur_pattern->bus_id != bus->sim->bus_id))
1334 			continue;
1335 
1336 		if (((cur_pattern->flags & BUS_MATCH_UNIT) != 0)
1337 		 && (cur_pattern->unit_number != bus->sim->unit_number))
1338 			continue;
1339 
1340 		if (((cur_pattern->flags & BUS_MATCH_NAME) != 0)
1341 		 && (strncmp(cur_pattern->dev_name, bus->sim->sim_name,
1342 			     DEV_IDLEN) != 0))
1343 			continue;
1344 
1345 		/*
1346 		 * If we get to this point, the user definitely wants
1347 		 * information on this bus.  So tell the caller to copy the
1348 		 * data out.
1349 		 */
1350 		retval |= DM_RET_COPY;
1351 
1352 		/*
1353 		 * If the return action has been set to descend, then we
1354 		 * know that we've already seen a non-bus matching
1355 		 * expression, therefore we need to further descend the tree.
1356 		 * This won't change by continuing around the loop, so we
1357 		 * go ahead and return.  If we haven't seen a non-bus
1358 		 * matching expression, we keep going around the loop until
1359 		 * we exhaust the matching expressions.  We'll set the stop
1360 		 * flag once we fall out of the loop.
1361 		 */
1362 		if ((retval & DM_RET_ACTION_MASK) == DM_RET_DESCEND)
1363 			return(retval);
1364 	}
1365 
1366 	/*
1367 	 * If the return action hasn't been set to descend yet, that means
1368 	 * we haven't seen anything other than bus matching patterns.  So
1369 	 * tell the caller to stop descending the tree -- the user doesn't
1370 	 * want to match against lower level tree elements.
1371 	 */
1372 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1373 		retval |= DM_RET_STOP;
1374 
1375 	return(retval);
1376 }
1377 
1378 static dev_match_ret
xptdevicematch(struct dev_match_pattern * patterns,u_int num_patterns,struct cam_ed * device)1379 xptdevicematch(struct dev_match_pattern *patterns, u_int num_patterns,
1380 	       struct cam_ed *device)
1381 {
1382 	dev_match_ret retval;
1383 	u_int i;
1384 
1385 	retval = DM_RET_NONE;
1386 
1387 	/*
1388 	 * If we aren't given something to match against, that's an error.
1389 	 */
1390 	if (device == NULL)
1391 		return(DM_RET_ERROR);
1392 
1393 	/*
1394 	 * If there are no match entries, then this device matches no
1395 	 * matter what.
1396 	 */
1397 	if ((patterns == NULL) || (num_patterns == 0))
1398 		return(DM_RET_DESCEND | DM_RET_COPY);
1399 
1400 	for (i = 0; i < num_patterns; i++) {
1401 		struct device_match_pattern *cur_pattern;
1402 		struct scsi_vpd_device_id *device_id_page;
1403 		struct periph_match_pattern *pp = &patterns[i].pattern.periph_pattern;
1404 
1405 		/*
1406 		 * If the pattern in question isn't for a device node, we
1407 		 * aren't interested.
1408 		 */
1409 		if (patterns[i].type == DEV_MATCH_PERIPH &&
1410 		    (pp->flags & PERIPH_MATCH_TARGET) != 0 &&
1411 		    pp->target_id != device->target->target_id)
1412 			continue;
1413 		if (patterns[i].type == DEV_MATCH_PERIPH &&
1414 		    (pp->flags & PERIPH_MATCH_LUN) != 0 &&
1415 		    pp->target_lun != device->lun_id)
1416 			continue;
1417 		if (patterns[i].type != DEV_MATCH_DEVICE) {
1418 			if ((patterns[i].type == DEV_MATCH_PERIPH)
1419 			 && ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE))
1420 				retval |= DM_RET_DESCEND;
1421 			continue;
1422 		}
1423 
1424 		cur_pattern = &patterns[i].pattern.device_pattern;
1425 
1426 		/* Error out if mutually exclusive options are specified. */
1427 		if ((cur_pattern->flags & (DEV_MATCH_INQUIRY|DEV_MATCH_DEVID))
1428 		 == (DEV_MATCH_INQUIRY|DEV_MATCH_DEVID))
1429 			return(DM_RET_ERROR);
1430 
1431 		if (((cur_pattern->flags & DEV_MATCH_PATH) != 0)
1432 		 && (cur_pattern->path_id != device->target->bus->path_id))
1433 			continue;
1434 
1435 		if (((cur_pattern->flags & DEV_MATCH_TARGET) != 0)
1436 		 && (cur_pattern->target_id != device->target->target_id))
1437 			continue;
1438 
1439 		if (((cur_pattern->flags & DEV_MATCH_LUN) != 0)
1440 		 && (cur_pattern->target_lun != device->lun_id))
1441 			continue;
1442 
1443 		if (((cur_pattern->flags & DEV_MATCH_INQUIRY) != 0)
1444 		 && (cam_quirkmatch((caddr_t)&device->inq_data,
1445 				    (caddr_t)&cur_pattern->data.inq_pat,
1446 				    1, sizeof(cur_pattern->data.inq_pat),
1447 				    scsi_static_inquiry_match) == NULL))
1448 			continue;
1449 
1450 		device_id_page = (struct scsi_vpd_device_id *)device->device_id;
1451 		if (((cur_pattern->flags & DEV_MATCH_DEVID) != 0)
1452 		 && (device->device_id_len < SVPD_DEVICE_ID_HDR_LEN
1453 		  || scsi_devid_match((uint8_t *)device_id_page->desc_list,
1454 				      device->device_id_len
1455 				    - SVPD_DEVICE_ID_HDR_LEN,
1456 				      cur_pattern->data.devid_pat.id,
1457 				      cur_pattern->data.devid_pat.id_len) != 0))
1458 			continue;
1459 
1460 		/*
1461 		 * If we get to this point, the user definitely wants
1462 		 * information on this device.  So tell the caller to copy
1463 		 * the data out.
1464 		 */
1465 		retval |= DM_RET_COPY;
1466 
1467 		/*
1468 		 * If the return action has been set to descend, then we
1469 		 * know that we've already seen a peripheral matching
1470 		 * expression, therefore we need to further descend the tree.
1471 		 * This won't change by continuing around the loop, so we
1472 		 * go ahead and return.  If we haven't seen a peripheral
1473 		 * matching expression, we keep going around the loop until
1474 		 * we exhaust the matching expressions.  We'll set the stop
1475 		 * flag once we fall out of the loop.
1476 		 */
1477 		if ((retval & DM_RET_ACTION_MASK) == DM_RET_DESCEND)
1478 			return(retval);
1479 	}
1480 
1481 	/*
1482 	 * If the return action hasn't been set to descend yet, that means
1483 	 * we haven't seen any peripheral matching patterns.  So tell the
1484 	 * caller to stop descending the tree -- the user doesn't want to
1485 	 * match against lower level tree elements.
1486 	 */
1487 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1488 		retval |= DM_RET_STOP;
1489 
1490 	return(retval);
1491 }
1492 
1493 /*
1494  * Match a single peripheral against any number of match patterns.
1495  */
1496 static dev_match_ret
xptperiphmatch(struct dev_match_pattern * patterns,u_int num_patterns,struct cam_periph * periph)1497 xptperiphmatch(struct dev_match_pattern *patterns, u_int num_patterns,
1498 	       struct cam_periph *periph)
1499 {
1500 	dev_match_ret retval;
1501 	u_int i;
1502 
1503 	/*
1504 	 * If we aren't given something to match against, that's an error.
1505 	 */
1506 	if (periph == NULL)
1507 		return(DM_RET_ERROR);
1508 
1509 	/*
1510 	 * If there are no match entries, then this peripheral matches no
1511 	 * matter what.
1512 	 */
1513 	if ((patterns == NULL) || (num_patterns == 0))
1514 		return(DM_RET_STOP | DM_RET_COPY);
1515 
1516 	/*
1517 	 * There aren't any nodes below a peripheral node, so there's no
1518 	 * reason to descend the tree any further.
1519 	 */
1520 	retval = DM_RET_STOP;
1521 
1522 	for (i = 0; i < num_patterns; i++) {
1523 		struct periph_match_pattern *cur_pattern;
1524 
1525 		/*
1526 		 * If the pattern in question isn't for a peripheral, we
1527 		 * aren't interested.
1528 		 */
1529 		if (patterns[i].type != DEV_MATCH_PERIPH)
1530 			continue;
1531 
1532 		cur_pattern = &patterns[i].pattern.periph_pattern;
1533 
1534 		if (((cur_pattern->flags & PERIPH_MATCH_PATH) != 0)
1535 		 && (cur_pattern->path_id != periph->path->bus->path_id))
1536 			continue;
1537 
1538 		/*
1539 		 * For the target and lun id's, we have to make sure the
1540 		 * target and lun pointers aren't NULL.  The xpt peripheral
1541 		 * has a wildcard target and device.
1542 		 */
1543 		if (((cur_pattern->flags & PERIPH_MATCH_TARGET) != 0)
1544 		 && ((periph->path->target == NULL)
1545 		 ||(cur_pattern->target_id != periph->path->target->target_id)))
1546 			continue;
1547 
1548 		if (((cur_pattern->flags & PERIPH_MATCH_LUN) != 0)
1549 		 && ((periph->path->device == NULL)
1550 		 || (cur_pattern->target_lun != periph->path->device->lun_id)))
1551 			continue;
1552 
1553 		if (((cur_pattern->flags & PERIPH_MATCH_UNIT) != 0)
1554 		 && (cur_pattern->unit_number != periph->unit_number))
1555 			continue;
1556 
1557 		if (((cur_pattern->flags & PERIPH_MATCH_NAME) != 0)
1558 		 && (strncmp(cur_pattern->periph_name, periph->periph_name,
1559 			     DEV_IDLEN) != 0))
1560 			continue;
1561 
1562 		/*
1563 		 * If we get to this point, the user definitely wants
1564 		 * information on this peripheral.  So tell the caller to
1565 		 * copy the data out.
1566 		 */
1567 		retval |= DM_RET_COPY;
1568 
1569 		/*
1570 		 * The return action has already been set to stop, since
1571 		 * peripherals don't have any nodes below them in the EDT.
1572 		 */
1573 		return(retval);
1574 	}
1575 
1576 	/*
1577 	 * If we get to this point, the peripheral that was passed in
1578 	 * doesn't match any of the patterns.
1579 	 */
1580 	return(retval);
1581 }
1582 
1583 static int
xptedtbusfunc(struct cam_eb * bus,void * arg)1584 xptedtbusfunc(struct cam_eb *bus, void *arg)
1585 {
1586 	struct ccb_dev_match *cdm;
1587 	struct cam_et *target;
1588 	dev_match_ret retval;
1589 
1590 	cdm = (struct ccb_dev_match *)arg;
1591 
1592 	/*
1593 	 * If our position is for something deeper in the tree, that means
1594 	 * that we've already seen this node.  So, we keep going down.
1595 	 */
1596 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1597 	 && (cdm->pos.cookie.bus == bus)
1598 	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1599 	 && (cdm->pos.cookie.target != NULL))
1600 		retval = DM_RET_DESCEND;
1601 	else
1602 		retval = xptbusmatch(cdm->patterns, cdm->num_patterns, bus);
1603 
1604 	/*
1605 	 * If we got an error, bail out of the search.
1606 	 */
1607 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
1608 		cdm->status = CAM_DEV_MATCH_ERROR;
1609 		return(0);
1610 	}
1611 
1612 	/*
1613 	 * If the copy flag is set, copy this bus out.
1614 	 */
1615 	if (retval & DM_RET_COPY) {
1616 		int spaceleft, j;
1617 
1618 		spaceleft = cdm->match_buf_len - (cdm->num_matches *
1619 			sizeof(struct dev_match_result));
1620 
1621 		/*
1622 		 * If we don't have enough space to put in another
1623 		 * match result, save our position and tell the
1624 		 * user there are more devices to check.
1625 		 */
1626 		if (spaceleft < sizeof(struct dev_match_result)) {
1627 			bzero(&cdm->pos, sizeof(cdm->pos));
1628 			cdm->pos.position_type =
1629 				CAM_DEV_POS_EDT | CAM_DEV_POS_BUS;
1630 
1631 			cdm->pos.cookie.bus = bus;
1632 			cdm->pos.generations[CAM_BUS_GENERATION]=
1633 				xsoftc.bus_generation;
1634 			cdm->status = CAM_DEV_MATCH_MORE;
1635 			return(0);
1636 		}
1637 		j = cdm->num_matches;
1638 		cdm->num_matches++;
1639 		cdm->matches[j].type = DEV_MATCH_BUS;
1640 		cdm->matches[j].result.bus_result.path_id = bus->path_id;
1641 		cdm->matches[j].result.bus_result.bus_id = bus->sim->bus_id;
1642 		cdm->matches[j].result.bus_result.unit_number =
1643 			bus->sim->unit_number;
1644 		strlcpy(cdm->matches[j].result.bus_result.dev_name,
1645 			bus->sim->sim_name,
1646 			sizeof(cdm->matches[j].result.bus_result.dev_name));
1647 	}
1648 
1649 	/*
1650 	 * If the user is only interested in buses, there's no
1651 	 * reason to descend to the next level in the tree.
1652 	 */
1653 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_STOP)
1654 		return(1);
1655 
1656 	/*
1657 	 * If there is a target generation recorded, check it to
1658 	 * make sure the target list hasn't changed.
1659 	 */
1660 	mtx_lock(&bus->eb_mtx);
1661 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1662 	 && (cdm->pos.cookie.bus == bus)
1663 	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1664 	 && (cdm->pos.cookie.target != NULL)) {
1665 		if ((cdm->pos.generations[CAM_TARGET_GENERATION] !=
1666 		    bus->generation)) {
1667 			mtx_unlock(&bus->eb_mtx);
1668 			cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1669 			return (0);
1670 		}
1671 		target = (struct cam_et *)cdm->pos.cookie.target;
1672 		target->refcount++;
1673 	} else
1674 		target = NULL;
1675 	mtx_unlock(&bus->eb_mtx);
1676 
1677 	return (xpttargettraverse(bus, target, xptedttargetfunc, arg));
1678 }
1679 
1680 static int
xptedttargetfunc(struct cam_et * target,void * arg)1681 xptedttargetfunc(struct cam_et *target, void *arg)
1682 {
1683 	struct ccb_dev_match *cdm;
1684 	struct cam_eb *bus;
1685 	struct cam_ed *device;
1686 
1687 	cdm = (struct ccb_dev_match *)arg;
1688 	bus = target->bus;
1689 
1690 	/*
1691 	 * If there is a device list generation recorded, check it to
1692 	 * make sure the device list hasn't changed.
1693 	 */
1694 	mtx_lock(&bus->eb_mtx);
1695 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1696 	 && (cdm->pos.cookie.bus == bus)
1697 	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1698 	 && (cdm->pos.cookie.target == target)
1699 	 && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
1700 	 && (cdm->pos.cookie.device != NULL)) {
1701 		if (cdm->pos.generations[CAM_DEV_GENERATION] !=
1702 		    target->generation) {
1703 			mtx_unlock(&bus->eb_mtx);
1704 			cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1705 			return(0);
1706 		}
1707 		device = (struct cam_ed *)cdm->pos.cookie.device;
1708 		device->refcount++;
1709 	} else
1710 		device = NULL;
1711 	mtx_unlock(&bus->eb_mtx);
1712 
1713 	return (xptdevicetraverse(target, device, xptedtdevicefunc, arg));
1714 }
1715 
1716 static int
xptedtdevicefunc(struct cam_ed * device,void * arg)1717 xptedtdevicefunc(struct cam_ed *device, void *arg)
1718 {
1719 	struct cam_eb *bus;
1720 	struct cam_periph *periph;
1721 	struct ccb_dev_match *cdm;
1722 	dev_match_ret retval;
1723 
1724 	cdm = (struct ccb_dev_match *)arg;
1725 	bus = device->target->bus;
1726 
1727 	/*
1728 	 * If our position is for something deeper in the tree, that means
1729 	 * that we've already seen this node.  So, we keep going down.
1730 	 */
1731 	if ((cdm->pos.position_type & CAM_DEV_POS_DEVICE)
1732 	 && (cdm->pos.cookie.device == device)
1733 	 && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
1734 	 && (cdm->pos.cookie.periph != NULL))
1735 		retval = DM_RET_DESCEND;
1736 	else
1737 		retval = xptdevicematch(cdm->patterns, cdm->num_patterns,
1738 					device);
1739 
1740 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
1741 		cdm->status = CAM_DEV_MATCH_ERROR;
1742 		return(0);
1743 	}
1744 
1745 	/*
1746 	 * If the copy flag is set, copy this device out.
1747 	 */
1748 	if (retval & DM_RET_COPY) {
1749 		int spaceleft, j;
1750 
1751 		spaceleft = cdm->match_buf_len - (cdm->num_matches *
1752 			sizeof(struct dev_match_result));
1753 
1754 		/*
1755 		 * If we don't have enough space to put in another
1756 		 * match result, save our position and tell the
1757 		 * user there are more devices to check.
1758 		 */
1759 		if (spaceleft < sizeof(struct dev_match_result)) {
1760 			bzero(&cdm->pos, sizeof(cdm->pos));
1761 			cdm->pos.position_type =
1762 				CAM_DEV_POS_EDT | CAM_DEV_POS_BUS |
1763 				CAM_DEV_POS_TARGET | CAM_DEV_POS_DEVICE;
1764 
1765 			cdm->pos.cookie.bus = device->target->bus;
1766 			cdm->pos.generations[CAM_BUS_GENERATION]=
1767 				xsoftc.bus_generation;
1768 			cdm->pos.cookie.target = device->target;
1769 			cdm->pos.generations[CAM_TARGET_GENERATION] =
1770 				device->target->bus->generation;
1771 			cdm->pos.cookie.device = device;
1772 			cdm->pos.generations[CAM_DEV_GENERATION] =
1773 				device->target->generation;
1774 			cdm->status = CAM_DEV_MATCH_MORE;
1775 			return(0);
1776 		}
1777 		j = cdm->num_matches;
1778 		cdm->num_matches++;
1779 		cdm->matches[j].type = DEV_MATCH_DEVICE;
1780 		cdm->matches[j].result.device_result.path_id =
1781 			device->target->bus->path_id;
1782 		cdm->matches[j].result.device_result.target_id =
1783 			device->target->target_id;
1784 		cdm->matches[j].result.device_result.target_lun =
1785 			device->lun_id;
1786 		cdm->matches[j].result.device_result.protocol =
1787 			device->protocol;
1788 		bcopy(&device->inq_data,
1789 		      &cdm->matches[j].result.device_result.inq_data,
1790 		      sizeof(struct scsi_inquiry_data));
1791 		bcopy(&device->ident_data,
1792 		      &cdm->matches[j].result.device_result.ident_data,
1793 		      sizeof(struct ata_params));
1794 
1795 		/* Let the user know whether this device is unconfigured */
1796 		if (device->flags & CAM_DEV_UNCONFIGURED)
1797 			cdm->matches[j].result.device_result.flags =
1798 				DEV_RESULT_UNCONFIGURED;
1799 		else
1800 			cdm->matches[j].result.device_result.flags =
1801 				DEV_RESULT_NOFLAG;
1802 	}
1803 
1804 	/*
1805 	 * If the user isn't interested in peripherals, don't descend
1806 	 * the tree any further.
1807 	 */
1808 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_STOP)
1809 		return(1);
1810 
1811 	/*
1812 	 * If there is a peripheral list generation recorded, make sure
1813 	 * it hasn't changed.
1814 	 */
1815 	xpt_lock_buses();
1816 	mtx_lock(&bus->eb_mtx);
1817 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1818 	 && (cdm->pos.cookie.bus == bus)
1819 	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1820 	 && (cdm->pos.cookie.target == device->target)
1821 	 && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
1822 	 && (cdm->pos.cookie.device == device)
1823 	 && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
1824 	 && (cdm->pos.cookie.periph != NULL)) {
1825 		if (cdm->pos.generations[CAM_PERIPH_GENERATION] !=
1826 		    device->generation) {
1827 			mtx_unlock(&bus->eb_mtx);
1828 			xpt_unlock_buses();
1829 			cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1830 			return(0);
1831 		}
1832 		periph = (struct cam_periph *)cdm->pos.cookie.periph;
1833 		periph->refcount++;
1834 	} else
1835 		periph = NULL;
1836 	mtx_unlock(&bus->eb_mtx);
1837 	xpt_unlock_buses();
1838 
1839 	return (xptperiphtraverse(device, periph, xptedtperiphfunc, arg));
1840 }
1841 
1842 static int
xptedtperiphfunc(struct cam_periph * periph,void * arg)1843 xptedtperiphfunc(struct cam_periph *periph, void *arg)
1844 {
1845 	struct ccb_dev_match *cdm;
1846 	dev_match_ret retval;
1847 
1848 	cdm = (struct ccb_dev_match *)arg;
1849 
1850 	retval = xptperiphmatch(cdm->patterns, cdm->num_patterns, periph);
1851 
1852 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
1853 		cdm->status = CAM_DEV_MATCH_ERROR;
1854 		return(0);
1855 	}
1856 
1857 	/*
1858 	 * If the copy flag is set, copy this peripheral out.
1859 	 */
1860 	if (retval & DM_RET_COPY) {
1861 		int spaceleft, j;
1862 		size_t l;
1863 
1864 		spaceleft = cdm->match_buf_len - (cdm->num_matches *
1865 			sizeof(struct dev_match_result));
1866 
1867 		/*
1868 		 * If we don't have enough space to put in another
1869 		 * match result, save our position and tell the
1870 		 * user there are more devices to check.
1871 		 */
1872 		if (spaceleft < sizeof(struct dev_match_result)) {
1873 			bzero(&cdm->pos, sizeof(cdm->pos));
1874 			cdm->pos.position_type =
1875 				CAM_DEV_POS_EDT | CAM_DEV_POS_BUS |
1876 				CAM_DEV_POS_TARGET | CAM_DEV_POS_DEVICE |
1877 				CAM_DEV_POS_PERIPH;
1878 
1879 			cdm->pos.cookie.bus = periph->path->bus;
1880 			cdm->pos.generations[CAM_BUS_GENERATION]=
1881 				xsoftc.bus_generation;
1882 			cdm->pos.cookie.target = periph->path->target;
1883 			cdm->pos.generations[CAM_TARGET_GENERATION] =
1884 				periph->path->bus->generation;
1885 			cdm->pos.cookie.device = periph->path->device;
1886 			cdm->pos.generations[CAM_DEV_GENERATION] =
1887 				periph->path->target->generation;
1888 			cdm->pos.cookie.periph = periph;
1889 			cdm->pos.generations[CAM_PERIPH_GENERATION] =
1890 				periph->path->device->generation;
1891 			cdm->status = CAM_DEV_MATCH_MORE;
1892 			return(0);
1893 		}
1894 
1895 		j = cdm->num_matches;
1896 		cdm->num_matches++;
1897 		cdm->matches[j].type = DEV_MATCH_PERIPH;
1898 		cdm->matches[j].result.periph_result.path_id =
1899 			periph->path->bus->path_id;
1900 		cdm->matches[j].result.periph_result.target_id =
1901 			periph->path->target->target_id;
1902 		cdm->matches[j].result.periph_result.target_lun =
1903 			periph->path->device->lun_id;
1904 		cdm->matches[j].result.periph_result.unit_number =
1905 			periph->unit_number;
1906 		l = sizeof(cdm->matches[j].result.periph_result.periph_name);
1907 		strlcpy(cdm->matches[j].result.periph_result.periph_name,
1908 			periph->periph_name, l);
1909 	}
1910 
1911 	return(1);
1912 }
1913 
1914 static int
xptedtmatch(struct ccb_dev_match * cdm)1915 xptedtmatch(struct ccb_dev_match *cdm)
1916 {
1917 	struct cam_eb *bus;
1918 	int ret;
1919 
1920 	cdm->num_matches = 0;
1921 
1922 	/*
1923 	 * Check the bus list generation.  If it has changed, the user
1924 	 * needs to reset everything and start over.
1925 	 */
1926 	xpt_lock_buses();
1927 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1928 	 && (cdm->pos.cookie.bus != NULL)) {
1929 		if (cdm->pos.generations[CAM_BUS_GENERATION] !=
1930 		    xsoftc.bus_generation) {
1931 			xpt_unlock_buses();
1932 			cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1933 			return(0);
1934 		}
1935 		bus = (struct cam_eb *)cdm->pos.cookie.bus;
1936 		bus->refcount++;
1937 	} else
1938 		bus = NULL;
1939 	xpt_unlock_buses();
1940 
1941 	ret = xptbustraverse(bus, xptedtbusfunc, cdm);
1942 
1943 	/*
1944 	 * If we get back 0, that means that we had to stop before fully
1945 	 * traversing the EDT.  It also means that one of the subroutines
1946 	 * has set the status field to the proper value.  If we get back 1,
1947 	 * we've fully traversed the EDT and copied out any matching entries.
1948 	 */
1949 	if (ret == 1)
1950 		cdm->status = CAM_DEV_MATCH_LAST;
1951 
1952 	return(ret);
1953 }
1954 
1955 static int
xptplistpdrvfunc(struct periph_driver ** pdrv,void * arg)1956 xptplistpdrvfunc(struct periph_driver **pdrv, void *arg)
1957 {
1958 	struct cam_periph *periph;
1959 	struct ccb_dev_match *cdm;
1960 
1961 	cdm = (struct ccb_dev_match *)arg;
1962 
1963 	xpt_lock_buses();
1964 	if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
1965 	 && (cdm->pos.cookie.pdrv == pdrv)
1966 	 && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
1967 	 && (cdm->pos.cookie.periph != NULL)) {
1968 		if (cdm->pos.generations[CAM_PERIPH_GENERATION] !=
1969 		    (*pdrv)->generation) {
1970 			xpt_unlock_buses();
1971 			cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1972 			return(0);
1973 		}
1974 		periph = (struct cam_periph *)cdm->pos.cookie.periph;
1975 		periph->refcount++;
1976 	} else
1977 		periph = NULL;
1978 	xpt_unlock_buses();
1979 
1980 	return (xptpdperiphtraverse(pdrv, periph, xptplistperiphfunc, arg));
1981 }
1982 
1983 static int
xptplistperiphfunc(struct cam_periph * periph,void * arg)1984 xptplistperiphfunc(struct cam_periph *periph, void *arg)
1985 {
1986 	struct ccb_dev_match *cdm;
1987 	dev_match_ret retval;
1988 
1989 	cdm = (struct ccb_dev_match *)arg;
1990 
1991 	retval = xptperiphmatch(cdm->patterns, cdm->num_patterns, periph);
1992 
1993 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
1994 		cdm->status = CAM_DEV_MATCH_ERROR;
1995 		return(0);
1996 	}
1997 
1998 	/*
1999 	 * If the copy flag is set, copy this peripheral out.
2000 	 */
2001 	if (retval & DM_RET_COPY) {
2002 		int spaceleft, j;
2003 		size_t l;
2004 
2005 		spaceleft = cdm->match_buf_len - (cdm->num_matches *
2006 			sizeof(struct dev_match_result));
2007 
2008 		/*
2009 		 * If we don't have enough space to put in another
2010 		 * match result, save our position and tell the
2011 		 * user there are more devices to check.
2012 		 */
2013 		if (spaceleft < sizeof(struct dev_match_result)) {
2014 			struct periph_driver **pdrv;
2015 
2016 			pdrv = NULL;
2017 			bzero(&cdm->pos, sizeof(cdm->pos));
2018 			cdm->pos.position_type =
2019 				CAM_DEV_POS_PDRV | CAM_DEV_POS_PDPTR |
2020 				CAM_DEV_POS_PERIPH;
2021 
2022 			/*
2023 			 * This may look a bit non-sensical, but it is
2024 			 * actually quite logical.  There are very few
2025 			 * peripheral drivers, and bloating every peripheral
2026 			 * structure with a pointer back to its parent
2027 			 * peripheral driver linker set entry would cost
2028 			 * more in the long run than doing this quick lookup.
2029 			 */
2030 			for (pdrv = periph_drivers; *pdrv != NULL; pdrv++) {
2031 				if (strcmp((*pdrv)->driver_name,
2032 				    periph->periph_name) == 0)
2033 					break;
2034 			}
2035 
2036 			if (*pdrv == NULL) {
2037 				cdm->status = CAM_DEV_MATCH_ERROR;
2038 				return(0);
2039 			}
2040 
2041 			cdm->pos.cookie.pdrv = pdrv;
2042 			/*
2043 			 * The periph generation slot does double duty, as
2044 			 * does the periph pointer slot.  They are used for
2045 			 * both edt and pdrv lookups and positioning.
2046 			 */
2047 			cdm->pos.cookie.periph = periph;
2048 			cdm->pos.generations[CAM_PERIPH_GENERATION] =
2049 				(*pdrv)->generation;
2050 			cdm->status = CAM_DEV_MATCH_MORE;
2051 			return(0);
2052 		}
2053 
2054 		j = cdm->num_matches;
2055 		cdm->num_matches++;
2056 		cdm->matches[j].type = DEV_MATCH_PERIPH;
2057 		cdm->matches[j].result.periph_result.path_id =
2058 			periph->path->bus->path_id;
2059 
2060 		/*
2061 		 * The transport layer peripheral doesn't have a target or
2062 		 * lun.
2063 		 */
2064 		if (periph->path->target)
2065 			cdm->matches[j].result.periph_result.target_id =
2066 				periph->path->target->target_id;
2067 		else
2068 			cdm->matches[j].result.periph_result.target_id =
2069 				CAM_TARGET_WILDCARD;
2070 
2071 		if (periph->path->device)
2072 			cdm->matches[j].result.periph_result.target_lun =
2073 				periph->path->device->lun_id;
2074 		else
2075 			cdm->matches[j].result.periph_result.target_lun =
2076 				CAM_LUN_WILDCARD;
2077 
2078 		cdm->matches[j].result.periph_result.unit_number =
2079 			periph->unit_number;
2080 		l = sizeof(cdm->matches[j].result.periph_result.periph_name);
2081 		strlcpy(cdm->matches[j].result.periph_result.periph_name,
2082 			periph->periph_name, l);
2083 	}
2084 
2085 	return(1);
2086 }
2087 
2088 static int
xptperiphlistmatch(struct ccb_dev_match * cdm)2089 xptperiphlistmatch(struct ccb_dev_match *cdm)
2090 {
2091 	int ret;
2092 
2093 	cdm->num_matches = 0;
2094 
2095 	/*
2096 	 * At this point in the edt traversal function, we check the bus
2097 	 * list generation to make sure that no buses have been added or
2098 	 * removed since the user last sent a XPT_DEV_MATCH ccb through.
2099 	 * For the peripheral driver list traversal function, however, we
2100 	 * don't have to worry about new peripheral driver types coming or
2101 	 * going; they're in a linker set, and therefore can't change
2102 	 * without a recompile.
2103 	 */
2104 
2105 	if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
2106 	 && (cdm->pos.cookie.pdrv != NULL))
2107 		ret = xptpdrvtraverse(
2108 				(struct periph_driver **)cdm->pos.cookie.pdrv,
2109 				xptplistpdrvfunc, cdm);
2110 	else
2111 		ret = xptpdrvtraverse(NULL, xptplistpdrvfunc, cdm);
2112 
2113 	/*
2114 	 * If we get back 0, that means that we had to stop before fully
2115 	 * traversing the peripheral driver tree.  It also means that one of
2116 	 * the subroutines has set the status field to the proper value.  If
2117 	 * we get back 1, we've fully traversed the EDT and copied out any
2118 	 * matching entries.
2119 	 */
2120 	if (ret == 1)
2121 		cdm->status = CAM_DEV_MATCH_LAST;
2122 
2123 	return(ret);
2124 }
2125 
2126 static int
xptbustraverse(struct cam_eb * start_bus,xpt_busfunc_t * tr_func,void * arg)2127 xptbustraverse(struct cam_eb *start_bus, xpt_busfunc_t *tr_func, void *arg)
2128 {
2129 	struct cam_eb *bus, *next_bus;
2130 	int retval;
2131 
2132 	retval = 1;
2133 	if (start_bus)
2134 		bus = start_bus;
2135 	else {
2136 		xpt_lock_buses();
2137 		bus = TAILQ_FIRST(&xsoftc.xpt_busses);
2138 		if (bus == NULL) {
2139 			xpt_unlock_buses();
2140 			return (retval);
2141 		}
2142 		bus->refcount++;
2143 		xpt_unlock_buses();
2144 	}
2145 	for (; bus != NULL; bus = next_bus) {
2146 		retval = tr_func(bus, arg);
2147 		if (retval == 0) {
2148 			xpt_release_bus(bus);
2149 			break;
2150 		}
2151 		xpt_lock_buses();
2152 		next_bus = TAILQ_NEXT(bus, links);
2153 		if (next_bus)
2154 			next_bus->refcount++;
2155 		xpt_unlock_buses();
2156 		xpt_release_bus(bus);
2157 	}
2158 	return(retval);
2159 }
2160 
2161 static int
xpttargettraverse(struct cam_eb * bus,struct cam_et * start_target,xpt_targetfunc_t * tr_func,void * arg)2162 xpttargettraverse(struct cam_eb *bus, struct cam_et *start_target,
2163 		  xpt_targetfunc_t *tr_func, void *arg)
2164 {
2165 	struct cam_et *target, *next_target;
2166 	int retval;
2167 
2168 	retval = 1;
2169 	if (start_target)
2170 		target = start_target;
2171 	else {
2172 		mtx_lock(&bus->eb_mtx);
2173 		target = TAILQ_FIRST(&bus->et_entries);
2174 		if (target == NULL) {
2175 			mtx_unlock(&bus->eb_mtx);
2176 			return (retval);
2177 		}
2178 		target->refcount++;
2179 		mtx_unlock(&bus->eb_mtx);
2180 	}
2181 	for (; target != NULL; target = next_target) {
2182 		retval = tr_func(target, arg);
2183 		if (retval == 0) {
2184 			xpt_release_target(target);
2185 			break;
2186 		}
2187 		mtx_lock(&bus->eb_mtx);
2188 		next_target = TAILQ_NEXT(target, links);
2189 		if (next_target)
2190 			next_target->refcount++;
2191 		mtx_unlock(&bus->eb_mtx);
2192 		xpt_release_target(target);
2193 	}
2194 	return(retval);
2195 }
2196 
2197 static int
xptdevicetraverse(struct cam_et * target,struct cam_ed * start_device,xpt_devicefunc_t * tr_func,void * arg)2198 xptdevicetraverse(struct cam_et *target, struct cam_ed *start_device,
2199 		  xpt_devicefunc_t *tr_func, void *arg)
2200 {
2201 	struct cam_eb *bus;
2202 	struct cam_ed *device, *next_device;
2203 	int retval;
2204 
2205 	retval = 1;
2206 	bus = target->bus;
2207 	if (start_device)
2208 		device = start_device;
2209 	else {
2210 		mtx_lock(&bus->eb_mtx);
2211 		device = TAILQ_FIRST(&target->ed_entries);
2212 		if (device == NULL) {
2213 			mtx_unlock(&bus->eb_mtx);
2214 			return (retval);
2215 		}
2216 		device->refcount++;
2217 		mtx_unlock(&bus->eb_mtx);
2218 	}
2219 	for (; device != NULL; device = next_device) {
2220 		mtx_lock(&device->device_mtx);
2221 		retval = tr_func(device, arg);
2222 		mtx_unlock(&device->device_mtx);
2223 		if (retval == 0) {
2224 			xpt_release_device(device);
2225 			break;
2226 		}
2227 		mtx_lock(&bus->eb_mtx);
2228 		next_device = TAILQ_NEXT(device, links);
2229 		if (next_device)
2230 			next_device->refcount++;
2231 		mtx_unlock(&bus->eb_mtx);
2232 		xpt_release_device(device);
2233 	}
2234 	return(retval);
2235 }
2236 
2237 static int
xptperiphtraverse(struct cam_ed * device,struct cam_periph * start_periph,xpt_periphfunc_t * tr_func,void * arg)2238 xptperiphtraverse(struct cam_ed *device, struct cam_periph *start_periph,
2239 		  xpt_periphfunc_t *tr_func, void *arg)
2240 {
2241 	struct cam_eb *bus;
2242 	struct cam_periph *periph, *next_periph;
2243 	int retval;
2244 
2245 	retval = 1;
2246 
2247 	bus = device->target->bus;
2248 	if (start_periph)
2249 		periph = start_periph;
2250 	else {
2251 		xpt_lock_buses();
2252 		mtx_lock(&bus->eb_mtx);
2253 		periph = SLIST_FIRST(&device->periphs);
2254 		while (periph != NULL && (periph->flags & CAM_PERIPH_FREE) != 0)
2255 			periph = SLIST_NEXT(periph, periph_links);
2256 		if (periph == NULL) {
2257 			mtx_unlock(&bus->eb_mtx);
2258 			xpt_unlock_buses();
2259 			return (retval);
2260 		}
2261 		periph->refcount++;
2262 		mtx_unlock(&bus->eb_mtx);
2263 		xpt_unlock_buses();
2264 	}
2265 	for (; periph != NULL; periph = next_periph) {
2266 		retval = tr_func(periph, arg);
2267 		if (retval == 0) {
2268 			cam_periph_release_locked(periph);
2269 			break;
2270 		}
2271 		xpt_lock_buses();
2272 		mtx_lock(&bus->eb_mtx);
2273 		next_periph = SLIST_NEXT(periph, periph_links);
2274 		while (next_periph != NULL &&
2275 		    (next_periph->flags & CAM_PERIPH_FREE) != 0)
2276 			next_periph = SLIST_NEXT(next_periph, periph_links);
2277 		if (next_periph)
2278 			next_periph->refcount++;
2279 		mtx_unlock(&bus->eb_mtx);
2280 		xpt_unlock_buses();
2281 		cam_periph_release_locked(periph);
2282 	}
2283 	return(retval);
2284 }
2285 
2286 static int
xptpdrvtraverse(struct periph_driver ** start_pdrv,xpt_pdrvfunc_t * tr_func,void * arg)2287 xptpdrvtraverse(struct periph_driver **start_pdrv,
2288 		xpt_pdrvfunc_t *tr_func, void *arg)
2289 {
2290 	struct periph_driver **pdrv;
2291 	int retval;
2292 
2293 	retval = 1;
2294 
2295 	/*
2296 	 * We don't traverse the peripheral driver list like we do the
2297 	 * other lists, because it is a linker set, and therefore cannot be
2298 	 * changed during runtime.  If the peripheral driver list is ever
2299 	 * re-done to be something other than a linker set (i.e. it can
2300 	 * change while the system is running), the list traversal should
2301 	 * be modified to work like the other traversal functions.
2302 	 */
2303 	for (pdrv = (start_pdrv ? start_pdrv : periph_drivers);
2304 	     *pdrv != NULL; pdrv++) {
2305 		retval = tr_func(pdrv, arg);
2306 
2307 		if (retval == 0)
2308 			return(retval);
2309 	}
2310 
2311 	return(retval);
2312 }
2313 
2314 static int
xptpdperiphtraverse(struct periph_driver ** pdrv,struct cam_periph * start_periph,xpt_periphfunc_t * tr_func,void * arg)2315 xptpdperiphtraverse(struct periph_driver **pdrv,
2316 		    struct cam_periph *start_periph,
2317 		    xpt_periphfunc_t *tr_func, void *arg)
2318 {
2319 	struct cam_periph *periph, *next_periph;
2320 	int retval;
2321 
2322 	retval = 1;
2323 
2324 	if (start_periph)
2325 		periph = start_periph;
2326 	else {
2327 		xpt_lock_buses();
2328 		periph = TAILQ_FIRST(&(*pdrv)->units);
2329 		while (periph != NULL && (periph->flags & CAM_PERIPH_FREE) != 0)
2330 			periph = TAILQ_NEXT(periph, unit_links);
2331 		if (periph == NULL) {
2332 			xpt_unlock_buses();
2333 			return (retval);
2334 		}
2335 		periph->refcount++;
2336 		xpt_unlock_buses();
2337 	}
2338 	for (; periph != NULL; periph = next_periph) {
2339 		cam_periph_lock(periph);
2340 		retval = tr_func(periph, arg);
2341 		cam_periph_unlock(periph);
2342 		if (retval == 0) {
2343 			cam_periph_release(periph);
2344 			break;
2345 		}
2346 		xpt_lock_buses();
2347 		next_periph = TAILQ_NEXT(periph, unit_links);
2348 		while (next_periph != NULL &&
2349 		    (next_periph->flags & CAM_PERIPH_FREE) != 0)
2350 			next_periph = TAILQ_NEXT(next_periph, unit_links);
2351 		if (next_periph)
2352 			next_periph->refcount++;
2353 		xpt_unlock_buses();
2354 		cam_periph_release(periph);
2355 	}
2356 	return(retval);
2357 }
2358 
2359 static int
xptdefbusfunc(struct cam_eb * bus,void * arg)2360 xptdefbusfunc(struct cam_eb *bus, void *arg)
2361 {
2362 	struct xpt_traverse_config *tr_config;
2363 
2364 	tr_config = (struct xpt_traverse_config *)arg;
2365 
2366 	if (tr_config->depth == XPT_DEPTH_BUS) {
2367 		xpt_busfunc_t *tr_func;
2368 
2369 		tr_func = (xpt_busfunc_t *)tr_config->tr_func;
2370 
2371 		return(tr_func(bus, tr_config->tr_arg));
2372 	} else
2373 		return(xpttargettraverse(bus, NULL, xptdeftargetfunc, arg));
2374 }
2375 
2376 static int
xptdeftargetfunc(struct cam_et * target,void * arg)2377 xptdeftargetfunc(struct cam_et *target, void *arg)
2378 {
2379 	struct xpt_traverse_config *tr_config;
2380 
2381 	tr_config = (struct xpt_traverse_config *)arg;
2382 
2383 	if (tr_config->depth == XPT_DEPTH_TARGET) {
2384 		xpt_targetfunc_t *tr_func;
2385 
2386 		tr_func = (xpt_targetfunc_t *)tr_config->tr_func;
2387 
2388 		return(tr_func(target, tr_config->tr_arg));
2389 	} else
2390 		return(xptdevicetraverse(target, NULL, xptdefdevicefunc, arg));
2391 }
2392 
2393 static int
xptdefdevicefunc(struct cam_ed * device,void * arg)2394 xptdefdevicefunc(struct cam_ed *device, void *arg)
2395 {
2396 	struct xpt_traverse_config *tr_config;
2397 
2398 	tr_config = (struct xpt_traverse_config *)arg;
2399 
2400 	if (tr_config->depth == XPT_DEPTH_DEVICE) {
2401 		xpt_devicefunc_t *tr_func;
2402 
2403 		tr_func = (xpt_devicefunc_t *)tr_config->tr_func;
2404 
2405 		return(tr_func(device, tr_config->tr_arg));
2406 	} else
2407 		return(xptperiphtraverse(device, NULL, xptdefperiphfunc, arg));
2408 }
2409 
2410 static int
xptdefperiphfunc(struct cam_periph * periph,void * arg)2411 xptdefperiphfunc(struct cam_periph *periph, void *arg)
2412 {
2413 	struct xpt_traverse_config *tr_config;
2414 	xpt_periphfunc_t *tr_func;
2415 
2416 	tr_config = (struct xpt_traverse_config *)arg;
2417 
2418 	tr_func = (xpt_periphfunc_t *)tr_config->tr_func;
2419 
2420 	/*
2421 	 * Unlike the other default functions, we don't check for depth
2422 	 * here.  The peripheral driver level is the last level in the EDT,
2423 	 * so if we're here, we should execute the function in question.
2424 	 */
2425 	return(tr_func(periph, tr_config->tr_arg));
2426 }
2427 
2428 /*
2429  * Execute the given function for every bus in the EDT.
2430  */
2431 static int
xpt_for_all_busses(xpt_busfunc_t * tr_func,void * arg)2432 xpt_for_all_busses(xpt_busfunc_t *tr_func, void *arg)
2433 {
2434 	struct xpt_traverse_config tr_config;
2435 
2436 	tr_config.depth = XPT_DEPTH_BUS;
2437 	tr_config.tr_func = tr_func;
2438 	tr_config.tr_arg = arg;
2439 
2440 	return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2441 }
2442 
2443 /*
2444  * Execute the given function for every device in the EDT.
2445  */
2446 static int
xpt_for_all_devices(xpt_devicefunc_t * tr_func,void * arg)2447 xpt_for_all_devices(xpt_devicefunc_t *tr_func, void *arg)
2448 {
2449 	struct xpt_traverse_config tr_config;
2450 
2451 	tr_config.depth = XPT_DEPTH_DEVICE;
2452 	tr_config.tr_func = tr_func;
2453 	tr_config.tr_arg = arg;
2454 
2455 	return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2456 }
2457 
2458 static int
xptsetasyncfunc(struct cam_ed * device,void * arg)2459 xptsetasyncfunc(struct cam_ed *device, void *arg)
2460 {
2461 	struct cam_path path;
2462 	struct ccb_getdev cgd;
2463 	struct ccb_setasync *csa = (struct ccb_setasync *)arg;
2464 
2465 	/*
2466 	 * Don't report unconfigured devices (Wildcard devs,
2467 	 * devices only for target mode, device instances
2468 	 * that have been invalidated but are waiting for
2469 	 * their last reference count to be released).
2470 	 */
2471 	if ((device->flags & CAM_DEV_UNCONFIGURED) != 0)
2472 		return (1);
2473 
2474 	xpt_compile_path(&path,
2475 			 NULL,
2476 			 device->target->bus->path_id,
2477 			 device->target->target_id,
2478 			 device->lun_id);
2479 	xpt_gdev_type(&cgd, &path);
2480 	csa->callback(csa->callback_arg,
2481 			    AC_FOUND_DEVICE,
2482 			    &path, &cgd);
2483 	xpt_release_path(&path);
2484 
2485 	return(1);
2486 }
2487 
2488 static int
xptsetasyncbusfunc(struct cam_eb * bus,void * arg)2489 xptsetasyncbusfunc(struct cam_eb *bus, void *arg)
2490 {
2491 	struct cam_path path;
2492 	struct ccb_pathinq cpi;
2493 	struct ccb_setasync *csa = (struct ccb_setasync *)arg;
2494 
2495 	xpt_compile_path(&path, /*periph*/NULL,
2496 			 bus->path_id,
2497 			 CAM_TARGET_WILDCARD,
2498 			 CAM_LUN_WILDCARD);
2499 	xpt_path_lock(&path);
2500 	xpt_path_inq(&cpi, &path);
2501 	csa->callback(csa->callback_arg,
2502 			    AC_PATH_REGISTERED,
2503 			    &path, &cpi);
2504 	xpt_path_unlock(&path);
2505 	xpt_release_path(&path);
2506 
2507 	return(1);
2508 }
2509 
2510 void
xpt_action(union ccb * start_ccb)2511 xpt_action(union ccb *start_ccb)
2512 {
2513 
2514 	CAM_DEBUG(start_ccb->ccb_h.path, CAM_DEBUG_TRACE,
2515 	    ("xpt_action: func %#x %s\n", start_ccb->ccb_h.func_code,
2516 		xpt_action_name(start_ccb->ccb_h.func_code)));
2517 
2518 	start_ccb->ccb_h.status = CAM_REQ_INPROG;
2519 	(*(start_ccb->ccb_h.path->bus->xport->ops->action))(start_ccb);
2520 }
2521 
2522 void
xpt_action_default(union ccb * start_ccb)2523 xpt_action_default(union ccb *start_ccb)
2524 {
2525 	struct cam_path *path;
2526 	struct cam_sim *sim;
2527 	struct mtx *mtx;
2528 
2529 	path = start_ccb->ccb_h.path;
2530 	CAM_DEBUG(path, CAM_DEBUG_TRACE,
2531 	    ("xpt_action_default: func %#x %s\n", start_ccb->ccb_h.func_code,
2532 		xpt_action_name(start_ccb->ccb_h.func_code)));
2533 
2534 	switch (start_ccb->ccb_h.func_code) {
2535 	case XPT_SCSI_IO:
2536 	{
2537 		struct cam_ed *device;
2538 
2539 		/*
2540 		 * For the sake of compatibility with SCSI-1
2541 		 * devices that may not understand the identify
2542 		 * message, we include lun information in the
2543 		 * second byte of all commands.  SCSI-1 specifies
2544 		 * that luns are a 3 bit value and reserves only 3
2545 		 * bits for lun information in the CDB.  Later
2546 		 * revisions of the SCSI spec allow for more than 8
2547 		 * luns, but have deprecated lun information in the
2548 		 * CDB.  So, if the lun won't fit, we must omit.
2549 		 *
2550 		 * Also be aware that during initial probing for devices,
2551 		 * the inquiry information is unknown but initialized to 0.
2552 		 * This means that this code will be exercised while probing
2553 		 * devices with an ANSI revision greater than 2.
2554 		 */
2555 		device = path->device;
2556 		if (device->protocol_version <= SCSI_REV_2
2557 		 && start_ccb->ccb_h.target_lun < 8
2558 		 && (start_ccb->ccb_h.flags & CAM_CDB_POINTER) == 0) {
2559 			start_ccb->csio.cdb_io.cdb_bytes[1] |=
2560 			    start_ccb->ccb_h.target_lun << 5;
2561 		}
2562 		start_ccb->csio.scsi_status = SCSI_STATUS_OK;
2563 	}
2564 	/* FALLTHROUGH */
2565 	case XPT_TARGET_IO:
2566 	case XPT_CONT_TARGET_IO:
2567 		start_ccb->csio.sense_resid = 0;
2568 		start_ccb->csio.resid = 0;
2569 		/* FALLTHROUGH */
2570 	case XPT_ATA_IO:
2571 		if (start_ccb->ccb_h.func_code == XPT_ATA_IO)
2572 			start_ccb->ataio.resid = 0;
2573 		/* FALLTHROUGH */
2574 	case XPT_NVME_IO:
2575 	case XPT_NVME_ADMIN:
2576 	case XPT_MMC_IO:
2577 	case XPT_MMC_GET_TRAN_SETTINGS:
2578 	case XPT_MMC_SET_TRAN_SETTINGS:
2579 	case XPT_RESET_DEV:
2580 	case XPT_ENG_EXEC:
2581 	case XPT_SMP_IO:
2582 	{
2583 		struct cam_devq *devq;
2584 
2585 		devq = path->bus->sim->devq;
2586 		mtx_lock(&devq->send_mtx);
2587 		cam_ccbq_insert_ccb(&path->device->ccbq, start_ccb);
2588 		if (xpt_schedule_devq(devq, path->device) != 0)
2589 			xpt_run_devq(devq);
2590 		mtx_unlock(&devq->send_mtx);
2591 		break;
2592 	}
2593 	case XPT_CALC_GEOMETRY:
2594 		/* Filter out garbage */
2595 		if (start_ccb->ccg.block_size == 0
2596 		 || start_ccb->ccg.volume_size == 0) {
2597 			start_ccb->ccg.cylinders = 0;
2598 			start_ccb->ccg.heads = 0;
2599 			start_ccb->ccg.secs_per_track = 0;
2600 			start_ccb->ccb_h.status = CAM_REQ_CMP;
2601 			break;
2602 		}
2603 		goto call_sim;
2604 	case XPT_ABORT:
2605 	{
2606 		union ccb* abort_ccb;
2607 
2608 		abort_ccb = start_ccb->cab.abort_ccb;
2609 		if (XPT_FC_IS_DEV_QUEUED(abort_ccb)) {
2610 			struct cam_ed *device;
2611 			struct cam_devq *devq;
2612 
2613 			device = abort_ccb->ccb_h.path->device;
2614 			devq = device->sim->devq;
2615 
2616 			mtx_lock(&devq->send_mtx);
2617 			if (abort_ccb->ccb_h.pinfo.index > 0) {
2618 				cam_ccbq_remove_ccb(&device->ccbq, abort_ccb);
2619 				abort_ccb->ccb_h.status =
2620 				    CAM_REQ_ABORTED|CAM_DEV_QFRZN;
2621 				xpt_freeze_devq_device(device, 1);
2622 				mtx_unlock(&devq->send_mtx);
2623 				xpt_done(abort_ccb);
2624 				start_ccb->ccb_h.status = CAM_REQ_CMP;
2625 				break;
2626 			}
2627 			mtx_unlock(&devq->send_mtx);
2628 
2629 			if (abort_ccb->ccb_h.pinfo.index == CAM_UNQUEUED_INDEX
2630 			 && (abort_ccb->ccb_h.status & CAM_SIM_QUEUED) == 0) {
2631 				/*
2632 				 * We've caught this ccb en route to
2633 				 * the SIM.  Flag it for abort and the
2634 				 * SIM will do so just before starting
2635 				 * real work on the CCB.
2636 				 */
2637 				abort_ccb->ccb_h.status =
2638 				    CAM_REQ_ABORTED|CAM_DEV_QFRZN;
2639 				xpt_freeze_devq(abort_ccb->ccb_h.path, 1);
2640 				start_ccb->ccb_h.status = CAM_REQ_CMP;
2641 				break;
2642 			}
2643 		}
2644 		if (XPT_FC_IS_QUEUED(abort_ccb)
2645 		 && (abort_ccb->ccb_h.pinfo.index == CAM_DONEQ_INDEX)) {
2646 			/*
2647 			 * It's already completed but waiting
2648 			 * for our SWI to get to it.
2649 			 */
2650 			start_ccb->ccb_h.status = CAM_UA_ABORT;
2651 			break;
2652 		}
2653 		/*
2654 		 * If we weren't able to take care of the abort request
2655 		 * in the XPT, pass the request down to the SIM for processing.
2656 		 */
2657 	}
2658 	/* FALLTHROUGH */
2659 	case XPT_ACCEPT_TARGET_IO:
2660 	case XPT_EN_LUN:
2661 	case XPT_IMMED_NOTIFY:
2662 	case XPT_NOTIFY_ACK:
2663 	case XPT_RESET_BUS:
2664 	case XPT_IMMEDIATE_NOTIFY:
2665 	case XPT_NOTIFY_ACKNOWLEDGE:
2666 	case XPT_GET_SIM_KNOB_OLD:
2667 	case XPT_GET_SIM_KNOB:
2668 	case XPT_SET_SIM_KNOB:
2669 	case XPT_GET_TRAN_SETTINGS:
2670 	case XPT_SET_TRAN_SETTINGS:
2671 	case XPT_PATH_INQ:
2672 call_sim:
2673 		sim = path->bus->sim;
2674 		mtx = sim->mtx;
2675 		if (mtx && !mtx_owned(mtx))
2676 			mtx_lock(mtx);
2677 		else
2678 			mtx = NULL;
2679 
2680 		CAM_DEBUG(path, CAM_DEBUG_TRACE,
2681 		    ("Calling sim->sim_action(): func=%#x\n", start_ccb->ccb_h.func_code));
2682 		(*(sim->sim_action))(sim, start_ccb);
2683 		CAM_DEBUG(path, CAM_DEBUG_TRACE,
2684 		    ("sim->sim_action returned: status=%#x\n", start_ccb->ccb_h.status));
2685 		if (mtx)
2686 			mtx_unlock(mtx);
2687 		break;
2688 	case XPT_PATH_STATS:
2689 		start_ccb->cpis.last_reset = path->bus->last_reset;
2690 		start_ccb->ccb_h.status = CAM_REQ_CMP;
2691 		break;
2692 	case XPT_GDEV_TYPE:
2693 	{
2694 		struct cam_ed *dev;
2695 
2696 		dev = path->device;
2697 		if ((dev->flags & CAM_DEV_UNCONFIGURED) != 0) {
2698 			start_ccb->ccb_h.status = CAM_DEV_NOT_THERE;
2699 		} else {
2700 			struct ccb_getdev *cgd;
2701 
2702 			cgd = &start_ccb->cgd;
2703 			cgd->protocol = dev->protocol;
2704 			cgd->inq_data = dev->inq_data;
2705 			cgd->ident_data = dev->ident_data;
2706 			cgd->inq_flags = dev->inq_flags;
2707 			cgd->ccb_h.status = CAM_REQ_CMP;
2708 			cgd->serial_num_len = dev->serial_num_len;
2709 			if ((dev->serial_num_len > 0)
2710 			 && (dev->serial_num != NULL))
2711 				bcopy(dev->serial_num, cgd->serial_num,
2712 				      dev->serial_num_len);
2713 		}
2714 		break;
2715 	}
2716 	case XPT_GDEV_STATS:
2717 	{
2718 		struct ccb_getdevstats *cgds = &start_ccb->cgds;
2719 		struct cam_ed *dev = path->device;
2720 		struct cam_eb *bus = path->bus;
2721 		struct cam_et *tar = path->target;
2722 		struct cam_devq *devq = bus->sim->devq;
2723 
2724 		mtx_lock(&devq->send_mtx);
2725 		cgds->dev_openings = dev->ccbq.dev_openings;
2726 		cgds->dev_active = dev->ccbq.dev_active;
2727 		cgds->allocated = dev->ccbq.allocated;
2728 		cgds->queued = cam_ccbq_pending_ccb_count(&dev->ccbq);
2729 		cgds->held = cgds->allocated - cgds->dev_active - cgds->queued;
2730 		cgds->last_reset = tar->last_reset;
2731 		cgds->maxtags = dev->maxtags;
2732 		cgds->mintags = dev->mintags;
2733 		if (timevalcmp(&tar->last_reset, &bus->last_reset, <))
2734 			cgds->last_reset = bus->last_reset;
2735 		mtx_unlock(&devq->send_mtx);
2736 		cgds->ccb_h.status = CAM_REQ_CMP;
2737 		break;
2738 	}
2739 	case XPT_GDEVLIST:
2740 	{
2741 		struct cam_periph	*nperiph;
2742 		struct periph_list	*periph_head;
2743 		struct ccb_getdevlist	*cgdl;
2744 		u_int			i;
2745 		struct cam_ed		*device;
2746 		bool			found;
2747 
2748 		found = false;
2749 
2750 		/*
2751 		 * Don't want anyone mucking with our data.
2752 		 */
2753 		device = path->device;
2754 		periph_head = &device->periphs;
2755 		cgdl = &start_ccb->cgdl;
2756 
2757 		/*
2758 		 * Check and see if the list has changed since the user
2759 		 * last requested a list member.  If so, tell them that the
2760 		 * list has changed, and therefore they need to start over
2761 		 * from the beginning.
2762 		 */
2763 		if ((cgdl->index != 0) &&
2764 		    (cgdl->generation != device->generation)) {
2765 			cgdl->status = CAM_GDEVLIST_LIST_CHANGED;
2766 			break;
2767 		}
2768 
2769 		/*
2770 		 * Traverse the list of peripherals and attempt to find
2771 		 * the requested peripheral.
2772 		 */
2773 		for (nperiph = SLIST_FIRST(periph_head), i = 0;
2774 		     (nperiph != NULL) && (i <= cgdl->index);
2775 		     nperiph = SLIST_NEXT(nperiph, periph_links), i++) {
2776 			if (i == cgdl->index) {
2777 				strlcpy(cgdl->periph_name,
2778 					nperiph->periph_name,
2779 					sizeof(cgdl->periph_name));
2780 				cgdl->unit_number = nperiph->unit_number;
2781 				found = true;
2782 			}
2783 		}
2784 		if (!found) {
2785 			cgdl->status = CAM_GDEVLIST_ERROR;
2786 			break;
2787 		}
2788 
2789 		if (nperiph == NULL)
2790 			cgdl->status = CAM_GDEVLIST_LAST_DEVICE;
2791 		else
2792 			cgdl->status = CAM_GDEVLIST_MORE_DEVS;
2793 
2794 		cgdl->index++;
2795 		cgdl->generation = device->generation;
2796 
2797 		cgdl->ccb_h.status = CAM_REQ_CMP;
2798 		break;
2799 	}
2800 	case XPT_DEV_MATCH:
2801 	{
2802 		dev_pos_type position_type;
2803 		struct ccb_dev_match *cdm;
2804 
2805 		cdm = &start_ccb->cdm;
2806 
2807 		/*
2808 		 * There are two ways of getting at information in the EDT.
2809 		 * The first way is via the primary EDT tree.  It starts
2810 		 * with a list of buses, then a list of targets on a bus,
2811 		 * then devices/luns on a target, and then peripherals on a
2812 		 * device/lun.  The "other" way is by the peripheral driver
2813 		 * lists.  The peripheral driver lists are organized by
2814 		 * peripheral driver.  (obviously)  So it makes sense to
2815 		 * use the peripheral driver list if the user is looking
2816 		 * for something like "da1", or all "da" devices.  If the
2817 		 * user is looking for something on a particular bus/target
2818 		 * or lun, it's generally better to go through the EDT tree.
2819 		 */
2820 
2821 		if (cdm->pos.position_type != CAM_DEV_POS_NONE)
2822 			position_type = cdm->pos.position_type;
2823 		else {
2824 			u_int i;
2825 
2826 			position_type = CAM_DEV_POS_NONE;
2827 
2828 			for (i = 0; i < cdm->num_patterns; i++) {
2829 				if ((cdm->patterns[i].type == DEV_MATCH_BUS)
2830 				 ||(cdm->patterns[i].type == DEV_MATCH_DEVICE)){
2831 					position_type = CAM_DEV_POS_EDT;
2832 					break;
2833 				}
2834 			}
2835 
2836 			if (cdm->num_patterns == 0)
2837 				position_type = CAM_DEV_POS_EDT;
2838 			else if (position_type == CAM_DEV_POS_NONE)
2839 				position_type = CAM_DEV_POS_PDRV;
2840 		}
2841 
2842 		switch(position_type & CAM_DEV_POS_TYPEMASK) {
2843 		case CAM_DEV_POS_EDT:
2844 			xptedtmatch(cdm);
2845 			break;
2846 		case CAM_DEV_POS_PDRV:
2847 			xptperiphlistmatch(cdm);
2848 			break;
2849 		default:
2850 			cdm->status = CAM_DEV_MATCH_ERROR;
2851 			break;
2852 		}
2853 
2854 		if (cdm->status == CAM_DEV_MATCH_ERROR)
2855 			start_ccb->ccb_h.status = CAM_REQ_CMP_ERR;
2856 		else
2857 			start_ccb->ccb_h.status = CAM_REQ_CMP;
2858 
2859 		break;
2860 	}
2861 	case XPT_SASYNC_CB:
2862 	{
2863 		struct ccb_setasync *csa;
2864 		struct async_node *cur_entry;
2865 		struct async_list *async_head;
2866 		uint32_t added;
2867 
2868 		csa = &start_ccb->csa;
2869 		added = csa->event_enable;
2870 		async_head = &path->device->asyncs;
2871 
2872 		/*
2873 		 * If there is already an entry for us, simply
2874 		 * update it.
2875 		 */
2876 		cur_entry = SLIST_FIRST(async_head);
2877 		while (cur_entry != NULL) {
2878 			if ((cur_entry->callback_arg == csa->callback_arg)
2879 			 && (cur_entry->callback == csa->callback))
2880 				break;
2881 			cur_entry = SLIST_NEXT(cur_entry, links);
2882 		}
2883 
2884 		if (cur_entry != NULL) {
2885 		 	/*
2886 			 * If the request has no flags set,
2887 			 * remove the entry.
2888 			 */
2889 			added &= ~cur_entry->event_enable;
2890 			if (csa->event_enable == 0) {
2891 				SLIST_REMOVE(async_head, cur_entry,
2892 					     async_node, links);
2893 				xpt_release_device(path->device);
2894 				free(cur_entry, M_CAMXPT);
2895 			} else {
2896 				cur_entry->event_enable = csa->event_enable;
2897 			}
2898 			csa->event_enable = added;
2899 		} else {
2900 			cur_entry = malloc(sizeof(*cur_entry), M_CAMXPT,
2901 					   M_NOWAIT);
2902 			if (cur_entry == NULL) {
2903 				csa->ccb_h.status = CAM_RESRC_UNAVAIL;
2904 				break;
2905 			}
2906 			cur_entry->event_enable = csa->event_enable;
2907 			cur_entry->event_lock = (path->bus->sim->mtx &&
2908 			    mtx_owned(path->bus->sim->mtx)) ? 1 : 0;
2909 			cur_entry->callback_arg = csa->callback_arg;
2910 			cur_entry->callback = csa->callback;
2911 			SLIST_INSERT_HEAD(async_head, cur_entry, links);
2912 			xpt_acquire_device(path->device);
2913 		}
2914 		start_ccb->ccb_h.status = CAM_REQ_CMP;
2915 		break;
2916 	}
2917 	case XPT_REL_SIMQ:
2918 	{
2919 		struct ccb_relsim *crs;
2920 		struct cam_ed *dev;
2921 
2922 		crs = &start_ccb->crs;
2923 		dev = path->device;
2924 		if (dev == NULL) {
2925 			crs->ccb_h.status = CAM_DEV_NOT_THERE;
2926 			break;
2927 		}
2928 
2929 		if ((crs->release_flags & RELSIM_ADJUST_OPENINGS) != 0) {
2930 			/* Don't ever go below one opening */
2931 			if (crs->openings > 0) {
2932 				xpt_dev_ccbq_resize(path, crs->openings);
2933 				if (bootverbose) {
2934 					xpt_print(path,
2935 					    "number of openings is now %d\n",
2936 					    crs->openings);
2937 				}
2938 			}
2939 		}
2940 
2941 		mtx_lock(&dev->sim->devq->send_mtx);
2942 		if ((crs->release_flags & RELSIM_RELEASE_AFTER_TIMEOUT) != 0) {
2943 			if ((dev->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
2944 				/*
2945 				 * Just extend the old timeout and decrement
2946 				 * the freeze count so that a single timeout
2947 				 * is sufficient for releasing the queue.
2948 				 */
2949 				start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
2950 				callout_stop(&dev->callout);
2951 			} else {
2952 				start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
2953 			}
2954 
2955 			callout_reset_sbt(&dev->callout,
2956 			    SBT_1MS * crs->release_timeout, SBT_1MS,
2957 			    xpt_release_devq_timeout, dev, 0);
2958 
2959 			dev->flags |= CAM_DEV_REL_TIMEOUT_PENDING;
2960 		}
2961 
2962 		if ((crs->release_flags & RELSIM_RELEASE_AFTER_CMDCMPLT) != 0) {
2963 			if ((dev->flags & CAM_DEV_REL_ON_COMPLETE) != 0) {
2964 				/*
2965 				 * Decrement the freeze count so that a single
2966 				 * completion is still sufficient to unfreeze
2967 				 * the queue.
2968 				 */
2969 				start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
2970 			} else {
2971 				dev->flags |= CAM_DEV_REL_ON_COMPLETE;
2972 				start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
2973 			}
2974 		}
2975 
2976 		if ((crs->release_flags & RELSIM_RELEASE_AFTER_QEMPTY) != 0) {
2977 			if ((dev->flags & CAM_DEV_REL_ON_QUEUE_EMPTY) != 0
2978 			 || (dev->ccbq.dev_active == 0)) {
2979 				start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
2980 			} else {
2981 				dev->flags |= CAM_DEV_REL_ON_QUEUE_EMPTY;
2982 				start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
2983 			}
2984 		}
2985 		mtx_unlock(&dev->sim->devq->send_mtx);
2986 
2987 		if ((start_ccb->ccb_h.flags & CAM_DEV_QFREEZE) == 0)
2988 			xpt_release_devq(path, /*count*/1, /*run_queue*/TRUE);
2989 		start_ccb->crs.qfrozen_cnt = dev->ccbq.queue.qfrozen_cnt;
2990 		start_ccb->ccb_h.status = CAM_REQ_CMP;
2991 		break;
2992 	}
2993 	case XPT_DEBUG: {
2994 		struct cam_path *oldpath;
2995 
2996 		/* Check that all request bits are supported. */
2997 		if (start_ccb->cdbg.flags & ~(CAM_DEBUG_COMPILE)) {
2998 			start_ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
2999 			break;
3000 		}
3001 
3002 		cam_dflags = CAM_DEBUG_NONE;
3003 		if (cam_dpath != NULL) {
3004 			oldpath = cam_dpath;
3005 			cam_dpath = NULL;
3006 			xpt_free_path(oldpath);
3007 		}
3008 		if (start_ccb->cdbg.flags != CAM_DEBUG_NONE) {
3009 			if (xpt_create_path(&cam_dpath, NULL,
3010 					    start_ccb->ccb_h.path_id,
3011 					    start_ccb->ccb_h.target_id,
3012 					    start_ccb->ccb_h.target_lun) !=
3013 					    CAM_REQ_CMP) {
3014 				start_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
3015 			} else {
3016 				cam_dflags = start_ccb->cdbg.flags;
3017 				start_ccb->ccb_h.status = CAM_REQ_CMP;
3018 				xpt_print(cam_dpath, "debugging flags now %x\n",
3019 				    cam_dflags);
3020 			}
3021 		} else
3022 			start_ccb->ccb_h.status = CAM_REQ_CMP;
3023 		break;
3024 	}
3025 	case XPT_NOOP:
3026 		if ((start_ccb->ccb_h.flags & CAM_DEV_QFREEZE) != 0)
3027 			xpt_freeze_devq(path, 1);
3028 		start_ccb->ccb_h.status = CAM_REQ_CMP;
3029 		break;
3030 	case XPT_REPROBE_LUN:
3031 		xpt_async(AC_INQ_CHANGED, path, NULL);
3032 		start_ccb->ccb_h.status = CAM_REQ_CMP;
3033 		xpt_done(start_ccb);
3034 		break;
3035 	case XPT_ASYNC:
3036 		/*
3037 		 * Queue the async operation so it can be run from a sleepable
3038 		 * context.
3039 		 */
3040 		start_ccb->ccb_h.status = CAM_REQ_CMP;
3041 		mtx_lock(&cam_async.cam_doneq_mtx);
3042 		STAILQ_INSERT_TAIL(&cam_async.cam_doneq, &start_ccb->ccb_h, sim_links.stqe);
3043 		start_ccb->ccb_h.pinfo.index = CAM_ASYNC_INDEX;
3044 		mtx_unlock(&cam_async.cam_doneq_mtx);
3045 		wakeup(&cam_async.cam_doneq);
3046 		break;
3047 	default:
3048 	case XPT_SDEV_TYPE:
3049 	case XPT_TERM_IO:
3050 	case XPT_ENG_INQ:
3051 		/* XXX Implement */
3052 		xpt_print(start_ccb->ccb_h.path,
3053 		    "%s: CCB type %#x %s not supported\n", __func__,
3054 		    start_ccb->ccb_h.func_code,
3055 		    xpt_action_name(start_ccb->ccb_h.func_code));
3056 		start_ccb->ccb_h.status = CAM_PROVIDE_FAIL;
3057 		if (start_ccb->ccb_h.func_code & XPT_FC_DEV_QUEUED) {
3058 			xpt_done(start_ccb);
3059 		}
3060 		break;
3061 	}
3062 	CAM_DEBUG(path, CAM_DEBUG_TRACE,
3063 	    ("xpt_action_default: func= %#x %s status %#x\n",
3064 		start_ccb->ccb_h.func_code,
3065  		xpt_action_name(start_ccb->ccb_h.func_code),
3066 		start_ccb->ccb_h.status));
3067 }
3068 
3069 /*
3070  * Call the sim poll routine to allow the sim to complete
3071  * any inflight requests, then call camisr_runqueue to
3072  * complete any CCB that the polling completed.
3073  */
3074 void
xpt_sim_poll(struct cam_sim * sim)3075 xpt_sim_poll(struct cam_sim *sim)
3076 {
3077 	struct mtx *mtx;
3078 
3079 	KASSERT(cam_sim_pollable(sim), ("%s: non-pollable sim", __func__));
3080 	mtx = sim->mtx;
3081 	if (mtx)
3082 		mtx_lock(mtx);
3083 	(*(sim->sim_poll))(sim);
3084 	if (mtx)
3085 		mtx_unlock(mtx);
3086 	camisr_runqueue();
3087 }
3088 
3089 uint32_t
xpt_poll_setup(union ccb * start_ccb)3090 xpt_poll_setup(union ccb *start_ccb)
3091 {
3092 	uint32_t timeout;
3093 	struct	  cam_sim *sim;
3094 	struct	  cam_devq *devq;
3095 	struct	  cam_ed *dev;
3096 
3097 	timeout = start_ccb->ccb_h.timeout * 10;
3098 	sim = start_ccb->ccb_h.path->bus->sim;
3099 	devq = sim->devq;
3100 	dev = start_ccb->ccb_h.path->device;
3101 
3102 	KASSERT(cam_sim_pollable(sim), ("%s: non-pollable sim", __func__));
3103 
3104 	/*
3105 	 * Steal an opening so that no other queued requests
3106 	 * can get it before us while we simulate interrupts.
3107 	 */
3108 	mtx_lock(&devq->send_mtx);
3109 	dev->ccbq.dev_openings--;
3110 	while((devq->send_openings <= 0 || dev->ccbq.dev_openings < 0) &&
3111 	    (--timeout > 0)) {
3112 		mtx_unlock(&devq->send_mtx);
3113 		DELAY(100);
3114 		xpt_sim_poll(sim);
3115 		mtx_lock(&devq->send_mtx);
3116 	}
3117 	dev->ccbq.dev_openings++;
3118 	mtx_unlock(&devq->send_mtx);
3119 
3120 	return (timeout);
3121 }
3122 
3123 void
xpt_pollwait(union ccb * start_ccb,uint32_t timeout)3124 xpt_pollwait(union ccb *start_ccb, uint32_t timeout)
3125 {
3126 
3127 	KASSERT(cam_sim_pollable(start_ccb->ccb_h.path->bus->sim),
3128 	    ("%s: non-pollable sim", __func__));
3129 	while (--timeout > 0) {
3130 		xpt_sim_poll(start_ccb->ccb_h.path->bus->sim);
3131 		if ((start_ccb->ccb_h.status & CAM_STATUS_MASK)
3132 		    != CAM_REQ_INPROG)
3133 			break;
3134 		DELAY(100);
3135 	}
3136 
3137 	if (timeout == 0) {
3138 		/*
3139 		 * XXX Is it worth adding a sim_timeout entry
3140 		 * point so we can attempt recovery?  If
3141 		 * this is only used for dumps, I don't think
3142 		 * it is.
3143 		 */
3144 		start_ccb->ccb_h.status = CAM_CMD_TIMEOUT;
3145 	}
3146 }
3147 
3148 /*
3149  * Schedule a peripheral driver to receive a ccb when its
3150  * target device has space for more transactions.
3151  */
3152 void
xpt_schedule(struct cam_periph * periph,uint32_t new_priority)3153 xpt_schedule(struct cam_periph *periph, uint32_t new_priority)
3154 {
3155 
3156 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("xpt_schedule\n"));
3157 	cam_periph_assert(periph, MA_OWNED);
3158 	if (new_priority < periph->scheduled_priority) {
3159 		periph->scheduled_priority = new_priority;
3160 		xpt_run_allocq(periph, 0);
3161 	}
3162 }
3163 
3164 /*
3165  * Schedule a device to run on a given queue.
3166  * If the device was inserted as a new entry on the queue,
3167  * return 1 meaning the device queue should be run. If we
3168  * were already queued, implying someone else has already
3169  * started the queue, return 0 so the caller doesn't attempt
3170  * to run the queue.
3171  */
3172 static int
xpt_schedule_dev(struct camq * queue,cam_pinfo * pinfo,uint32_t new_priority)3173 xpt_schedule_dev(struct camq *queue, cam_pinfo *pinfo,
3174 		 uint32_t new_priority)
3175 {
3176 	int retval;
3177 	uint32_t old_priority;
3178 
3179 	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_schedule_dev\n"));
3180 
3181 	old_priority = pinfo->priority;
3182 
3183 	/*
3184 	 * Are we already queued?
3185 	 */
3186 	if (pinfo->index != CAM_UNQUEUED_INDEX) {
3187 		/* Simply reorder based on new priority */
3188 		if (new_priority < old_priority) {
3189 			camq_change_priority(queue, pinfo->index,
3190 					     new_priority);
3191 			CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3192 					("changed priority to %d\n",
3193 					 new_priority));
3194 			retval = 1;
3195 		} else
3196 			retval = 0;
3197 	} else {
3198 		/* New entry on the queue */
3199 		if (new_priority < old_priority)
3200 			pinfo->priority = new_priority;
3201 
3202 		CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3203 				("Inserting onto queue\n"));
3204 		pinfo->generation = ++queue->generation;
3205 		camq_insert(queue, pinfo);
3206 		retval = 1;
3207 	}
3208 	return (retval);
3209 }
3210 
3211 static void
xpt_run_allocq_task(void * context,int pending)3212 xpt_run_allocq_task(void *context, int pending)
3213 {
3214 	struct cam_periph *periph = context;
3215 
3216 	cam_periph_lock(periph);
3217 	periph->flags &= ~CAM_PERIPH_RUN_TASK;
3218 	xpt_run_allocq(periph, 1);
3219 	cam_periph_unlock(periph);
3220 	cam_periph_release(periph);
3221 }
3222 
3223 static void
xpt_run_allocq(struct cam_periph * periph,int sleep)3224 xpt_run_allocq(struct cam_periph *periph, int sleep)
3225 {
3226 	struct cam_ed	*device;
3227 	union ccb	*ccb;
3228 	uint32_t	 prio;
3229 
3230 	cam_periph_assert(periph, MA_OWNED);
3231 	if (periph->periph_allocating)
3232 		return;
3233 	cam_periph_doacquire(periph);
3234 	periph->periph_allocating = 1;
3235 	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_allocq(%p)\n", periph));
3236 	device = periph->path->device;
3237 	ccb = NULL;
3238 restart:
3239 	while ((prio = min(periph->scheduled_priority,
3240 	    periph->immediate_priority)) != CAM_PRIORITY_NONE &&
3241 	    (periph->periph_allocated - (ccb != NULL ? 1 : 0) <
3242 	     device->ccbq.total_openings || prio <= CAM_PRIORITY_OOB)) {
3243 		if (ccb == NULL &&
3244 		    (ccb = xpt_get_ccb_nowait(periph)) == NULL) {
3245 			if (sleep) {
3246 				ccb = xpt_get_ccb(periph);
3247 				goto restart;
3248 			}
3249 			if (periph->flags & CAM_PERIPH_RUN_TASK)
3250 				break;
3251 			cam_periph_doacquire(periph);
3252 			periph->flags |= CAM_PERIPH_RUN_TASK;
3253 			taskqueue_enqueue(xsoftc.xpt_taskq,
3254 			    &periph->periph_run_task);
3255 			break;
3256 		}
3257 		xpt_setup_ccb(&ccb->ccb_h, periph->path, prio);
3258 		if (prio == periph->immediate_priority) {
3259 			periph->immediate_priority = CAM_PRIORITY_NONE;
3260 			CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3261 					("waking cam_periph_getccb()\n"));
3262 			SLIST_INSERT_HEAD(&periph->ccb_list, &ccb->ccb_h,
3263 					  periph_links.sle);
3264 			wakeup(&periph->ccb_list);
3265 		} else {
3266 			periph->scheduled_priority = CAM_PRIORITY_NONE;
3267 			CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3268 					("calling periph_start()\n"));
3269 			periph->periph_start(periph, ccb);
3270 		}
3271 		ccb = NULL;
3272 	}
3273 	if (ccb != NULL)
3274 		xpt_release_ccb(ccb);
3275 	periph->periph_allocating = 0;
3276 	cam_periph_release_locked(periph);
3277 }
3278 
3279 static void
xpt_run_devq(struct cam_devq * devq)3280 xpt_run_devq(struct cam_devq *devq)
3281 {
3282 	struct mtx *mtx;
3283 
3284 	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_devq\n"));
3285 
3286 	devq->send_queue.qfrozen_cnt++;
3287 	while ((devq->send_queue.entries > 0)
3288 	    && (devq->send_openings > 0)
3289 	    && (devq->send_queue.qfrozen_cnt <= 1)) {
3290 		struct	cam_ed *device;
3291 		union ccb *work_ccb;
3292 		struct	cam_sim *sim;
3293 		struct xpt_proto *proto;
3294 
3295 		device = (struct cam_ed *)camq_remove(&devq->send_queue,
3296 							   CAMQ_HEAD);
3297 		CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3298 				("running device %p\n", device));
3299 
3300 		work_ccb = cam_ccbq_peek_ccb(&device->ccbq, CAMQ_HEAD);
3301 		if (work_ccb == NULL) {
3302 			printf("device on run queue with no ccbs???\n");
3303 			continue;
3304 		}
3305 
3306 		if ((work_ccb->ccb_h.flags & CAM_HIGH_POWER) != 0) {
3307 			mtx_lock(&xsoftc.xpt_highpower_lock);
3308 		 	if (xsoftc.num_highpower <= 0) {
3309 				/*
3310 				 * We got a high power command, but we
3311 				 * don't have any available slots.  Freeze
3312 				 * the device queue until we have a slot
3313 				 * available.
3314 				 */
3315 				xpt_freeze_devq_device(device, 1);
3316 				STAILQ_INSERT_TAIL(&xsoftc.highpowerq, device,
3317 						   highpowerq_entry);
3318 
3319 				mtx_unlock(&xsoftc.xpt_highpower_lock);
3320 				continue;
3321 			} else {
3322 				/*
3323 				 * Consume a high power slot while
3324 				 * this ccb runs.
3325 				 */
3326 				xsoftc.num_highpower--;
3327 			}
3328 			mtx_unlock(&xsoftc.xpt_highpower_lock);
3329 		}
3330 		cam_ccbq_remove_ccb(&device->ccbq, work_ccb);
3331 		cam_ccbq_send_ccb(&device->ccbq, work_ccb);
3332 		devq->send_openings--;
3333 		devq->send_active++;
3334 		xpt_schedule_devq(devq, device);
3335 		mtx_unlock(&devq->send_mtx);
3336 
3337 		if ((work_ccb->ccb_h.flags & CAM_DEV_QFREEZE) != 0) {
3338 			/*
3339 			 * The client wants to freeze the queue
3340 			 * after this CCB is sent.
3341 			 */
3342 			xpt_freeze_devq(work_ccb->ccb_h.path, 1);
3343 		}
3344 
3345 		/* In Target mode, the peripheral driver knows best... */
3346 		if (work_ccb->ccb_h.func_code == XPT_SCSI_IO) {
3347 			if ((device->inq_flags & SID_CmdQue) != 0
3348 			 && work_ccb->csio.tag_action != CAM_TAG_ACTION_NONE)
3349 				work_ccb->ccb_h.flags |= CAM_TAG_ACTION_VALID;
3350 			else
3351 				/*
3352 				 * Clear this in case of a retried CCB that
3353 				 * failed due to a rejected tag.
3354 				 */
3355 				work_ccb->ccb_h.flags &= ~CAM_TAG_ACTION_VALID;
3356 		}
3357 
3358 		KASSERT(device == work_ccb->ccb_h.path->device,
3359 		    ("device (%p) / path->device (%p) mismatch",
3360 			device, work_ccb->ccb_h.path->device));
3361 		proto = xpt_proto_find(device->protocol);
3362 		if (proto && proto->ops->debug_out)
3363 			proto->ops->debug_out(work_ccb);
3364 
3365 		/*
3366 		 * Device queues can be shared among multiple SIM instances
3367 		 * that reside on different buses.  Use the SIM from the
3368 		 * queued device, rather than the one from the calling bus.
3369 		 */
3370 		sim = device->sim;
3371 		mtx = sim->mtx;
3372 		if (mtx && !mtx_owned(mtx))
3373 			mtx_lock(mtx);
3374 		else
3375 			mtx = NULL;
3376 		work_ccb->ccb_h.qos.periph_data = cam_iosched_now();
3377 		(*(sim->sim_action))(sim, work_ccb);
3378 		if (mtx)
3379 			mtx_unlock(mtx);
3380 		mtx_lock(&devq->send_mtx);
3381 	}
3382 	devq->send_queue.qfrozen_cnt--;
3383 }
3384 
3385 /*
3386  * This function merges stuff from the src ccb into the dst ccb, while keeping
3387  * important fields in the dst ccb constant.
3388  */
3389 void
xpt_merge_ccb(union ccb * dst_ccb,union ccb * src_ccb)3390 xpt_merge_ccb(union ccb *dst_ccb, union ccb *src_ccb)
3391 {
3392 
3393 	/*
3394 	 * Pull fields that are valid for peripheral drivers to set
3395 	 * into the dst CCB along with the CCB "payload".
3396 	 */
3397 	dst_ccb->ccb_h.retry_count = src_ccb->ccb_h.retry_count;
3398 	dst_ccb->ccb_h.func_code = src_ccb->ccb_h.func_code;
3399 	dst_ccb->ccb_h.timeout = src_ccb->ccb_h.timeout;
3400 	dst_ccb->ccb_h.flags = src_ccb->ccb_h.flags;
3401 	bcopy(&(&src_ccb->ccb_h)[1], &(&dst_ccb->ccb_h)[1],
3402 	      sizeof(union ccb) - sizeof(struct ccb_hdr));
3403 }
3404 
3405 void
xpt_setup_ccb_flags(struct ccb_hdr * ccb_h,struct cam_path * path,uint32_t priority,uint32_t flags)3406 xpt_setup_ccb_flags(struct ccb_hdr *ccb_h, struct cam_path *path,
3407 		    uint32_t priority, uint32_t flags)
3408 {
3409 
3410 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_setup_ccb\n"));
3411 	ccb_h->pinfo.priority = priority;
3412 	ccb_h->path = path;
3413 	ccb_h->path_id = path->bus->path_id;
3414 	if (path->target)
3415 		ccb_h->target_id = path->target->target_id;
3416 	else
3417 		ccb_h->target_id = CAM_TARGET_WILDCARD;
3418 	if (path->device) {
3419 		ccb_h->target_lun = path->device->lun_id;
3420 		ccb_h->pinfo.generation = ++path->device->ccbq.queue.generation;
3421 	} else {
3422 		ccb_h->target_lun = CAM_TARGET_WILDCARD;
3423 	}
3424 	ccb_h->pinfo.index = CAM_UNQUEUED_INDEX;
3425 	ccb_h->flags = flags;
3426 	ccb_h->xflags = 0;
3427 }
3428 
3429 void
xpt_setup_ccb(struct ccb_hdr * ccb_h,struct cam_path * path,uint32_t priority)3430 xpt_setup_ccb(struct ccb_hdr *ccb_h, struct cam_path *path, uint32_t priority)
3431 {
3432 	xpt_setup_ccb_flags(ccb_h, path, priority, /*flags*/ 0);
3433 }
3434 
3435 /* Path manipulation functions */
3436 cam_status
xpt_create_path(struct cam_path ** new_path_ptr,struct cam_periph * perph,path_id_t path_id,target_id_t target_id,lun_id_t lun_id)3437 xpt_create_path(struct cam_path **new_path_ptr, struct cam_periph *perph,
3438 		path_id_t path_id, target_id_t target_id, lun_id_t lun_id)
3439 {
3440 	struct	   cam_path *path;
3441 	cam_status status;
3442 
3443 	path = (struct cam_path *)malloc(sizeof(*path), M_CAMPATH, M_NOWAIT);
3444 
3445 	if (path == NULL) {
3446 		status = CAM_RESRC_UNAVAIL;
3447 		return(status);
3448 	}
3449 	status = xpt_compile_path(path, perph, path_id, target_id, lun_id);
3450 	if (status != CAM_REQ_CMP) {
3451 		free(path, M_CAMPATH);
3452 		path = NULL;
3453 	}
3454 	*new_path_ptr = path;
3455 	return (status);
3456 }
3457 
3458 cam_status
xpt_create_path_unlocked(struct cam_path ** new_path_ptr,struct cam_periph * periph,path_id_t path_id,target_id_t target_id,lun_id_t lun_id)3459 xpt_create_path_unlocked(struct cam_path **new_path_ptr,
3460 			 struct cam_periph *periph, path_id_t path_id,
3461 			 target_id_t target_id, lun_id_t lun_id)
3462 {
3463 
3464 	return (xpt_create_path(new_path_ptr, periph, path_id, target_id,
3465 	    lun_id));
3466 }
3467 
3468 cam_status
xpt_compile_path(struct cam_path * new_path,struct cam_periph * perph,path_id_t path_id,target_id_t target_id,lun_id_t lun_id)3469 xpt_compile_path(struct cam_path *new_path, struct cam_periph *perph,
3470 		 path_id_t path_id, target_id_t target_id, lun_id_t lun_id)
3471 {
3472 	struct	     cam_eb *bus;
3473 	struct	     cam_et *target;
3474 	struct	     cam_ed *device;
3475 	cam_status   status;
3476 
3477 	status = CAM_REQ_CMP;	/* Completed without error */
3478 	target = NULL;		/* Wildcarded */
3479 	device = NULL;		/* Wildcarded */
3480 
3481 	/*
3482 	 * We will potentially modify the EDT, so block interrupts
3483 	 * that may attempt to create cam paths.
3484 	 */
3485 	bus = xpt_find_bus(path_id);
3486 	if (bus == NULL) {
3487 		status = CAM_PATH_INVALID;
3488 	} else {
3489 		xpt_lock_buses();
3490 		mtx_lock(&bus->eb_mtx);
3491 		target = xpt_find_target(bus, target_id);
3492 		if (target == NULL) {
3493 			/* Create one */
3494 			struct cam_et *new_target;
3495 
3496 			new_target = xpt_alloc_target(bus, target_id);
3497 			if (new_target == NULL) {
3498 				status = CAM_RESRC_UNAVAIL;
3499 			} else {
3500 				target = new_target;
3501 			}
3502 		}
3503 		xpt_unlock_buses();
3504 		if (target != NULL) {
3505 			device = xpt_find_device(target, lun_id);
3506 			if (device == NULL) {
3507 				/* Create one */
3508 				struct cam_ed *new_device;
3509 
3510 				new_device =
3511 				    (*(bus->xport->ops->alloc_device))(bus,
3512 								       target,
3513 								       lun_id);
3514 				if (new_device == NULL) {
3515 					status = CAM_RESRC_UNAVAIL;
3516 				} else {
3517 					device = new_device;
3518 				}
3519 			}
3520 		}
3521 		mtx_unlock(&bus->eb_mtx);
3522 	}
3523 
3524 	/*
3525 	 * Only touch the user's data if we are successful.
3526 	 */
3527 	if (status == CAM_REQ_CMP) {
3528 		new_path->periph = perph;
3529 		new_path->bus = bus;
3530 		new_path->target = target;
3531 		new_path->device = device;
3532 		CAM_DEBUG(new_path, CAM_DEBUG_TRACE, ("xpt_compile_path\n"));
3533 	} else {
3534 		if (device != NULL)
3535 			xpt_release_device(device);
3536 		if (target != NULL)
3537 			xpt_release_target(target);
3538 		if (bus != NULL)
3539 			xpt_release_bus(bus);
3540 	}
3541 	return (status);
3542 }
3543 
3544 int
xpt_clone_path(struct cam_path ** new_path_ptr,struct cam_path * path)3545 xpt_clone_path(struct cam_path **new_path_ptr, struct cam_path *path)
3546 {
3547 	struct	   cam_path *new_path;
3548 
3549 	new_path = (struct cam_path *)malloc(sizeof(*path), M_CAMPATH, M_NOWAIT);
3550 	if (new_path == NULL)
3551 		return (ENOMEM);
3552 	*new_path = *path;
3553 	if (path->bus != NULL)
3554 		xpt_acquire_bus(path->bus);
3555 	if (path->target != NULL)
3556 		xpt_acquire_target(path->target);
3557 	if (path->device != NULL)
3558 		xpt_acquire_device(path->device);
3559 	*new_path_ptr = new_path;
3560 	return (0);
3561 }
3562 
3563 void
xpt_release_path(struct cam_path * path)3564 xpt_release_path(struct cam_path *path)
3565 {
3566 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_release_path\n"));
3567 	if (path->device != NULL) {
3568 		xpt_release_device(path->device);
3569 		path->device = NULL;
3570 	}
3571 	if (path->target != NULL) {
3572 		xpt_release_target(path->target);
3573 		path->target = NULL;
3574 	}
3575 	if (path->bus != NULL) {
3576 		xpt_release_bus(path->bus);
3577 		path->bus = NULL;
3578 	}
3579 }
3580 
3581 void
xpt_free_path(struct cam_path * path)3582 xpt_free_path(struct cam_path *path)
3583 {
3584 
3585 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_free_path\n"));
3586 	xpt_release_path(path);
3587 	free(path, M_CAMPATH);
3588 }
3589 
3590 void
xpt_path_counts(struct cam_path * path,uint32_t * bus_ref,uint32_t * periph_ref,uint32_t * target_ref,uint32_t * device_ref)3591 xpt_path_counts(struct cam_path *path, uint32_t *bus_ref,
3592     uint32_t *periph_ref, uint32_t *target_ref, uint32_t *device_ref)
3593 {
3594 
3595 	xpt_lock_buses();
3596 	if (bus_ref) {
3597 		if (path->bus)
3598 			*bus_ref = path->bus->refcount;
3599 		else
3600 			*bus_ref = 0;
3601 	}
3602 	if (periph_ref) {
3603 		if (path->periph)
3604 			*periph_ref = path->periph->refcount;
3605 		else
3606 			*periph_ref = 0;
3607 	}
3608 	xpt_unlock_buses();
3609 	if (target_ref) {
3610 		if (path->target)
3611 			*target_ref = path->target->refcount;
3612 		else
3613 			*target_ref = 0;
3614 	}
3615 	if (device_ref) {
3616 		if (path->device)
3617 			*device_ref = path->device->refcount;
3618 		else
3619 			*device_ref = 0;
3620 	}
3621 }
3622 
3623 /*
3624  * Return -1 for failure, 0 for exact match, 1 for match with wildcards
3625  * in path1, 2 for match with wildcards in path2.
3626  */
3627 int
xpt_path_comp(struct cam_path * path1,struct cam_path * path2)3628 xpt_path_comp(struct cam_path *path1, struct cam_path *path2)
3629 {
3630 	int retval = 0;
3631 
3632 	if (path1->bus != path2->bus) {
3633 		if (path1->bus->path_id == CAM_BUS_WILDCARD)
3634 			retval = 1;
3635 		else if (path2->bus->path_id == CAM_BUS_WILDCARD)
3636 			retval = 2;
3637 		else
3638 			return (-1);
3639 	}
3640 	if (path1->target != path2->target) {
3641 		if (path1->target->target_id == CAM_TARGET_WILDCARD) {
3642 			if (retval == 0)
3643 				retval = 1;
3644 		} else if (path2->target->target_id == CAM_TARGET_WILDCARD)
3645 			retval = 2;
3646 		else
3647 			return (-1);
3648 	}
3649 	if (path1->device != path2->device) {
3650 		if (path1->device->lun_id == CAM_LUN_WILDCARD) {
3651 			if (retval == 0)
3652 				retval = 1;
3653 		} else if (path2->device->lun_id == CAM_LUN_WILDCARD)
3654 			retval = 2;
3655 		else
3656 			return (-1);
3657 	}
3658 	return (retval);
3659 }
3660 
3661 int
xpt_path_comp_dev(struct cam_path * path,struct cam_ed * dev)3662 xpt_path_comp_dev(struct cam_path *path, struct cam_ed *dev)
3663 {
3664 	int retval = 0;
3665 
3666 	if (path->bus != dev->target->bus) {
3667 		if (path->bus->path_id == CAM_BUS_WILDCARD)
3668 			retval = 1;
3669 		else if (dev->target->bus->path_id == CAM_BUS_WILDCARD)
3670 			retval = 2;
3671 		else
3672 			return (-1);
3673 	}
3674 	if (path->target != dev->target) {
3675 		if (path->target->target_id == CAM_TARGET_WILDCARD) {
3676 			if (retval == 0)
3677 				retval = 1;
3678 		} else if (dev->target->target_id == CAM_TARGET_WILDCARD)
3679 			retval = 2;
3680 		else
3681 			return (-1);
3682 	}
3683 	if (path->device != dev) {
3684 		if (path->device->lun_id == CAM_LUN_WILDCARD) {
3685 			if (retval == 0)
3686 				retval = 1;
3687 		} else if (dev->lun_id == CAM_LUN_WILDCARD)
3688 			retval = 2;
3689 		else
3690 			return (-1);
3691 	}
3692 	return (retval);
3693 }
3694 
3695 void
xpt_print_path(struct cam_path * path)3696 xpt_print_path(struct cam_path *path)
3697 {
3698 	struct sbuf sb;
3699 	char buffer[XPT_PRINT_LEN];
3700 
3701 	sbuf_new(&sb, buffer, XPT_PRINT_LEN, SBUF_FIXEDLEN);
3702 	xpt_path_sbuf(path, &sb);
3703 	sbuf_finish(&sb);
3704 	printf("%s", sbuf_data(&sb));
3705 	sbuf_delete(&sb);
3706 }
3707 
3708 static void
xpt_device_sbuf(struct cam_ed * device,struct sbuf * sb)3709 xpt_device_sbuf(struct cam_ed *device, struct sbuf *sb)
3710 {
3711 	if (device == NULL)
3712 		sbuf_cat(sb, "(nopath): ");
3713 	else {
3714 		sbuf_printf(sb, "(noperiph:%s%d:%d:%d:%jx): ",
3715 		    device->sim->sim_name,
3716 		    device->sim->unit_number,
3717 		    device->sim->bus_id,
3718 		    device->target->target_id,
3719 		    (uintmax_t)device->lun_id);
3720 	}
3721 }
3722 
3723 void
xpt_print(struct cam_path * path,const char * fmt,...)3724 xpt_print(struct cam_path *path, const char *fmt, ...)
3725 {
3726 	va_list ap;
3727 	struct sbuf sb;
3728 	char buffer[XPT_PRINT_LEN];
3729 
3730 	sbuf_new(&sb, buffer, XPT_PRINT_LEN, SBUF_FIXEDLEN);
3731 
3732 	xpt_path_sbuf(path, &sb);
3733 	va_start(ap, fmt);
3734 	sbuf_vprintf(&sb, fmt, ap);
3735 	va_end(ap);
3736 
3737 	sbuf_finish(&sb);
3738 	printf("%s", sbuf_data(&sb));
3739 	sbuf_delete(&sb);
3740 }
3741 
3742 char *
xpt_path_string(struct cam_path * path,char * str,size_t str_len)3743 xpt_path_string(struct cam_path *path, char *str, size_t str_len)
3744 {
3745 	struct sbuf sb;
3746 
3747 	sbuf_new(&sb, str, str_len, 0);
3748 	xpt_path_sbuf(path, &sb);
3749 	sbuf_finish(&sb);
3750 	return (str);
3751 }
3752 
3753 void
xpt_path_sbuf(struct cam_path * path,struct sbuf * sb)3754 xpt_path_sbuf(struct cam_path *path, struct sbuf *sb)
3755 {
3756 
3757 	if (path == NULL)
3758 		sbuf_cat(sb, "(nopath): ");
3759 	else {
3760 		if (path->periph != NULL)
3761 			sbuf_printf(sb, "(%s%d:", path->periph->periph_name,
3762 				    path->periph->unit_number);
3763 		else
3764 			sbuf_cat(sb, "(noperiph:");
3765 
3766 		if (path->bus != NULL)
3767 			sbuf_printf(sb, "%s%d:%d:", path->bus->sim->sim_name,
3768 				    path->bus->sim->unit_number,
3769 				    path->bus->sim->bus_id);
3770 		else
3771 			sbuf_cat(sb, "nobus:");
3772 
3773 		if (path->target != NULL)
3774 			sbuf_printf(sb, "%d:", path->target->target_id);
3775 		else
3776 			sbuf_cat(sb, "X:");
3777 
3778 		if (path->device != NULL)
3779 			sbuf_printf(sb, "%jx): ",
3780 			    (uintmax_t)path->device->lun_id);
3781 		else
3782 			sbuf_cat(sb, "X): ");
3783 	}
3784 }
3785 
3786 path_id_t
xpt_path_path_id(struct cam_path * path)3787 xpt_path_path_id(struct cam_path *path)
3788 {
3789 	return(path->bus->path_id);
3790 }
3791 
3792 target_id_t
xpt_path_target_id(struct cam_path * path)3793 xpt_path_target_id(struct cam_path *path)
3794 {
3795 	if (path->target != NULL)
3796 		return (path->target->target_id);
3797 	else
3798 		return (CAM_TARGET_WILDCARD);
3799 }
3800 
3801 lun_id_t
xpt_path_lun_id(struct cam_path * path)3802 xpt_path_lun_id(struct cam_path *path)
3803 {
3804 	if (path->device != NULL)
3805 		return (path->device->lun_id);
3806 	else
3807 		return (CAM_LUN_WILDCARD);
3808 }
3809 
3810 struct cam_sim *
xpt_path_sim(struct cam_path * path)3811 xpt_path_sim(struct cam_path *path)
3812 {
3813 
3814 	return (path->bus->sim);
3815 }
3816 
3817 struct cam_periph*
xpt_path_periph(struct cam_path * path)3818 xpt_path_periph(struct cam_path *path)
3819 {
3820 
3821 	return (path->periph);
3822 }
3823 
3824 /*
3825  * Release a CAM control block for the caller.  Remit the cost of the structure
3826  * to the device referenced by the path.  If the this device had no 'credits'
3827  * and peripheral drivers have registered async callbacks for this notification
3828  * call them now.
3829  */
3830 void
xpt_release_ccb(union ccb * free_ccb)3831 xpt_release_ccb(union ccb *free_ccb)
3832 {
3833 	struct	 cam_ed *device;
3834 	struct	 cam_periph *periph;
3835 
3836 	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_release_ccb\n"));
3837 	xpt_path_assert(free_ccb->ccb_h.path, MA_OWNED);
3838 	device = free_ccb->ccb_h.path->device;
3839 	periph = free_ccb->ccb_h.path->periph;
3840 
3841 	xpt_free_ccb(free_ccb);
3842 	periph->periph_allocated--;
3843 	cam_ccbq_release_opening(&device->ccbq);
3844 	xpt_run_allocq(periph, 0);
3845 }
3846 
3847 /* Functions accessed by SIM drivers */
3848 
3849 static struct xpt_xport_ops xport_default_ops = {
3850 	.alloc_device = xpt_alloc_device_default,
3851 	.action = xpt_action_default,
3852 	.async = xpt_dev_async_default,
3853 };
3854 static struct xpt_xport xport_default = {
3855 	.xport = XPORT_UNKNOWN,
3856 	.name = "unknown",
3857 	.ops = &xport_default_ops,
3858 };
3859 
3860 CAM_XPT_XPORT(xport_default);
3861 
3862 /*
3863  * A sim structure, listing the SIM entry points and instance
3864  * identification info is passed to xpt_bus_register to hook the SIM
3865  * into the CAM framework.  xpt_bus_register creates a cam_eb entry
3866  * for this new bus and places it in the array of buses and assigns
3867  * it a path_id.  The path_id may be influenced by "hard wiring"
3868  * information specified by the user.  Once interrupt services are
3869  * available, the bus will be probed.
3870  */
3871 int
xpt_bus_register(struct cam_sim * sim,device_t parent,uint32_t bus)3872 xpt_bus_register(struct cam_sim *sim, device_t parent, uint32_t bus)
3873 {
3874 	struct cam_eb *new_bus;
3875 	struct cam_eb *old_bus;
3876 	struct ccb_pathinq cpi;
3877 	struct cam_path *path;
3878 	cam_status status;
3879 
3880 	sim->bus_id = bus;
3881 	new_bus = (struct cam_eb *)malloc(sizeof(*new_bus),
3882 					  M_CAMXPT, M_NOWAIT|M_ZERO);
3883 	if (new_bus == NULL) {
3884 		/* Couldn't satisfy request */
3885 		return (ENOMEM);
3886 	}
3887 
3888 	mtx_init(&new_bus->eb_mtx, "CAM bus lock", NULL, MTX_DEF);
3889 	TAILQ_INIT(&new_bus->et_entries);
3890 	cam_sim_hold(sim);
3891 	new_bus->sim = sim;
3892 	timevalclear(&new_bus->last_reset);
3893 	new_bus->flags = 0;
3894 	new_bus->refcount = 1;	/* Held until a bus_deregister event */
3895 	new_bus->generation = 0;
3896 	new_bus->parent_dev = parent;
3897 
3898 	xpt_lock_buses();
3899 	sim->path_id = new_bus->path_id =
3900 	    xptpathid(sim->sim_name, sim->unit_number, sim->bus_id);
3901 	old_bus = TAILQ_FIRST(&xsoftc.xpt_busses);
3902 	while (old_bus != NULL
3903 	    && old_bus->path_id < new_bus->path_id)
3904 		old_bus = TAILQ_NEXT(old_bus, links);
3905 	if (old_bus != NULL)
3906 		TAILQ_INSERT_BEFORE(old_bus, new_bus, links);
3907 	else
3908 		TAILQ_INSERT_TAIL(&xsoftc.xpt_busses, new_bus, links);
3909 	xsoftc.bus_generation++;
3910 	xpt_unlock_buses();
3911 
3912 	/*
3913 	 * Set a default transport so that a PATH_INQ can be issued to
3914 	 * the SIM.  This will then allow for probing and attaching of
3915 	 * a more appropriate transport.
3916 	 */
3917 	new_bus->xport = &xport_default;
3918 
3919 	status = xpt_create_path(&path, /*periph*/NULL, sim->path_id,
3920 				  CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
3921 	if (status != CAM_REQ_CMP) {
3922 		xpt_release_bus(new_bus);
3923 		return (ENOMEM);
3924 	}
3925 
3926 	xpt_path_inq(&cpi, path);
3927 
3928 	/*
3929 	 * Use the results of PATH_INQ to pick a transport.  Note that
3930 	 * the xpt bus (which uses XPORT_UNSPECIFIED) always uses
3931 	 * xport_default instead of a transport from
3932 	 * cam_xpt_port_set.
3933 	 */
3934 	if (cam_ccb_success((union ccb *)&cpi) &&
3935 	    cpi.transport != XPORT_UNSPECIFIED) {
3936 		struct xpt_xport **xpt;
3937 
3938 		SET_FOREACH(xpt, cam_xpt_xport_set) {
3939 			if ((*xpt)->xport == cpi.transport) {
3940 				new_bus->xport = *xpt;
3941 				break;
3942 			}
3943 		}
3944 		if (new_bus->xport == &xport_default) {
3945 			xpt_print(path,
3946 			    "No transport found for %d\n", cpi.transport);
3947 			xpt_release_bus(new_bus);
3948 			xpt_free_path(path);
3949 			return (EINVAL);
3950 		}
3951 	}
3952 
3953 	/* Notify interested parties */
3954 	if (sim->path_id != CAM_XPT_PATH_ID) {
3955 		xpt_async(AC_PATH_REGISTERED, path, &cpi);
3956 		if ((cpi.hba_misc & PIM_NOSCAN) == 0) {
3957 			union	ccb *scan_ccb;
3958 
3959 			/* Initiate bus rescan. */
3960 			scan_ccb = xpt_alloc_ccb_nowait();
3961 			if (scan_ccb != NULL) {
3962 				scan_ccb->ccb_h.path = path;
3963 				scan_ccb->ccb_h.func_code = XPT_SCAN_BUS;
3964 				scan_ccb->crcn.flags = 0;
3965 				xpt_rescan(scan_ccb);
3966 			} else {
3967 				xpt_print(path,
3968 					  "Can't allocate CCB to scan bus\n");
3969 				xpt_free_path(path);
3970 			}
3971 		} else
3972 			xpt_free_path(path);
3973 	} else
3974 		xpt_free_path(path);
3975 	return (CAM_SUCCESS);
3976 }
3977 
3978 int
xpt_bus_deregister(path_id_t pathid)3979 xpt_bus_deregister(path_id_t pathid)
3980 {
3981 	struct cam_path bus_path;
3982 	cam_status status;
3983 
3984 	status = xpt_compile_path(&bus_path, NULL, pathid,
3985 				  CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
3986 	if (status != CAM_REQ_CMP)
3987 		return (ENOMEM);
3988 
3989 	xpt_async(AC_LOST_DEVICE, &bus_path, NULL);
3990 	xpt_async(AC_PATH_DEREGISTERED, &bus_path, NULL);
3991 
3992 	/* Release the reference count held while registered. */
3993 	xpt_release_bus(bus_path.bus);
3994 	xpt_release_path(&bus_path);
3995 
3996 	return (CAM_SUCCESS);
3997 }
3998 
3999 static path_id_t
xptnextfreepathid(void)4000 xptnextfreepathid(void)
4001 {
4002 	struct cam_eb *bus;
4003 	path_id_t pathid;
4004 	const char *strval;
4005 
4006 	mtx_assert(&xsoftc.xpt_topo_lock, MA_OWNED);
4007 	pathid = 0;
4008 	bus = TAILQ_FIRST(&xsoftc.xpt_busses);
4009 retry:
4010 	/* Find an unoccupied pathid */
4011 	while (bus != NULL && bus->path_id <= pathid) {
4012 		if (bus->path_id == pathid)
4013 			pathid++;
4014 		bus = TAILQ_NEXT(bus, links);
4015 	}
4016 
4017 	/*
4018 	 * Ensure that this pathid is not reserved for
4019 	 * a bus that may be registered in the future.
4020 	 */
4021 	if (resource_string_value("scbus", pathid, "at", &strval) == 0) {
4022 		++pathid;
4023 		/* Start the search over */
4024 		goto retry;
4025 	}
4026 	return (pathid);
4027 }
4028 
4029 static path_id_t
xptpathid(const char * sim_name,int sim_unit,int sim_bus)4030 xptpathid(const char *sim_name, int sim_unit, int sim_bus)
4031 {
4032 	path_id_t pathid;
4033 	int i, dunit, val;
4034 	char buf[32];
4035 	const char *dname;
4036 
4037 	pathid = CAM_XPT_PATH_ID;
4038 	snprintf(buf, sizeof(buf), "%s%d", sim_name, sim_unit);
4039 	if (strcmp(buf, "xpt0") == 0 && sim_bus == 0)
4040 		return (pathid);
4041 	i = 0;
4042 	while ((resource_find_match(&i, &dname, &dunit, "at", buf)) == 0) {
4043 		if (strcmp(dname, "scbus")) {
4044 			/* Avoid a bit of foot shooting. */
4045 			continue;
4046 		}
4047 		if (dunit < 0)		/* unwired?! */
4048 			continue;
4049 		if (resource_int_value("scbus", dunit, "bus", &val) == 0) {
4050 			if (sim_bus == val) {
4051 				pathid = dunit;
4052 				break;
4053 			}
4054 		} else if (sim_bus == 0) {
4055 			/* Unspecified matches bus 0 */
4056 			pathid = dunit;
4057 			break;
4058 		} else {
4059 			printf(
4060 "Ambiguous scbus configuration for %s%d bus %d, cannot wire down.  The kernel\n"
4061 "config entry for scbus%d should specify a controller bus.\n"
4062 "Scbus will be assigned dynamically.\n",
4063 			    sim_name, sim_unit, sim_bus, dunit);
4064 			break;
4065 		}
4066 	}
4067 
4068 	if (pathid == CAM_XPT_PATH_ID)
4069 		pathid = xptnextfreepathid();
4070 	return (pathid);
4071 }
4072 
4073 static const char *
xpt_async_string(uint32_t async_code)4074 xpt_async_string(uint32_t async_code)
4075 {
4076 
4077 	switch (async_code) {
4078 	case AC_BUS_RESET: return ("AC_BUS_RESET");
4079 	case AC_UNSOL_RESEL: return ("AC_UNSOL_RESEL");
4080 	case AC_SCSI_AEN: return ("AC_SCSI_AEN");
4081 	case AC_SENT_BDR: return ("AC_SENT_BDR");
4082 	case AC_PATH_REGISTERED: return ("AC_PATH_REGISTERED");
4083 	case AC_PATH_DEREGISTERED: return ("AC_PATH_DEREGISTERED");
4084 	case AC_FOUND_DEVICE: return ("AC_FOUND_DEVICE");
4085 	case AC_LOST_DEVICE: return ("AC_LOST_DEVICE");
4086 	case AC_TRANSFER_NEG: return ("AC_TRANSFER_NEG");
4087 	case AC_INQ_CHANGED: return ("AC_INQ_CHANGED");
4088 	case AC_GETDEV_CHANGED: return ("AC_GETDEV_CHANGED");
4089 	case AC_CONTRACT: return ("AC_CONTRACT");
4090 	case AC_ADVINFO_CHANGED: return ("AC_ADVINFO_CHANGED");
4091 	case AC_UNIT_ATTENTION: return ("AC_UNIT_ATTENTION");
4092 	}
4093 	return ("AC_UNKNOWN");
4094 }
4095 
4096 static int
xpt_async_size(uint32_t async_code)4097 xpt_async_size(uint32_t async_code)
4098 {
4099 
4100 	switch (async_code) {
4101 	case AC_BUS_RESET: return (0);
4102 	case AC_UNSOL_RESEL: return (0);
4103 	case AC_SCSI_AEN: return (0);
4104 	case AC_SENT_BDR: return (0);
4105 	case AC_PATH_REGISTERED: return (sizeof(struct ccb_pathinq));
4106 	case AC_PATH_DEREGISTERED: return (0);
4107 	case AC_FOUND_DEVICE: return (sizeof(struct ccb_getdev));
4108 	case AC_LOST_DEVICE: return (0);
4109 	case AC_TRANSFER_NEG: return (sizeof(struct ccb_trans_settings));
4110 	case AC_INQ_CHANGED: return (0);
4111 	case AC_GETDEV_CHANGED: return (0);
4112 	case AC_CONTRACT: return (sizeof(struct ac_contract));
4113 	case AC_ADVINFO_CHANGED: return (-1);
4114 	case AC_UNIT_ATTENTION: return (sizeof(struct ccb_scsiio));
4115 	}
4116 	return (0);
4117 }
4118 
4119 static int
xpt_async_process_dev(struct cam_ed * device,void * arg)4120 xpt_async_process_dev(struct cam_ed *device, void *arg)
4121 {
4122 	union ccb *ccb = arg;
4123 	struct cam_path *path = ccb->ccb_h.path;
4124 	void *async_arg = ccb->casync.async_arg_ptr;
4125 	uint32_t async_code = ccb->casync.async_code;
4126 	bool relock;
4127 
4128 	if (path->device != device
4129 	 && path->device->lun_id != CAM_LUN_WILDCARD
4130 	 && device->lun_id != CAM_LUN_WILDCARD)
4131 		return (1);
4132 
4133 	/*
4134 	 * The async callback could free the device.
4135 	 * If it is a broadcast async, it doesn't hold
4136 	 * device reference, so take our own reference.
4137 	 */
4138 	xpt_acquire_device(device);
4139 
4140 	/*
4141 	 * If async for specific device is to be delivered to
4142 	 * the wildcard client, take the specific device lock.
4143 	 * XXX: We may need a way for client to specify it.
4144 	 */
4145 	if ((device->lun_id == CAM_LUN_WILDCARD &&
4146 	     path->device->lun_id != CAM_LUN_WILDCARD) ||
4147 	    (device->target->target_id == CAM_TARGET_WILDCARD &&
4148 	     path->target->target_id != CAM_TARGET_WILDCARD) ||
4149 	    (device->target->bus->path_id == CAM_BUS_WILDCARD &&
4150 	     path->target->bus->path_id != CAM_BUS_WILDCARD)) {
4151 		mtx_unlock(&device->device_mtx);
4152 		xpt_path_lock(path);
4153 		relock = true;
4154 	} else
4155 		relock = false;
4156 
4157 	(*(device->target->bus->xport->ops->async))(async_code,
4158 	    device->target->bus, device->target, device, async_arg);
4159 	xpt_async_bcast(&device->asyncs, async_code, path, async_arg);
4160 
4161 	if (relock) {
4162 		xpt_path_unlock(path);
4163 		mtx_lock(&device->device_mtx);
4164 	}
4165 	xpt_release_device(device);
4166 	return (1);
4167 }
4168 
4169 static int
xpt_async_process_tgt(struct cam_et * target,void * arg)4170 xpt_async_process_tgt(struct cam_et *target, void *arg)
4171 {
4172 	union ccb *ccb = arg;
4173 	struct cam_path *path = ccb->ccb_h.path;
4174 
4175 	if (path->target != target
4176 	 && path->target->target_id != CAM_TARGET_WILDCARD
4177 	 && target->target_id != CAM_TARGET_WILDCARD)
4178 		return (1);
4179 
4180 	if (ccb->casync.async_code == AC_SENT_BDR) {
4181 		/* Update our notion of when the last reset occurred */
4182 		microtime(&target->last_reset);
4183 	}
4184 
4185 	return (xptdevicetraverse(target, NULL, xpt_async_process_dev, ccb));
4186 }
4187 
4188 static void
xpt_async_process(struct cam_periph * periph,union ccb * ccb)4189 xpt_async_process(struct cam_periph *periph, union ccb *ccb)
4190 {
4191 	struct cam_eb *bus;
4192 	struct cam_path *path;
4193 	void *async_arg;
4194 	uint32_t async_code;
4195 
4196 	path = ccb->ccb_h.path;
4197 	async_code = ccb->casync.async_code;
4198 	async_arg = ccb->casync.async_arg_ptr;
4199 	CAM_DEBUG(path, CAM_DEBUG_TRACE | CAM_DEBUG_INFO,
4200 	    ("xpt_async(%s)\n", xpt_async_string(async_code)));
4201 	bus = path->bus;
4202 
4203 	if (async_code == AC_BUS_RESET) {
4204 		/* Update our notion of when the last reset occurred */
4205 		microtime(&bus->last_reset);
4206 	}
4207 
4208 	xpttargettraverse(bus, NULL, xpt_async_process_tgt, ccb);
4209 
4210 	/*
4211 	 * If this wasn't a fully wildcarded async, tell all
4212 	 * clients that want all async events.
4213 	 */
4214 	if (bus != xpt_periph->path->bus) {
4215 		xpt_path_lock(xpt_periph->path);
4216 		xpt_async_process_dev(xpt_periph->path->device, ccb);
4217 		xpt_path_unlock(xpt_periph->path);
4218 	}
4219 
4220 	if (path->device != NULL && path->device->lun_id != CAM_LUN_WILDCARD)
4221 		xpt_release_devq(path, 1, TRUE);
4222 	else
4223 		xpt_release_simq(path->bus->sim, TRUE);
4224 	if (ccb->casync.async_arg_size > 0)
4225 		free(async_arg, M_CAMXPT);
4226 	xpt_free_path(path);
4227 	xpt_free_ccb(ccb);
4228 }
4229 
4230 static void
xpt_async_bcast(struct async_list * async_head,uint32_t async_code,struct cam_path * path,void * async_arg)4231 xpt_async_bcast(struct async_list *async_head,
4232 		uint32_t async_code,
4233 		struct cam_path *path, void *async_arg)
4234 {
4235 	struct async_node *cur_entry;
4236 	struct mtx *mtx;
4237 
4238 	cur_entry = SLIST_FIRST(async_head);
4239 	while (cur_entry != NULL) {
4240 		struct async_node *next_entry;
4241 		/*
4242 		 * Grab the next list entry before we call the current
4243 		 * entry's callback.  This is because the callback function
4244 		 * can delete its async callback entry.
4245 		 */
4246 		next_entry = SLIST_NEXT(cur_entry, links);
4247 		if ((cur_entry->event_enable & async_code) != 0) {
4248 			mtx = cur_entry->event_lock ?
4249 			    path->device->sim->mtx : NULL;
4250 			if (mtx)
4251 				mtx_lock(mtx);
4252 			cur_entry->callback(cur_entry->callback_arg,
4253 					    async_code, path,
4254 					    async_arg);
4255 			if (mtx)
4256 				mtx_unlock(mtx);
4257 		}
4258 		cur_entry = next_entry;
4259 	}
4260 }
4261 
4262 void
xpt_async(uint32_t async_code,struct cam_path * path,void * async_arg)4263 xpt_async(uint32_t async_code, struct cam_path *path, void *async_arg)
4264 {
4265 	union ccb *ccb;
4266 	int size;
4267 
4268 	ccb = xpt_alloc_ccb_nowait();
4269 	if (ccb == NULL) {
4270 		xpt_print(path, "Can't allocate CCB to send %s\n",
4271 		    xpt_async_string(async_code));
4272 		return;
4273 	}
4274 
4275 	if (xpt_clone_path(&ccb->ccb_h.path, path) != 0) {
4276 		xpt_print(path, "Can't allocate path to send %s\n",
4277 		    xpt_async_string(async_code));
4278 		xpt_free_ccb(ccb);
4279 		return;
4280 	}
4281 	ccb->ccb_h.path->periph = NULL;
4282 	ccb->ccb_h.func_code = XPT_ASYNC;
4283 	ccb->ccb_h.cbfcnp = xpt_async_process;
4284 	ccb->ccb_h.flags |= CAM_UNLOCKED;
4285 	ccb->casync.async_code = async_code;
4286 	ccb->casync.async_arg_size = 0;
4287 	size = xpt_async_size(async_code);
4288 	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE,
4289 	    ("xpt_async: func %#x %s aync_code %d %s\n",
4290 		ccb->ccb_h.func_code,
4291 		xpt_action_name(ccb->ccb_h.func_code),
4292 		async_code,
4293 		xpt_async_string(async_code)));
4294 	if (size > 0 && async_arg != NULL) {
4295 		ccb->casync.async_arg_ptr = malloc(size, M_CAMXPT, M_NOWAIT);
4296 		if (ccb->casync.async_arg_ptr == NULL) {
4297 			xpt_print(path, "Can't allocate argument to send %s\n",
4298 			    xpt_async_string(async_code));
4299 			xpt_free_path(ccb->ccb_h.path);
4300 			xpt_free_ccb(ccb);
4301 			return;
4302 		}
4303 		memcpy(ccb->casync.async_arg_ptr, async_arg, size);
4304 		ccb->casync.async_arg_size = size;
4305 	} else if (size < 0) {
4306 		ccb->casync.async_arg_ptr = async_arg;
4307 		ccb->casync.async_arg_size = size;
4308 	}
4309 	if (path->device != NULL && path->device->lun_id != CAM_LUN_WILDCARD)
4310 		xpt_freeze_devq(path, 1);
4311 	else
4312 		xpt_freeze_simq(path->bus->sim, 1);
4313 	xpt_action(ccb);
4314 }
4315 
4316 static void
xpt_dev_async_default(uint32_t async_code,struct cam_eb * bus,struct cam_et * target,struct cam_ed * device,void * async_arg)4317 xpt_dev_async_default(uint32_t async_code, struct cam_eb *bus,
4318 		      struct cam_et *target, struct cam_ed *device,
4319 		      void *async_arg)
4320 {
4321 
4322 	/*
4323 	 * We only need to handle events for real devices.
4324 	 */
4325 	if (target->target_id == CAM_TARGET_WILDCARD
4326 	 || device->lun_id == CAM_LUN_WILDCARD)
4327 		return;
4328 
4329 	printf("%s called\n", __func__);
4330 }
4331 
4332 static uint32_t
xpt_freeze_devq_device(struct cam_ed * dev,u_int count)4333 xpt_freeze_devq_device(struct cam_ed *dev, u_int count)
4334 {
4335 	struct cam_devq	*devq;
4336 	uint32_t freeze;
4337 
4338 	devq = dev->sim->devq;
4339 	mtx_assert(&devq->send_mtx, MA_OWNED);
4340 	CAM_DEBUG_DEV(dev, CAM_DEBUG_TRACE,
4341 	    ("xpt_freeze_devq_device(%d) %u->%u\n", count,
4342 	    dev->ccbq.queue.qfrozen_cnt, dev->ccbq.queue.qfrozen_cnt + count));
4343 	freeze = (dev->ccbq.queue.qfrozen_cnt += count);
4344 	/* Remove frozen device from sendq. */
4345 	if (device_is_queued(dev))
4346 		camq_remove(&devq->send_queue, dev->devq_entry.index);
4347 	return (freeze);
4348 }
4349 
4350 uint32_t
xpt_freeze_devq(struct cam_path * path,u_int count)4351 xpt_freeze_devq(struct cam_path *path, u_int count)
4352 {
4353 	struct cam_ed	*dev = path->device;
4354 	struct cam_devq	*devq;
4355 	uint32_t	 freeze;
4356 
4357 	devq = dev->sim->devq;
4358 	mtx_lock(&devq->send_mtx);
4359 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_freeze_devq(%d)\n", count));
4360 	freeze = xpt_freeze_devq_device(dev, count);
4361 	mtx_unlock(&devq->send_mtx);
4362 	return (freeze);
4363 }
4364 
4365 uint32_t
xpt_freeze_simq(struct cam_sim * sim,u_int count)4366 xpt_freeze_simq(struct cam_sim *sim, u_int count)
4367 {
4368 	struct cam_devq	*devq;
4369 	uint32_t	 freeze;
4370 
4371 	devq = sim->devq;
4372 	mtx_lock(&devq->send_mtx);
4373 	freeze = (devq->send_queue.qfrozen_cnt += count);
4374 	mtx_unlock(&devq->send_mtx);
4375 	return (freeze);
4376 }
4377 
4378 static void
xpt_release_devq_timeout(void * arg)4379 xpt_release_devq_timeout(void *arg)
4380 {
4381 	struct cam_ed *dev;
4382 	struct cam_devq *devq;
4383 
4384 	dev = (struct cam_ed *)arg;
4385 	CAM_DEBUG_DEV(dev, CAM_DEBUG_TRACE, ("xpt_release_devq_timeout\n"));
4386 	devq = dev->sim->devq;
4387 	mtx_assert(&devq->send_mtx, MA_OWNED);
4388 	if (xpt_release_devq_device(dev, /*count*/1, /*run_queue*/TRUE))
4389 		xpt_run_devq(devq);
4390 }
4391 
4392 void
xpt_release_devq(struct cam_path * path,u_int count,int run_queue)4393 xpt_release_devq(struct cam_path *path, u_int count, int run_queue)
4394 {
4395 	struct cam_ed *dev;
4396 	struct cam_devq *devq;
4397 
4398 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_release_devq(%d, %d)\n",
4399 	    count, run_queue));
4400 	dev = path->device;
4401 	devq = dev->sim->devq;
4402 	mtx_lock(&devq->send_mtx);
4403 	if (xpt_release_devq_device(dev, count, run_queue))
4404 		xpt_run_devq(dev->sim->devq);
4405 	mtx_unlock(&devq->send_mtx);
4406 }
4407 
4408 static int
xpt_release_devq_device(struct cam_ed * dev,u_int count,int run_queue)4409 xpt_release_devq_device(struct cam_ed *dev, u_int count, int run_queue)
4410 {
4411 
4412 	mtx_assert(&dev->sim->devq->send_mtx, MA_OWNED);
4413 	CAM_DEBUG_DEV(dev, CAM_DEBUG_TRACE,
4414 	    ("xpt_release_devq_device(%d, %d) %u->%u\n", count, run_queue,
4415 	    dev->ccbq.queue.qfrozen_cnt, dev->ccbq.queue.qfrozen_cnt - count));
4416 	if (count > dev->ccbq.queue.qfrozen_cnt) {
4417 #ifdef INVARIANTS
4418 		printf("xpt_release_devq(): requested %u > present %u\n",
4419 		    count, dev->ccbq.queue.qfrozen_cnt);
4420 #endif
4421 		count = dev->ccbq.queue.qfrozen_cnt;
4422 	}
4423 	dev->ccbq.queue.qfrozen_cnt -= count;
4424 	if (dev->ccbq.queue.qfrozen_cnt == 0) {
4425 		/*
4426 		 * No longer need to wait for a successful
4427 		 * command completion.
4428 		 */
4429 		dev->flags &= ~CAM_DEV_REL_ON_COMPLETE;
4430 		/*
4431 		 * Remove any timeouts that might be scheduled
4432 		 * to release this queue.
4433 		 */
4434 		if ((dev->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
4435 			callout_stop(&dev->callout);
4436 			dev->flags &= ~CAM_DEV_REL_TIMEOUT_PENDING;
4437 		}
4438 		/*
4439 		 * Now that we are unfrozen schedule the
4440 		 * device so any pending transactions are
4441 		 * run.
4442 		 */
4443 		xpt_schedule_devq(dev->sim->devq, dev);
4444 	} else
4445 		run_queue = 0;
4446 	return (run_queue);
4447 }
4448 
4449 void
xpt_release_simq(struct cam_sim * sim,int run_queue)4450 xpt_release_simq(struct cam_sim *sim, int run_queue)
4451 {
4452 	struct cam_devq	*devq;
4453 
4454 	devq = sim->devq;
4455 	mtx_lock(&devq->send_mtx);
4456 	if (devq->send_queue.qfrozen_cnt <= 0) {
4457 #ifdef INVARIANTS
4458 		printf("xpt_release_simq: requested 1 > present %u\n",
4459 		    devq->send_queue.qfrozen_cnt);
4460 #endif
4461 	} else
4462 		devq->send_queue.qfrozen_cnt--;
4463 	if (devq->send_queue.qfrozen_cnt == 0) {
4464 		if (run_queue) {
4465 			/*
4466 			 * Now that we are unfrozen run the send queue.
4467 			 */
4468 			xpt_run_devq(sim->devq);
4469 		}
4470 	}
4471 	mtx_unlock(&devq->send_mtx);
4472 }
4473 
4474 void
xpt_done(union ccb * done_ccb)4475 xpt_done(union ccb *done_ccb)
4476 {
4477 	struct cam_doneq *queue;
4478 	int	run, hash;
4479 
4480 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
4481 	if (done_ccb->ccb_h.func_code == XPT_SCSI_IO &&
4482 	    done_ccb->csio.bio != NULL)
4483 		biotrack(done_ccb->csio.bio, __func__);
4484 #endif
4485 
4486 	CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE,
4487 	    ("xpt_done: func= %#x %s status %#x\n",
4488 		done_ccb->ccb_h.func_code,
4489 		xpt_action_name(done_ccb->ccb_h.func_code),
4490 		done_ccb->ccb_h.status));
4491 	if ((done_ccb->ccb_h.func_code & XPT_FC_QUEUED) == 0)
4492 		return;
4493 
4494 	/* Store the time the ccb was in the sim */
4495 	done_ccb->ccb_h.qos.periph_data = cam_iosched_delta_t(done_ccb->ccb_h.qos.periph_data);
4496 	done_ccb->ccb_h.status |= CAM_QOS_VALID;
4497 	hash = (u_int)(done_ccb->ccb_h.path_id + done_ccb->ccb_h.target_id +
4498 	    done_ccb->ccb_h.target_lun) % cam_num_doneqs;
4499 	queue = &cam_doneqs[hash];
4500 	mtx_lock(&queue->cam_doneq_mtx);
4501 	run = (queue->cam_doneq_sleep && STAILQ_EMPTY(&queue->cam_doneq));
4502 	STAILQ_INSERT_TAIL(&queue->cam_doneq, &done_ccb->ccb_h, sim_links.stqe);
4503 	done_ccb->ccb_h.pinfo.index = CAM_DONEQ_INDEX;
4504 	mtx_unlock(&queue->cam_doneq_mtx);
4505 	if (run && !dumping)
4506 		wakeup(&queue->cam_doneq);
4507 }
4508 
4509 void
xpt_done_direct(union ccb * done_ccb)4510 xpt_done_direct(union ccb *done_ccb)
4511 {
4512 
4513 	CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE,
4514 	    ("xpt_done_direct: status %#x\n", done_ccb->ccb_h.status));
4515 	if ((done_ccb->ccb_h.func_code & XPT_FC_QUEUED) == 0)
4516 		return;
4517 
4518 	/* Store the time the ccb was in the sim */
4519 	done_ccb->ccb_h.qos.periph_data = cam_iosched_delta_t(done_ccb->ccb_h.qos.periph_data);
4520 	done_ccb->ccb_h.status |= CAM_QOS_VALID;
4521 	xpt_done_process(&done_ccb->ccb_h);
4522 }
4523 
4524 union ccb *
xpt_alloc_ccb(void)4525 xpt_alloc_ccb(void)
4526 {
4527 	union ccb *new_ccb;
4528 
4529 	new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_WAITOK);
4530 	return (new_ccb);
4531 }
4532 
4533 union ccb *
xpt_alloc_ccb_nowait(void)4534 xpt_alloc_ccb_nowait(void)
4535 {
4536 	union ccb *new_ccb;
4537 
4538 	new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_NOWAIT);
4539 	return (new_ccb);
4540 }
4541 
4542 void
xpt_free_ccb(union ccb * free_ccb)4543 xpt_free_ccb(union ccb *free_ccb)
4544 {
4545 	struct cam_periph *periph;
4546 
4547 	if (free_ccb->ccb_h.alloc_flags & CAM_CCB_FROM_UMA) {
4548 		/*
4549 		 * Looks like a CCB allocated from a periph UMA zone.
4550 		 */
4551 		periph = free_ccb->ccb_h.path->periph;
4552 		uma_zfree(periph->ccb_zone, free_ccb);
4553 	} else {
4554 		free(free_ccb, M_CAMCCB);
4555 	}
4556 }
4557 
4558 /* Private XPT functions */
4559 
4560 /*
4561  * Get a CAM control block for the caller. Charge the structure to the device
4562  * referenced by the path.  If we don't have sufficient resources to allocate
4563  * more ccbs, we return NULL.
4564  */
4565 static union ccb *
xpt_get_ccb_nowait(struct cam_periph * periph)4566 xpt_get_ccb_nowait(struct cam_periph *periph)
4567 {
4568 	union ccb *new_ccb;
4569 	int alloc_flags;
4570 
4571 	if (periph->ccb_zone != NULL) {
4572 		alloc_flags = CAM_CCB_FROM_UMA;
4573 		new_ccb = uma_zalloc(periph->ccb_zone, M_ZERO|M_NOWAIT);
4574 	} else {
4575 		alloc_flags = 0;
4576 		new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_NOWAIT);
4577 	}
4578 	if (new_ccb == NULL)
4579 		return (NULL);
4580 	new_ccb->ccb_h.alloc_flags = alloc_flags;
4581 	periph->periph_allocated++;
4582 	cam_ccbq_take_opening(&periph->path->device->ccbq);
4583 	return (new_ccb);
4584 }
4585 
4586 static union ccb *
xpt_get_ccb(struct cam_periph * periph)4587 xpt_get_ccb(struct cam_periph *periph)
4588 {
4589 	union ccb *new_ccb;
4590 	int alloc_flags;
4591 
4592 	cam_periph_unlock(periph);
4593 	if (periph->ccb_zone != NULL) {
4594 		alloc_flags = CAM_CCB_FROM_UMA;
4595 		new_ccb = uma_zalloc(periph->ccb_zone, M_ZERO|M_WAITOK);
4596 	} else {
4597 		alloc_flags = 0;
4598 		new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_WAITOK);
4599 	}
4600 	new_ccb->ccb_h.alloc_flags = alloc_flags;
4601 	cam_periph_lock(periph);
4602 	periph->periph_allocated++;
4603 	cam_ccbq_take_opening(&periph->path->device->ccbq);
4604 	return (new_ccb);
4605 }
4606 
4607 union ccb *
cam_periph_getccb(struct cam_periph * periph,uint32_t priority)4608 cam_periph_getccb(struct cam_periph *periph, uint32_t priority)
4609 {
4610 	struct ccb_hdr *ccb_h;
4611 
4612 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("cam_periph_getccb\n"));
4613 	cam_periph_assert(periph, MA_OWNED);
4614 	while ((ccb_h = SLIST_FIRST(&periph->ccb_list)) == NULL ||
4615 	    ccb_h->pinfo.priority != priority) {
4616 		if (priority < periph->immediate_priority) {
4617 			periph->immediate_priority = priority;
4618 			xpt_run_allocq(periph, 0);
4619 		} else
4620 			cam_periph_sleep(periph, &periph->ccb_list, PRIBIO,
4621 			    "cgticb", 0);
4622 	}
4623 	SLIST_REMOVE_HEAD(&periph->ccb_list, periph_links.sle);
4624 	return ((union ccb *)ccb_h);
4625 }
4626 
4627 static void
xpt_acquire_bus(struct cam_eb * bus)4628 xpt_acquire_bus(struct cam_eb *bus)
4629 {
4630 
4631 	xpt_lock_buses();
4632 	bus->refcount++;
4633 	xpt_unlock_buses();
4634 }
4635 
4636 static void
xpt_release_bus(struct cam_eb * bus)4637 xpt_release_bus(struct cam_eb *bus)
4638 {
4639 
4640 	xpt_lock_buses();
4641 	KASSERT(bus->refcount >= 1, ("bus->refcount >= 1"));
4642 	if (--bus->refcount > 0) {
4643 		xpt_unlock_buses();
4644 		return;
4645 	}
4646 	TAILQ_REMOVE(&xsoftc.xpt_busses, bus, links);
4647 	xsoftc.bus_generation++;
4648 	xpt_unlock_buses();
4649 	KASSERT(TAILQ_EMPTY(&bus->et_entries),
4650 	    ("destroying bus, but target list is not empty"));
4651 	cam_sim_release(bus->sim);
4652 	mtx_destroy(&bus->eb_mtx);
4653 	free(bus, M_CAMXPT);
4654 }
4655 
4656 static struct cam_et *
xpt_alloc_target(struct cam_eb * bus,target_id_t target_id)4657 xpt_alloc_target(struct cam_eb *bus, target_id_t target_id)
4658 {
4659 	struct cam_et *cur_target, *target;
4660 
4661 	mtx_assert(&xsoftc.xpt_topo_lock, MA_OWNED);
4662 	mtx_assert(&bus->eb_mtx, MA_OWNED);
4663 	target = (struct cam_et *)malloc(sizeof(*target), M_CAMXPT,
4664 					 M_NOWAIT|M_ZERO);
4665 	if (target == NULL)
4666 		return (NULL);
4667 
4668 	TAILQ_INIT(&target->ed_entries);
4669 	target->bus = bus;
4670 	target->target_id = target_id;
4671 	target->refcount = 1;
4672 	target->generation = 0;
4673 	target->luns = NULL;
4674 	mtx_init(&target->luns_mtx, "CAM LUNs lock", NULL, MTX_DEF);
4675 	timevalclear(&target->last_reset);
4676 	/*
4677 	 * Hold a reference to our parent bus so it
4678 	 * will not go away before we do.
4679 	 */
4680 	bus->refcount++;
4681 
4682 	/* Insertion sort into our bus's target list */
4683 	cur_target = TAILQ_FIRST(&bus->et_entries);
4684 	while (cur_target != NULL && cur_target->target_id < target_id)
4685 		cur_target = TAILQ_NEXT(cur_target, links);
4686 	if (cur_target != NULL) {
4687 		TAILQ_INSERT_BEFORE(cur_target, target, links);
4688 	} else {
4689 		TAILQ_INSERT_TAIL(&bus->et_entries, target, links);
4690 	}
4691 	bus->generation++;
4692 	return (target);
4693 }
4694 
4695 static void
xpt_acquire_target(struct cam_et * target)4696 xpt_acquire_target(struct cam_et *target)
4697 {
4698 	struct cam_eb *bus = target->bus;
4699 
4700 	mtx_lock(&bus->eb_mtx);
4701 	target->refcount++;
4702 	mtx_unlock(&bus->eb_mtx);
4703 }
4704 
4705 static void
xpt_release_target(struct cam_et * target)4706 xpt_release_target(struct cam_et *target)
4707 {
4708 	struct cam_eb *bus = target->bus;
4709 
4710 	mtx_lock(&bus->eb_mtx);
4711 	if (--target->refcount > 0) {
4712 		mtx_unlock(&bus->eb_mtx);
4713 		return;
4714 	}
4715 	TAILQ_REMOVE(&bus->et_entries, target, links);
4716 	bus->generation++;
4717 	mtx_unlock(&bus->eb_mtx);
4718 	KASSERT(TAILQ_EMPTY(&target->ed_entries),
4719 	    ("destroying target, but device list is not empty"));
4720 	xpt_release_bus(bus);
4721 	mtx_destroy(&target->luns_mtx);
4722 	if (target->luns)
4723 		free(target->luns, M_CAMXPT);
4724 	free(target, M_CAMXPT);
4725 }
4726 
4727 static struct cam_ed *
xpt_alloc_device_default(struct cam_eb * bus,struct cam_et * target,lun_id_t lun_id)4728 xpt_alloc_device_default(struct cam_eb *bus, struct cam_et *target,
4729 			 lun_id_t lun_id)
4730 {
4731 	struct cam_ed *device;
4732 
4733 	device = xpt_alloc_device(bus, target, lun_id);
4734 	if (device == NULL)
4735 		return (NULL);
4736 
4737 	device->mintags = 1;
4738 	device->maxtags = 1;
4739 	return (device);
4740 }
4741 
4742 static void
xpt_destroy_device(void * context,int pending)4743 xpt_destroy_device(void *context, int pending)
4744 {
4745 	struct cam_ed	*device = context;
4746 
4747 	mtx_lock(&device->device_mtx);
4748 	mtx_destroy(&device->device_mtx);
4749 	free(device, M_CAMDEV);
4750 }
4751 
4752 struct cam_ed *
xpt_alloc_device(struct cam_eb * bus,struct cam_et * target,lun_id_t lun_id)4753 xpt_alloc_device(struct cam_eb *bus, struct cam_et *target, lun_id_t lun_id)
4754 {
4755 	struct cam_ed	*cur_device, *device;
4756 	struct cam_devq	*devq;
4757 	cam_status status;
4758 
4759 	mtx_assert(&bus->eb_mtx, MA_OWNED);
4760 	/* Make space for us in the device queue on our bus */
4761 	devq = bus->sim->devq;
4762 	mtx_lock(&devq->send_mtx);
4763 	status = cam_devq_resize(devq, devq->send_queue.array_size + 1);
4764 	mtx_unlock(&devq->send_mtx);
4765 	if (status != CAM_REQ_CMP)
4766 		return (NULL);
4767 
4768 	device = (struct cam_ed *)malloc(sizeof(*device),
4769 					 M_CAMDEV, M_NOWAIT|M_ZERO);
4770 	if (device == NULL)
4771 		return (NULL);
4772 
4773 	cam_init_pinfo(&device->devq_entry);
4774 	device->target = target;
4775 	device->lun_id = lun_id;
4776 	device->sim = bus->sim;
4777 	if (cam_ccbq_init(&device->ccbq,
4778 			  bus->sim->max_dev_openings) != 0) {
4779 		free(device, M_CAMDEV);
4780 		return (NULL);
4781 	}
4782 	SLIST_INIT(&device->asyncs);
4783 	SLIST_INIT(&device->periphs);
4784 	device->generation = 0;
4785 	device->flags = CAM_DEV_UNCONFIGURED;
4786 	device->tag_delay_count = 0;
4787 	device->tag_saved_openings = 0;
4788 	device->refcount = 1;
4789 	mtx_init(&device->device_mtx, "CAM device lock", NULL, MTX_DEF);
4790 	callout_init_mtx(&device->callout, &devq->send_mtx, 0);
4791 	TASK_INIT(&device->device_destroy_task, 0, xpt_destroy_device, device);
4792 	/*
4793 	 * Hold a reference to our parent bus so it
4794 	 * will not go away before we do.
4795 	 */
4796 	target->refcount++;
4797 
4798 	cur_device = TAILQ_FIRST(&target->ed_entries);
4799 	while (cur_device != NULL && cur_device->lun_id < lun_id)
4800 		cur_device = TAILQ_NEXT(cur_device, links);
4801 	if (cur_device != NULL)
4802 		TAILQ_INSERT_BEFORE(cur_device, device, links);
4803 	else
4804 		TAILQ_INSERT_TAIL(&target->ed_entries, device, links);
4805 	target->generation++;
4806 	return (device);
4807 }
4808 
4809 void
xpt_acquire_device(struct cam_ed * device)4810 xpt_acquire_device(struct cam_ed *device)
4811 {
4812 	struct cam_eb *bus = device->target->bus;
4813 
4814 	mtx_lock(&bus->eb_mtx);
4815 	device->refcount++;
4816 	mtx_unlock(&bus->eb_mtx);
4817 }
4818 
4819 void
xpt_release_device(struct cam_ed * device)4820 xpt_release_device(struct cam_ed *device)
4821 {
4822 	struct cam_eb *bus = device->target->bus;
4823 	struct cam_devq *devq;
4824 
4825 	mtx_lock(&bus->eb_mtx);
4826 	if (--device->refcount > 0) {
4827 		mtx_unlock(&bus->eb_mtx);
4828 		return;
4829 	}
4830 
4831 	TAILQ_REMOVE(&device->target->ed_entries, device,links);
4832 	device->target->generation++;
4833 	mtx_unlock(&bus->eb_mtx);
4834 
4835 	/* Release our slot in the devq */
4836 	devq = bus->sim->devq;
4837 	mtx_lock(&devq->send_mtx);
4838 	cam_devq_resize(devq, devq->send_queue.array_size - 1);
4839 
4840 	KASSERT(SLIST_EMPTY(&device->periphs),
4841 	    ("destroying device, but periphs list is not empty"));
4842 	KASSERT(device->devq_entry.index == CAM_UNQUEUED_INDEX,
4843 	    ("destroying device while still queued for ccbs"));
4844 
4845 	/* The send_mtx must be held when accessing the callout */
4846 	if ((device->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0)
4847 		callout_stop(&device->callout);
4848 
4849 	mtx_unlock(&devq->send_mtx);
4850 
4851 	xpt_release_target(device->target);
4852 
4853 	cam_ccbq_fini(&device->ccbq);
4854 	/*
4855 	 * Free allocated memory.  free(9) does nothing if the
4856 	 * supplied pointer is NULL, so it is safe to call without
4857 	 * checking.
4858 	 */
4859 	free(device->supported_vpds, M_CAMXPT);
4860 	free(device->device_id, M_CAMXPT);
4861 	free(device->ext_inq, M_CAMXPT);
4862 	free(device->physpath, M_CAMXPT);
4863 	free(device->rcap_buf, M_CAMXPT);
4864 	free(device->serial_num, M_CAMXPT);
4865 	free(device->nvme_data, M_CAMXPT);
4866 	free(device->nvme_cdata, M_CAMXPT);
4867 	taskqueue_enqueue(xsoftc.xpt_taskq, &device->device_destroy_task);
4868 }
4869 
4870 uint32_t
xpt_dev_ccbq_resize(struct cam_path * path,int newopenings)4871 xpt_dev_ccbq_resize(struct cam_path *path, int newopenings)
4872 {
4873 	int	result;
4874 	struct	cam_ed *dev;
4875 
4876 	dev = path->device;
4877 	mtx_lock(&dev->sim->devq->send_mtx);
4878 	result = cam_ccbq_resize(&dev->ccbq, newopenings);
4879 	mtx_unlock(&dev->sim->devq->send_mtx);
4880 	if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
4881 	 || (dev->inq_flags & SID_CmdQue) != 0)
4882 		dev->tag_saved_openings = newopenings;
4883 	return (result);
4884 }
4885 
4886 static struct cam_eb *
xpt_find_bus(path_id_t path_id)4887 xpt_find_bus(path_id_t path_id)
4888 {
4889 	struct cam_eb *bus;
4890 
4891 	xpt_lock_buses();
4892 	for (bus = TAILQ_FIRST(&xsoftc.xpt_busses);
4893 	     bus != NULL;
4894 	     bus = TAILQ_NEXT(bus, links)) {
4895 		if (bus->path_id == path_id) {
4896 			bus->refcount++;
4897 			break;
4898 		}
4899 	}
4900 	xpt_unlock_buses();
4901 	return (bus);
4902 }
4903 
4904 static struct cam_et *
xpt_find_target(struct cam_eb * bus,target_id_t target_id)4905 xpt_find_target(struct cam_eb *bus, target_id_t	target_id)
4906 {
4907 	struct cam_et *target;
4908 
4909 	mtx_assert(&bus->eb_mtx, MA_OWNED);
4910 	for (target = TAILQ_FIRST(&bus->et_entries);
4911 	     target != NULL;
4912 	     target = TAILQ_NEXT(target, links)) {
4913 		if (target->target_id == target_id) {
4914 			target->refcount++;
4915 			break;
4916 		}
4917 	}
4918 	return (target);
4919 }
4920 
4921 static struct cam_ed *
xpt_find_device(struct cam_et * target,lun_id_t lun_id)4922 xpt_find_device(struct cam_et *target, lun_id_t lun_id)
4923 {
4924 	struct cam_ed *device;
4925 
4926 	mtx_assert(&target->bus->eb_mtx, MA_OWNED);
4927 	for (device = TAILQ_FIRST(&target->ed_entries);
4928 	     device != NULL;
4929 	     device = TAILQ_NEXT(device, links)) {
4930 		if (device->lun_id == lun_id) {
4931 			device->refcount++;
4932 			break;
4933 		}
4934 	}
4935 	return (device);
4936 }
4937 
4938 void
xpt_start_tags(struct cam_path * path)4939 xpt_start_tags(struct cam_path *path)
4940 {
4941 	struct ccb_relsim crs;
4942 	struct cam_ed *device;
4943 	struct cam_sim *sim;
4944 	int    newopenings;
4945 
4946 	device = path->device;
4947 	sim = path->bus->sim;
4948 	device->flags &= ~CAM_DEV_TAG_AFTER_COUNT;
4949 	xpt_freeze_devq(path, /*count*/1);
4950 	device->inq_flags |= SID_CmdQue;
4951 	if (device->tag_saved_openings != 0)
4952 		newopenings = device->tag_saved_openings;
4953 	else
4954 		newopenings = min(device->maxtags,
4955 				  sim->max_tagged_dev_openings);
4956 	xpt_dev_ccbq_resize(path, newopenings);
4957 	xpt_async(AC_GETDEV_CHANGED, path, NULL);
4958 	memset(&crs, 0, sizeof(crs));
4959 	xpt_setup_ccb(&crs.ccb_h, path, CAM_PRIORITY_NORMAL);
4960 	crs.ccb_h.func_code = XPT_REL_SIMQ;
4961 	crs.release_flags = RELSIM_RELEASE_AFTER_QEMPTY;
4962 	crs.openings
4963 	    = crs.release_timeout
4964 	    = crs.qfrozen_cnt
4965 	    = 0;
4966 	xpt_action((union ccb *)&crs);
4967 }
4968 
4969 void
xpt_stop_tags(struct cam_path * path)4970 xpt_stop_tags(struct cam_path *path)
4971 {
4972 	struct ccb_relsim crs;
4973 	struct cam_ed *device;
4974 	struct cam_sim *sim;
4975 
4976 	device = path->device;
4977 	sim = path->bus->sim;
4978 	device->flags &= ~CAM_DEV_TAG_AFTER_COUNT;
4979 	device->tag_delay_count = 0;
4980 	xpt_freeze_devq(path, /*count*/1);
4981 	device->inq_flags &= ~SID_CmdQue;
4982 	xpt_dev_ccbq_resize(path, sim->max_dev_openings);
4983 	xpt_async(AC_GETDEV_CHANGED, path, NULL);
4984 	memset(&crs, 0, sizeof(crs));
4985 	xpt_setup_ccb(&crs.ccb_h, path, CAM_PRIORITY_NORMAL);
4986 	crs.ccb_h.func_code = XPT_REL_SIMQ;
4987 	crs.release_flags = RELSIM_RELEASE_AFTER_QEMPTY;
4988 	crs.openings
4989 	    = crs.release_timeout
4990 	    = crs.qfrozen_cnt
4991 	    = 0;
4992 	xpt_action((union ccb *)&crs);
4993 }
4994 
4995 /*
4996  * Assume all possible buses are detected by this time, so allow boot
4997  * as soon as they all are scanned.
4998  */
4999 static void
xpt_boot_delay(void * arg)5000 xpt_boot_delay(void *arg)
5001 {
5002 
5003 	xpt_release_boot();
5004 }
5005 
5006 /*
5007  * Now that all config hooks have completed, start boot_delay timer,
5008  * waiting for possibly still undetected buses (USB) to appear.
5009  */
5010 static void
xpt_ch_done(void * arg)5011 xpt_ch_done(void *arg)
5012 {
5013 
5014 	callout_init(&xsoftc.boot_callout, 1);
5015 	callout_reset_sbt(&xsoftc.boot_callout, SBT_1MS * xsoftc.boot_delay,
5016 	    SBT_1MS, xpt_boot_delay, NULL, 0);
5017 }
5018 SYSINIT(xpt_hw_delay, SI_SUB_INT_CONFIG_HOOKS, SI_ORDER_ANY, xpt_ch_done, NULL);
5019 
5020 /*
5021  * Now that interrupts are enabled, go find our devices
5022  */
5023 static void
xpt_config(void * arg)5024 xpt_config(void *arg)
5025 {
5026 	if (taskqueue_start_threads(&xsoftc.xpt_taskq, 1, PRIBIO, "CAM taskq"))
5027 		printf("xpt_config: failed to create taskqueue thread.\n");
5028 
5029 	/* Setup debugging path */
5030 	if (cam_dflags != CAM_DEBUG_NONE) {
5031 		if (xpt_create_path(&cam_dpath, NULL,
5032 				    CAM_DEBUG_BUS, CAM_DEBUG_TARGET,
5033 				    CAM_DEBUG_LUN) != CAM_REQ_CMP) {
5034 			printf(
5035 "xpt_config: xpt_create_path() failed for debug target %d:%d:%d, debugging disabled\n",
5036 			    CAM_DEBUG_BUS, CAM_DEBUG_TARGET, CAM_DEBUG_LUN);
5037 			cam_dflags = CAM_DEBUG_NONE;
5038 		}
5039 	} else
5040 		cam_dpath = NULL;
5041 
5042 	periphdriver_init(1);
5043 	xpt_hold_boot();
5044 
5045 	/* Fire up rescan thread. */
5046 	if (kproc_kthread_add(xpt_scanner_thread, NULL, &cam_proc, NULL, 0, 0,
5047 	    "cam", "scanner")) {
5048 		printf("xpt_config: failed to create rescan thread.\n");
5049 	}
5050 }
5051 
5052 void
xpt_hold_boot_locked(void)5053 xpt_hold_boot_locked(void)
5054 {
5055 
5056 	if (xsoftc.buses_to_config++ == 0)
5057 		root_mount_hold_token("CAM", &xsoftc.xpt_rootmount);
5058 }
5059 
5060 void
xpt_hold_boot(void)5061 xpt_hold_boot(void)
5062 {
5063 
5064 	xpt_lock_buses();
5065 	xpt_hold_boot_locked();
5066 	xpt_unlock_buses();
5067 }
5068 
5069 void
xpt_release_boot(void)5070 xpt_release_boot(void)
5071 {
5072 
5073 	xpt_lock_buses();
5074 	if (--xsoftc.buses_to_config == 0) {
5075 		if (xsoftc.buses_config_done == 0) {
5076 			xsoftc.buses_config_done = 1;
5077 			xsoftc.buses_to_config++;
5078 			TASK_INIT(&xsoftc.boot_task, 0, xpt_finishconfig_task,
5079 			    NULL);
5080 			taskqueue_enqueue(taskqueue_thread, &xsoftc.boot_task);
5081 		} else
5082 			root_mount_rel(&xsoftc.xpt_rootmount);
5083 	}
5084 	xpt_unlock_buses();
5085 }
5086 
5087 /*
5088  * If the given device only has one peripheral attached to it, and if that
5089  * peripheral is the passthrough driver, announce it.  This insures that the
5090  * user sees some sort of announcement for every peripheral in their system.
5091  */
5092 static int
xptpassannouncefunc(struct cam_ed * device,void * arg)5093 xptpassannouncefunc(struct cam_ed *device, void *arg)
5094 {
5095 	struct cam_periph *periph;
5096 	int i;
5097 
5098 	for (periph = SLIST_FIRST(&device->periphs), i = 0; periph != NULL;
5099 	     periph = SLIST_NEXT(periph, periph_links), i++);
5100 
5101 	periph = SLIST_FIRST(&device->periphs);
5102 	if ((i == 1)
5103 	 && (strncmp(periph->periph_name, "pass", 4) == 0))
5104 		xpt_announce_periph(periph, NULL);
5105 
5106 	return(1);
5107 }
5108 
5109 static void
xpt_finishconfig_task(void * context,int pending)5110 xpt_finishconfig_task(void *context, int pending)
5111 {
5112 
5113 	periphdriver_init(2);
5114 	/*
5115 	 * Check for devices with no "standard" peripheral driver
5116 	 * attached.  For any devices like that, announce the
5117 	 * passthrough driver so the user will see something.
5118 	 */
5119 	if (!bootverbose)
5120 		xpt_for_all_devices(xptpassannouncefunc, NULL);
5121 
5122 	xpt_release_boot();
5123 }
5124 
5125 cam_status
xpt_register_async(int event,ac_callback_t * cbfunc,void * cbarg,struct cam_path * path)5126 xpt_register_async(int event, ac_callback_t *cbfunc, void *cbarg,
5127 		   struct cam_path *path)
5128 {
5129 	struct ccb_setasync csa;
5130 	cam_status status;
5131 	bool xptpath = false;
5132 
5133 	if (path == NULL) {
5134 		status = xpt_create_path(&path, /*periph*/NULL, CAM_XPT_PATH_ID,
5135 					 CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
5136 		if (status != CAM_REQ_CMP)
5137 			return (status);
5138 		xpt_path_lock(path);
5139 		xptpath = true;
5140 	}
5141 
5142 	memset(&csa, 0, sizeof(csa));
5143 	xpt_setup_ccb(&csa.ccb_h, path, CAM_PRIORITY_NORMAL);
5144 	csa.ccb_h.func_code = XPT_SASYNC_CB;
5145 	csa.event_enable = event;
5146 	csa.callback = cbfunc;
5147 	csa.callback_arg = cbarg;
5148 	xpt_action((union ccb *)&csa);
5149 	status = csa.ccb_h.status;
5150 
5151 	CAM_DEBUG(csa.ccb_h.path, CAM_DEBUG_TRACE,
5152 	    ("xpt_register_async: func %p\n", cbfunc));
5153 
5154 	if (xptpath) {
5155 		xpt_path_unlock(path);
5156 		xpt_free_path(path);
5157 	}
5158 
5159 	if ((status == CAM_REQ_CMP) &&
5160 	    (csa.event_enable & AC_FOUND_DEVICE)) {
5161 		/*
5162 		 * Get this peripheral up to date with all
5163 		 * the currently existing devices.
5164 		 */
5165 		xpt_for_all_devices(xptsetasyncfunc, &csa);
5166 	}
5167 	if ((status == CAM_REQ_CMP) &&
5168 	    (csa.event_enable & AC_PATH_REGISTERED)) {
5169 		/*
5170 		 * Get this peripheral up to date with all
5171 		 * the currently existing buses.
5172 		 */
5173 		xpt_for_all_busses(xptsetasyncbusfunc, &csa);
5174 	}
5175 
5176 	return (status);
5177 }
5178 
5179 static void
xptaction(struct cam_sim * sim,union ccb * work_ccb)5180 xptaction(struct cam_sim *sim, union ccb *work_ccb)
5181 {
5182 	CAM_DEBUG(work_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("xptaction\n"));
5183 
5184 	switch (work_ccb->ccb_h.func_code) {
5185 	/* Common cases first */
5186 	case XPT_PATH_INQ:		/* Path routing inquiry */
5187 	{
5188 		struct ccb_pathinq *cpi;
5189 
5190 		cpi = &work_ccb->cpi;
5191 		cpi->version_num = 1; /* XXX??? */
5192 		cpi->hba_inquiry = 0;
5193 		cpi->target_sprt = 0;
5194 		cpi->hba_misc = 0;
5195 		cpi->hba_eng_cnt = 0;
5196 		cpi->max_target = 0;
5197 		cpi->max_lun = 0;
5198 		cpi->initiator_id = 0;
5199 		strlcpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
5200 		strlcpy(cpi->hba_vid, "", HBA_IDLEN);
5201 		strlcpy(cpi->dev_name, sim->sim_name, DEV_IDLEN);
5202 		cpi->unit_number = sim->unit_number;
5203 		cpi->bus_id = sim->bus_id;
5204 		cpi->base_transfer_speed = 0;
5205 		cpi->protocol = PROTO_UNSPECIFIED;
5206 		cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
5207 		cpi->transport = XPORT_UNSPECIFIED;
5208 		cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
5209 		cpi->ccb_h.status = CAM_REQ_CMP;
5210 		break;
5211 	}
5212 	default:
5213 		work_ccb->ccb_h.status = CAM_REQ_INVALID;
5214 		break;
5215 	}
5216 	xpt_done(work_ccb);
5217 }
5218 
5219 /*
5220  * The xpt as a "controller" has no interrupt sources, so polling
5221  * is a no-op.
5222  */
5223 static void
xptpoll(struct cam_sim * sim)5224 xptpoll(struct cam_sim *sim)
5225 {
5226 }
5227 
5228 void
xpt_lock_buses(void)5229 xpt_lock_buses(void)
5230 {
5231 	mtx_lock(&xsoftc.xpt_topo_lock);
5232 }
5233 
5234 void
xpt_unlock_buses(void)5235 xpt_unlock_buses(void)
5236 {
5237 	mtx_unlock(&xsoftc.xpt_topo_lock);
5238 }
5239 
5240 struct mtx *
xpt_path_mtx(struct cam_path * path)5241 xpt_path_mtx(struct cam_path *path)
5242 {
5243 
5244 	return (&path->device->device_mtx);
5245 }
5246 
5247 static void
xpt_done_process(struct ccb_hdr * ccb_h)5248 xpt_done_process(struct ccb_hdr *ccb_h)
5249 {
5250 	struct cam_sim *sim = NULL;
5251 	struct cam_devq *devq = NULL;
5252 	struct mtx *mtx = NULL;
5253 
5254 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
5255 	struct ccb_scsiio *csio;
5256 
5257 	if (ccb_h->func_code == XPT_SCSI_IO) {
5258 		csio = &((union ccb *)ccb_h)->csio;
5259 		if (csio->bio != NULL)
5260 			biotrack(csio->bio, __func__);
5261 	}
5262 #endif
5263 
5264 	if (ccb_h->flags & CAM_HIGH_POWER) {
5265 		struct highpowerlist	*hphead;
5266 		struct cam_ed		*device;
5267 
5268 		mtx_lock(&xsoftc.xpt_highpower_lock);
5269 		hphead = &xsoftc.highpowerq;
5270 
5271 		device = STAILQ_FIRST(hphead);
5272 
5273 		/*
5274 		 * Increment the count since this command is done.
5275 		 */
5276 		xsoftc.num_highpower++;
5277 
5278 		/*
5279 		 * Any high powered commands queued up?
5280 		 */
5281 		if (device != NULL) {
5282 			STAILQ_REMOVE_HEAD(hphead, highpowerq_entry);
5283 			mtx_unlock(&xsoftc.xpt_highpower_lock);
5284 
5285 			mtx_lock(&device->sim->devq->send_mtx);
5286 			xpt_release_devq_device(device,
5287 					 /*count*/1, /*runqueue*/TRUE);
5288 			mtx_unlock(&device->sim->devq->send_mtx);
5289 		} else
5290 			mtx_unlock(&xsoftc.xpt_highpower_lock);
5291 	}
5292 
5293 	/*
5294 	 * Insulate against a race where the periph is destroyed but CCBs are
5295 	 * still not all processed. This shouldn't happen, but allows us better
5296 	 * bug diagnostic when it does.
5297 	 */
5298 	if (ccb_h->path->bus)
5299 		sim = ccb_h->path->bus->sim;
5300 
5301 	if (ccb_h->status & CAM_RELEASE_SIMQ) {
5302 		KASSERT(sim, ("sim missing for CAM_RELEASE_SIMQ request"));
5303 		xpt_release_simq(sim, /*run_queue*/FALSE);
5304 		ccb_h->status &= ~CAM_RELEASE_SIMQ;
5305 	}
5306 
5307 	if ((ccb_h->flags & CAM_DEV_QFRZDIS)
5308 	 && (ccb_h->status & CAM_DEV_QFRZN)) {
5309 		xpt_release_devq(ccb_h->path, /*count*/1, /*run_queue*/TRUE);
5310 		ccb_h->status &= ~CAM_DEV_QFRZN;
5311 	}
5312 
5313 	if ((ccb_h->func_code & XPT_FC_USER_CCB) == 0) {
5314 		struct cam_ed *dev = ccb_h->path->device;
5315 
5316 		if (sim)
5317 			devq = sim->devq;
5318 		KASSERT(devq, ("Periph disappeared with CCB %p %s request pending.",
5319 			ccb_h, xpt_action_name(ccb_h->func_code)));
5320 
5321 		mtx_lock(&devq->send_mtx);
5322 		devq->send_active--;
5323 		devq->send_openings++;
5324 		cam_ccbq_ccb_done(&dev->ccbq, (union ccb *)ccb_h);
5325 
5326 		if (((dev->flags & CAM_DEV_REL_ON_QUEUE_EMPTY) != 0
5327 		  && (dev->ccbq.dev_active == 0))) {
5328 			dev->flags &= ~CAM_DEV_REL_ON_QUEUE_EMPTY;
5329 			xpt_release_devq_device(dev, /*count*/1,
5330 					 /*run_queue*/FALSE);
5331 		}
5332 
5333 		if (((dev->flags & CAM_DEV_REL_ON_COMPLETE) != 0
5334 		  && (ccb_h->status&CAM_STATUS_MASK) != CAM_REQUEUE_REQ)) {
5335 			dev->flags &= ~CAM_DEV_REL_ON_COMPLETE;
5336 			xpt_release_devq_device(dev, /*count*/1,
5337 					 /*run_queue*/FALSE);
5338 		}
5339 
5340 		if (!device_is_queued(dev))
5341 			(void)xpt_schedule_devq(devq, dev);
5342 		xpt_run_devq(devq);
5343 		mtx_unlock(&devq->send_mtx);
5344 
5345 		if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0) {
5346 			mtx = xpt_path_mtx(ccb_h->path);
5347 			mtx_lock(mtx);
5348 
5349 			if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
5350 			 && (--dev->tag_delay_count == 0))
5351 				xpt_start_tags(ccb_h->path);
5352 		}
5353 	}
5354 
5355 	if ((ccb_h->flags & CAM_UNLOCKED) == 0) {
5356 		if (mtx == NULL) {
5357 			mtx = xpt_path_mtx(ccb_h->path);
5358 			mtx_lock(mtx);
5359 		}
5360 	} else {
5361 		if (mtx != NULL) {
5362 			mtx_unlock(mtx);
5363 			mtx = NULL;
5364 		}
5365 	}
5366 
5367 	/* Call the peripheral driver's callback */
5368 	ccb_h->pinfo.index = CAM_UNQUEUED_INDEX;
5369 	(*ccb_h->cbfcnp)(ccb_h->path->periph, (union ccb *)ccb_h);
5370 	if (mtx != NULL)
5371 		mtx_unlock(mtx);
5372 }
5373 
5374 /*
5375  * Parameterize instead and use xpt_done_td?
5376  */
5377 static void
xpt_async_td(void * arg)5378 xpt_async_td(void *arg)
5379 {
5380 	struct cam_doneq *queue = arg;
5381 	struct ccb_hdr *ccb_h;
5382 	STAILQ_HEAD(, ccb_hdr)	doneq;
5383 
5384 	STAILQ_INIT(&doneq);
5385 	mtx_lock(&queue->cam_doneq_mtx);
5386 	while (1) {
5387 		while (STAILQ_EMPTY(&queue->cam_doneq))
5388 			msleep(&queue->cam_doneq, &queue->cam_doneq_mtx,
5389 			    PRIBIO, "-", 0);
5390 		STAILQ_CONCAT(&doneq, &queue->cam_doneq);
5391 		mtx_unlock(&queue->cam_doneq_mtx);
5392 
5393 		while ((ccb_h = STAILQ_FIRST(&doneq)) != NULL) {
5394 			STAILQ_REMOVE_HEAD(&doneq, sim_links.stqe);
5395 			xpt_done_process(ccb_h);
5396 		}
5397 
5398 		mtx_lock(&queue->cam_doneq_mtx);
5399 	}
5400 }
5401 
5402 void
xpt_done_td(void * arg)5403 xpt_done_td(void *arg)
5404 {
5405 	struct cam_doneq *queue = arg;
5406 	struct ccb_hdr *ccb_h;
5407 	STAILQ_HEAD(, ccb_hdr)	doneq;
5408 
5409 	STAILQ_INIT(&doneq);
5410 	mtx_lock(&queue->cam_doneq_mtx);
5411 	while (1) {
5412 		while (STAILQ_EMPTY(&queue->cam_doneq)) {
5413 			queue->cam_doneq_sleep = 1;
5414 			msleep(&queue->cam_doneq, &queue->cam_doneq_mtx,
5415 			    PRIBIO, "-", 0);
5416 			queue->cam_doneq_sleep = 0;
5417 		}
5418 		STAILQ_CONCAT(&doneq, &queue->cam_doneq);
5419 		mtx_unlock(&queue->cam_doneq_mtx);
5420 
5421 		THREAD_NO_SLEEPING();
5422 		while ((ccb_h = STAILQ_FIRST(&doneq)) != NULL) {
5423 			STAILQ_REMOVE_HEAD(&doneq, sim_links.stqe);
5424 			xpt_done_process(ccb_h);
5425 		}
5426 		THREAD_SLEEPING_OK();
5427 
5428 		mtx_lock(&queue->cam_doneq_mtx);
5429 	}
5430 }
5431 
5432 static void
camisr_runqueue(void)5433 camisr_runqueue(void)
5434 {
5435 	struct	ccb_hdr *ccb_h;
5436 	struct cam_doneq *queue;
5437 	int i;
5438 
5439 	/* Process global queues. */
5440 	for (i = 0; i < cam_num_doneqs; i++) {
5441 		queue = &cam_doneqs[i];
5442 		mtx_lock(&queue->cam_doneq_mtx);
5443 		while ((ccb_h = STAILQ_FIRST(&queue->cam_doneq)) != NULL) {
5444 			STAILQ_REMOVE_HEAD(&queue->cam_doneq, sim_links.stqe);
5445 			mtx_unlock(&queue->cam_doneq_mtx);
5446 			xpt_done_process(ccb_h);
5447 			mtx_lock(&queue->cam_doneq_mtx);
5448 		}
5449 		mtx_unlock(&queue->cam_doneq_mtx);
5450 	}
5451 }
5452 
5453 /**
5454  * @brief Return the device_t associated with the path
5455  *
5456  * When a SIM is created, it registers a bus with a NEWBUS device_t. This is
5457  * stored in the internal cam_eb bus structure. There is no guarnatee any given
5458  * path will have a @c device_t associated with it (it's legal to call @c
5459  * xpt_bus_register with a @c NULL @c device_t.
5460  *
5461  * @param path		Path to return the device_t for.
5462  */
5463 device_t
xpt_path_sim_device(const struct cam_path * path)5464 xpt_path_sim_device(const struct cam_path *path)
5465 {
5466 	return (path->bus->parent_dev);
5467 }
5468 
5469 struct kv
5470 {
5471 	uint32_t v;
5472 	const char *name;
5473 };
5474 
5475 static struct kv map[] = {
5476 	{ XPT_NOOP, "XPT_NOOP" },
5477 	{ XPT_SCSI_IO, "XPT_SCSI_IO" },
5478 	{ XPT_GDEV_TYPE, "XPT_GDEV_TYPE" },
5479 	{ XPT_GDEVLIST, "XPT_GDEVLIST" },
5480 	{ XPT_PATH_INQ, "XPT_PATH_INQ" },
5481 	{ XPT_REL_SIMQ, "XPT_REL_SIMQ" },
5482 	{ XPT_SASYNC_CB, "XPT_SASYNC_CB" },
5483 	{ XPT_SDEV_TYPE, "XPT_SDEV_TYPE" },
5484 	{ XPT_SCAN_BUS, "XPT_SCAN_BUS" },
5485 	{ XPT_DEV_MATCH, "XPT_DEV_MATCH" },
5486 	{ XPT_DEBUG, "XPT_DEBUG" },
5487 	{ XPT_PATH_STATS, "XPT_PATH_STATS" },
5488 	{ XPT_GDEV_STATS, "XPT_GDEV_STATS" },
5489 	{ XPT_DEV_ADVINFO, "XPT_DEV_ADVINFO" },
5490 	{ XPT_ASYNC, "XPT_ASYNC" },
5491 	{ XPT_ABORT, "XPT_ABORT" },
5492 	{ XPT_RESET_BUS, "XPT_RESET_BUS" },
5493 	{ XPT_RESET_DEV, "XPT_RESET_DEV" },
5494 	{ XPT_TERM_IO, "XPT_TERM_IO" },
5495 	{ XPT_SCAN_LUN, "XPT_SCAN_LUN" },
5496 	{ XPT_GET_TRAN_SETTINGS, "XPT_GET_TRAN_SETTINGS" },
5497 	{ XPT_SET_TRAN_SETTINGS, "XPT_SET_TRAN_SETTINGS" },
5498 	{ XPT_CALC_GEOMETRY, "XPT_CALC_GEOMETRY" },
5499 	{ XPT_ATA_IO, "XPT_ATA_IO" },
5500 	{ XPT_GET_SIM_KNOB, "XPT_GET_SIM_KNOB" },
5501 	{ XPT_SET_SIM_KNOB, "XPT_SET_SIM_KNOB" },
5502 	{ XPT_NVME_IO, "XPT_NVME_IO" },
5503 	{ XPT_MMC_IO, "XPT_MMC_IO" },
5504 	{ XPT_SMP_IO, "XPT_SMP_IO" },
5505 	{ XPT_SCAN_TGT, "XPT_SCAN_TGT" },
5506 	{ XPT_NVME_ADMIN, "XPT_NVME_ADMIN" },
5507 	{ XPT_ENG_INQ, "XPT_ENG_INQ" },
5508 	{ XPT_ENG_EXEC, "XPT_ENG_EXEC" },
5509 	{ XPT_EN_LUN, "XPT_EN_LUN" },
5510 	{ XPT_TARGET_IO, "XPT_TARGET_IO" },
5511 	{ XPT_ACCEPT_TARGET_IO, "XPT_ACCEPT_TARGET_IO" },
5512 	{ XPT_CONT_TARGET_IO, "XPT_CONT_TARGET_IO" },
5513 	{ XPT_IMMED_NOTIFY, "XPT_IMMED_NOTIFY" },
5514 	{ XPT_NOTIFY_ACK, "XPT_NOTIFY_ACK" },
5515 	{ XPT_IMMEDIATE_NOTIFY, "XPT_IMMEDIATE_NOTIFY" },
5516 	{ XPT_NOTIFY_ACKNOWLEDGE, "XPT_NOTIFY_ACKNOWLEDGE" },
5517 	{ 0, 0 }
5518 };
5519 
5520 const char *
xpt_action_name(uint32_t action)5521 xpt_action_name(uint32_t action)
5522 {
5523 	static char buffer[32];	/* Only for unknown messages -- racy */
5524 	struct kv *walker = map;
5525 
5526 	while (walker->name != NULL) {
5527 		if (walker->v == action)
5528 			return (walker->name);
5529 		walker++;
5530 	}
5531 
5532 	snprintf(buffer, sizeof(buffer), "%#x", action);
5533 	return (buffer);
5534 }
5535 
5536 void
xpt_cam_path_debug(struct cam_path * path,const char * fmt,...)5537 xpt_cam_path_debug(struct cam_path *path, const char *fmt, ...)
5538 {
5539 	struct sbuf sbuf;
5540 	char buf[XPT_PRINT_LEN]; /* balance to not eat too much stack */
5541 	struct sbuf *sb = sbuf_new(&sbuf, buf, sizeof(buf), SBUF_FIXEDLEN);
5542 	va_list ap;
5543 
5544 	sbuf_set_drain(sb, sbuf_printf_drain, NULL);
5545 	xpt_path_sbuf(path, sb);
5546 	va_start(ap, fmt);
5547 	sbuf_vprintf(sb, fmt, ap);
5548 	va_end(ap);
5549 	sbuf_finish(sb);
5550 	sbuf_delete(sb);
5551 	if (cam_debug_delay != 0)
5552 		DELAY(cam_debug_delay);
5553 }
5554 
5555 void
xpt_cam_dev_debug(struct cam_ed * dev,const char * fmt,...)5556 xpt_cam_dev_debug(struct cam_ed *dev, const char *fmt, ...)
5557 {
5558 	struct sbuf sbuf;
5559 	char buf[XPT_PRINT_LEN]; /* balance to not eat too much stack */
5560 	struct sbuf *sb = sbuf_new(&sbuf, buf, sizeof(buf), SBUF_FIXEDLEN);
5561 	va_list ap;
5562 
5563 	sbuf_set_drain(sb, sbuf_printf_drain, NULL);
5564 	xpt_device_sbuf(dev, sb);
5565 	va_start(ap, fmt);
5566 	sbuf_vprintf(sb, fmt, ap);
5567 	va_end(ap);
5568 	sbuf_finish(sb);
5569 	sbuf_delete(sb);
5570 	if (cam_debug_delay != 0)
5571 		DELAY(cam_debug_delay);
5572 }
5573 
5574 void
xpt_cam_debug(const char * fmt,...)5575 xpt_cam_debug(const char *fmt, ...)
5576 {
5577 	struct sbuf sbuf;
5578 	char buf[XPT_PRINT_LEN]; /* balance to not eat too much stack */
5579 	struct sbuf *sb = sbuf_new(&sbuf, buf, sizeof(buf), SBUF_FIXEDLEN);
5580 	va_list ap;
5581 
5582 	sbuf_set_drain(sb, sbuf_printf_drain, NULL);
5583 	sbuf_cat(sb, "cam_debug: ");
5584 	va_start(ap, fmt);
5585 	sbuf_vprintf(sb, fmt, ap);
5586 	va_end(ap);
5587 	sbuf_finish(sb);
5588 	sbuf_delete(sb);
5589 	if (cam_debug_delay != 0)
5590 		DELAY(cam_debug_delay);
5591 }
5592