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