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