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