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