xref: /dragonfly/sys/bus/cam/cam_xpt.c (revision 521a7b05)
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  * $FreeBSD: src/sys/cam/cam_xpt.c,v 1.80.2.18 2002/12/09 17:31:55 gibbs Exp $
30  * $DragonFly: src/sys/bus/cam/cam_xpt.c,v 1.34 2006/12/22 23:12:16 swildner Exp $
31  */
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/types.h>
35 #include <sys/malloc.h>
36 #include <sys/kernel.h>
37 #include <sys/time.h>
38 #include <sys/conf.h>
39 #include <sys/device.h>
40 #include <sys/fcntl.h>
41 #include <sys/md5.h>
42 #include <sys/devicestat.h>
43 #include <sys/interrupt.h>
44 #include <sys/bus.h>
45 #include <sys/thread.h>
46 #include <sys/thread2.h>
47 
48 #include <machine/clock.h>
49 
50 #include "cam.h"
51 #include "cam_ccb.h"
52 #include "cam_periph.h"
53 #include "cam_sim.h"
54 #include "cam_xpt.h"
55 #include "cam_xpt_sim.h"
56 #include "cam_xpt_periph.h"
57 #include "cam_debug.h"
58 
59 #include "scsi/scsi_all.h"
60 #include "scsi/scsi_message.h"
61 #include "scsi/scsi_pass.h"
62 #include "opt_cam.h"
63 
64 /* Datastructures internal to the xpt layer */
65 
66 /*
67  * Definition of an async handler callback block.  These are used to add
68  * SIMs and peripherals to the async callback lists.
69  */
70 struct async_node {
71 	SLIST_ENTRY(async_node)	links;
72 	u_int32_t	event_enable;	/* Async Event enables */
73 	void		(*callback)(void *arg, u_int32_t code,
74 				    struct cam_path *path, void *args);
75 	void		*callback_arg;
76 };
77 
78 SLIST_HEAD(async_list, async_node);
79 SLIST_HEAD(periph_list, cam_periph);
80 static STAILQ_HEAD(highpowerlist, ccb_hdr) highpowerq;
81 
82 /*
83  * This is the maximum number of high powered commands (e.g. start unit)
84  * that can be outstanding at a particular time.
85  */
86 #ifndef CAM_MAX_HIGHPOWER
87 #define CAM_MAX_HIGHPOWER  4
88 #endif
89 
90 /* number of high powered commands that can go through right now */
91 static int num_highpower = CAM_MAX_HIGHPOWER;
92 
93 /*
94  * Structure for queueing a device in a run queue.
95  * There is one run queue for allocating new ccbs,
96  * and another for sending ccbs to the controller.
97  */
98 struct cam_ed_qinfo {
99 	cam_pinfo pinfo;
100 	struct	  cam_ed *device;
101 };
102 
103 /*
104  * The CAM EDT (Existing Device Table) contains the device information for
105  * all devices for all busses in the system.  The table contains a
106  * cam_ed structure for each device on the bus.
107  */
108 struct cam_ed {
109 	TAILQ_ENTRY(cam_ed) links;
110 	struct	cam_ed_qinfo alloc_ccb_entry;
111 	struct	cam_ed_qinfo send_ccb_entry;
112 	struct	cam_et	 *target;
113 	lun_id_t	 lun_id;
114 	struct	camq drvq;		/*
115 					 * Queue of type drivers wanting to do
116 					 * work on this device.
117 					 */
118 	struct	cam_ccbq ccbq;		/* Queue of pending ccbs */
119 	struct	async_list asyncs;	/* Async callback info for this B/T/L */
120 	struct	periph_list periphs;	/* All attached devices */
121 	u_int	generation;		/* Generation number */
122 	struct	cam_periph *owner;	/* Peripheral driver's ownership tag */
123 	struct	xpt_quirk_entry *quirk;	/* Oddities about this device */
124 					/* Storage for the inquiry data */
125 	struct	scsi_inquiry_data inq_data;
126 	u_int8_t	 inq_flags;	/*
127 					 * Current settings for inquiry flags.
128 					 * This allows us to override settings
129 					 * like disconnection and tagged
130 					 * queuing for a device.
131 					 */
132 	u_int8_t	 queue_flags;	/* Queue flags from the control page */
133 	u_int8_t	 serial_num_len;
134 	u_int8_t	 *serial_num;
135 	u_int32_t	 qfrozen_cnt;
136 	u_int32_t	 flags;
137 #define CAM_DEV_UNCONFIGURED	 	0x01
138 #define CAM_DEV_REL_TIMEOUT_PENDING	0x02
139 #define CAM_DEV_REL_ON_COMPLETE		0x04
140 #define CAM_DEV_REL_ON_QUEUE_EMPTY	0x08
141 #define CAM_DEV_RESIZE_QUEUE_NEEDED	0x10
142 #define CAM_DEV_TAG_AFTER_COUNT		0x20
143 #define CAM_DEV_INQUIRY_DATA_VALID	0x40
144 	u_int32_t	 tag_delay_count;
145 #define	CAM_TAG_DELAY_COUNT		5
146 	u_int32_t	 refcount;
147 	struct		 callout c_handle;
148 };
149 
150 /*
151  * Each target is represented by an ET (Existing Target).  These
152  * entries are created when a target is successfully probed with an
153  * identify, and removed when a device fails to respond after a number
154  * of retries, or a bus rescan finds the device missing.
155  */
156 struct cam_et {
157 	TAILQ_HEAD(, cam_ed) ed_entries;
158 	TAILQ_ENTRY(cam_et) links;
159 	struct	cam_eb	*bus;
160 	target_id_t	target_id;
161 	u_int32_t	refcount;
162 	u_int		generation;
163 	struct		timeval last_reset;	/* uptime of last reset */
164 };
165 
166 /*
167  * Each bus is represented by an EB (Existing Bus).  These entries
168  * are created by calls to xpt_bus_register and deleted by calls to
169  * xpt_bus_deregister.
170  */
171 struct cam_eb {
172 	TAILQ_HEAD(, cam_et) et_entries;
173 	TAILQ_ENTRY(cam_eb)  links;
174 	path_id_t	     path_id;
175 	struct cam_sim	     *sim;
176 	struct timeval	     last_reset;	/* uptime of last reset */
177 	u_int32_t	     flags;
178 #define	CAM_EB_RUNQ_SCHEDULED	0x01
179 	u_int32_t	     refcount;
180 	u_int		     generation;
181 };
182 
183 struct cam_path {
184 	struct cam_periph *periph;
185 	struct cam_eb	  *bus;
186 	struct cam_et	  *target;
187 	struct cam_ed	  *device;
188 };
189 
190 struct xpt_quirk_entry {
191 	struct scsi_inquiry_pattern inq_pat;
192 	u_int8_t quirks;
193 #define	CAM_QUIRK_NOLUNS	0x01
194 #define	CAM_QUIRK_NOSERIAL	0x02
195 #define	CAM_QUIRK_HILUNS	0x04
196 	u_int mintags;
197 	u_int maxtags;
198 };
199 #define	CAM_SCSI2_MAXLUN	8
200 
201 typedef enum {
202 	XPT_FLAG_OPEN		= 0x01
203 } xpt_flags;
204 
205 struct xpt_softc {
206 	xpt_flags	flags;
207 	u_int32_t	generation;
208 };
209 
210 static const char quantum[] = "QUANTUM";
211 static const char sony[] = "SONY";
212 static const char west_digital[] = "WDIGTL";
213 static const char samsung[] = "SAMSUNG";
214 static const char seagate[] = "SEAGATE";
215 static const char microp[] = "MICROP";
216 
217 static struct xpt_quirk_entry xpt_quirk_table[] =
218 {
219 	{
220 		/* Reports QUEUE FULL for temporary resource shortages */
221 		{ T_DIRECT, SIP_MEDIA_FIXED, quantum, "XP39100*", "*" },
222 		/*quirks*/0, /*mintags*/24, /*maxtags*/32
223 	},
224 	{
225 		/* Reports QUEUE FULL for temporary resource shortages */
226 		{ T_DIRECT, SIP_MEDIA_FIXED, quantum, "XP34550*", "*" },
227 		/*quirks*/0, /*mintags*/24, /*maxtags*/32
228 	},
229 	{
230 		/* Reports QUEUE FULL for temporary resource shortages */
231 		{ T_DIRECT, SIP_MEDIA_FIXED, quantum, "XP32275*", "*" },
232 		/*quirks*/0, /*mintags*/24, /*maxtags*/32
233 	},
234 	{
235 		/* Broken tagged queuing drive */
236 		{ T_DIRECT, SIP_MEDIA_FIXED, microp, "4421-07*", "*" },
237 		/*quirks*/0, /*mintags*/0, /*maxtags*/0
238 	},
239 	{
240 		/* Broken tagged queuing drive */
241 		{ T_DIRECT, SIP_MEDIA_FIXED, "HP", "C372*", "*" },
242 		/*quirks*/0, /*mintags*/0, /*maxtags*/0
243 	},
244 	{
245 		/* Broken tagged queuing drive */
246 		{ T_DIRECT, SIP_MEDIA_FIXED, microp, "3391*", "x43h" },
247 		/*quirks*/0, /*mintags*/0, /*maxtags*/0
248 	},
249 	{
250 		/*
251 		 * Unfortunately, the Quantum Atlas III has the same
252 		 * problem as the Atlas II drives above.
253 		 * Reported by: "Johan Granlund" <johan@granlund.nu>
254 		 *
255 		 * For future reference, the drive with the problem was:
256 		 * QUANTUM QM39100TD-SW N1B0
257 		 *
258 		 * It's possible that Quantum will fix the problem in later
259 		 * firmware revisions.  If that happens, the quirk entry
260 		 * will need to be made specific to the firmware revisions
261 		 * with the problem.
262 		 *
263 		 */
264 		/* Reports QUEUE FULL for temporary resource shortages */
265 		{ T_DIRECT, SIP_MEDIA_FIXED, quantum, "QM39100*", "*" },
266 		/*quirks*/0, /*mintags*/24, /*maxtags*/32
267 	},
268 	{
269 		/*
270 		 * 18 Gig Atlas III, same problem as the 9G version.
271 		 * Reported by: Andre Albsmeier
272 		 *		<andre.albsmeier@mchp.siemens.de>
273 		 *
274 		 * For future reference, the drive with the problem was:
275 		 * QUANTUM QM318000TD-S N491
276 		 */
277 		/* Reports QUEUE FULL for temporary resource shortages */
278 		{ T_DIRECT, SIP_MEDIA_FIXED, quantum, "QM318000*", "*" },
279 		/*quirks*/0, /*mintags*/24, /*maxtags*/32
280 	},
281 	{
282 		/*
283 		 * Broken tagged queuing drive
284 		 * Reported by: Bret Ford <bford@uop.cs.uop.edu>
285 		 *         and: Martin Renters <martin@tdc.on.ca>
286 		 */
287 		{ T_DIRECT, SIP_MEDIA_FIXED, seagate, "ST410800*", "71*" },
288 		/*quirks*/0, /*mintags*/0, /*maxtags*/0
289 	},
290 		/*
291 		 * The Seagate Medalist Pro drives have very poor write
292 		 * performance with anything more than 2 tags.
293 		 *
294 		 * Reported by:  Paul van der Zwan <paulz@trantor.xs4all.nl>
295 		 * Drive:  <SEAGATE ST36530N 1444>
296 		 *
297 		 * Reported by:  Jeremy Lea <reg@shale.csir.co.za>
298 		 * Drive:  <SEAGATE ST34520W 1281>
299 		 *
300 		 * No one has actually reported that the 9G version
301 		 * (ST39140*) of the Medalist Pro has the same problem, but
302 		 * we're assuming that it does because the 4G and 6.5G
303 		 * versions of the drive are broken.
304 		 */
305 	{
306 		{ T_DIRECT, SIP_MEDIA_FIXED, seagate, "ST34520*", "*"},
307 		/*quirks*/0, /*mintags*/2, /*maxtags*/2
308 	},
309 	{
310 		{ T_DIRECT, SIP_MEDIA_FIXED, seagate, "ST36530*", "*"},
311 		/*quirks*/0, /*mintags*/2, /*maxtags*/2
312 	},
313 	{
314 		{ T_DIRECT, SIP_MEDIA_FIXED, seagate, "ST39140*", "*"},
315 		/*quirks*/0, /*mintags*/2, /*maxtags*/2
316 	},
317 	{
318 		/*
319 		 * Slow when tagged queueing is enabled.  Write performance
320 		 * steadily drops off with more and more concurrent
321 		 * transactions.  Best sequential write performance with
322 		 * tagged queueing turned off and write caching turned on.
323 		 *
324 		 * PR:  kern/10398
325 		 * Submitted by:  Hideaki Okada <hokada@isl.melco.co.jp>
326 		 * Drive:  DCAS-34330 w/ "S65A" firmware.
327 		 *
328 		 * The drive with the problem had the "S65A" firmware
329 		 * revision, and has also been reported (by Stephen J.
330 		 * Roznowski <sjr@home.net>) for a drive with the "S61A"
331 		 * firmware revision.
332 		 *
333 		 * Although no one has reported problems with the 2 gig
334 		 * version of the DCAS drive, the assumption is that it
335 		 * has the same problems as the 4 gig version.  Therefore
336 		 * this quirk entries disables tagged queueing for all
337 		 * DCAS drives.
338 		 */
339 		{ T_DIRECT, SIP_MEDIA_FIXED, "IBM", "DCAS*", "*" },
340 		/*quirks*/0, /*mintags*/0, /*maxtags*/0
341 	},
342 	{
343 		/* Broken tagged queuing drive */
344 		{ T_DIRECT, SIP_MEDIA_REMOVABLE, "iomega", "jaz*", "*" },
345 		/*quirks*/0, /*mintags*/0, /*maxtags*/0
346 	},
347 	{
348 		/* Broken tagged queuing drive */
349 		{ T_DIRECT, SIP_MEDIA_FIXED, "CONNER", "CFP2107*", "*" },
350 		/*quirks*/0, /*mintags*/0, /*maxtags*/0
351 	},
352 	{
353 		/*
354 		 * Broken tagged queuing drive.
355 		 * Submitted by:
356 		 * NAKAJI Hiroyuki <nakaji@zeisei.dpri.kyoto-u.ac.jp>
357 		 * in PR kern/9535
358 		 */
359 		{ T_DIRECT, SIP_MEDIA_FIXED, samsung, "WN34324U*", "*" },
360 		/*quirks*/0, /*mintags*/0, /*maxtags*/0
361 	},
362         {
363 		/*
364 		 * Slow when tagged queueing is enabled. (1.5MB/sec versus
365 		 * 8MB/sec.)
366 		 * Submitted by: Andrew Gallatin <gallatin@cs.duke.edu>
367 		 * Best performance with these drives is achieved with
368 		 * tagged queueing turned off, and write caching turned on.
369 		 */
370 		{ T_DIRECT, SIP_MEDIA_FIXED, west_digital, "WDE*", "*" },
371 		/*quirks*/0, /*mintags*/0, /*maxtags*/0
372         },
373         {
374 		/*
375 		 * Slow when tagged queueing is enabled. (1.5MB/sec versus
376 		 * 8MB/sec.)
377 		 * Submitted by: Andrew Gallatin <gallatin@cs.duke.edu>
378 		 * Best performance with these drives is achieved with
379 		 * tagged queueing turned off, and write caching turned on.
380 		 */
381 		{ T_DIRECT, SIP_MEDIA_FIXED, west_digital, "ENTERPRISE", "*" },
382 		/*quirks*/0, /*mintags*/0, /*maxtags*/0
383         },
384 	{
385 		/*
386 		 * Doesn't handle queue full condition correctly,
387 		 * so we need to limit maxtags to what the device
388 		 * can handle instead of determining this automatically.
389 		 */
390 		{ T_DIRECT, SIP_MEDIA_FIXED, samsung, "WN321010S*", "*" },
391 		/*quirks*/0, /*mintags*/2, /*maxtags*/32
392 	},
393 	{
394 		/* Really only one LUN */
395 		{ T_ENCLOSURE, SIP_MEDIA_FIXED, "SUN", "SENA", "*" },
396 		CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
397 	},
398 	{
399 		/* I can't believe we need a quirk for DPT volumes. */
400 		{ T_ANY, SIP_MEDIA_FIXED|SIP_MEDIA_REMOVABLE, "DPT", "*", "*" },
401 		CAM_QUIRK_NOSERIAL|CAM_QUIRK_NOLUNS,
402 		/*mintags*/0, /*maxtags*/255
403 	},
404 	{
405 		/*
406 		 * Many Sony CDROM drives don't like multi-LUN probing.
407 		 */
408 		{ T_CDROM, SIP_MEDIA_REMOVABLE, sony, "CD-ROM CDU*", "*" },
409 		CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
410 	},
411 	{
412 		/*
413 		 * This drive doesn't like multiple LUN probing.
414 		 * Submitted by:  Parag Patel <parag@cgt.com>
415 		 */
416 		{ T_WORM, SIP_MEDIA_REMOVABLE, sony, "CD-R   CDU9*", "*" },
417 		CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
418 	},
419 	{
420 		{ T_WORM, SIP_MEDIA_REMOVABLE, "YAMAHA", "CDR100*", "*" },
421 		CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
422 	},
423 	{
424 		/*
425 		 * The 8200 doesn't like multi-lun probing, and probably
426 		 * don't like serial number requests either.
427 		 */
428 		{
429 			T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "EXABYTE",
430 			"EXB-8200*", "*"
431 		},
432 		CAM_QUIRK_NOSERIAL|CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
433 	},
434 	{
435 		/*
436 		 * Let's try the same as above, but for a drive that says
437 		 * it's an IPL-6860 but is actually an EXB 8200.
438 		 */
439 		{
440 			T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "EXABYTE",
441 			"IPL-6860*", "*"
442 		},
443 		CAM_QUIRK_NOSERIAL|CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
444 	},
445 	{
446 		/*
447 		 * These Hitachi drives don't like multi-lun probing.
448 		 * The PR submitter has a DK319H, but says that the Linux
449 		 * kernel has a similar work-around for the DK312 and DK314,
450 		 * so all DK31* drives are quirked here.
451 		 * PR:            misc/18793
452 		 * Submitted by:  Paul Haddad <paul@pth.com>
453 		 */
454 		{ T_DIRECT, SIP_MEDIA_FIXED, "HITACHI", "DK31*", "*" },
455 		CAM_QUIRK_NOLUNS, /*mintags*/2, /*maxtags*/255
456 	},
457 	{
458 		/*
459 		 * This old revision of the TDC3600 is also SCSI-1, and
460 		 * hangs upon serial number probing.
461 		 */
462 		{
463 			T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "TANDBERG",
464 			" TDC 3600", "U07:"
465 		},
466 		CAM_QUIRK_NOSERIAL, /*mintags*/0, /*maxtags*/0
467 	},
468 	{
469 		/*
470 		 * Would repond to all LUNs if asked for.
471 		 */
472 		{
473 			T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "CALIPER",
474 			"CP150", "*"
475 		},
476 		CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
477 	},
478 	{
479 		/*
480 		 * Would repond to all LUNs if asked for.
481 		 */
482 		{
483 			T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "KENNEDY",
484 			"96X2*", "*"
485 		},
486 		CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
487 	},
488 	{
489 		/* Submitted by: Matthew Dodd <winter@jurai.net> */
490 		{ T_PROCESSOR, SIP_MEDIA_FIXED, "Cabletrn", "EA41*", "*" },
491 		CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
492 	},
493 	{
494 		/* Submitted by: Matthew Dodd <winter@jurai.net> */
495 		{ T_PROCESSOR, SIP_MEDIA_FIXED, "CABLETRN", "EA41*", "*" },
496 		CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
497 	},
498 	{
499 		/* TeraSolutions special settings for TRC-22 RAID */
500 		{ T_DIRECT, SIP_MEDIA_FIXED, "TERASOLU", "TRC-22", "*" },
501 		  /*quirks*/0, /*mintags*/55, /*maxtags*/255
502 	},
503 	{
504 		/* Veritas Storage Appliance */
505 		{ T_DIRECT, SIP_MEDIA_FIXED, "VERITAS", "*", "*" },
506 		  CAM_QUIRK_HILUNS, /*mintags*/2, /*maxtags*/1024
507 	},
508 	{
509 		/*
510 		 * Would respond to all LUNs.  Device type and removable
511 		 * flag are jumper-selectable.
512 		 */
513 		{ T_ANY, SIP_MEDIA_REMOVABLE|SIP_MEDIA_FIXED, "MaxOptix",
514 		  "Tahiti 1", "*"
515 		},
516 		CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
517 	},
518 	{
519 		/* Default tagged queuing parameters for all devices */
520 		{
521 		  T_ANY, SIP_MEDIA_REMOVABLE|SIP_MEDIA_FIXED,
522 		  /*vendor*/"*", /*product*/"*", /*revision*/"*"
523 		},
524 		/*quirks*/0, /*mintags*/2, /*maxtags*/255
525 	},
526 };
527 
528 static const int xpt_quirk_table_size =
529 	sizeof(xpt_quirk_table) / sizeof(*xpt_quirk_table);
530 
531 typedef enum {
532 	DM_RET_COPY		= 0x01,
533 	DM_RET_FLAG_MASK	= 0x0f,
534 	DM_RET_NONE		= 0x00,
535 	DM_RET_STOP		= 0x10,
536 	DM_RET_DESCEND		= 0x20,
537 	DM_RET_ERROR		= 0x30,
538 	DM_RET_ACTION_MASK	= 0xf0
539 } dev_match_ret;
540 
541 typedef enum {
542 	XPT_DEPTH_BUS,
543 	XPT_DEPTH_TARGET,
544 	XPT_DEPTH_DEVICE,
545 	XPT_DEPTH_PERIPH
546 } xpt_traverse_depth;
547 
548 struct xpt_traverse_config {
549 	xpt_traverse_depth	depth;
550 	void			*tr_func;
551 	void			*tr_arg;
552 };
553 
554 typedef	int	xpt_busfunc_t (struct cam_eb *bus, void *arg);
555 typedef	int	xpt_targetfunc_t (struct cam_et *target, void *arg);
556 typedef	int	xpt_devicefunc_t (struct cam_ed *device, void *arg);
557 typedef	int	xpt_periphfunc_t (struct cam_periph *periph, void *arg);
558 typedef int	xpt_pdrvfunc_t (struct periph_driver **pdrv, void *arg);
559 
560 /* Transport layer configuration information */
561 static struct xpt_softc xsoftc;
562 
563 /* Queues for our software interrupt handler */
564 typedef TAILQ_HEAD(cam_isrq, ccb_hdr) cam_isrq_t;
565 static cam_isrq_t cam_bioq;
566 static cam_isrq_t cam_netq;
567 
568 /* "Pool" of inactive ccbs managed by xpt_alloc_ccb and xpt_free_ccb */
569 static SLIST_HEAD(,ccb_hdr) ccb_freeq;
570 static u_int xpt_max_ccbs;	/*
571 				 * Maximum size of ccb pool.  Modified as
572 				 * devices are added/removed or have their
573 				 * opening counts changed.
574 				 */
575 static u_int xpt_ccb_count;	/* Current count of allocated ccbs */
576 
577 struct cam_periph *xpt_periph;
578 
579 static periph_init_t xpt_periph_init;
580 
581 static periph_init_t probe_periph_init;
582 
583 static struct periph_driver xpt_driver =
584 {
585 	xpt_periph_init, "xpt",
586 	TAILQ_HEAD_INITIALIZER(xpt_driver.units)
587 };
588 
589 static struct periph_driver probe_driver =
590 {
591 	probe_periph_init, "probe",
592 	TAILQ_HEAD_INITIALIZER(probe_driver.units)
593 };
594 
595 DATA_SET(periphdriver_set, xpt_driver);
596 DATA_SET(periphdriver_set, probe_driver);
597 
598 #define XPT_CDEV_MAJOR 104
599 
600 static d_open_t xptopen;
601 static d_close_t xptclose;
602 static d_ioctl_t xptioctl;
603 
604 static struct dev_ops xpt_ops = {
605 	{ "xpt", XPT_CDEV_MAJOR, 0 },
606 	.d_open = xptopen,
607 	.d_close = xptclose,
608 	.d_ioctl = xptioctl
609 };
610 
611 static struct intr_config_hook *xpt_config_hook;
612 
613 /* Registered busses */
614 static TAILQ_HEAD(,cam_eb) xpt_busses;
615 static u_int bus_generation;
616 
617 /* Storage for debugging datastructures */
618 #ifdef	CAMDEBUG
619 struct cam_path *cam_dpath;
620 u_int32_t cam_dflags;
621 u_int32_t cam_debug_delay;
622 #endif
623 
624 #if defined(CAM_DEBUG_FLAGS) && !defined(CAMDEBUG)
625 #error "You must have options CAMDEBUG to use options CAM_DEBUG_FLAGS"
626 #endif
627 
628 /*
629  * In order to enable the CAM_DEBUG_* options, the user must have CAMDEBUG
630  * enabled.  Also, the user must have either none, or all of CAM_DEBUG_BUS,
631  * CAM_DEBUG_TARGET, and CAM_DEBUG_LUN specified.
632  */
633 #if defined(CAM_DEBUG_BUS) || defined(CAM_DEBUG_TARGET) \
634     || defined(CAM_DEBUG_LUN)
635 #ifdef CAMDEBUG
636 #if !defined(CAM_DEBUG_BUS) || !defined(CAM_DEBUG_TARGET) \
637     || !defined(CAM_DEBUG_LUN)
638 #error "You must define all or none of CAM_DEBUG_BUS, CAM_DEBUG_TARGET \
639         and CAM_DEBUG_LUN"
640 #endif /* !CAM_DEBUG_BUS || !CAM_DEBUG_TARGET || !CAM_DEBUG_LUN */
641 #else /* !CAMDEBUG */
642 #error "You must use options CAMDEBUG if you use the CAM_DEBUG_* options"
643 #endif /* CAMDEBUG */
644 #endif /* CAM_DEBUG_BUS || CAM_DEBUG_TARGET || CAM_DEBUG_LUN */
645 
646 /* Our boot-time initialization hook */
647 static void	xpt_init(void *);
648 SYSINIT(cam, SI_SUB_CONFIGURE, SI_ORDER_SECOND, xpt_init, NULL);
649 
650 static cam_status	xpt_compile_path(struct cam_path *new_path,
651 					 struct cam_periph *perph,
652 					 path_id_t path_id,
653 					 target_id_t target_id,
654 					 lun_id_t lun_id);
655 
656 static void		xpt_release_path(struct cam_path *path);
657 
658 static void		xpt_async_bcast(struct async_list *async_head,
659 					u_int32_t async_code,
660 					struct cam_path *path,
661 					void *async_arg);
662 static void		xpt_dev_async(u_int32_t async_code,
663 				      struct cam_eb *bus,
664 				      struct cam_et *target,
665 				      struct cam_ed *device,
666 				      void *async_arg);
667 static path_id_t xptnextfreepathid(void);
668 static path_id_t xptpathid(const char *sim_name, int sim_unit, int sim_bus);
669 static union ccb *xpt_get_ccb(struct cam_ed *device);
670 static int	 xpt_schedule_dev(struct camq *queue, cam_pinfo *dev_pinfo,
671 				  u_int32_t new_priority);
672 static void	 xpt_run_dev_allocq(struct cam_eb *bus);
673 static void	 xpt_run_dev_sendq(struct cam_eb *bus);
674 static timeout_t xpt_release_devq_timeout;
675 static void	 xpt_release_bus(struct cam_eb *bus);
676 static void	 xpt_release_devq_device(struct cam_ed *dev, u_int count,
677 					 int run_queue);
678 static struct cam_et*
679 		 xpt_alloc_target(struct cam_eb *bus, target_id_t target_id);
680 static void	 xpt_release_target(struct cam_eb *bus, struct cam_et *target);
681 static struct cam_ed*
682 		 xpt_alloc_device(struct cam_eb *bus, struct cam_et *target,
683 				  lun_id_t lun_id);
684 static void	 xpt_release_device(struct cam_eb *bus, struct cam_et *target,
685 				    struct cam_ed *device);
686 static u_int32_t xpt_dev_ccbq_resize(struct cam_path *path, int newopenings);
687 static struct cam_eb*
688 		 xpt_find_bus(path_id_t path_id);
689 static struct cam_et*
690 		 xpt_find_target(struct cam_eb *bus, target_id_t target_id);
691 static struct cam_ed*
692 		 xpt_find_device(struct cam_et *target, lun_id_t lun_id);
693 static void	 xpt_scan_bus(struct cam_periph *periph, union ccb *ccb);
694 static void	 xpt_scan_lun(struct cam_periph *periph,
695 			      struct cam_path *path, cam_flags flags,
696 			      union ccb *ccb);
697 static void	 xptscandone(struct cam_periph *periph, union ccb *done_ccb);
698 static xpt_busfunc_t	xptconfigbuscountfunc;
699 static xpt_busfunc_t	xptconfigfunc;
700 static void	 xpt_config(void *arg);
701 static xpt_devicefunc_t xptpassannouncefunc;
702 static void	 xpt_finishconfig(struct cam_periph *periph, union ccb *ccb);
703 static void	 xptaction(struct cam_sim *sim, union ccb *work_ccb);
704 static void	 xptpoll(struct cam_sim *sim);
705 static inthand2_t swi_camnet;
706 static inthand2_t swi_cambio;
707 static void	 camisr(cam_isrq_t *queue);
708 #if 0
709 static void	 xptstart(struct cam_periph *periph, union ccb *work_ccb);
710 static void	 xptasync(struct cam_periph *periph,
711 			  u_int32_t code, cam_path *path);
712 #endif
713 static dev_match_ret	xptbusmatch(struct dev_match_pattern *patterns,
714 				    int num_patterns, struct cam_eb *bus);
715 static dev_match_ret	xptdevicematch(struct dev_match_pattern *patterns,
716 				       int num_patterns, struct cam_ed *device);
717 static dev_match_ret	xptperiphmatch(struct dev_match_pattern *patterns,
718 				       int num_patterns,
719 				       struct cam_periph *periph);
720 static xpt_busfunc_t	xptedtbusfunc;
721 static xpt_targetfunc_t	xptedttargetfunc;
722 static xpt_devicefunc_t	xptedtdevicefunc;
723 static xpt_periphfunc_t	xptedtperiphfunc;
724 static xpt_pdrvfunc_t	xptplistpdrvfunc;
725 static xpt_periphfunc_t	xptplistperiphfunc;
726 static int		xptedtmatch(struct ccb_dev_match *cdm);
727 static int		xptperiphlistmatch(struct ccb_dev_match *cdm);
728 static int		xptbustraverse(struct cam_eb *start_bus,
729 				       xpt_busfunc_t *tr_func, void *arg);
730 static int		xpttargettraverse(struct cam_eb *bus,
731 					  struct cam_et *start_target,
732 					  xpt_targetfunc_t *tr_func, void *arg);
733 static int		xptdevicetraverse(struct cam_et *target,
734 					  struct cam_ed *start_device,
735 					  xpt_devicefunc_t *tr_func, void *arg);
736 static int		xptperiphtraverse(struct cam_ed *device,
737 					  struct cam_periph *start_periph,
738 					  xpt_periphfunc_t *tr_func, void *arg);
739 static int		xptpdrvtraverse(struct periph_driver **start_pdrv,
740 					xpt_pdrvfunc_t *tr_func, void *arg);
741 static int		xptpdperiphtraverse(struct periph_driver **pdrv,
742 					    struct cam_periph *start_periph,
743 					    xpt_periphfunc_t *tr_func,
744 					    void *arg);
745 static xpt_busfunc_t	xptdefbusfunc;
746 static xpt_targetfunc_t	xptdeftargetfunc;
747 static xpt_devicefunc_t	xptdefdevicefunc;
748 static xpt_periphfunc_t	xptdefperiphfunc;
749 static int		xpt_for_all_busses(xpt_busfunc_t *tr_func, void *arg);
750 #ifdef notusedyet
751 static int		xpt_for_all_targets(xpt_targetfunc_t *tr_func,
752 					    void *arg);
753 #endif
754 static int		xpt_for_all_devices(xpt_devicefunc_t *tr_func,
755 					    void *arg);
756 #ifdef notusedyet
757 static int		xpt_for_all_periphs(xpt_periphfunc_t *tr_func,
758 					    void *arg);
759 #endif
760 static xpt_devicefunc_t	xptsetasyncfunc;
761 static xpt_busfunc_t	xptsetasyncbusfunc;
762 static cam_status	xptregister(struct cam_periph *periph,
763 				    void *arg);
764 static cam_status	proberegister(struct cam_periph *periph,
765 				      void *arg);
766 static void	 probeschedule(struct cam_periph *probe_periph);
767 static void	 probestart(struct cam_periph *periph, union ccb *start_ccb);
768 static void	 proberequestdefaultnegotiation(struct cam_periph *periph);
769 static void	 probedone(struct cam_periph *periph, union ccb *done_ccb);
770 static void	 probecleanup(struct cam_periph *periph);
771 static void	 xpt_find_quirk(struct cam_ed *device);
772 static void	 xpt_set_transfer_settings(struct ccb_trans_settings *cts,
773 					   struct cam_ed *device,
774 					   int async_update);
775 static void	 xpt_toggle_tags(struct cam_path *path);
776 static void	 xpt_start_tags(struct cam_path *path);
777 static __inline int xpt_schedule_dev_allocq(struct cam_eb *bus,
778 					    struct cam_ed *dev);
779 static __inline int xpt_schedule_dev_sendq(struct cam_eb *bus,
780 					   struct cam_ed *dev);
781 static __inline int periph_is_queued(struct cam_periph *periph);
782 static __inline int device_is_alloc_queued(struct cam_ed *device);
783 static __inline int device_is_send_queued(struct cam_ed *device);
784 static __inline int dev_allocq_is_runnable(struct cam_devq *devq);
785 
786 static __inline int
787 xpt_schedule_dev_allocq(struct cam_eb *bus, struct cam_ed *dev)
788 {
789 	int retval;
790 
791 	if (bus->sim->devq && dev->ccbq.devq_openings > 0) {
792 		if ((dev->flags & CAM_DEV_RESIZE_QUEUE_NEEDED) != 0) {
793 			cam_ccbq_resize(&dev->ccbq,
794 					dev->ccbq.dev_openings
795 					+ dev->ccbq.dev_active);
796 			dev->flags &= ~CAM_DEV_RESIZE_QUEUE_NEEDED;
797 		}
798 		/*
799 		 * The priority of a device waiting for CCB resources
800 		 * is that of the the highest priority peripheral driver
801 		 * enqueued.
802 		 */
803 		retval = xpt_schedule_dev(&bus->sim->devq->alloc_queue,
804 					  &dev->alloc_ccb_entry.pinfo,
805 					  CAMQ_GET_HEAD(&dev->drvq)->priority);
806 	} else {
807 		retval = 0;
808 	}
809 
810 	return (retval);
811 }
812 
813 static __inline int
814 xpt_schedule_dev_sendq(struct cam_eb *bus, struct cam_ed *dev)
815 {
816 	int	retval;
817 
818 	if (bus->sim->devq && dev->ccbq.dev_openings > 0) {
819 		/*
820 		 * The priority of a device waiting for controller
821 		 * resources is that of the the highest priority CCB
822 		 * enqueued.
823 		 */
824 		retval =
825 		    xpt_schedule_dev(&bus->sim->devq->send_queue,
826 				     &dev->send_ccb_entry.pinfo,
827 				     CAMQ_GET_HEAD(&dev->ccbq.queue)->priority);
828 	} else {
829 		retval = 0;
830 	}
831 	return (retval);
832 }
833 
834 static __inline int
835 periph_is_queued(struct cam_periph *periph)
836 {
837 	return (periph->pinfo.index != CAM_UNQUEUED_INDEX);
838 }
839 
840 static __inline int
841 device_is_alloc_queued(struct cam_ed *device)
842 {
843 	return (device->alloc_ccb_entry.pinfo.index != CAM_UNQUEUED_INDEX);
844 }
845 
846 static __inline int
847 device_is_send_queued(struct cam_ed *device)
848 {
849 	return (device->send_ccb_entry.pinfo.index != CAM_UNQUEUED_INDEX);
850 }
851 
852 static __inline int
853 dev_allocq_is_runnable(struct cam_devq *devq)
854 {
855 	/*
856 	 * Have work to do.
857 	 * Have space to do more work.
858 	 * Allowed to do work.
859 	 */
860 	return ((devq->alloc_queue.qfrozen_cnt == 0)
861 	     && (devq->alloc_queue.entries > 0)
862 	     && (devq->alloc_openings > 0));
863 }
864 
865 static void
866 xpt_periph_init(void)
867 {
868 	dev_ops_add(&xpt_ops, 0, 0);
869 	make_dev(&xpt_ops, 0, UID_ROOT, GID_OPERATOR, 0600, "xpt0");
870 }
871 
872 static void
873 probe_periph_init(void)
874 {
875 }
876 
877 
878 static void
879 xptdone(struct cam_periph *periph, union ccb *done_ccb)
880 {
881 	/* Caller will release the CCB */
882 	wakeup(&done_ccb->ccb_h.cbfcnp);
883 }
884 
885 static int
886 xptopen(struct dev_open_args *ap)
887 {
888 	cdev_t dev = ap->a_head.a_dev;
889 	int unit;
890 
891 	unit = minor(dev) & 0xff;
892 
893 	/*
894 	 * Only allow read-write access.
895 	 */
896 	if (((ap->a_oflags & FWRITE) == 0) || ((ap->a_oflags & FREAD) == 0))
897 		return(EPERM);
898 
899 	/*
900 	 * We don't allow nonblocking access.
901 	 */
902 	if ((ap->a_oflags & O_NONBLOCK) != 0) {
903 		kprintf("xpt%d: can't do nonblocking access\n", unit);
904 		return(ENODEV);
905 	}
906 
907 	/*
908 	 * We only have one transport layer right now.  If someone accesses
909 	 * us via something other than minor number 1, point out their
910 	 * mistake.
911 	 */
912 	if (unit != 0) {
913 		kprintf("xptopen: got invalid xpt unit %d\n", unit);
914 		return(ENXIO);
915 	}
916 
917 	/* Mark ourselves open */
918 	xsoftc.flags |= XPT_FLAG_OPEN;
919 
920 	return(0);
921 }
922 
923 static int
924 xptclose(struct dev_close_args *ap)
925 {
926 	cdev_t dev = ap->a_head.a_dev;
927 	int unit;
928 
929 	unit = minor(dev) & 0xff;
930 
931 	/*
932 	 * We only have one transport layer right now.  If someone accesses
933 	 * us via something other than minor number 1, point out their
934 	 * mistake.
935 	 */
936 	if (unit != 0) {
937 		kprintf("xptclose: got invalid xpt unit %d\n", unit);
938 		return(ENXIO);
939 	}
940 
941 	/* Mark ourselves closed */
942 	xsoftc.flags &= ~XPT_FLAG_OPEN;
943 
944 	return(0);
945 }
946 
947 static int
948 xptioctl(struct dev_ioctl_args *ap)
949 {
950 	cdev_t dev = ap->a_head.a_dev;
951 	int unit, error;
952 
953 	error = 0;
954 	unit = minor(dev) & 0xff;
955 
956 	/*
957 	 * We only have one transport layer right now.  If someone accesses
958 	 * us via something other than minor number 1, point out their
959 	 * mistake.
960 	 */
961 	if (unit != 0) {
962 		kprintf("xptioctl: got invalid xpt unit %d\n", unit);
963 		return(ENXIO);
964 	}
965 
966 	switch(ap->a_cmd) {
967 	/*
968 	 * For the transport layer CAMIOCOMMAND ioctl, we really only want
969 	 * to accept CCB types that don't quite make sense to send through a
970 	 * passthrough driver.
971 	 */
972 	case CAMIOCOMMAND: {
973 		union ccb *ccb;
974 		union ccb *inccb;
975 
976 		inccb = (union ccb *)ap->a_data;
977 
978 		switch(inccb->ccb_h.func_code) {
979 		case XPT_SCAN_BUS:
980 		case XPT_RESET_BUS:
981 			if ((inccb->ccb_h.target_id != CAM_TARGET_WILDCARD)
982 			 || (inccb->ccb_h.target_lun != CAM_LUN_WILDCARD)) {
983 				error = EINVAL;
984 				break;
985 			}
986 			/* FALLTHROUGH */
987 		case XPT_PATH_INQ:
988 		case XPT_ENG_INQ:
989 		case XPT_SCAN_LUN:
990 
991 			ccb = xpt_alloc_ccb();
992 
993 			/*
994 			 * Create a path using the bus, target, and lun the
995 			 * user passed in.
996 			 */
997 			if (xpt_create_path(&ccb->ccb_h.path, xpt_periph,
998 					    inccb->ccb_h.path_id,
999 					    inccb->ccb_h.target_id,
1000 					    inccb->ccb_h.target_lun) !=
1001 					    CAM_REQ_CMP){
1002 				error = EINVAL;
1003 				xpt_free_ccb(ccb);
1004 				break;
1005 			}
1006 			/* Ensure all of our fields are correct */
1007 			xpt_setup_ccb(&ccb->ccb_h, ccb->ccb_h.path,
1008 				      inccb->ccb_h.pinfo.priority);
1009 			xpt_merge_ccb(ccb, inccb);
1010 			ccb->ccb_h.cbfcnp = xptdone;
1011 			cam_periph_runccb(ccb, NULL, 0, 0, NULL);
1012 			bcopy(ccb, inccb, sizeof(union ccb));
1013 			xpt_free_path(ccb->ccb_h.path);
1014 			xpt_free_ccb(ccb);
1015 			break;
1016 
1017 		case XPT_DEBUG: {
1018 			union ccb ccb;
1019 
1020 			/*
1021 			 * This is an immediate CCB, so it's okay to
1022 			 * allocate it on the stack.
1023 			 */
1024 
1025 			/*
1026 			 * Create a path using the bus, target, and lun the
1027 			 * user passed in.
1028 			 */
1029 			if (xpt_create_path(&ccb.ccb_h.path, xpt_periph,
1030 					    inccb->ccb_h.path_id,
1031 					    inccb->ccb_h.target_id,
1032 					    inccb->ccb_h.target_lun) !=
1033 					    CAM_REQ_CMP){
1034 				error = EINVAL;
1035 				break;
1036 			}
1037 			/* Ensure all of our fields are correct */
1038 			xpt_setup_ccb(&ccb.ccb_h, ccb.ccb_h.path,
1039 				      inccb->ccb_h.pinfo.priority);
1040 			xpt_merge_ccb(&ccb, inccb);
1041 			ccb.ccb_h.cbfcnp = xptdone;
1042 			xpt_action(&ccb);
1043 			bcopy(&ccb, inccb, sizeof(union ccb));
1044 			xpt_free_path(ccb.ccb_h.path);
1045 			break;
1046 
1047 		}
1048 		case XPT_DEV_MATCH: {
1049 			struct cam_periph_map_info mapinfo;
1050 			struct cam_path *old_path;
1051 
1052 			/*
1053 			 * We can't deal with physical addresses for this
1054 			 * type of transaction.
1055 			 */
1056 			if (inccb->ccb_h.flags & CAM_DATA_PHYS) {
1057 				error = EINVAL;
1058 				break;
1059 			}
1060 
1061 			/*
1062 			 * Save this in case the caller had it set to
1063 			 * something in particular.
1064 			 */
1065 			old_path = inccb->ccb_h.path;
1066 
1067 			/*
1068 			 * We really don't need a path for the matching
1069 			 * code.  The path is needed because of the
1070 			 * debugging statements in xpt_action().  They
1071 			 * assume that the CCB has a valid path.
1072 			 */
1073 			inccb->ccb_h.path = xpt_periph->path;
1074 
1075 			bzero(&mapinfo, sizeof(mapinfo));
1076 
1077 			/*
1078 			 * Map the pattern and match buffers into kernel
1079 			 * virtual address space.
1080 			 */
1081 			error = cam_periph_mapmem(inccb, &mapinfo);
1082 
1083 			if (error) {
1084 				inccb->ccb_h.path = old_path;
1085 				break;
1086 			}
1087 
1088 			/*
1089 			 * This is an immediate CCB, we can send it on directly.
1090 			 */
1091 			xpt_action(inccb);
1092 
1093 			/*
1094 			 * Map the buffers back into user space.
1095 			 */
1096 			cam_periph_unmapmem(inccb, &mapinfo);
1097 
1098 			inccb->ccb_h.path = old_path;
1099 
1100 			error = 0;
1101 			break;
1102 		}
1103 		default:
1104 			error = ENOTSUP;
1105 			break;
1106 		}
1107 		break;
1108 	}
1109 	/*
1110 	 * This is the getpassthru ioctl. It takes a XPT_GDEVLIST ccb as input,
1111 	 * with the periphal driver name and unit name filled in.  The other
1112 	 * fields don't really matter as input.  The passthrough driver name
1113 	 * ("pass"), and unit number are passed back in the ccb.  The current
1114 	 * device generation number, and the index into the device peripheral
1115 	 * driver list, and the status are also passed back.  Note that
1116 	 * since we do everything in one pass, unlike the XPT_GDEVLIST ccb,
1117 	 * we never return a status of CAM_GDEVLIST_LIST_CHANGED.  It is
1118 	 * (or rather should be) impossible for the device peripheral driver
1119 	 * list to change since we look at the whole thing in one pass, and
1120 	 * we do it within a critical section.
1121 	 *
1122 	 */
1123 	case CAMGETPASSTHRU: {
1124 		union ccb *ccb;
1125 		struct cam_periph *periph;
1126 		struct periph_driver **p_drv;
1127 		char   *name;
1128 		int unit;
1129 		int cur_generation;
1130 		int base_periph_found;
1131 		int splbreaknum;
1132 
1133 		ccb = (union ccb *)ap->a_data;
1134 		unit = ccb->cgdl.unit_number;
1135 		name = ccb->cgdl.periph_name;
1136 		/*
1137 		 * Every 100 devices, we want to call splz() to check for
1138 		 * and allow the software interrupt handler a chance to run.
1139 		 *
1140 		 * Most systems won't run into this check, but this should
1141 		 * avoid starvation in the software interrupt handler in
1142 		 * large systems.
1143 		 */
1144 		splbreaknum = 100;
1145 
1146 		ccb = (union ccb *)ap->a_data;
1147 
1148 		base_periph_found = 0;
1149 
1150 		/*
1151 		 * Sanity check -- make sure we don't get a null peripheral
1152 		 * driver name.
1153 		 */
1154 		if (*ccb->cgdl.periph_name == '\0') {
1155 			error = EINVAL;
1156 			break;
1157 		}
1158 
1159 		/* Keep the list from changing while we traverse it */
1160 		crit_enter();
1161 ptstartover:
1162 		cur_generation = xsoftc.generation;
1163 
1164 		/* first find our driver in the list of drivers */
1165 		SET_FOREACH(p_drv, periphdriver_set) {
1166 			if (strcmp((*p_drv)->driver_name, name) == 0)
1167 				break;
1168 		}
1169 
1170 		if (*p_drv == NULL) {
1171 			crit_exit();
1172 			ccb->ccb_h.status = CAM_REQ_CMP_ERR;
1173 			ccb->cgdl.status = CAM_GDEVLIST_ERROR;
1174 			*ccb->cgdl.periph_name = '\0';
1175 			ccb->cgdl.unit_number = 0;
1176 			error = ENOENT;
1177 			break;
1178 		}
1179 
1180 		/*
1181 		 * Run through every peripheral instance of this driver
1182 		 * and check to see whether it matches the unit passed
1183 		 * in by the user.  If it does, get out of the loops and
1184 		 * find the passthrough driver associated with that
1185 		 * peripheral driver.
1186 		 */
1187 		for (periph = TAILQ_FIRST(&(*p_drv)->units); periph != NULL;
1188 		     periph = TAILQ_NEXT(periph, unit_links)) {
1189 
1190 			if (periph->unit_number == unit) {
1191 				break;
1192 			} else if (--splbreaknum == 0) {
1193 				splz();
1194 				splbreaknum = 100;
1195 				if (cur_generation != xsoftc.generation)
1196 				       goto ptstartover;
1197 			}
1198 		}
1199 		/*
1200 		 * If we found the peripheral driver that the user passed
1201 		 * in, go through all of the peripheral drivers for that
1202 		 * particular device and look for a passthrough driver.
1203 		 */
1204 		if (periph != NULL) {
1205 			struct cam_ed *device;
1206 			int i;
1207 
1208 			base_periph_found = 1;
1209 			device = periph->path->device;
1210 			for (i = 0, periph = device->periphs.slh_first;
1211 			     periph != NULL;
1212 			     periph = periph->periph_links.sle_next, i++) {
1213 				/*
1214 				 * Check to see whether we have a
1215 				 * passthrough device or not.
1216 				 */
1217 				if (strcmp(periph->periph_name, "pass") == 0) {
1218 					/*
1219 					 * Fill in the getdevlist fields.
1220 					 */
1221 					strcpy(ccb->cgdl.periph_name,
1222 					       periph->periph_name);
1223 					ccb->cgdl.unit_number =
1224 						periph->unit_number;
1225 					if (periph->periph_links.sle_next)
1226 						ccb->cgdl.status =
1227 							CAM_GDEVLIST_MORE_DEVS;
1228 					else
1229 						ccb->cgdl.status =
1230 						       CAM_GDEVLIST_LAST_DEVICE;
1231 					ccb->cgdl.generation =
1232 						device->generation;
1233 					ccb->cgdl.index = i;
1234 					/*
1235 					 * Fill in some CCB header fields
1236 					 * that the user may want.
1237 					 */
1238 					ccb->ccb_h.path_id =
1239 						periph->path->bus->path_id;
1240 					ccb->ccb_h.target_id =
1241 						periph->path->target->target_id;
1242 					ccb->ccb_h.target_lun =
1243 						periph->path->device->lun_id;
1244 					ccb->ccb_h.status = CAM_REQ_CMP;
1245 					break;
1246 				}
1247 			}
1248 		}
1249 
1250 		/*
1251 		 * If the periph is null here, one of two things has
1252 		 * happened.  The first possibility is that we couldn't
1253 		 * find the unit number of the particular peripheral driver
1254 		 * that the user is asking about.  e.g. the user asks for
1255 		 * the passthrough driver for "da11".  We find the list of
1256 		 * "da" peripherals all right, but there is no unit 11.
1257 		 * The other possibility is that we went through the list
1258 		 * of peripheral drivers attached to the device structure,
1259 		 * but didn't find one with the name "pass".  Either way,
1260 		 * we return ENOENT, since we couldn't find something.
1261 		 */
1262 		if (periph == NULL) {
1263 			ccb->ccb_h.status = CAM_REQ_CMP_ERR;
1264 			ccb->cgdl.status = CAM_GDEVLIST_ERROR;
1265 			*ccb->cgdl.periph_name = '\0';
1266 			ccb->cgdl.unit_number = 0;
1267 			error = ENOENT;
1268 			/*
1269 			 * It is unfortunate that this is even necessary,
1270 			 * but there are many, many clueless users out there.
1271 			 * If this is true, the user is looking for the
1272 			 * passthrough driver, but doesn't have one in his
1273 			 * kernel.
1274 			 */
1275 			if (base_periph_found == 1) {
1276 				kprintf("xptioctl: pass driver is not in the "
1277 				       "kernel\n");
1278 				kprintf("xptioctl: put \"device pass0\" in "
1279 				       "your kernel config file\n");
1280 			}
1281 		}
1282 		crit_exit();
1283 		break;
1284 		}
1285 	default:
1286 		error = ENOTTY;
1287 		break;
1288 	}
1289 
1290 	return(error);
1291 }
1292 
1293 /* Functions accessed by the peripheral drivers */
1294 static void
1295 xpt_init(void *dummy)
1296 {
1297 	struct cam_sim *xpt_sim;
1298 	struct cam_path *path;
1299 	struct cam_devq *devq;
1300 	cam_status status;
1301 
1302 	TAILQ_INIT(&xpt_busses);
1303 	TAILQ_INIT(&cam_bioq);
1304 	TAILQ_INIT(&cam_netq);
1305 	SLIST_INIT(&ccb_freeq);
1306 	STAILQ_INIT(&highpowerq);
1307 
1308 	/*
1309 	 * The xpt layer is, itself, the equivelent of a SIM.
1310 	 * Allow 16 ccbs in the ccb pool for it.  This should
1311 	 * give decent parallelism when we probe busses and
1312 	 * perform other XPT functions.
1313 	 */
1314 	devq = cam_simq_alloc(16);
1315 	xpt_sim = cam_sim_alloc(xptaction,
1316 				xptpoll,
1317 				"xpt",
1318 				/*softc*/NULL,
1319 				/*unit*/0,
1320 				/*max_dev_transactions*/0,
1321 				/*max_tagged_dev_transactions*/0,
1322 				devq);
1323 	cam_simq_release(devq);
1324 	xpt_max_ccbs = 16;
1325 
1326 	xpt_bus_register(xpt_sim, /*bus #*/0);
1327 
1328 	/*
1329 	 * Looking at the XPT from the SIM layer, the XPT is
1330 	 * the equivelent of a peripheral driver.  Allocate
1331 	 * a peripheral driver entry for us.
1332 	 */
1333 	if ((status = xpt_create_path(&path, NULL, CAM_XPT_PATH_ID,
1334 				      CAM_TARGET_WILDCARD,
1335 				      CAM_LUN_WILDCARD)) != CAM_REQ_CMP) {
1336 		kprintf("xpt_init: xpt_create_path failed with status %#x,"
1337 		       " failing attach\n", status);
1338 		return;
1339 	}
1340 
1341 	cam_periph_alloc(xptregister, NULL, NULL, NULL, "xpt", CAM_PERIPH_BIO,
1342 			 path, NULL, 0, NULL);
1343 	xpt_free_path(path);
1344 
1345 	xpt_sim->softc = xpt_periph;
1346 
1347 	/*
1348 	 * Register a callback for when interrupts are enabled.
1349 	 */
1350 	xpt_config_hook = kmalloc(sizeof(struct intr_config_hook),
1351 				  M_TEMP, M_INTWAIT | M_ZERO);
1352 	xpt_config_hook->ich_func = xpt_config;
1353 	xpt_config_hook->ich_desc = "xpt";
1354 	if (config_intrhook_establish(xpt_config_hook) != 0) {
1355 		kfree (xpt_config_hook, M_TEMP);
1356 		kprintf("xpt_init: config_intrhook_establish failed "
1357 		       "- failing attach\n");
1358 	}
1359 
1360 	/* Install our software interrupt handlers */
1361 	register_swi(SWI_CAMNET, swi_camnet, NULL, "swi_camnet", NULL);
1362 	register_swi(SWI_CAMBIO, swi_cambio, NULL, "swi_cambio", NULL);
1363 }
1364 
1365 static cam_status
1366 xptregister(struct cam_periph *periph, void *arg)
1367 {
1368 	if (periph == NULL) {
1369 		kprintf("xptregister: periph was NULL!!\n");
1370 		return(CAM_REQ_CMP_ERR);
1371 	}
1372 
1373 	periph->softc = NULL;
1374 
1375 	xpt_periph = periph;
1376 
1377 	return(CAM_REQ_CMP);
1378 }
1379 
1380 int32_t
1381 xpt_add_periph(struct cam_periph *periph)
1382 {
1383 	struct cam_ed *device;
1384 	int32_t	 status;
1385 	struct periph_list *periph_head;
1386 
1387 	device = periph->path->device;
1388 
1389 	periph_head = &device->periphs;
1390 
1391 	status = CAM_REQ_CMP;
1392 
1393 	if (device != NULL) {
1394 		/*
1395 		 * Make room for this peripheral
1396 		 * so it will fit in the queue
1397 		 * when it's scheduled to run
1398 		 */
1399 		crit_enter();
1400 		status = camq_resize(&device->drvq,
1401 				     device->drvq.array_size + 1);
1402 
1403 		device->generation++;
1404 
1405 		SLIST_INSERT_HEAD(periph_head, periph, periph_links);
1406 		crit_exit();
1407 	}
1408 
1409 	xsoftc.generation++;
1410 
1411 	return (status);
1412 }
1413 
1414 void
1415 xpt_remove_periph(struct cam_periph *periph)
1416 {
1417 	struct cam_ed *device;
1418 
1419 	device = periph->path->device;
1420 
1421 	if (device != NULL) {
1422 		struct periph_list *periph_head;
1423 
1424 		periph_head = &device->periphs;
1425 
1426 		/* Release the slot for this peripheral */
1427 		crit_enter();
1428 		camq_resize(&device->drvq, device->drvq.array_size - 1);
1429 
1430 		device->generation++;
1431 
1432 		SLIST_REMOVE(periph_head, periph, cam_periph, periph_links);
1433 		crit_exit();
1434 	}
1435 
1436 	xsoftc.generation++;
1437 
1438 }
1439 
1440 void
1441 xpt_announce_periph(struct cam_periph *periph, char *announce_string)
1442 {
1443 	u_int mb;
1444 	struct cam_path *path;
1445 	struct ccb_trans_settings cts;
1446 
1447 	path = periph->path;
1448 	/*
1449 	 * To ensure that this is printed in one piece,
1450 	 * mask out CAM interrupts.
1451 	 */
1452 	crit_enter();
1453 	kprintf("%s%d at %s%d bus %d target %d lun %d\n",
1454 	       periph->periph_name, periph->unit_number,
1455 	       path->bus->sim->sim_name,
1456 	       path->bus->sim->unit_number,
1457 	       path->bus->sim->bus_id,
1458 	       path->target->target_id,
1459 	       path->device->lun_id);
1460 	kprintf("%s%d: ", periph->periph_name, periph->unit_number);
1461 	scsi_print_inquiry(&path->device->inq_data);
1462 	if ((bootverbose)
1463 	 && (path->device->serial_num_len > 0)) {
1464 		/* Don't wrap the screen  - print only the first 60 chars */
1465 		kprintf("%s%d: Serial Number %.60s\n", periph->periph_name,
1466 		       periph->unit_number, path->device->serial_num);
1467 	}
1468 	xpt_setup_ccb(&cts.ccb_h, path, /*priority*/1);
1469 	cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
1470 	cts.flags = CCB_TRANS_CURRENT_SETTINGS;
1471 	xpt_action((union ccb*)&cts);
1472 	if (cts.ccb_h.status == CAM_REQ_CMP) {
1473 		u_int speed;
1474 		u_int freq;
1475 
1476 		if ((cts.valid & CCB_TRANS_SYNC_OFFSET_VALID) != 0
1477 		  && cts.sync_offset != 0) {
1478 			freq = scsi_calc_syncsrate(cts.sync_period);
1479 			speed = freq;
1480 		} else {
1481 			struct ccb_pathinq cpi;
1482 
1483 			/* Ask the SIM for its base transfer speed */
1484 			xpt_setup_ccb(&cpi.ccb_h, path, /*priority*/1);
1485 			cpi.ccb_h.func_code = XPT_PATH_INQ;
1486 			xpt_action((union ccb *)&cpi);
1487 
1488 			speed = cpi.base_transfer_speed;
1489 			freq = 0;
1490 		}
1491 		if ((cts.valid & CCB_TRANS_BUS_WIDTH_VALID) != 0)
1492 			speed *= (0x01 << cts.bus_width);
1493 		mb = speed / 1000;
1494 		if (mb > 0)
1495 			kprintf("%s%d: %d.%03dMB/s transfers",
1496 			       periph->periph_name, periph->unit_number,
1497 			       mb, speed % 1000);
1498 		else
1499 			kprintf("%s%d: %dKB/s transfers", periph->periph_name,
1500 			       periph->unit_number, speed);
1501 		if ((cts.valid & CCB_TRANS_SYNC_OFFSET_VALID) != 0
1502 		 && cts.sync_offset != 0) {
1503 			kprintf(" (%d.%03dMHz, offset %d", freq / 1000,
1504 			       freq % 1000, cts.sync_offset);
1505 		}
1506 		if ((cts.valid & CCB_TRANS_BUS_WIDTH_VALID) != 0
1507 		 && cts.bus_width > 0) {
1508 			if ((cts.valid & CCB_TRANS_SYNC_OFFSET_VALID) != 0
1509 			 && cts.sync_offset != 0) {
1510 				kprintf(", ");
1511 			} else {
1512 				kprintf(" (");
1513 			}
1514 			kprintf("%dbit)", 8 * (0x01 << cts.bus_width));
1515 		} else if ((cts.valid & CCB_TRANS_SYNC_OFFSET_VALID) != 0
1516 			&& cts.sync_offset != 0) {
1517 			kprintf(")");
1518 		}
1519 
1520 		if (path->device->inq_flags & SID_CmdQue
1521 		 || path->device->flags & CAM_DEV_TAG_AFTER_COUNT) {
1522 			kprintf(", Tagged Queueing Enabled");
1523 		}
1524 
1525 		kprintf("\n");
1526 	} else if (path->device->inq_flags & SID_CmdQue
1527    		|| path->device->flags & CAM_DEV_TAG_AFTER_COUNT) {
1528 		kprintf("%s%d: Tagged Queueing Enabled\n",
1529 		       periph->periph_name, periph->unit_number);
1530 	}
1531 
1532 	/*
1533 	 * We only want to print the caller's announce string if they've
1534 	 * passed one in..
1535 	 */
1536 	if (announce_string != NULL)
1537 		kprintf("%s%d: %s\n", periph->periph_name,
1538 		       periph->unit_number, announce_string);
1539 	crit_exit();
1540 }
1541 
1542 
1543 static dev_match_ret
1544 xptbusmatch(struct dev_match_pattern *patterns, int num_patterns,
1545 	    struct cam_eb *bus)
1546 {
1547 	dev_match_ret retval;
1548 	int i;
1549 
1550 	retval = DM_RET_NONE;
1551 
1552 	/*
1553 	 * If we aren't given something to match against, that's an error.
1554 	 */
1555 	if (bus == NULL)
1556 		return(DM_RET_ERROR);
1557 
1558 	/*
1559 	 * If there are no match entries, then this bus matches no
1560 	 * matter what.
1561 	 */
1562 	if ((patterns == NULL) || (num_patterns == 0))
1563 		return(DM_RET_DESCEND | DM_RET_COPY);
1564 
1565 	for (i = 0; i < num_patterns; i++) {
1566 		struct bus_match_pattern *cur_pattern;
1567 
1568 		/*
1569 		 * If the pattern in question isn't for a bus node, we
1570 		 * aren't interested.  However, we do indicate to the
1571 		 * calling routine that we should continue descending the
1572 		 * tree, since the user wants to match against lower-level
1573 		 * EDT elements.
1574 		 */
1575 		if (patterns[i].type != DEV_MATCH_BUS) {
1576 			if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1577 				retval |= DM_RET_DESCEND;
1578 			continue;
1579 		}
1580 
1581 		cur_pattern = &patterns[i].pattern.bus_pattern;
1582 
1583 		/*
1584 		 * If they want to match any bus node, we give them any
1585 		 * device node.
1586 		 */
1587 		if (cur_pattern->flags == BUS_MATCH_ANY) {
1588 			/* set the copy flag */
1589 			retval |= DM_RET_COPY;
1590 
1591 			/*
1592 			 * If we've already decided on an action, go ahead
1593 			 * and return.
1594 			 */
1595 			if ((retval & DM_RET_ACTION_MASK) != DM_RET_NONE)
1596 				return(retval);
1597 		}
1598 
1599 		/*
1600 		 * Not sure why someone would do this...
1601 		 */
1602 		if (cur_pattern->flags == BUS_MATCH_NONE)
1603 			continue;
1604 
1605 		if (((cur_pattern->flags & BUS_MATCH_PATH) != 0)
1606 		 && (cur_pattern->path_id != bus->path_id))
1607 			continue;
1608 
1609 		if (((cur_pattern->flags & BUS_MATCH_BUS_ID) != 0)
1610 		 && (cur_pattern->bus_id != bus->sim->bus_id))
1611 			continue;
1612 
1613 		if (((cur_pattern->flags & BUS_MATCH_UNIT) != 0)
1614 		 && (cur_pattern->unit_number != bus->sim->unit_number))
1615 			continue;
1616 
1617 		if (((cur_pattern->flags & BUS_MATCH_NAME) != 0)
1618 		 && (strncmp(cur_pattern->dev_name, bus->sim->sim_name,
1619 			     DEV_IDLEN) != 0))
1620 			continue;
1621 
1622 		/*
1623 		 * If we get to this point, the user definitely wants
1624 		 * information on this bus.  So tell the caller to copy the
1625 		 * data out.
1626 		 */
1627 		retval |= DM_RET_COPY;
1628 
1629 		/*
1630 		 * If the return action has been set to descend, then we
1631 		 * know that we've already seen a non-bus matching
1632 		 * expression, therefore we need to further descend the tree.
1633 		 * This won't change by continuing around the loop, so we
1634 		 * go ahead and return.  If we haven't seen a non-bus
1635 		 * matching expression, we keep going around the loop until
1636 		 * we exhaust the matching expressions.  We'll set the stop
1637 		 * flag once we fall out of the loop.
1638 		 */
1639 		if ((retval & DM_RET_ACTION_MASK) == DM_RET_DESCEND)
1640 			return(retval);
1641 	}
1642 
1643 	/*
1644 	 * If the return action hasn't been set to descend yet, that means
1645 	 * we haven't seen anything other than bus matching patterns.  So
1646 	 * tell the caller to stop descending the tree -- the user doesn't
1647 	 * want to match against lower level tree elements.
1648 	 */
1649 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1650 		retval |= DM_RET_STOP;
1651 
1652 	return(retval);
1653 }
1654 
1655 static dev_match_ret
1656 xptdevicematch(struct dev_match_pattern *patterns, int num_patterns,
1657 	       struct cam_ed *device)
1658 {
1659 	dev_match_ret retval;
1660 	int i;
1661 
1662 	retval = DM_RET_NONE;
1663 
1664 	/*
1665 	 * If we aren't given something to match against, that's an error.
1666 	 */
1667 	if (device == NULL)
1668 		return(DM_RET_ERROR);
1669 
1670 	/*
1671 	 * If there are no match entries, then this device matches no
1672 	 * matter what.
1673 	 */
1674 	if ((patterns == NULL) || (patterns == 0))
1675 		return(DM_RET_DESCEND | DM_RET_COPY);
1676 
1677 	for (i = 0; i < num_patterns; i++) {
1678 		struct device_match_pattern *cur_pattern;
1679 
1680 		/*
1681 		 * If the pattern in question isn't for a device node, we
1682 		 * aren't interested.
1683 		 */
1684 		if (patterns[i].type != DEV_MATCH_DEVICE) {
1685 			if ((patterns[i].type == DEV_MATCH_PERIPH)
1686 			 && ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE))
1687 				retval |= DM_RET_DESCEND;
1688 			continue;
1689 		}
1690 
1691 		cur_pattern = &patterns[i].pattern.device_pattern;
1692 
1693 		/*
1694 		 * If they want to match any device node, we give them any
1695 		 * device node.
1696 		 */
1697 		if (cur_pattern->flags == DEV_MATCH_ANY) {
1698 			/* set the copy flag */
1699 			retval |= DM_RET_COPY;
1700 
1701 
1702 			/*
1703 			 * If we've already decided on an action, go ahead
1704 			 * and return.
1705 			 */
1706 			if ((retval & DM_RET_ACTION_MASK) != DM_RET_NONE)
1707 				return(retval);
1708 		}
1709 
1710 		/*
1711 		 * Not sure why someone would do this...
1712 		 */
1713 		if (cur_pattern->flags == DEV_MATCH_NONE)
1714 			continue;
1715 
1716 		if (((cur_pattern->flags & DEV_MATCH_PATH) != 0)
1717 		 && (cur_pattern->path_id != device->target->bus->path_id))
1718 			continue;
1719 
1720 		if (((cur_pattern->flags & DEV_MATCH_TARGET) != 0)
1721 		 && (cur_pattern->target_id != device->target->target_id))
1722 			continue;
1723 
1724 		if (((cur_pattern->flags & DEV_MATCH_LUN) != 0)
1725 		 && (cur_pattern->target_lun != device->lun_id))
1726 			continue;
1727 
1728 		if (((cur_pattern->flags & DEV_MATCH_INQUIRY) != 0)
1729 		 && (cam_quirkmatch((caddr_t)&device->inq_data,
1730 				    (caddr_t)&cur_pattern->inq_pat,
1731 				    1, sizeof(cur_pattern->inq_pat),
1732 				    scsi_static_inquiry_match) == NULL))
1733 			continue;
1734 
1735 		/*
1736 		 * If we get to this point, the user definitely wants
1737 		 * information on this device.  So tell the caller to copy
1738 		 * the data out.
1739 		 */
1740 		retval |= DM_RET_COPY;
1741 
1742 		/*
1743 		 * If the return action has been set to descend, then we
1744 		 * know that we've already seen a peripheral matching
1745 		 * expression, therefore we need to further descend the tree.
1746 		 * This won't change by continuing around the loop, so we
1747 		 * go ahead and return.  If we haven't seen a peripheral
1748 		 * matching expression, we keep going around the loop until
1749 		 * we exhaust the matching expressions.  We'll set the stop
1750 		 * flag once we fall out of the loop.
1751 		 */
1752 		if ((retval & DM_RET_ACTION_MASK) == DM_RET_DESCEND)
1753 			return(retval);
1754 	}
1755 
1756 	/*
1757 	 * If the return action hasn't been set to descend yet, that means
1758 	 * we haven't seen any peripheral matching patterns.  So tell the
1759 	 * caller to stop descending the tree -- the user doesn't want to
1760 	 * match against lower level tree elements.
1761 	 */
1762 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1763 		retval |= DM_RET_STOP;
1764 
1765 	return(retval);
1766 }
1767 
1768 /*
1769  * Match a single peripheral against any number of match patterns.
1770  */
1771 static dev_match_ret
1772 xptperiphmatch(struct dev_match_pattern *patterns, int num_patterns,
1773 	       struct cam_periph *periph)
1774 {
1775 	dev_match_ret retval;
1776 	int i;
1777 
1778 	/*
1779 	 * If we aren't given something to match against, that's an error.
1780 	 */
1781 	if (periph == NULL)
1782 		return(DM_RET_ERROR);
1783 
1784 	/*
1785 	 * If there are no match entries, then this peripheral matches no
1786 	 * matter what.
1787 	 */
1788 	if ((patterns == NULL) || (num_patterns == 0))
1789 		return(DM_RET_STOP | DM_RET_COPY);
1790 
1791 	/*
1792 	 * There aren't any nodes below a peripheral node, so there's no
1793 	 * reason to descend the tree any further.
1794 	 */
1795 	retval = DM_RET_STOP;
1796 
1797 	for (i = 0; i < num_patterns; i++) {
1798 		struct periph_match_pattern *cur_pattern;
1799 
1800 		/*
1801 		 * If the pattern in question isn't for a peripheral, we
1802 		 * aren't interested.
1803 		 */
1804 		if (patterns[i].type != DEV_MATCH_PERIPH)
1805 			continue;
1806 
1807 		cur_pattern = &patterns[i].pattern.periph_pattern;
1808 
1809 		/*
1810 		 * If they want to match on anything, then we will do so.
1811 		 */
1812 		if (cur_pattern->flags == PERIPH_MATCH_ANY) {
1813 			/* set the copy flag */
1814 			retval |= DM_RET_COPY;
1815 
1816 			/*
1817 			 * We've already set the return action to stop,
1818 			 * since there are no nodes below peripherals in
1819 			 * the tree.
1820 			 */
1821 			return(retval);
1822 		}
1823 
1824 		/*
1825 		 * Not sure why someone would do this...
1826 		 */
1827 		if (cur_pattern->flags == PERIPH_MATCH_NONE)
1828 			continue;
1829 
1830 		if (((cur_pattern->flags & PERIPH_MATCH_PATH) != 0)
1831 		 && (cur_pattern->path_id != periph->path->bus->path_id))
1832 			continue;
1833 
1834 		/*
1835 		 * For the target and lun id's, we have to make sure the
1836 		 * target and lun pointers aren't NULL.  The xpt peripheral
1837 		 * has a wildcard target and device.
1838 		 */
1839 		if (((cur_pattern->flags & PERIPH_MATCH_TARGET) != 0)
1840 		 && ((periph->path->target == NULL)
1841 		 ||(cur_pattern->target_id != periph->path->target->target_id)))
1842 			continue;
1843 
1844 		if (((cur_pattern->flags & PERIPH_MATCH_LUN) != 0)
1845 		 && ((periph->path->device == NULL)
1846 		 || (cur_pattern->target_lun != periph->path->device->lun_id)))
1847 			continue;
1848 
1849 		if (((cur_pattern->flags & PERIPH_MATCH_UNIT) != 0)
1850 		 && (cur_pattern->unit_number != periph->unit_number))
1851 			continue;
1852 
1853 		if (((cur_pattern->flags & PERIPH_MATCH_NAME) != 0)
1854 		 && (strncmp(cur_pattern->periph_name, periph->periph_name,
1855 			     DEV_IDLEN) != 0))
1856 			continue;
1857 
1858 		/*
1859 		 * If we get to this point, the user definitely wants
1860 		 * information on this peripheral.  So tell the caller to
1861 		 * copy the data out.
1862 		 */
1863 		retval |= DM_RET_COPY;
1864 
1865 		/*
1866 		 * The return action has already been set to stop, since
1867 		 * peripherals don't have any nodes below them in the EDT.
1868 		 */
1869 		return(retval);
1870 	}
1871 
1872 	/*
1873 	 * If we get to this point, the peripheral that was passed in
1874 	 * doesn't match any of the patterns.
1875 	 */
1876 	return(retval);
1877 }
1878 
1879 static int
1880 xptedtbusfunc(struct cam_eb *bus, void *arg)
1881 {
1882 	struct ccb_dev_match *cdm;
1883 	dev_match_ret retval;
1884 
1885 	cdm = (struct ccb_dev_match *)arg;
1886 
1887 	/*
1888 	 * If our position is for something deeper in the tree, that means
1889 	 * that we've already seen this node.  So, we keep going down.
1890 	 */
1891 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1892 	 && (cdm->pos.cookie.bus == bus)
1893 	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1894 	 && (cdm->pos.cookie.target != NULL))
1895 		retval = DM_RET_DESCEND;
1896 	else
1897 		retval = xptbusmatch(cdm->patterns, cdm->num_patterns, bus);
1898 
1899 	/*
1900 	 * If we got an error, bail out of the search.
1901 	 */
1902 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
1903 		cdm->status = CAM_DEV_MATCH_ERROR;
1904 		return(0);
1905 	}
1906 
1907 	/*
1908 	 * If the copy flag is set, copy this bus out.
1909 	 */
1910 	if (retval & DM_RET_COPY) {
1911 		int spaceleft, j;
1912 
1913 		spaceleft = cdm->match_buf_len - (cdm->num_matches *
1914 			sizeof(struct dev_match_result));
1915 
1916 		/*
1917 		 * If we don't have enough space to put in another
1918 		 * match result, save our position and tell the
1919 		 * user there are more devices to check.
1920 		 */
1921 		if (spaceleft < sizeof(struct dev_match_result)) {
1922 			bzero(&cdm->pos, sizeof(cdm->pos));
1923 			cdm->pos.position_type =
1924 				CAM_DEV_POS_EDT | CAM_DEV_POS_BUS;
1925 
1926 			cdm->pos.cookie.bus = bus;
1927 			cdm->pos.generations[CAM_BUS_GENERATION]=
1928 				bus_generation;
1929 			cdm->status = CAM_DEV_MATCH_MORE;
1930 			return(0);
1931 		}
1932 		j = cdm->num_matches;
1933 		cdm->num_matches++;
1934 		cdm->matches[j].type = DEV_MATCH_BUS;
1935 		cdm->matches[j].result.bus_result.path_id = bus->path_id;
1936 		cdm->matches[j].result.bus_result.bus_id = bus->sim->bus_id;
1937 		cdm->matches[j].result.bus_result.unit_number =
1938 			bus->sim->unit_number;
1939 		strncpy(cdm->matches[j].result.bus_result.dev_name,
1940 			bus->sim->sim_name, DEV_IDLEN);
1941 	}
1942 
1943 	/*
1944 	 * If the user is only interested in busses, there's no
1945 	 * reason to descend to the next level in the tree.
1946 	 */
1947 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_STOP)
1948 		return(1);
1949 
1950 	/*
1951 	 * If there is a target generation recorded, check it to
1952 	 * make sure the target list hasn't changed.
1953 	 */
1954 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1955 	 && (bus == cdm->pos.cookie.bus)
1956 	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1957 	 && (cdm->pos.generations[CAM_TARGET_GENERATION] != 0)
1958 	 && (cdm->pos.generations[CAM_TARGET_GENERATION] !=
1959 	     bus->generation)) {
1960 		cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1961 		return(0);
1962 	}
1963 
1964 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1965 	 && (cdm->pos.cookie.bus == bus)
1966 	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1967 	 && (cdm->pos.cookie.target != NULL))
1968 		return(xpttargettraverse(bus,
1969 					(struct cam_et *)cdm->pos.cookie.target,
1970 					 xptedttargetfunc, arg));
1971 	else
1972 		return(xpttargettraverse(bus, NULL, xptedttargetfunc, arg));
1973 }
1974 
1975 static int
1976 xptedttargetfunc(struct cam_et *target, void *arg)
1977 {
1978 	struct ccb_dev_match *cdm;
1979 
1980 	cdm = (struct ccb_dev_match *)arg;
1981 
1982 	/*
1983 	 * If there is a device list generation recorded, check it to
1984 	 * make sure the device list hasn't changed.
1985 	 */
1986 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1987 	 && (cdm->pos.cookie.bus == target->bus)
1988 	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1989 	 && (cdm->pos.cookie.target == target)
1990 	 && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
1991 	 && (cdm->pos.generations[CAM_DEV_GENERATION] != 0)
1992 	 && (cdm->pos.generations[CAM_DEV_GENERATION] !=
1993 	     target->generation)) {
1994 		cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1995 		return(0);
1996 	}
1997 
1998 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1999 	 && (cdm->pos.cookie.bus == target->bus)
2000 	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2001 	 && (cdm->pos.cookie.target == target)
2002 	 && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
2003 	 && (cdm->pos.cookie.device != NULL))
2004 		return(xptdevicetraverse(target,
2005 					(struct cam_ed *)cdm->pos.cookie.device,
2006 					 xptedtdevicefunc, arg));
2007 	else
2008 		return(xptdevicetraverse(target, NULL, xptedtdevicefunc, arg));
2009 }
2010 
2011 static int
2012 xptedtdevicefunc(struct cam_ed *device, void *arg)
2013 {
2014 
2015 	struct ccb_dev_match *cdm;
2016 	dev_match_ret retval;
2017 
2018 	cdm = (struct ccb_dev_match *)arg;
2019 
2020 	/*
2021 	 * If our position is for something deeper in the tree, that means
2022 	 * that we've already seen this node.  So, we keep going down.
2023 	 */
2024 	if ((cdm->pos.position_type & CAM_DEV_POS_DEVICE)
2025 	 && (cdm->pos.cookie.device == device)
2026 	 && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2027 	 && (cdm->pos.cookie.periph != NULL))
2028 		retval = DM_RET_DESCEND;
2029 	else
2030 		retval = xptdevicematch(cdm->patterns, cdm->num_patterns,
2031 					device);
2032 
2033 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
2034 		cdm->status = CAM_DEV_MATCH_ERROR;
2035 		return(0);
2036 	}
2037 
2038 	/*
2039 	 * If the copy flag is set, copy this device out.
2040 	 */
2041 	if (retval & DM_RET_COPY) {
2042 		int spaceleft, j;
2043 
2044 		spaceleft = cdm->match_buf_len - (cdm->num_matches *
2045 			sizeof(struct dev_match_result));
2046 
2047 		/*
2048 		 * If we don't have enough space to put in another
2049 		 * match result, save our position and tell the
2050 		 * user there are more devices to check.
2051 		 */
2052 		if (spaceleft < sizeof(struct dev_match_result)) {
2053 			bzero(&cdm->pos, sizeof(cdm->pos));
2054 			cdm->pos.position_type =
2055 				CAM_DEV_POS_EDT | CAM_DEV_POS_BUS |
2056 				CAM_DEV_POS_TARGET | CAM_DEV_POS_DEVICE;
2057 
2058 			cdm->pos.cookie.bus = device->target->bus;
2059 			cdm->pos.generations[CAM_BUS_GENERATION]=
2060 				bus_generation;
2061 			cdm->pos.cookie.target = device->target;
2062 			cdm->pos.generations[CAM_TARGET_GENERATION] =
2063 				device->target->bus->generation;
2064 			cdm->pos.cookie.device = device;
2065 			cdm->pos.generations[CAM_DEV_GENERATION] =
2066 				device->target->generation;
2067 			cdm->status = CAM_DEV_MATCH_MORE;
2068 			return(0);
2069 		}
2070 		j = cdm->num_matches;
2071 		cdm->num_matches++;
2072 		cdm->matches[j].type = DEV_MATCH_DEVICE;
2073 		cdm->matches[j].result.device_result.path_id =
2074 			device->target->bus->path_id;
2075 		cdm->matches[j].result.device_result.target_id =
2076 			device->target->target_id;
2077 		cdm->matches[j].result.device_result.target_lun =
2078 			device->lun_id;
2079 		bcopy(&device->inq_data,
2080 		      &cdm->matches[j].result.device_result.inq_data,
2081 		      sizeof(struct scsi_inquiry_data));
2082 
2083 		/* Let the user know whether this device is unconfigured */
2084 		if (device->flags & CAM_DEV_UNCONFIGURED)
2085 			cdm->matches[j].result.device_result.flags =
2086 				DEV_RESULT_UNCONFIGURED;
2087 		else
2088 			cdm->matches[j].result.device_result.flags =
2089 				DEV_RESULT_NOFLAG;
2090 	}
2091 
2092 	/*
2093 	 * If the user isn't interested in peripherals, don't descend
2094 	 * the tree any further.
2095 	 */
2096 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_STOP)
2097 		return(1);
2098 
2099 	/*
2100 	 * If there is a peripheral list generation recorded, make sure
2101 	 * it hasn't changed.
2102 	 */
2103 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2104 	 && (device->target->bus == cdm->pos.cookie.bus)
2105 	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2106 	 && (device->target == cdm->pos.cookie.target)
2107 	 && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
2108 	 && (device == cdm->pos.cookie.device)
2109 	 && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2110 	 && (cdm->pos.generations[CAM_PERIPH_GENERATION] != 0)
2111 	 && (cdm->pos.generations[CAM_PERIPH_GENERATION] !=
2112 	     device->generation)){
2113 		cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
2114 		return(0);
2115 	}
2116 
2117 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2118 	 && (cdm->pos.cookie.bus == device->target->bus)
2119 	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2120 	 && (cdm->pos.cookie.target == device->target)
2121 	 && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
2122 	 && (cdm->pos.cookie.device == device)
2123 	 && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2124 	 && (cdm->pos.cookie.periph != NULL))
2125 		return(xptperiphtraverse(device,
2126 				(struct cam_periph *)cdm->pos.cookie.periph,
2127 				xptedtperiphfunc, arg));
2128 	else
2129 		return(xptperiphtraverse(device, NULL, xptedtperiphfunc, arg));
2130 }
2131 
2132 static int
2133 xptedtperiphfunc(struct cam_periph *periph, void *arg)
2134 {
2135 	struct ccb_dev_match *cdm;
2136 	dev_match_ret retval;
2137 
2138 	cdm = (struct ccb_dev_match *)arg;
2139 
2140 	retval = xptperiphmatch(cdm->patterns, cdm->num_patterns, periph);
2141 
2142 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
2143 		cdm->status = CAM_DEV_MATCH_ERROR;
2144 		return(0);
2145 	}
2146 
2147 	/*
2148 	 * If the copy flag is set, copy this peripheral out.
2149 	 */
2150 	if (retval & DM_RET_COPY) {
2151 		int spaceleft, j;
2152 
2153 		spaceleft = cdm->match_buf_len - (cdm->num_matches *
2154 			sizeof(struct dev_match_result));
2155 
2156 		/*
2157 		 * If we don't have enough space to put in another
2158 		 * match result, save our position and tell the
2159 		 * user there are more devices to check.
2160 		 */
2161 		if (spaceleft < sizeof(struct dev_match_result)) {
2162 			bzero(&cdm->pos, sizeof(cdm->pos));
2163 			cdm->pos.position_type =
2164 				CAM_DEV_POS_EDT | CAM_DEV_POS_BUS |
2165 				CAM_DEV_POS_TARGET | CAM_DEV_POS_DEVICE |
2166 				CAM_DEV_POS_PERIPH;
2167 
2168 			cdm->pos.cookie.bus = periph->path->bus;
2169 			cdm->pos.generations[CAM_BUS_GENERATION]=
2170 				bus_generation;
2171 			cdm->pos.cookie.target = periph->path->target;
2172 			cdm->pos.generations[CAM_TARGET_GENERATION] =
2173 				periph->path->bus->generation;
2174 			cdm->pos.cookie.device = periph->path->device;
2175 			cdm->pos.generations[CAM_DEV_GENERATION] =
2176 				periph->path->target->generation;
2177 			cdm->pos.cookie.periph = periph;
2178 			cdm->pos.generations[CAM_PERIPH_GENERATION] =
2179 				periph->path->device->generation;
2180 			cdm->status = CAM_DEV_MATCH_MORE;
2181 			return(0);
2182 		}
2183 
2184 		j = cdm->num_matches;
2185 		cdm->num_matches++;
2186 		cdm->matches[j].type = DEV_MATCH_PERIPH;
2187 		cdm->matches[j].result.periph_result.path_id =
2188 			periph->path->bus->path_id;
2189 		cdm->matches[j].result.periph_result.target_id =
2190 			periph->path->target->target_id;
2191 		cdm->matches[j].result.periph_result.target_lun =
2192 			periph->path->device->lun_id;
2193 		cdm->matches[j].result.periph_result.unit_number =
2194 			periph->unit_number;
2195 		strncpy(cdm->matches[j].result.periph_result.periph_name,
2196 			periph->periph_name, DEV_IDLEN);
2197 	}
2198 
2199 	return(1);
2200 }
2201 
2202 static int
2203 xptedtmatch(struct ccb_dev_match *cdm)
2204 {
2205 	int ret;
2206 
2207 	cdm->num_matches = 0;
2208 
2209 	/*
2210 	 * Check the bus list generation.  If it has changed, the user
2211 	 * needs to reset everything and start over.
2212 	 */
2213 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2214 	 && (cdm->pos.generations[CAM_BUS_GENERATION] != 0)
2215 	 && (cdm->pos.generations[CAM_BUS_GENERATION] != bus_generation)) {
2216 		cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
2217 		return(0);
2218 	}
2219 
2220 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2221 	 && (cdm->pos.cookie.bus != NULL))
2222 		ret = xptbustraverse((struct cam_eb *)cdm->pos.cookie.bus,
2223 				     xptedtbusfunc, cdm);
2224 	else
2225 		ret = xptbustraverse(NULL, xptedtbusfunc, cdm);
2226 
2227 	/*
2228 	 * If we get back 0, that means that we had to stop before fully
2229 	 * traversing the EDT.  It also means that one of the subroutines
2230 	 * has set the status field to the proper value.  If we get back 1,
2231 	 * we've fully traversed the EDT and copied out any matching entries.
2232 	 */
2233 	if (ret == 1)
2234 		cdm->status = CAM_DEV_MATCH_LAST;
2235 
2236 	return(ret);
2237 }
2238 
2239 static int
2240 xptplistpdrvfunc(struct periph_driver **pdrv, void *arg)
2241 {
2242 	struct ccb_dev_match *cdm;
2243 
2244 	cdm = (struct ccb_dev_match *)arg;
2245 
2246 	if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
2247 	 && (cdm->pos.cookie.pdrv == pdrv)
2248 	 && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2249 	 && (cdm->pos.generations[CAM_PERIPH_GENERATION] != 0)
2250 	 && (cdm->pos.generations[CAM_PERIPH_GENERATION] !=
2251 	     (*pdrv)->generation)) {
2252 		cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
2253 		return(0);
2254 	}
2255 
2256 	if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
2257 	 && (cdm->pos.cookie.pdrv == pdrv)
2258 	 && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2259 	 && (cdm->pos.cookie.periph != NULL))
2260 		return(xptpdperiphtraverse(pdrv,
2261 				(struct cam_periph *)cdm->pos.cookie.periph,
2262 				xptplistperiphfunc, arg));
2263 	else
2264 		return(xptpdperiphtraverse(pdrv, NULL,xptplistperiphfunc, arg));
2265 }
2266 
2267 static int
2268 xptplistperiphfunc(struct cam_periph *periph, void *arg)
2269 {
2270 	struct ccb_dev_match *cdm;
2271 	dev_match_ret retval;
2272 
2273 	cdm = (struct ccb_dev_match *)arg;
2274 
2275 	retval = xptperiphmatch(cdm->patterns, cdm->num_patterns, periph);
2276 
2277 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
2278 		cdm->status = CAM_DEV_MATCH_ERROR;
2279 		return(0);
2280 	}
2281 
2282 	/*
2283 	 * If the copy flag is set, copy this peripheral out.
2284 	 */
2285 	if (retval & DM_RET_COPY) {
2286 		int spaceleft, j;
2287 
2288 		spaceleft = cdm->match_buf_len - (cdm->num_matches *
2289 			sizeof(struct dev_match_result));
2290 
2291 		/*
2292 		 * If we don't have enough space to put in another
2293 		 * match result, save our position and tell the
2294 		 * user there are more devices to check.
2295 		 */
2296 		if (spaceleft < sizeof(struct dev_match_result)) {
2297 			struct periph_driver **pdrv;
2298 
2299 			pdrv = NULL;
2300 			bzero(&cdm->pos, sizeof(cdm->pos));
2301 			cdm->pos.position_type =
2302 				CAM_DEV_POS_PDRV | CAM_DEV_POS_PDPTR |
2303 				CAM_DEV_POS_PERIPH;
2304 
2305 			/*
2306 			 * This may look a bit non-sensical, but it is
2307 			 * actually quite logical.  There are very few
2308 			 * peripheral drivers, and bloating every peripheral
2309 			 * structure with a pointer back to its parent
2310 			 * peripheral driver linker set entry would cost
2311 			 * more in the long run than doing this quick lookup.
2312 			 */
2313 			SET_FOREACH(pdrv, periphdriver_set) {
2314 				if (strcmp((*pdrv)->driver_name,
2315 				    periph->periph_name) == 0)
2316 					break;
2317 			}
2318 
2319 			if (*pdrv == NULL) {
2320 				cdm->status = CAM_DEV_MATCH_ERROR;
2321 				return(0);
2322 			}
2323 
2324 			cdm->pos.cookie.pdrv = pdrv;
2325 			/*
2326 			 * The periph generation slot does double duty, as
2327 			 * does the periph pointer slot.  They are used for
2328 			 * both edt and pdrv lookups and positioning.
2329 			 */
2330 			cdm->pos.cookie.periph = periph;
2331 			cdm->pos.generations[CAM_PERIPH_GENERATION] =
2332 				(*pdrv)->generation;
2333 			cdm->status = CAM_DEV_MATCH_MORE;
2334 			return(0);
2335 		}
2336 
2337 		j = cdm->num_matches;
2338 		cdm->num_matches++;
2339 		cdm->matches[j].type = DEV_MATCH_PERIPH;
2340 		cdm->matches[j].result.periph_result.path_id =
2341 			periph->path->bus->path_id;
2342 
2343 		/*
2344 		 * The transport layer peripheral doesn't have a target or
2345 		 * lun.
2346 		 */
2347 		if (periph->path->target)
2348 			cdm->matches[j].result.periph_result.target_id =
2349 				periph->path->target->target_id;
2350 		else
2351 			cdm->matches[j].result.periph_result.target_id = -1;
2352 
2353 		if (periph->path->device)
2354 			cdm->matches[j].result.periph_result.target_lun =
2355 				periph->path->device->lun_id;
2356 		else
2357 			cdm->matches[j].result.periph_result.target_lun = -1;
2358 
2359 		cdm->matches[j].result.periph_result.unit_number =
2360 			periph->unit_number;
2361 		strncpy(cdm->matches[j].result.periph_result.periph_name,
2362 			periph->periph_name, DEV_IDLEN);
2363 	}
2364 
2365 	return(1);
2366 }
2367 
2368 static int
2369 xptperiphlistmatch(struct ccb_dev_match *cdm)
2370 {
2371 	int ret;
2372 
2373 	cdm->num_matches = 0;
2374 
2375 	/*
2376 	 * At this point in the edt traversal function, we check the bus
2377 	 * list generation to make sure that no busses have been added or
2378 	 * removed since the user last sent a XPT_DEV_MATCH ccb through.
2379 	 * For the peripheral driver list traversal function, however, we
2380 	 * don't have to worry about new peripheral driver types coming or
2381 	 * going; they're in a linker set, and therefore can't change
2382 	 * without a recompile.
2383 	 */
2384 
2385 	if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
2386 	 && (cdm->pos.cookie.pdrv != NULL))
2387 		ret = xptpdrvtraverse(
2388 				(struct periph_driver **)cdm->pos.cookie.pdrv,
2389 				xptplistpdrvfunc, cdm);
2390 	else
2391 		ret = xptpdrvtraverse(NULL, xptplistpdrvfunc, cdm);
2392 
2393 	/*
2394 	 * If we get back 0, that means that we had to stop before fully
2395 	 * traversing the peripheral driver tree.  It also means that one of
2396 	 * the subroutines has set the status field to the proper value.  If
2397 	 * we get back 1, we've fully traversed the EDT and copied out any
2398 	 * matching entries.
2399 	 */
2400 	if (ret == 1)
2401 		cdm->status = CAM_DEV_MATCH_LAST;
2402 
2403 	return(ret);
2404 }
2405 
2406 static int
2407 xptbustraverse(struct cam_eb *start_bus, xpt_busfunc_t *tr_func, void *arg)
2408 {
2409 	struct cam_eb *bus, *next_bus;
2410 	int retval;
2411 
2412 	retval = 1;
2413 
2414 	for (bus = (start_bus ? start_bus : TAILQ_FIRST(&xpt_busses));
2415 	     bus != NULL;
2416 	     bus = next_bus) {
2417 		next_bus = TAILQ_NEXT(bus, links);
2418 
2419 		retval = tr_func(bus, arg);
2420 		if (retval == 0)
2421 			return(retval);
2422 	}
2423 
2424 	return(retval);
2425 }
2426 
2427 static int
2428 xpttargettraverse(struct cam_eb *bus, struct cam_et *start_target,
2429 		  xpt_targetfunc_t *tr_func, void *arg)
2430 {
2431 	struct cam_et *target, *next_target;
2432 	int retval;
2433 
2434 	retval = 1;
2435 	for (target = (start_target ? start_target :
2436 		       TAILQ_FIRST(&bus->et_entries));
2437 	     target != NULL; target = next_target) {
2438 
2439 		next_target = TAILQ_NEXT(target, links);
2440 
2441 		retval = tr_func(target, arg);
2442 
2443 		if (retval == 0)
2444 			return(retval);
2445 	}
2446 
2447 	return(retval);
2448 }
2449 
2450 static int
2451 xptdevicetraverse(struct cam_et *target, struct cam_ed *start_device,
2452 		  xpt_devicefunc_t *tr_func, void *arg)
2453 {
2454 	struct cam_ed *device, *next_device;
2455 	int retval;
2456 
2457 	retval = 1;
2458 	for (device = (start_device ? start_device :
2459 		       TAILQ_FIRST(&target->ed_entries));
2460 	     device != NULL;
2461 	     device = next_device) {
2462 
2463 		next_device = TAILQ_NEXT(device, links);
2464 
2465 		retval = tr_func(device, arg);
2466 
2467 		if (retval == 0)
2468 			return(retval);
2469 	}
2470 
2471 	return(retval);
2472 }
2473 
2474 static int
2475 xptperiphtraverse(struct cam_ed *device, struct cam_periph *start_periph,
2476 		  xpt_periphfunc_t *tr_func, void *arg)
2477 {
2478 	struct cam_periph *periph, *next_periph;
2479 	int retval;
2480 
2481 	retval = 1;
2482 
2483 	for (periph = (start_periph ? start_periph :
2484 		       SLIST_FIRST(&device->periphs));
2485 	     periph != NULL;
2486 	     periph = next_periph) {
2487 
2488 		next_periph = SLIST_NEXT(periph, periph_links);
2489 
2490 		retval = tr_func(periph, arg);
2491 		if (retval == 0)
2492 			return(retval);
2493 	}
2494 
2495 	return(retval);
2496 }
2497 
2498 static int
2499 xptpdrvtraverse(struct periph_driver **start_pdrv,
2500 		xpt_pdrvfunc_t *tr_func, void *arg)
2501 {
2502 	struct periph_driver **pdrv;
2503 	int retval;
2504 
2505 	retval = 1;
2506 
2507 	/*
2508 	 * We don't traverse the peripheral driver list like we do the
2509 	 * other lists, because it is a linker set, and therefore cannot be
2510 	 * changed during runtime.  If the peripheral driver list is ever
2511 	 * re-done to be something other than a linker set (i.e. it can
2512 	 * change while the system is running), the list traversal should
2513 	 * be modified to work like the other traversal functions.
2514 	 */
2515 	SET_FOREACH(pdrv, periphdriver_set) {
2516 		if (start_pdrv == NULL || start_pdrv == pdrv) {
2517 			retval = tr_func(pdrv, arg);
2518 			if (retval == 0)
2519 				return(retval);
2520 			start_pdrv = NULL; /* traverse remainder */
2521 		}
2522 	}
2523 	return(retval);
2524 }
2525 
2526 static int
2527 xptpdperiphtraverse(struct periph_driver **pdrv,
2528 		    struct cam_periph *start_periph,
2529 		    xpt_periphfunc_t *tr_func, void *arg)
2530 {
2531 	struct cam_periph *periph, *next_periph;
2532 	int retval;
2533 
2534 	retval = 1;
2535 
2536 	for (periph = (start_periph ? start_periph :
2537 	     TAILQ_FIRST(&(*pdrv)->units)); periph != NULL;
2538 	     periph = next_periph) {
2539 
2540 		next_periph = TAILQ_NEXT(periph, unit_links);
2541 
2542 		retval = tr_func(periph, arg);
2543 		if (retval == 0)
2544 			return(retval);
2545 	}
2546 	return(retval);
2547 }
2548 
2549 static int
2550 xptdefbusfunc(struct cam_eb *bus, void *arg)
2551 {
2552 	struct xpt_traverse_config *tr_config;
2553 
2554 	tr_config = (struct xpt_traverse_config *)arg;
2555 
2556 	if (tr_config->depth == XPT_DEPTH_BUS) {
2557 		xpt_busfunc_t *tr_func;
2558 
2559 		tr_func = (xpt_busfunc_t *)tr_config->tr_func;
2560 
2561 		return(tr_func(bus, tr_config->tr_arg));
2562 	} else
2563 		return(xpttargettraverse(bus, NULL, xptdeftargetfunc, arg));
2564 }
2565 
2566 static int
2567 xptdeftargetfunc(struct cam_et *target, void *arg)
2568 {
2569 	struct xpt_traverse_config *tr_config;
2570 
2571 	tr_config = (struct xpt_traverse_config *)arg;
2572 
2573 	if (tr_config->depth == XPT_DEPTH_TARGET) {
2574 		xpt_targetfunc_t *tr_func;
2575 
2576 		tr_func = (xpt_targetfunc_t *)tr_config->tr_func;
2577 
2578 		return(tr_func(target, tr_config->tr_arg));
2579 	} else
2580 		return(xptdevicetraverse(target, NULL, xptdefdevicefunc, arg));
2581 }
2582 
2583 static int
2584 xptdefdevicefunc(struct cam_ed *device, void *arg)
2585 {
2586 	struct xpt_traverse_config *tr_config;
2587 
2588 	tr_config = (struct xpt_traverse_config *)arg;
2589 
2590 	if (tr_config->depth == XPT_DEPTH_DEVICE) {
2591 		xpt_devicefunc_t *tr_func;
2592 
2593 		tr_func = (xpt_devicefunc_t *)tr_config->tr_func;
2594 
2595 		return(tr_func(device, tr_config->tr_arg));
2596 	} else
2597 		return(xptperiphtraverse(device, NULL, xptdefperiphfunc, arg));
2598 }
2599 
2600 static int
2601 xptdefperiphfunc(struct cam_periph *periph, void *arg)
2602 {
2603 	struct xpt_traverse_config *tr_config;
2604 	xpt_periphfunc_t *tr_func;
2605 
2606 	tr_config = (struct xpt_traverse_config *)arg;
2607 
2608 	tr_func = (xpt_periphfunc_t *)tr_config->tr_func;
2609 
2610 	/*
2611 	 * Unlike the other default functions, we don't check for depth
2612 	 * here.  The peripheral driver level is the last level in the EDT,
2613 	 * so if we're here, we should execute the function in question.
2614 	 */
2615 	return(tr_func(periph, tr_config->tr_arg));
2616 }
2617 
2618 /*
2619  * Execute the given function for every bus in the EDT.
2620  */
2621 static int
2622 xpt_for_all_busses(xpt_busfunc_t *tr_func, void *arg)
2623 {
2624 	struct xpt_traverse_config tr_config;
2625 
2626 	tr_config.depth = XPT_DEPTH_BUS;
2627 	tr_config.tr_func = tr_func;
2628 	tr_config.tr_arg = arg;
2629 
2630 	return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2631 }
2632 
2633 #ifdef notusedyet
2634 /*
2635  * Execute the given function for every target in the EDT.
2636  */
2637 static int
2638 xpt_for_all_targets(xpt_targetfunc_t *tr_func, void *arg)
2639 {
2640 	struct xpt_traverse_config tr_config;
2641 
2642 	tr_config.depth = XPT_DEPTH_TARGET;
2643 	tr_config.tr_func = tr_func;
2644 	tr_config.tr_arg = arg;
2645 
2646 	return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2647 }
2648 #endif /* notusedyet */
2649 
2650 /*
2651  * Execute the given function for every device in the EDT.
2652  */
2653 static int
2654 xpt_for_all_devices(xpt_devicefunc_t *tr_func, void *arg)
2655 {
2656 	struct xpt_traverse_config tr_config;
2657 
2658 	tr_config.depth = XPT_DEPTH_DEVICE;
2659 	tr_config.tr_func = tr_func;
2660 	tr_config.tr_arg = arg;
2661 
2662 	return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2663 }
2664 
2665 #ifdef notusedyet
2666 /*
2667  * Execute the given function for every peripheral in the EDT.
2668  */
2669 static int
2670 xpt_for_all_periphs(xpt_periphfunc_t *tr_func, void *arg)
2671 {
2672 	struct xpt_traverse_config tr_config;
2673 
2674 	tr_config.depth = XPT_DEPTH_PERIPH;
2675 	tr_config.tr_func = tr_func;
2676 	tr_config.tr_arg = arg;
2677 
2678 	return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2679 }
2680 #endif /* notusedyet */
2681 
2682 static int
2683 xptsetasyncfunc(struct cam_ed *device, void *arg)
2684 {
2685 	struct cam_path path;
2686 	struct ccb_getdev cgd;
2687 	struct async_node *cur_entry;
2688 
2689 	cur_entry = (struct async_node *)arg;
2690 
2691 	/*
2692 	 * Don't report unconfigured devices (Wildcard devs,
2693 	 * devices only for target mode, device instances
2694 	 * that have been invalidated but are waiting for
2695 	 * their last reference count to be released).
2696 	 */
2697 	if ((device->flags & CAM_DEV_UNCONFIGURED) != 0)
2698 		return (1);
2699 
2700 	xpt_compile_path(&path,
2701 			 NULL,
2702 			 device->target->bus->path_id,
2703 			 device->target->target_id,
2704 			 device->lun_id);
2705 	xpt_setup_ccb(&cgd.ccb_h, &path, /*priority*/1);
2706 	cgd.ccb_h.func_code = XPT_GDEV_TYPE;
2707 	xpt_action((union ccb *)&cgd);
2708 	cur_entry->callback(cur_entry->callback_arg,
2709 			    AC_FOUND_DEVICE,
2710 			    &path, &cgd);
2711 	xpt_release_path(&path);
2712 
2713 	return(1);
2714 }
2715 
2716 static int
2717 xptsetasyncbusfunc(struct cam_eb *bus, void *arg)
2718 {
2719 	struct cam_path path;
2720 	struct ccb_pathinq cpi;
2721 	struct async_node *cur_entry;
2722 
2723 	cur_entry = (struct async_node *)arg;
2724 
2725 	xpt_compile_path(&path, /*periph*/NULL,
2726 			 bus->sim->path_id,
2727 			 CAM_TARGET_WILDCARD,
2728 			 CAM_LUN_WILDCARD);
2729 	xpt_setup_ccb(&cpi.ccb_h, &path, /*priority*/1);
2730 	cpi.ccb_h.func_code = XPT_PATH_INQ;
2731 	xpt_action((union ccb *)&cpi);
2732 	cur_entry->callback(cur_entry->callback_arg,
2733 			    AC_PATH_REGISTERED,
2734 			    &path, &cpi);
2735 	xpt_release_path(&path);
2736 
2737 	return(1);
2738 }
2739 
2740 void
2741 xpt_action(union ccb *start_ccb)
2742 {
2743 	CAM_DEBUG(start_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("xpt_action\n"));
2744 
2745 	start_ccb->ccb_h.status = CAM_REQ_INPROG;
2746 
2747 	crit_enter();
2748 
2749 	switch (start_ccb->ccb_h.func_code) {
2750 	case XPT_SCSI_IO:
2751 	{
2752 #ifdef CAMDEBUG
2753 		char cdb_str[(SCSI_MAX_CDBLEN * 3) + 1];
2754 		struct cam_path *path;
2755 
2756 		path = start_ccb->ccb_h.path;
2757 #endif
2758 
2759 		/*
2760 		 * For the sake of compatibility with SCSI-1
2761 		 * devices that may not understand the identify
2762 		 * message, we include lun information in the
2763 		 * second byte of all commands.  SCSI-1 specifies
2764 		 * that luns are a 3 bit value and reserves only 3
2765 		 * bits for lun information in the CDB.  Later
2766 		 * revisions of the SCSI spec allow for more than 8
2767 		 * luns, but have deprecated lun information in the
2768 		 * CDB.  So, if the lun won't fit, we must omit.
2769 		 *
2770 		 * Also be aware that during initial probing for devices,
2771 		 * the inquiry information is unknown but initialized to 0.
2772 		 * This means that this code will be exercised while probing
2773 		 * devices with an ANSI revision greater than 2.
2774 		 */
2775 		if (SID_ANSI_REV(&start_ccb->ccb_h.path->device->inq_data) <= 2
2776 		 && start_ccb->ccb_h.target_lun < 8
2777 		 && (start_ccb->ccb_h.flags & CAM_CDB_POINTER) == 0) {
2778 
2779 			start_ccb->csio.cdb_io.cdb_bytes[1] |=
2780 			    start_ccb->ccb_h.target_lun << 5;
2781 		}
2782 		start_ccb->csio.scsi_status = SCSI_STATUS_OK;
2783 		CAM_DEBUG(path, CAM_DEBUG_CDB,("%s. CDB: %s\n",
2784 			  scsi_op_desc(start_ccb->csio.cdb_io.cdb_bytes[0],
2785 			  	       &path->device->inq_data),
2786 			  scsi_cdb_string(start_ccb->csio.cdb_io.cdb_bytes,
2787 					  cdb_str, sizeof(cdb_str))));
2788 		/* FALLTHROUGH */
2789 	}
2790 	case XPT_TARGET_IO:
2791 	case XPT_CONT_TARGET_IO:
2792 		start_ccb->csio.sense_resid = 0;
2793 		start_ccb->csio.resid = 0;
2794 		/* FALLTHROUGH */
2795 	case XPT_RESET_DEV:
2796 	case XPT_ENG_EXEC:
2797 	{
2798 		struct cam_path *path;
2799 		int runq;
2800 
2801 		path = start_ccb->ccb_h.path;
2802 
2803 		cam_ccbq_insert_ccb(&path->device->ccbq, start_ccb);
2804 		if (path->device->qfrozen_cnt == 0)
2805 			runq = xpt_schedule_dev_sendq(path->bus, path->device);
2806 		else
2807 			runq = 0;
2808 		if (runq != 0)
2809 			xpt_run_dev_sendq(path->bus);
2810 		break;
2811 	}
2812 	case XPT_SET_TRAN_SETTINGS:
2813 	{
2814 		xpt_set_transfer_settings(&start_ccb->cts,
2815 					  start_ccb->ccb_h.path->device,
2816 					  /*async_update*/FALSE);
2817 		break;
2818 	}
2819 	case XPT_CALC_GEOMETRY:
2820 	{
2821 		struct cam_sim *sim;
2822 
2823 		/* Filter out garbage */
2824 		if (start_ccb->ccg.block_size == 0
2825 		 || start_ccb->ccg.volume_size == 0) {
2826 			start_ccb->ccg.cylinders = 0;
2827 			start_ccb->ccg.heads = 0;
2828 			start_ccb->ccg.secs_per_track = 0;
2829 			start_ccb->ccb_h.status = CAM_REQ_CMP;
2830 			break;
2831 		}
2832 		sim = start_ccb->ccb_h.path->bus->sim;
2833 		(*(sim->sim_action))(sim, start_ccb);
2834 		break;
2835 	}
2836 	case XPT_ABORT:
2837 	{
2838 		union ccb* abort_ccb;
2839 
2840 		abort_ccb = start_ccb->cab.abort_ccb;
2841 		if (XPT_FC_IS_DEV_QUEUED(abort_ccb)) {
2842 
2843 			if (abort_ccb->ccb_h.pinfo.index >= 0) {
2844 				struct cam_ccbq *ccbq;
2845 
2846 				ccbq = &abort_ccb->ccb_h.path->device->ccbq;
2847 				cam_ccbq_remove_ccb(ccbq, abort_ccb);
2848 				abort_ccb->ccb_h.status =
2849 				    CAM_REQ_ABORTED|CAM_DEV_QFRZN;
2850 				xpt_freeze_devq(abort_ccb->ccb_h.path, 1);
2851 				xpt_done(abort_ccb);
2852 				start_ccb->ccb_h.status = CAM_REQ_CMP;
2853 				break;
2854 			}
2855 			if (abort_ccb->ccb_h.pinfo.index == CAM_UNQUEUED_INDEX
2856 			 && (abort_ccb->ccb_h.status & CAM_SIM_QUEUED) == 0) {
2857 				/*
2858 				 * We've caught this ccb en route to
2859 				 * the SIM.  Flag it for abort and the
2860 				 * SIM will do so just before starting
2861 				 * real work on the CCB.
2862 				 */
2863 				abort_ccb->ccb_h.status =
2864 				    CAM_REQ_ABORTED|CAM_DEV_QFRZN;
2865 				xpt_freeze_devq(abort_ccb->ccb_h.path, 1);
2866 				start_ccb->ccb_h.status = CAM_REQ_CMP;
2867 				break;
2868 			}
2869 		}
2870 		if (XPT_FC_IS_QUEUED(abort_ccb)
2871 		 && (abort_ccb->ccb_h.pinfo.index == CAM_DONEQ_INDEX)) {
2872 			/*
2873 			 * It's already completed but waiting
2874 			 * for our SWI to get to it.
2875 			 */
2876 			start_ccb->ccb_h.status = CAM_UA_ABORT;
2877 			break;
2878 		}
2879 		/*
2880 		 * If we weren't able to take care of the abort request
2881 		 * in the XPT, pass the request down to the SIM for processing.
2882 		 */
2883 		/* FALLTHROUGH */
2884 	}
2885 	case XPT_ACCEPT_TARGET_IO:
2886 	case XPT_EN_LUN:
2887 	case XPT_IMMED_NOTIFY:
2888 	case XPT_NOTIFY_ACK:
2889 	case XPT_GET_TRAN_SETTINGS:
2890 	case XPT_RESET_BUS:
2891 	{
2892 		struct cam_sim *sim;
2893 
2894 		sim = start_ccb->ccb_h.path->bus->sim;
2895 		(*(sim->sim_action))(sim, start_ccb);
2896 		break;
2897 	}
2898 	case XPT_PATH_INQ:
2899 	{
2900 		struct cam_sim *sim;
2901 
2902 		sim = start_ccb->ccb_h.path->bus->sim;
2903 		(*(sim->sim_action))(sim, start_ccb);
2904 		break;
2905 	}
2906 	case XPT_PATH_STATS:
2907 		start_ccb->cpis.last_reset =
2908 			start_ccb->ccb_h.path->bus->last_reset;
2909 		start_ccb->ccb_h.status = CAM_REQ_CMP;
2910 		break;
2911 	case XPT_GDEV_TYPE:
2912 	{
2913 		struct cam_ed *dev;
2914 
2915 		dev = start_ccb->ccb_h.path->device;
2916 		if ((dev->flags & CAM_DEV_UNCONFIGURED) != 0) {
2917 			start_ccb->ccb_h.status = CAM_DEV_NOT_THERE;
2918 		} else {
2919 			struct ccb_getdev *cgd;
2920 			struct cam_eb *bus;
2921 			struct cam_et *tar;
2922 
2923 			cgd = &start_ccb->cgd;
2924 			bus = cgd->ccb_h.path->bus;
2925 			tar = cgd->ccb_h.path->target;
2926 			cgd->inq_data = dev->inq_data;
2927 			cgd->ccb_h.status = CAM_REQ_CMP;
2928 			cgd->serial_num_len = dev->serial_num_len;
2929 			if ((dev->serial_num_len > 0)
2930 			 && (dev->serial_num != NULL))
2931 				bcopy(dev->serial_num, cgd->serial_num,
2932 				      dev->serial_num_len);
2933 		}
2934 		break;
2935 	}
2936 	case XPT_GDEV_STATS:
2937 	{
2938 		struct cam_ed *dev;
2939 
2940 		dev = start_ccb->ccb_h.path->device;
2941 		if ((dev->flags & CAM_DEV_UNCONFIGURED) != 0) {
2942 			start_ccb->ccb_h.status = CAM_DEV_NOT_THERE;
2943 		} else {
2944 			struct ccb_getdevstats *cgds;
2945 			struct cam_eb *bus;
2946 			struct cam_et *tar;
2947 
2948 			cgds = &start_ccb->cgds;
2949 			bus = cgds->ccb_h.path->bus;
2950 			tar = cgds->ccb_h.path->target;
2951 			cgds->dev_openings = dev->ccbq.dev_openings;
2952 			cgds->dev_active = dev->ccbq.dev_active;
2953 			cgds->devq_openings = dev->ccbq.devq_openings;
2954 			cgds->devq_queued = dev->ccbq.queue.entries;
2955 			cgds->held = dev->ccbq.held;
2956 			cgds->last_reset = tar->last_reset;
2957 			cgds->maxtags = dev->quirk->maxtags;
2958 			cgds->mintags = dev->quirk->mintags;
2959 			if (timevalcmp(&tar->last_reset, &bus->last_reset, <))
2960 				cgds->last_reset = bus->last_reset;
2961 			cgds->ccb_h.status = CAM_REQ_CMP;
2962 		}
2963 		break;
2964 	}
2965 	case XPT_GDEVLIST:
2966 	{
2967 		struct cam_periph	*nperiph;
2968 		struct periph_list	*periph_head;
2969 		struct ccb_getdevlist	*cgdl;
2970 		int			i;
2971 		struct cam_ed		*device;
2972 		int			found;
2973 
2974 
2975 		found = 0;
2976 
2977 		/*
2978 		 * Don't want anyone mucking with our data.
2979 		 */
2980 		device = start_ccb->ccb_h.path->device;
2981 		periph_head = &device->periphs;
2982 		cgdl = &start_ccb->cgdl;
2983 
2984 		/*
2985 		 * Check and see if the list has changed since the user
2986 		 * last requested a list member.  If so, tell them that the
2987 		 * list has changed, and therefore they need to start over
2988 		 * from the beginning.
2989 		 */
2990 		if ((cgdl->index != 0) &&
2991 		    (cgdl->generation != device->generation)) {
2992 			cgdl->status = CAM_GDEVLIST_LIST_CHANGED;
2993 			break;
2994 		}
2995 
2996 		/*
2997 		 * Traverse the list of peripherals and attempt to find
2998 		 * the requested peripheral.
2999 		 */
3000 		for (nperiph = periph_head->slh_first, i = 0;
3001 		     (nperiph != NULL) && (i <= cgdl->index);
3002 		     nperiph = nperiph->periph_links.sle_next, i++) {
3003 			if (i == cgdl->index) {
3004 				strncpy(cgdl->periph_name,
3005 					nperiph->periph_name,
3006 					DEV_IDLEN);
3007 				cgdl->unit_number = nperiph->unit_number;
3008 				found = 1;
3009 			}
3010 		}
3011 		if (found == 0) {
3012 			cgdl->status = CAM_GDEVLIST_ERROR;
3013 			break;
3014 		}
3015 
3016 		if (nperiph == NULL)
3017 			cgdl->status = CAM_GDEVLIST_LAST_DEVICE;
3018 		else
3019 			cgdl->status = CAM_GDEVLIST_MORE_DEVS;
3020 
3021 		cgdl->index++;
3022 		cgdl->generation = device->generation;
3023 
3024 		cgdl->ccb_h.status = CAM_REQ_CMP;
3025 		break;
3026 	}
3027 	case XPT_DEV_MATCH:
3028 	{
3029 		dev_pos_type position_type;
3030 		struct ccb_dev_match *cdm;
3031 		int ret;
3032 
3033 		cdm = &start_ccb->cdm;
3034 
3035 		/*
3036 		 * Prevent EDT changes while we traverse it.
3037 		 */
3038 		/*
3039 		 * There are two ways of getting at information in the EDT.
3040 		 * The first way is via the primary EDT tree.  It starts
3041 		 * with a list of busses, then a list of targets on a bus,
3042 		 * then devices/luns on a target, and then peripherals on a
3043 		 * device/lun.  The "other" way is by the peripheral driver
3044 		 * lists.  The peripheral driver lists are organized by
3045 		 * peripheral driver.  (obviously)  So it makes sense to
3046 		 * use the peripheral driver list if the user is looking
3047 		 * for something like "da1", or all "da" devices.  If the
3048 		 * user is looking for something on a particular bus/target
3049 		 * or lun, it's generally better to go through the EDT tree.
3050 		 */
3051 
3052 		if (cdm->pos.position_type != CAM_DEV_POS_NONE)
3053 			position_type = cdm->pos.position_type;
3054 		else {
3055 			int i;
3056 
3057 			position_type = CAM_DEV_POS_NONE;
3058 
3059 			for (i = 0; i < cdm->num_patterns; i++) {
3060 				if ((cdm->patterns[i].type == DEV_MATCH_BUS)
3061 				 ||(cdm->patterns[i].type == DEV_MATCH_DEVICE)){
3062 					position_type = CAM_DEV_POS_EDT;
3063 					break;
3064 				}
3065 			}
3066 
3067 			if (cdm->num_patterns == 0)
3068 				position_type = CAM_DEV_POS_EDT;
3069 			else if (position_type == CAM_DEV_POS_NONE)
3070 				position_type = CAM_DEV_POS_PDRV;
3071 		}
3072 
3073 		switch(position_type & CAM_DEV_POS_TYPEMASK) {
3074 		case CAM_DEV_POS_EDT:
3075 			ret = xptedtmatch(cdm);
3076 			break;
3077 		case CAM_DEV_POS_PDRV:
3078 			ret = xptperiphlistmatch(cdm);
3079 			break;
3080 		default:
3081 			cdm->status = CAM_DEV_MATCH_ERROR;
3082 			break;
3083 		}
3084 
3085 		if (cdm->status == CAM_DEV_MATCH_ERROR)
3086 			start_ccb->ccb_h.status = CAM_REQ_CMP_ERR;
3087 		else
3088 			start_ccb->ccb_h.status = CAM_REQ_CMP;
3089 
3090 		break;
3091 	}
3092 	case XPT_SASYNC_CB:
3093 	{
3094 		struct ccb_setasync *csa;
3095 		struct async_node *cur_entry;
3096 		struct async_list *async_head;
3097 		u_int32_t added;
3098 
3099 		csa = &start_ccb->csa;
3100 		added = csa->event_enable;
3101 		async_head = &csa->ccb_h.path->device->asyncs;
3102 
3103 		/*
3104 		 * If there is already an entry for us, simply
3105 		 * update it.
3106 		 */
3107 		cur_entry = SLIST_FIRST(async_head);
3108 		while (cur_entry != NULL) {
3109 			if ((cur_entry->callback_arg == csa->callback_arg)
3110 			 && (cur_entry->callback == csa->callback))
3111 				break;
3112 			cur_entry = SLIST_NEXT(cur_entry, links);
3113 		}
3114 
3115 		if (cur_entry != NULL) {
3116 		 	/*
3117 			 * If the request has no flags set,
3118 			 * remove the entry.
3119 			 */
3120 			added &= ~cur_entry->event_enable;
3121 			if (csa->event_enable == 0) {
3122 				SLIST_REMOVE(async_head, cur_entry,
3123 					     async_node, links);
3124 				csa->ccb_h.path->device->refcount--;
3125 				kfree(cur_entry, M_DEVBUF);
3126 			} else {
3127 				cur_entry->event_enable = csa->event_enable;
3128 			}
3129 		} else {
3130 			cur_entry = kmalloc(sizeof(*cur_entry),
3131 					    M_DEVBUF, M_INTWAIT);
3132 			cur_entry->event_enable = csa->event_enable;
3133 			cur_entry->callback_arg = csa->callback_arg;
3134 			cur_entry->callback = csa->callback;
3135 			SLIST_INSERT_HEAD(async_head, cur_entry, links);
3136 			csa->ccb_h.path->device->refcount++;
3137 		}
3138 
3139 		if ((added & AC_FOUND_DEVICE) != 0) {
3140 			/*
3141 			 * Get this peripheral up to date with all
3142 			 * the currently existing devices.
3143 			 */
3144 			xpt_for_all_devices(xptsetasyncfunc, cur_entry);
3145 		}
3146 		if ((added & AC_PATH_REGISTERED) != 0) {
3147 			/*
3148 			 * Get this peripheral up to date with all
3149 			 * the currently existing busses.
3150 			 */
3151 			xpt_for_all_busses(xptsetasyncbusfunc, cur_entry);
3152 		}
3153 		start_ccb->ccb_h.status = CAM_REQ_CMP;
3154 		break;
3155 	}
3156 	case XPT_REL_SIMQ:
3157 	{
3158 		struct ccb_relsim *crs;
3159 		struct cam_ed *dev;
3160 
3161 		crs = &start_ccb->crs;
3162 		dev = crs->ccb_h.path->device;
3163 		if (dev == NULL) {
3164 
3165 			crs->ccb_h.status = CAM_DEV_NOT_THERE;
3166 			break;
3167 		}
3168 
3169 		if ((crs->release_flags & RELSIM_ADJUST_OPENINGS) != 0) {
3170 
3171  			if ((dev->inq_data.flags & SID_CmdQue) != 0) {
3172 
3173 				/* Don't ever go below one opening */
3174 				if (crs->openings > 0) {
3175 					xpt_dev_ccbq_resize(crs->ccb_h.path,
3176 							    crs->openings);
3177 
3178 					if (bootverbose) {
3179 						xpt_print_path(crs->ccb_h.path);
3180 						kprintf("tagged openings "
3181 						       "now %d\n",
3182 						       crs->openings);
3183 					}
3184 				}
3185 			}
3186 		}
3187 
3188 		if ((crs->release_flags & RELSIM_RELEASE_AFTER_TIMEOUT) != 0) {
3189 
3190 			if ((dev->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
3191 
3192 				/*
3193 				 * Just extend the old timeout and decrement
3194 				 * the freeze count so that a single timeout
3195 				 * is sufficient for releasing the queue.
3196 				 */
3197 				start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
3198 				callout_stop(&dev->c_handle);
3199 			} else {
3200 
3201 				start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
3202 			}
3203 
3204 			callout_reset(&dev->c_handle,
3205 				      (crs->release_timeout * hz) / 1000,
3206 				      xpt_release_devq_timeout, dev);
3207 
3208 			dev->flags |= CAM_DEV_REL_TIMEOUT_PENDING;
3209 
3210 		}
3211 
3212 		if ((crs->release_flags & RELSIM_RELEASE_AFTER_CMDCMPLT) != 0) {
3213 
3214 			if ((dev->flags & CAM_DEV_REL_ON_COMPLETE) != 0) {
3215 				/*
3216 				 * Decrement the freeze count so that a single
3217 				 * completion is still sufficient to unfreeze
3218 				 * the queue.
3219 				 */
3220 				start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
3221 			} else {
3222 
3223 				dev->flags |= CAM_DEV_REL_ON_COMPLETE;
3224 				start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
3225 			}
3226 		}
3227 
3228 		if ((crs->release_flags & RELSIM_RELEASE_AFTER_QEMPTY) != 0) {
3229 
3230 			if ((dev->flags & CAM_DEV_REL_ON_QUEUE_EMPTY) != 0
3231 			 || (dev->ccbq.dev_active == 0)) {
3232 
3233 				start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
3234 			} else {
3235 
3236 				dev->flags |= CAM_DEV_REL_ON_QUEUE_EMPTY;
3237 				start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
3238 			}
3239 		}
3240 
3241 		if ((start_ccb->ccb_h.flags & CAM_DEV_QFREEZE) == 0) {
3242 
3243 			xpt_release_devq(crs->ccb_h.path, /*count*/1,
3244 					 /*run_queue*/TRUE);
3245 		}
3246 		start_ccb->crs.qfrozen_cnt = dev->qfrozen_cnt;
3247 		start_ccb->ccb_h.status = CAM_REQ_CMP;
3248 		break;
3249 	}
3250 	case XPT_SCAN_BUS:
3251 		xpt_scan_bus(start_ccb->ccb_h.path->periph, start_ccb);
3252 		break;
3253 	case XPT_SCAN_LUN:
3254 		xpt_scan_lun(start_ccb->ccb_h.path->periph,
3255 			     start_ccb->ccb_h.path, start_ccb->crcn.flags,
3256 			     start_ccb);
3257 		break;
3258 	case XPT_DEBUG: {
3259 #ifdef CAMDEBUG
3260 #ifdef CAM_DEBUG_DELAY
3261 		cam_debug_delay = CAM_DEBUG_DELAY;
3262 #endif
3263 		cam_dflags = start_ccb->cdbg.flags;
3264 		if (cam_dpath != NULL) {
3265 			xpt_free_path(cam_dpath);
3266 			cam_dpath = NULL;
3267 		}
3268 
3269 		if (cam_dflags != CAM_DEBUG_NONE) {
3270 			if (xpt_create_path(&cam_dpath, xpt_periph,
3271 					    start_ccb->ccb_h.path_id,
3272 					    start_ccb->ccb_h.target_id,
3273 					    start_ccb->ccb_h.target_lun) !=
3274 					    CAM_REQ_CMP) {
3275 				start_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
3276 				cam_dflags = CAM_DEBUG_NONE;
3277 			} else {
3278 				start_ccb->ccb_h.status = CAM_REQ_CMP;
3279 				xpt_print_path(cam_dpath);
3280 				kprintf("debugging flags now %x\n", cam_dflags);
3281 			}
3282 		} else {
3283 			cam_dpath = NULL;
3284 			start_ccb->ccb_h.status = CAM_REQ_CMP;
3285 		}
3286 #else /* !CAMDEBUG */
3287 		start_ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
3288 #endif /* CAMDEBUG */
3289 		break;
3290 	}
3291 	case XPT_NOOP:
3292 		if ((start_ccb->ccb_h.flags & CAM_DEV_QFREEZE) != 0)
3293 			xpt_freeze_devq(start_ccb->ccb_h.path, 1);
3294 		start_ccb->ccb_h.status = CAM_REQ_CMP;
3295 		break;
3296 	default:
3297 	case XPT_SDEV_TYPE:
3298 	case XPT_TERM_IO:
3299 	case XPT_ENG_INQ:
3300 		/* XXX Implement */
3301 		start_ccb->ccb_h.status = CAM_PROVIDE_FAIL;
3302 		break;
3303 	}
3304 	crit_exit();
3305 }
3306 
3307 void
3308 xpt_polled_action(union ccb *start_ccb)
3309 {
3310 	u_int32_t timeout;
3311 	struct	  cam_sim *sim;
3312 	struct	  cam_devq *devq;
3313 	struct	  cam_ed *dev;
3314 
3315 	timeout = start_ccb->ccb_h.timeout;
3316 	sim = start_ccb->ccb_h.path->bus->sim;
3317 	devq = sim->devq;
3318 	dev = start_ccb->ccb_h.path->device;
3319 
3320 	crit_enter();
3321 
3322 	/*
3323 	 * Steal an opening so that no other queued requests
3324 	 * can get it before us while we simulate interrupts.
3325 	 */
3326 	dev->ccbq.devq_openings--;
3327 	dev->ccbq.dev_openings--;
3328 
3329 	while(((devq && devq->send_openings <= 0) || dev->ccbq.dev_openings < 0)
3330 	   && (--timeout > 0)) {
3331 		DELAY(1000);
3332 		(*(sim->sim_poll))(sim);
3333 		swi_camnet(NULL, NULL);
3334 		swi_cambio(NULL, NULL);
3335 	}
3336 
3337 	dev->ccbq.devq_openings++;
3338 	dev->ccbq.dev_openings++;
3339 
3340 	if (timeout != 0) {
3341 		xpt_action(start_ccb);
3342 		while(--timeout > 0) {
3343 			(*(sim->sim_poll))(sim);
3344 			swi_camnet(NULL, NULL);
3345 			swi_cambio(NULL, NULL);
3346 			if ((start_ccb->ccb_h.status  & CAM_STATUS_MASK)
3347 			    != CAM_REQ_INPROG)
3348 				break;
3349 			DELAY(1000);
3350 		}
3351 		if (timeout == 0) {
3352 			/*
3353 			 * XXX Is it worth adding a sim_timeout entry
3354 			 * point so we can attempt recovery?  If
3355 			 * this is only used for dumps, I don't think
3356 			 * it is.
3357 			 */
3358 			start_ccb->ccb_h.status = CAM_CMD_TIMEOUT;
3359 		}
3360 	} else {
3361 		start_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
3362 	}
3363 	crit_exit();
3364 }
3365 
3366 /*
3367  * Schedule a peripheral driver to receive a ccb when it's
3368  * target device has space for more transactions.
3369  */
3370 void
3371 xpt_schedule(struct cam_periph *perph, u_int32_t new_priority)
3372 {
3373 	struct cam_ed *device;
3374 	int runq;
3375 
3376 	CAM_DEBUG(perph->path, CAM_DEBUG_TRACE, ("xpt_schedule\n"));
3377 	device = perph->path->device;
3378 	crit_enter();
3379 	if (periph_is_queued(perph)) {
3380 		/* Simply reorder based on new priority */
3381 		CAM_DEBUG(perph->path, CAM_DEBUG_SUBTRACE,
3382 			  ("   change priority to %d\n", new_priority));
3383 		if (new_priority < perph->pinfo.priority) {
3384 			camq_change_priority(&device->drvq,
3385 					     perph->pinfo.index,
3386 					     new_priority);
3387 		}
3388 		runq = 0;
3389 	} else {
3390 		/* New entry on the queue */
3391 		CAM_DEBUG(perph->path, CAM_DEBUG_SUBTRACE,
3392 			  ("   added periph to queue\n"));
3393 		perph->pinfo.priority = new_priority;
3394 		perph->pinfo.generation = ++device->drvq.generation;
3395 		camq_insert(&device->drvq, &perph->pinfo);
3396 		runq = xpt_schedule_dev_allocq(perph->path->bus, device);
3397 	}
3398 	crit_exit();
3399 	if (runq != 0) {
3400 		CAM_DEBUG(perph->path, CAM_DEBUG_SUBTRACE,
3401 			  ("   calling xpt_run_devq\n"));
3402 		xpt_run_dev_allocq(perph->path->bus);
3403 	}
3404 }
3405 
3406 
3407 /*
3408  * Schedule a device to run on a given queue.
3409  * If the device was inserted as a new entry on the queue,
3410  * return 1 meaning the device queue should be run. If we
3411  * were already queued, implying someone else has already
3412  * started the queue, return 0 so the caller doesn't attempt
3413  * to run the queue.  Must be run in a critical section.
3414  */
3415 static int
3416 xpt_schedule_dev(struct camq *queue, cam_pinfo *pinfo,
3417 		 u_int32_t new_priority)
3418 {
3419 	int retval;
3420 	u_int32_t old_priority;
3421 
3422 	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_schedule_dev\n"));
3423 
3424 	old_priority = pinfo->priority;
3425 
3426 	/*
3427 	 * Are we already queued?
3428 	 */
3429 	if (pinfo->index != CAM_UNQUEUED_INDEX) {
3430 		/* Simply reorder based on new priority */
3431 		if (new_priority < old_priority) {
3432 			camq_change_priority(queue, pinfo->index,
3433 					     new_priority);
3434 			CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3435 					("changed priority to %d\n",
3436 					 new_priority));
3437 		}
3438 		retval = 0;
3439 	} else {
3440 		/* New entry on the queue */
3441 		if (new_priority < old_priority)
3442 			pinfo->priority = new_priority;
3443 
3444 		CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3445 				("Inserting onto queue\n"));
3446 		pinfo->generation = ++queue->generation;
3447 		camq_insert(queue, pinfo);
3448 		retval = 1;
3449 	}
3450 	return (retval);
3451 }
3452 
3453 static void
3454 xpt_run_dev_allocq(struct cam_eb *bus)
3455 {
3456 	struct	cam_devq *devq;
3457 
3458 	if ((devq = bus->sim->devq) == NULL) {
3459 		CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_dev_allocq: NULL devq\n"));
3460 		return;
3461 	}
3462 	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_dev_allocq\n"));
3463 
3464 	CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3465 			("   qfrozen_cnt == 0x%x, entries == %d, "
3466 			 "openings == %d, active == %d\n",
3467 			 devq->alloc_queue.qfrozen_cnt,
3468 			 devq->alloc_queue.entries,
3469 			 devq->alloc_openings,
3470 			 devq->alloc_active));
3471 
3472 	crit_enter();
3473 	devq->alloc_queue.qfrozen_cnt++;
3474 	while ((devq->alloc_queue.entries > 0)
3475 	    && (devq->alloc_openings > 0)
3476 	    && (devq->alloc_queue.qfrozen_cnt <= 1)) {
3477 		struct	cam_ed_qinfo *qinfo;
3478 		struct	cam_ed *device;
3479 		union	ccb *work_ccb;
3480 		struct	cam_periph *drv;
3481 		struct	camq *drvq;
3482 
3483 		qinfo = (struct cam_ed_qinfo *)camq_remove(&devq->alloc_queue,
3484 							   CAMQ_HEAD);
3485 		device = qinfo->device;
3486 
3487 		CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3488 				("running device %p\n", device));
3489 
3490 		drvq = &device->drvq;
3491 
3492 #ifdef CAMDEBUG
3493 		if (drvq->entries <= 0) {
3494 			panic("xpt_run_dev_allocq: "
3495 			      "Device on queue without any work to do");
3496 		}
3497 #endif
3498 		if ((work_ccb = xpt_get_ccb(device)) != NULL) {
3499 			devq->alloc_openings--;
3500 			devq->alloc_active++;
3501 			drv = (struct cam_periph*)camq_remove(drvq, CAMQ_HEAD);
3502 			crit_exit();
3503 			xpt_setup_ccb(&work_ccb->ccb_h, drv->path,
3504 				      drv->pinfo.priority);
3505 			CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3506 					("calling periph start\n"));
3507 			drv->periph_start(drv, work_ccb);
3508 		} else {
3509 			/*
3510 			 * Malloc failure in alloc_ccb
3511 			 */
3512 			/*
3513 			 * XXX add us to a list to be run from free_ccb
3514 			 * if we don't have any ccbs active on this
3515 			 * device queue otherwise we may never get run
3516 			 * again.
3517 			 */
3518 			break;
3519 		}
3520 
3521 		/* Raise IPL for possible insertion and test at top of loop */
3522 		crit_enter();
3523 
3524 		if (drvq->entries > 0) {
3525 			/* We have more work.  Attempt to reschedule */
3526 			xpt_schedule_dev_allocq(bus, device);
3527 		}
3528 	}
3529 	devq->alloc_queue.qfrozen_cnt--;
3530 	crit_exit();
3531 }
3532 
3533 static void
3534 xpt_run_dev_sendq(struct cam_eb *bus)
3535 {
3536 	struct	cam_devq *devq;
3537 
3538 	if ((devq = bus->sim->devq) == NULL) {
3539 		CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_dev_sendq: NULL devq\n"));
3540 		return;
3541 	}
3542 	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_dev_sendq\n"));
3543 
3544 	crit_enter();
3545 	devq->send_queue.qfrozen_cnt++;
3546 	while ((devq->send_queue.entries > 0)
3547 	    && (devq->send_openings > 0)) {
3548 		struct	cam_ed_qinfo *qinfo;
3549 		struct	cam_ed *device;
3550 		union ccb *work_ccb;
3551 		struct	cam_sim *sim;
3552 
3553 	    	if (devq->send_queue.qfrozen_cnt > 1) {
3554 			break;
3555 		}
3556 
3557 		qinfo = (struct cam_ed_qinfo *)camq_remove(&devq->send_queue,
3558 							   CAMQ_HEAD);
3559 		device = qinfo->device;
3560 
3561 		/*
3562 		 * If the device has been "frozen", don't attempt
3563 		 * to run it.
3564 		 */
3565 		if (device->qfrozen_cnt > 0) {
3566 			continue;
3567 		}
3568 
3569 		CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3570 				("running device %p\n", device));
3571 
3572 		work_ccb = cam_ccbq_peek_ccb(&device->ccbq, CAMQ_HEAD);
3573 		if (work_ccb == NULL) {
3574 			kprintf("device on run queue with no ccbs???\n");
3575 			continue;
3576 		}
3577 
3578 		if ((work_ccb->ccb_h.flags & CAM_HIGH_POWER) != 0) {
3579 
3580 		 	if (num_highpower <= 0) {
3581 				/*
3582 				 * We got a high power command, but we
3583 				 * don't have any available slots.  Freeze
3584 				 * the device queue until we have a slot
3585 				 * available.
3586 				 */
3587 				device->qfrozen_cnt++;
3588 				STAILQ_INSERT_TAIL(&highpowerq,
3589 						   &work_ccb->ccb_h,
3590 						   xpt_links.stqe);
3591 
3592 				continue;
3593 			} else {
3594 				/*
3595 				 * Consume a high power slot while
3596 				 * this ccb runs.
3597 				 */
3598 				num_highpower--;
3599 			}
3600 		}
3601 		devq->active_dev = device;
3602 		cam_ccbq_remove_ccb(&device->ccbq, work_ccb);
3603 
3604 		cam_ccbq_send_ccb(&device->ccbq, work_ccb);
3605 
3606 		devq->send_openings--;
3607 		devq->send_active++;
3608 
3609 		if (device->ccbq.queue.entries > 0)
3610 			xpt_schedule_dev_sendq(bus, device);
3611 
3612 		if (work_ccb && (work_ccb->ccb_h.flags & CAM_DEV_QFREEZE) != 0){
3613 			/*
3614 			 * The client wants to freeze the queue
3615 			 * after this CCB is sent.
3616 			 */
3617 			device->qfrozen_cnt++;
3618 		}
3619 
3620 		/* In Target mode, the peripheral driver knows best... */
3621 		if (work_ccb->ccb_h.func_code == XPT_SCSI_IO) {
3622 			if ((device->inq_flags & SID_CmdQue) != 0
3623 			 && work_ccb->csio.tag_action != CAM_TAG_ACTION_NONE)
3624 				work_ccb->ccb_h.flags |= CAM_TAG_ACTION_VALID;
3625 			else
3626 				/*
3627 				 * Clear this in case of a retried CCB that
3628 				 * failed due to a rejected tag.
3629 				 */
3630 				work_ccb->ccb_h.flags &= ~CAM_TAG_ACTION_VALID;
3631 		}
3632 
3633 		/*
3634 		 * Device queues can be shared among multiple sim instances
3635 		 * that reside on different busses.  Use the SIM in the queue
3636 		 * CCB's path, rather than the one in the bus that was passed
3637 		 * into this function.
3638 		 */
3639 		sim = work_ccb->ccb_h.path->bus->sim;
3640 		(*(sim->sim_action))(sim, work_ccb);
3641 
3642 		devq->active_dev = NULL;
3643 		/* Raise IPL for possible insertion and test at top of loop */
3644 	}
3645 	devq->send_queue.qfrozen_cnt--;
3646 	crit_exit();
3647 }
3648 
3649 /*
3650  * This function merges stuff from the slave ccb into the master ccb, while
3651  * keeping important fields in the master ccb constant.
3652  */
3653 void
3654 xpt_merge_ccb(union ccb *master_ccb, union ccb *slave_ccb)
3655 {
3656 	/*
3657 	 * Pull fields that are valid for peripheral drivers to set
3658 	 * into the master CCB along with the CCB "payload".
3659 	 */
3660 	master_ccb->ccb_h.retry_count = slave_ccb->ccb_h.retry_count;
3661 	master_ccb->ccb_h.func_code = slave_ccb->ccb_h.func_code;
3662 	master_ccb->ccb_h.timeout = slave_ccb->ccb_h.timeout;
3663 	master_ccb->ccb_h.flags = slave_ccb->ccb_h.flags;
3664 	bcopy(&(&slave_ccb->ccb_h)[1], &(&master_ccb->ccb_h)[1],
3665 	      sizeof(union ccb) - sizeof(struct ccb_hdr));
3666 }
3667 
3668 void
3669 xpt_setup_ccb(struct ccb_hdr *ccb_h, struct cam_path *path, u_int32_t priority)
3670 {
3671 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_setup_ccb\n"));
3672 	callout_init(&ccb_h->timeout_ch);
3673 	ccb_h->pinfo.priority = priority;
3674 	ccb_h->path = path;
3675 	ccb_h->path_id = path->bus->path_id;
3676 	if (path->target)
3677 		ccb_h->target_id = path->target->target_id;
3678 	else
3679 		ccb_h->target_id = CAM_TARGET_WILDCARD;
3680 	if (path->device) {
3681 		ccb_h->target_lun = path->device->lun_id;
3682 		ccb_h->pinfo.generation = ++path->device->ccbq.queue.generation;
3683 	} else {
3684 		ccb_h->target_lun = CAM_TARGET_WILDCARD;
3685 	}
3686 	ccb_h->pinfo.index = CAM_UNQUEUED_INDEX;
3687 	ccb_h->flags = 0;
3688 }
3689 
3690 /* Path manipulation functions */
3691 cam_status
3692 xpt_create_path(struct cam_path **new_path_ptr, struct cam_periph *perph,
3693 		path_id_t path_id, target_id_t target_id, lun_id_t lun_id)
3694 {
3695 	struct	   cam_path *path;
3696 	cam_status status;
3697 
3698 	path = kmalloc(sizeof(*path), M_DEVBUF, M_INTWAIT);
3699 	status = xpt_compile_path(path, perph, path_id, target_id, lun_id);
3700 	if (status != CAM_REQ_CMP) {
3701 		kfree(path, M_DEVBUF);
3702 		path = NULL;
3703 	}
3704 	*new_path_ptr = path;
3705 	return (status);
3706 }
3707 
3708 static cam_status
3709 xpt_compile_path(struct cam_path *new_path, struct cam_periph *perph,
3710 		 path_id_t path_id, target_id_t target_id, lun_id_t lun_id)
3711 {
3712 	struct	     cam_eb *bus;
3713 	struct	     cam_et *target;
3714 	struct	     cam_ed *device;
3715 	cam_status   status;
3716 
3717 	status = CAM_REQ_CMP;	/* Completed without error */
3718 	target = NULL;		/* Wildcarded */
3719 	device = NULL;		/* Wildcarded */
3720 
3721 	/*
3722 	 * We will potentially modify the EDT, so block interrupts
3723 	 * that may attempt to create cam paths.
3724 	 */
3725 	crit_enter();
3726 	bus = xpt_find_bus(path_id);
3727 	if (bus == NULL) {
3728 		status = CAM_PATH_INVALID;
3729 	} else {
3730 		target = xpt_find_target(bus, target_id);
3731 		if (target == NULL) {
3732 			/* Create one */
3733 			struct cam_et *new_target;
3734 
3735 			new_target = xpt_alloc_target(bus, target_id);
3736 			if (new_target == NULL) {
3737 				status = CAM_RESRC_UNAVAIL;
3738 			} else {
3739 				target = new_target;
3740 			}
3741 		}
3742 		if (target != NULL) {
3743 			device = xpt_find_device(target, lun_id);
3744 			if (device == NULL) {
3745 				/* Create one */
3746 				struct cam_ed *new_device;
3747 
3748 				new_device = xpt_alloc_device(bus,
3749 							      target,
3750 							      lun_id);
3751 				if (new_device == NULL) {
3752 					status = CAM_RESRC_UNAVAIL;
3753 				} else {
3754 					device = new_device;
3755 				}
3756 			}
3757 		}
3758 	}
3759 	crit_exit();
3760 
3761 	/*
3762 	 * Only touch the user's data if we are successful.
3763 	 */
3764 	if (status == CAM_REQ_CMP) {
3765 		new_path->periph = perph;
3766 		new_path->bus = bus;
3767 		new_path->target = target;
3768 		new_path->device = device;
3769 		CAM_DEBUG(new_path, CAM_DEBUG_TRACE, ("xpt_compile_path\n"));
3770 	} else {
3771 		if (device != NULL)
3772 			xpt_release_device(bus, target, device);
3773 		if (target != NULL)
3774 			xpt_release_target(bus, target);
3775 		if (bus != NULL)
3776 			xpt_release_bus(bus);
3777 	}
3778 	return (status);
3779 }
3780 
3781 static void
3782 xpt_release_path(struct cam_path *path)
3783 {
3784 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_release_path\n"));
3785 	if (path->device != NULL) {
3786 		xpt_release_device(path->bus, path->target, path->device);
3787 		path->device = NULL;
3788 	}
3789 	if (path->target != NULL) {
3790 		xpt_release_target(path->bus, path->target);
3791 		path->target = NULL;
3792 	}
3793 	if (path->bus != NULL) {
3794 		xpt_release_bus(path->bus);
3795 		path->bus = NULL;
3796 	}
3797 }
3798 
3799 void
3800 xpt_free_path(struct cam_path *path)
3801 {
3802 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_free_path\n"));
3803 	xpt_release_path(path);
3804 	kfree(path, M_DEVBUF);
3805 }
3806 
3807 
3808 /*
3809  * Return -1 for failure, 0 for exact match, 1 for match with wildcards
3810  * in path1, 2 for match with wildcards in path2.
3811  */
3812 int
3813 xpt_path_comp(struct cam_path *path1, struct cam_path *path2)
3814 {
3815 	int retval = 0;
3816 
3817 	if (path1->bus != path2->bus) {
3818 		if (path1->bus->path_id == CAM_BUS_WILDCARD)
3819 			retval = 1;
3820 		else if (path2->bus->path_id == CAM_BUS_WILDCARD)
3821 			retval = 2;
3822 		else
3823 			return (-1);
3824 	}
3825 	if (path1->target != path2->target) {
3826 		if (path1->target->target_id == CAM_TARGET_WILDCARD) {
3827 			if (retval == 0)
3828 				retval = 1;
3829 		} else if (path2->target->target_id == CAM_TARGET_WILDCARD)
3830 			retval = 2;
3831 		else
3832 			return (-1);
3833 	}
3834 	if (path1->device != path2->device) {
3835 		if (path1->device->lun_id == CAM_LUN_WILDCARD) {
3836 			if (retval == 0)
3837 				retval = 1;
3838 		} else if (path2->device->lun_id == CAM_LUN_WILDCARD)
3839 			retval = 2;
3840 		else
3841 			return (-1);
3842 	}
3843 	return (retval);
3844 }
3845 
3846 void
3847 xpt_print_path(struct cam_path *path)
3848 {
3849 	if (path == NULL)
3850 		kprintf("(nopath): ");
3851 	else {
3852 		if (path->periph != NULL)
3853 			kprintf("(%s%d:", path->periph->periph_name,
3854 			       path->periph->unit_number);
3855 		else
3856 			kprintf("(noperiph:");
3857 
3858 		if (path->bus != NULL)
3859 			kprintf("%s%d:%d:", path->bus->sim->sim_name,
3860 			       path->bus->sim->unit_number,
3861 			       path->bus->sim->bus_id);
3862 		else
3863 			kprintf("nobus:");
3864 
3865 		if (path->target != NULL)
3866 			kprintf("%d:", path->target->target_id);
3867 		else
3868 			kprintf("X:");
3869 
3870 		if (path->device != NULL)
3871 			kprintf("%d): ", path->device->lun_id);
3872 		else
3873 			kprintf("X): ");
3874 	}
3875 }
3876 
3877 path_id_t
3878 xpt_path_path_id(struct cam_path *path)
3879 {
3880 	return(path->bus->path_id);
3881 }
3882 
3883 target_id_t
3884 xpt_path_target_id(struct cam_path *path)
3885 {
3886 	if (path->target != NULL)
3887 		return (path->target->target_id);
3888 	else
3889 		return (CAM_TARGET_WILDCARD);
3890 }
3891 
3892 lun_id_t
3893 xpt_path_lun_id(struct cam_path *path)
3894 {
3895 	if (path->device != NULL)
3896 		return (path->device->lun_id);
3897 	else
3898 		return (CAM_LUN_WILDCARD);
3899 }
3900 
3901 struct cam_sim *
3902 xpt_path_sim(struct cam_path *path)
3903 {
3904 	return (path->bus->sim);
3905 }
3906 
3907 struct cam_periph*
3908 xpt_path_periph(struct cam_path *path)
3909 {
3910 	return (path->periph);
3911 }
3912 
3913 /*
3914  * Release a CAM control block for the caller.  Remit the cost of the structure
3915  * to the device referenced by the path.  If the this device had no 'credits'
3916  * and peripheral drivers have registered async callbacks for this notification
3917  * call them now.
3918  */
3919 void
3920 xpt_release_ccb(union ccb *free_ccb)
3921 {
3922 	struct	 cam_path *path;
3923 	struct	 cam_ed *device;
3924 	struct	 cam_eb *bus;
3925 
3926 	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_release_ccb\n"));
3927 	path = free_ccb->ccb_h.path;
3928 	device = path->device;
3929 	bus = path->bus;
3930 	crit_enter();
3931 	cam_ccbq_release_opening(&device->ccbq);
3932 	if (xpt_ccb_count > xpt_max_ccbs) {
3933 		xpt_free_ccb(free_ccb);
3934 		xpt_ccb_count--;
3935 	} else {
3936 		SLIST_INSERT_HEAD(&ccb_freeq, &free_ccb->ccb_h, xpt_links.sle);
3937 	}
3938 	if (bus->sim->devq) {
3939 		bus->sim->devq->alloc_openings++;
3940 		bus->sim->devq->alloc_active--;
3941 	}
3942 	/* XXX Turn this into an inline function - xpt_run_device?? */
3943 	if ((device_is_alloc_queued(device) == 0)
3944 	 && (device->drvq.entries > 0)) {
3945 		xpt_schedule_dev_allocq(bus, device);
3946 	}
3947 	crit_exit();
3948 	if (bus->sim->devq && dev_allocq_is_runnable(bus->sim->devq))
3949 		xpt_run_dev_allocq(bus);
3950 }
3951 
3952 /* Functions accessed by SIM drivers */
3953 
3954 /*
3955  * A sim structure, listing the SIM entry points and instance
3956  * identification info is passed to xpt_bus_register to hook the SIM
3957  * into the CAM framework.  xpt_bus_register creates a cam_eb entry
3958  * for this new bus and places it in the array of busses and assigns
3959  * it a path_id.  The path_id may be influenced by "hard wiring"
3960  * information specified by the user.  Once interrupt services are
3961  * availible, the bus will be probed.
3962  */
3963 int32_t
3964 xpt_bus_register(struct cam_sim *sim, u_int32_t bus)
3965 {
3966 	struct cam_eb *new_bus;
3967 	struct cam_eb *old_bus;
3968 	struct ccb_pathinq cpi;
3969 
3970 	sim->bus_id = bus;
3971 	new_bus = kmalloc(sizeof(*new_bus), M_DEVBUF, M_INTWAIT);
3972 
3973 	if (strcmp(sim->sim_name, "xpt") != 0) {
3974 		sim->path_id =
3975 		    xptpathid(sim->sim_name, sim->unit_number, sim->bus_id);
3976 	}
3977 
3978 	TAILQ_INIT(&new_bus->et_entries);
3979 	new_bus->path_id = sim->path_id;
3980 	new_bus->sim = sim;
3981 	++sim->refcount;
3982 	timevalclear(&new_bus->last_reset);
3983 	new_bus->flags = 0;
3984 	new_bus->refcount = 1;	/* Held until a bus_deregister event */
3985 	new_bus->generation = 0;
3986 	crit_enter();
3987 	old_bus = TAILQ_FIRST(&xpt_busses);
3988 	while (old_bus != NULL
3989 	    && old_bus->path_id < new_bus->path_id)
3990 		old_bus = TAILQ_NEXT(old_bus, links);
3991 	if (old_bus != NULL)
3992 		TAILQ_INSERT_BEFORE(old_bus, new_bus, links);
3993 	else
3994 		TAILQ_INSERT_TAIL(&xpt_busses, new_bus, links);
3995 	bus_generation++;
3996 	crit_exit();
3997 
3998 	/* Notify interested parties */
3999 	if (sim->path_id != CAM_XPT_PATH_ID) {
4000 		struct cam_path path;
4001 
4002 		xpt_compile_path(&path, /*periph*/NULL, sim->path_id,
4003 			         CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
4004 		xpt_setup_ccb(&cpi.ccb_h, &path, /*priority*/1);
4005 		cpi.ccb_h.func_code = XPT_PATH_INQ;
4006 		xpt_action((union ccb *)&cpi);
4007 		xpt_async(AC_PATH_REGISTERED, xpt_periph->path, &cpi);
4008 		xpt_release_path(&path);
4009 	}
4010 	return (CAM_SUCCESS);
4011 }
4012 
4013 /*
4014  * Deregister a bus.  We must clean out all transactions pending on the bus.
4015  * This routine is typically called prior to cam_sim_free() (e.g. see
4016  * dev/usbmisc/umass/umass.c)
4017  */
4018 int32_t
4019 xpt_bus_deregister(path_id_t pathid)
4020 {
4021 	struct cam_path bus_path;
4022 	cam_status status;
4023 
4024 	status = xpt_compile_path(&bus_path, NULL, pathid,
4025 				  CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
4026 	if (status != CAM_REQ_CMP)
4027 		return (status);
4028 
4029 	/*
4030 	 * This should clear out all pending requests and timeouts, but
4031 	 * the ccb's may be queued to a software interrupt.
4032 	 *
4033 	 * XXX AC_LOST_DEVICE does not precisely abort the pending requests,
4034 	 * and it really ought to.
4035 	 */
4036 	xpt_async(AC_LOST_DEVICE, &bus_path, NULL);
4037 	xpt_async(AC_PATH_DEREGISTERED, &bus_path, NULL);
4038 
4039 	/* make sure all responses have been processed */
4040 	camisr(&cam_netq);
4041 	camisr(&cam_bioq);
4042 
4043 	/* Release the reference count held while registered. */
4044 	xpt_release_bus(bus_path.bus);
4045 	xpt_release_path(&bus_path);
4046 
4047 	return (CAM_REQ_CMP);
4048 }
4049 
4050 static path_id_t
4051 xptnextfreepathid(void)
4052 {
4053 	struct cam_eb *bus;
4054 	path_id_t pathid;
4055 	char *strval;
4056 
4057 	pathid = 0;
4058 	bus = TAILQ_FIRST(&xpt_busses);
4059 retry:
4060 	/* Find an unoccupied pathid */
4061 	while (bus != NULL
4062 	    && bus->path_id <= pathid) {
4063 		if (bus->path_id == pathid)
4064 			pathid++;
4065 		bus = TAILQ_NEXT(bus, links);
4066 	}
4067 
4068 	/*
4069 	 * Ensure that this pathid is not reserved for
4070 	 * a bus that may be registered in the future.
4071 	 */
4072 	if (resource_string_value("scbus", pathid, "at", &strval) == 0) {
4073 		++pathid;
4074 		/* Start the search over */
4075 		goto retry;
4076 	}
4077 	return (pathid);
4078 }
4079 
4080 static path_id_t
4081 xptpathid(const char *sim_name, int sim_unit, int sim_bus)
4082 {
4083 	path_id_t pathid;
4084 	int i, dunit, val;
4085 	char buf[32], *strval;
4086 
4087 	pathid = CAM_XPT_PATH_ID;
4088 	ksnprintf(buf, sizeof(buf), "%s%d", sim_name, sim_unit);
4089 	i = -1;
4090 	while ((i = resource_locate(i, "scbus")) != -1) {
4091 		dunit = resource_query_unit(i);
4092 		if (dunit < 0)		/* unwired?! */
4093 			continue;
4094 		if (resource_string_value("scbus", dunit, "at", &strval) != 0)
4095 			continue;
4096 		if (strcmp(buf, strval) != 0)
4097 			continue;
4098 		if (resource_int_value("scbus", dunit, "bus", &val) == 0) {
4099 			if (sim_bus == val) {
4100 				pathid = dunit;
4101 				break;
4102 			}
4103 		} else if (sim_bus == 0) {
4104 			/* Unspecified matches bus 0 */
4105 			pathid = dunit;
4106 			break;
4107 		} else {
4108 			kprintf("Ambiguous scbus configuration for %s%d "
4109 			       "bus %d, cannot wire down.  The kernel "
4110 			       "config entry for scbus%d should "
4111 			       "specify a controller bus.\n"
4112 			       "Scbus will be assigned dynamically.\n",
4113 			       sim_name, sim_unit, sim_bus, dunit);
4114 			break;
4115 		}
4116 	}
4117 
4118 	if (pathid == CAM_XPT_PATH_ID)
4119 		pathid = xptnextfreepathid();
4120 	return (pathid);
4121 }
4122 
4123 void
4124 xpt_async(u_int32_t async_code, struct cam_path *path, void *async_arg)
4125 {
4126 	struct cam_eb *bus;
4127 	struct cam_et *target, *next_target;
4128 	struct cam_ed *device, *next_device;
4129 
4130 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_async\n"));
4131 
4132 	/*
4133 	 * Most async events come from a CAM interrupt context.  In
4134 	 * a few cases, the error recovery code at the peripheral layer,
4135 	 * which may run from our SWI or a process context, may signal
4136 	 * deferred events with a call to xpt_async. Ensure async
4137 	 * notifications are serialized by blocking cam interrupts.
4138 	 */
4139 	crit_enter();
4140 
4141 	bus = path->bus;
4142 
4143 	if (async_code == AC_BUS_RESET) {
4144 		/* Update our notion of when the last reset occurred */
4145 		microuptime(&bus->last_reset);
4146 	}
4147 
4148 	for (target = TAILQ_FIRST(&bus->et_entries);
4149 	     target != NULL;
4150 	     target = next_target) {
4151 
4152 		next_target = TAILQ_NEXT(target, links);
4153 
4154 		if (path->target != target
4155 		 && path->target->target_id != CAM_TARGET_WILDCARD
4156 		 && target->target_id != CAM_TARGET_WILDCARD)
4157 			continue;
4158 
4159 		if (async_code == AC_SENT_BDR) {
4160 			/* Update our notion of when the last reset occurred */
4161 			microuptime(&path->target->last_reset);
4162 		}
4163 
4164 		for (device = TAILQ_FIRST(&target->ed_entries);
4165 		     device != NULL;
4166 		     device = next_device) {
4167 
4168 			next_device = TAILQ_NEXT(device, links);
4169 
4170 			if (path->device != device
4171 			 && path->device->lun_id != CAM_LUN_WILDCARD
4172 			 && device->lun_id != CAM_LUN_WILDCARD)
4173 				continue;
4174 
4175 			xpt_dev_async(async_code, bus, target,
4176 				      device, async_arg);
4177 
4178 			xpt_async_bcast(&device->asyncs, async_code,
4179 					path, async_arg);
4180 		}
4181 	}
4182 
4183 	/*
4184 	 * If this wasn't a fully wildcarded async, tell all
4185 	 * clients that want all async events.
4186 	 */
4187 	if (bus != xpt_periph->path->bus)
4188 		xpt_async_bcast(&xpt_periph->path->device->asyncs, async_code,
4189 				path, async_arg);
4190 	crit_exit();
4191 }
4192 
4193 static void
4194 xpt_async_bcast(struct async_list *async_head,
4195 		u_int32_t async_code,
4196 		struct cam_path *path, void *async_arg)
4197 {
4198 	struct async_node *cur_entry;
4199 
4200 	cur_entry = SLIST_FIRST(async_head);
4201 	while (cur_entry != NULL) {
4202 		struct async_node *next_entry;
4203 		/*
4204 		 * Grab the next list entry before we call the current
4205 		 * entry's callback.  This is because the callback function
4206 		 * can delete its async callback entry.
4207 		 */
4208 		next_entry = SLIST_NEXT(cur_entry, links);
4209 		if ((cur_entry->event_enable & async_code) != 0)
4210 			cur_entry->callback(cur_entry->callback_arg,
4211 					    async_code, path,
4212 					    async_arg);
4213 		cur_entry = next_entry;
4214 	}
4215 }
4216 
4217 /*
4218  * Handle any per-device event notifications that require action by the XPT.
4219  */
4220 static void
4221 xpt_dev_async(u_int32_t async_code, struct cam_eb *bus, struct cam_et *target,
4222 	      struct cam_ed *device, void *async_arg)
4223 {
4224 	cam_status status;
4225 	struct cam_path newpath;
4226 
4227 	/*
4228 	 * We only need to handle events for real devices.
4229 	 */
4230 	if (target->target_id == CAM_TARGET_WILDCARD
4231 	 || device->lun_id == CAM_LUN_WILDCARD)
4232 		return;
4233 
4234 	/*
4235 	 * We need our own path with wildcards expanded to
4236 	 * handle certain types of events.
4237 	 */
4238 	if ((async_code == AC_SENT_BDR)
4239 	 || (async_code == AC_BUS_RESET)
4240 	 || (async_code == AC_INQ_CHANGED))
4241 		status = xpt_compile_path(&newpath, NULL,
4242 					  bus->path_id,
4243 					  target->target_id,
4244 					  device->lun_id);
4245 	else
4246 		status = CAM_REQ_CMP_ERR;
4247 
4248 	if (status == CAM_REQ_CMP) {
4249 
4250 		/*
4251 		 * Allow transfer negotiation to occur in a
4252 		 * tag free environment.
4253 		 */
4254 		if (async_code == AC_SENT_BDR
4255 		 || async_code == AC_BUS_RESET)
4256 			xpt_toggle_tags(&newpath);
4257 
4258 		if (async_code == AC_INQ_CHANGED) {
4259 			/*
4260 			 * We've sent a start unit command, or
4261 			 * something similar to a device that
4262 			 * may have caused its inquiry data to
4263 			 * change. So we re-scan the device to
4264 			 * refresh the inquiry data for it.
4265 			 */
4266 			xpt_scan_lun(newpath.periph, &newpath,
4267 				     CAM_EXPECT_INQ_CHANGE, NULL);
4268 		}
4269 		xpt_release_path(&newpath);
4270 	} else if (async_code == AC_LOST_DEVICE) {
4271 		/*
4272 		 * When we lose a device the device may be about to detach
4273 		 * the sim, we have to clear out all pending timeouts and
4274 		 * requests before that happens.  XXX it would be nice if
4275 		 * we could abort the requests pertaining to the device.
4276 		 */
4277 		xpt_release_devq_timeout(device);
4278 		if ((device->flags & CAM_DEV_UNCONFIGURED) == 0) {
4279 			device->flags |= CAM_DEV_UNCONFIGURED;
4280 			xpt_release_device(bus, target, device);
4281 		}
4282 	} else if (async_code == AC_TRANSFER_NEG) {
4283 		struct ccb_trans_settings *settings;
4284 
4285 		settings = (struct ccb_trans_settings *)async_arg;
4286 		xpt_set_transfer_settings(settings, device,
4287 					  /*async_update*/TRUE);
4288 	}
4289 }
4290 
4291 u_int32_t
4292 xpt_freeze_devq(struct cam_path *path, u_int count)
4293 {
4294 	struct ccb_hdr *ccbh;
4295 
4296 	crit_enter();
4297 	path->device->qfrozen_cnt += count;
4298 
4299 	/*
4300 	 * Mark the last CCB in the queue as needing
4301 	 * to be requeued if the driver hasn't
4302 	 * changed it's state yet.  This fixes a race
4303 	 * where a ccb is just about to be queued to
4304 	 * a controller driver when it's interrupt routine
4305 	 * freezes the queue.  To completly close the
4306 	 * hole, controller drives must check to see
4307 	 * if a ccb's status is still CAM_REQ_INPROG
4308 	 * under critical section protection just before they queue
4309 	 * the CCB.  See ahc_action/ahc_freeze_devq for
4310 	 * an example.
4311 	 */
4312 	ccbh = TAILQ_LAST(&path->device->ccbq.active_ccbs, ccb_hdr_tailq);
4313 	if (ccbh && ccbh->status == CAM_REQ_INPROG)
4314 		ccbh->status = CAM_REQUEUE_REQ;
4315 	crit_exit();
4316 	return (path->device->qfrozen_cnt);
4317 }
4318 
4319 u_int32_t
4320 xpt_freeze_simq(struct cam_sim *sim, u_int count)
4321 {
4322 	if (sim->devq == NULL)
4323 		return(count);
4324 	sim->devq->send_queue.qfrozen_cnt += count;
4325 	if (sim->devq->active_dev != NULL) {
4326 		struct ccb_hdr *ccbh;
4327 
4328 		ccbh = TAILQ_LAST(&sim->devq->active_dev->ccbq.active_ccbs,
4329 				  ccb_hdr_tailq);
4330 		if (ccbh && ccbh->status == CAM_REQ_INPROG)
4331 			ccbh->status = CAM_REQUEUE_REQ;
4332 	}
4333 	return (sim->devq->send_queue.qfrozen_cnt);
4334 }
4335 
4336 /*
4337  * WARNING: most devices, especially USB/UMASS, may detach their sim early.
4338  * We ref-count the sim (and the bus only NULLs it out when the bus has been
4339  * freed, which is not the case here), but the device queue is also freed XXX
4340  * and we have to check that here.
4341  *
4342  * XXX fixme: could we simply not null-out the device queue via
4343  * cam_sim_free()?
4344  */
4345 static void
4346 xpt_release_devq_timeout(void *arg)
4347 {
4348 	struct cam_ed *device;
4349 
4350 	device = (struct cam_ed *)arg;
4351 
4352 	xpt_release_devq_device(device, /*count*/1, /*run_queue*/TRUE);
4353 }
4354 
4355 void
4356 xpt_release_devq(struct cam_path *path, u_int count, int run_queue)
4357 {
4358 	xpt_release_devq_device(path->device, count, run_queue);
4359 }
4360 
4361 static void
4362 xpt_release_devq_device(struct cam_ed *dev, u_int count, int run_queue)
4363 {
4364 	int	rundevq;
4365 
4366 	rundevq = 0;
4367 	crit_enter();
4368 
4369 	if (dev->qfrozen_cnt > 0) {
4370 
4371 		count = (count > dev->qfrozen_cnt) ? dev->qfrozen_cnt : count;
4372 		dev->qfrozen_cnt -= count;
4373 		if (dev->qfrozen_cnt == 0) {
4374 
4375 			/*
4376 			 * No longer need to wait for a successful
4377 			 * command completion.
4378 			 */
4379 			dev->flags &= ~CAM_DEV_REL_ON_COMPLETE;
4380 
4381 			/*
4382 			 * Remove any timeouts that might be scheduled
4383 			 * to release this queue.
4384 			 */
4385 			if ((dev->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
4386 				callout_stop(&dev->c_handle);
4387 				dev->flags &= ~CAM_DEV_REL_TIMEOUT_PENDING;
4388 			}
4389 
4390 			/*
4391 			 * Now that we are unfrozen schedule the
4392 			 * device so any pending transactions are
4393 			 * run.
4394 			 */
4395 			if ((dev->ccbq.queue.entries > 0)
4396 			 && (xpt_schedule_dev_sendq(dev->target->bus, dev))
4397 			 && (run_queue != 0)) {
4398 				rundevq = 1;
4399 			}
4400 		}
4401 	}
4402 	if (rundevq != 0)
4403 		xpt_run_dev_sendq(dev->target->bus);
4404 	crit_exit();
4405 }
4406 
4407 void
4408 xpt_release_simq(struct cam_sim *sim, int run_queue)
4409 {
4410 	struct	camq *sendq;
4411 
4412 	if (sim->devq == NULL)
4413 		return;
4414 
4415 	sendq = &(sim->devq->send_queue);
4416 	crit_enter();
4417 
4418 	if (sendq->qfrozen_cnt > 0) {
4419 		sendq->qfrozen_cnt--;
4420 		if (sendq->qfrozen_cnt == 0) {
4421 			struct cam_eb *bus;
4422 
4423 			/*
4424 			 * If there is a timeout scheduled to release this
4425 			 * sim queue, remove it.  The queue frozen count is
4426 			 * already at 0.
4427 			 */
4428 			if ((sim->flags & CAM_SIM_REL_TIMEOUT_PENDING) != 0){
4429 				callout_stop(&sim->c_handle);
4430 				sim->flags &= ~CAM_SIM_REL_TIMEOUT_PENDING;
4431 			}
4432 			bus = xpt_find_bus(sim->path_id);
4433 			crit_exit();
4434 
4435 			if (run_queue) {
4436 				/*
4437 				 * Now that we are unfrozen run the send queue.
4438 				 */
4439 				xpt_run_dev_sendq(bus);
4440 			}
4441 			xpt_release_bus(bus);
4442 		} else {
4443 			crit_exit();
4444 		}
4445 	} else {
4446 		crit_exit();
4447 	}
4448 }
4449 
4450 void
4451 xpt_done(union ccb *done_ccb)
4452 {
4453 	crit_enter();
4454 
4455 	CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("xpt_done\n"));
4456 	if ((done_ccb->ccb_h.func_code & XPT_FC_QUEUED) != 0) {
4457 		/*
4458 		 * Queue up the request for handling by our SWI handler
4459 		 * any of the "non-immediate" type of ccbs.
4460 		 */
4461 		switch (done_ccb->ccb_h.path->periph->type) {
4462 		case CAM_PERIPH_BIO:
4463 			TAILQ_INSERT_TAIL(&cam_bioq, &done_ccb->ccb_h,
4464 					  sim_links.tqe);
4465 			done_ccb->ccb_h.pinfo.index = CAM_DONEQ_INDEX;
4466 			setsoftcambio();
4467 			break;
4468 		case CAM_PERIPH_NET:
4469 			TAILQ_INSERT_TAIL(&cam_netq, &done_ccb->ccb_h,
4470 					  sim_links.tqe);
4471 			done_ccb->ccb_h.pinfo.index = CAM_DONEQ_INDEX;
4472 			setsoftcamnet();
4473 			break;
4474 		}
4475 	}
4476 	crit_exit();
4477 }
4478 
4479 union ccb *
4480 xpt_alloc_ccb(void)
4481 {
4482 	union ccb *new_ccb;
4483 
4484 	new_ccb = kmalloc(sizeof(*new_ccb), M_DEVBUF, M_INTWAIT);
4485 	return (new_ccb);
4486 }
4487 
4488 void
4489 xpt_free_ccb(union ccb *free_ccb)
4490 {
4491 	kfree(free_ccb, M_DEVBUF);
4492 }
4493 
4494 
4495 
4496 /* Private XPT functions */
4497 
4498 /*
4499  * Get a CAM control block for the caller. Charge the structure to the device
4500  * referenced by the path.  If the this device has no 'credits' then the
4501  * device already has the maximum number of outstanding operations under way
4502  * and we return NULL. If we don't have sufficient resources to allocate more
4503  * ccbs, we also return NULL.
4504  */
4505 static union ccb *
4506 xpt_get_ccb(struct cam_ed *device)
4507 {
4508 	union ccb *new_ccb;
4509 
4510 	crit_enter();
4511 	if ((new_ccb = (union ccb *)ccb_freeq.slh_first) == NULL) {
4512 		new_ccb = kmalloc(sizeof(*new_ccb), M_DEVBUF, M_INTWAIT);
4513 		SLIST_INSERT_HEAD(&ccb_freeq, &new_ccb->ccb_h,
4514 				  xpt_links.sle);
4515 		xpt_ccb_count++;
4516 	}
4517 	cam_ccbq_take_opening(&device->ccbq);
4518 	SLIST_REMOVE_HEAD(&ccb_freeq, xpt_links.sle);
4519 	crit_exit();
4520 	return (new_ccb);
4521 }
4522 
4523 static void
4524 xpt_release_bus(struct cam_eb *bus)
4525 {
4526 
4527 	crit_enter();
4528 	if (bus->refcount == 1) {
4529 		KKASSERT(TAILQ_FIRST(&bus->et_entries) == NULL);
4530 		TAILQ_REMOVE(&xpt_busses, bus, links);
4531 		if (bus->sim) {
4532 			cam_sim_release(bus->sim, 0);
4533 			bus->sim = NULL;
4534 		}
4535 		bus_generation++;
4536 		KKASSERT(bus->refcount == 1);
4537 		kfree(bus, M_DEVBUF);
4538 	} else {
4539 		--bus->refcount;
4540 	}
4541 	crit_exit();
4542 }
4543 
4544 static struct cam_et *
4545 xpt_alloc_target(struct cam_eb *bus, target_id_t target_id)
4546 {
4547 	struct cam_et *target;
4548 	struct cam_et *cur_target;
4549 
4550 	target = kmalloc(sizeof(*target), M_DEVBUF, M_INTWAIT);
4551 
4552 	TAILQ_INIT(&target->ed_entries);
4553 	target->bus = bus;
4554 	target->target_id = target_id;
4555 	target->refcount = 1;
4556 	target->generation = 0;
4557 	timevalclear(&target->last_reset);
4558 	/*
4559 	 * Hold a reference to our parent bus so it
4560 	 * will not go away before we do.
4561 	 */
4562 	bus->refcount++;
4563 
4564 	/* Insertion sort into our bus's target list */
4565 	cur_target = TAILQ_FIRST(&bus->et_entries);
4566 	while (cur_target != NULL && cur_target->target_id < target_id)
4567 		cur_target = TAILQ_NEXT(cur_target, links);
4568 
4569 	if (cur_target != NULL) {
4570 		TAILQ_INSERT_BEFORE(cur_target, target, links);
4571 	} else {
4572 		TAILQ_INSERT_TAIL(&bus->et_entries, target, links);
4573 	}
4574 	bus->generation++;
4575 	return (target);
4576 }
4577 
4578 static void
4579 xpt_release_target(struct cam_eb *bus, struct cam_et *target)
4580 {
4581 	crit_enter();
4582 	if (target->refcount == 1) {
4583 		KKASSERT(TAILQ_FIRST(&target->ed_entries) == NULL);
4584 		TAILQ_REMOVE(&bus->et_entries, target, links);
4585 		bus->generation++;
4586 		xpt_release_bus(bus);
4587 		KKASSERT(target->refcount == 1);
4588 		kfree(target, M_DEVBUF);
4589 	} else {
4590 		--target->refcount;
4591 	}
4592 	crit_exit();
4593 }
4594 
4595 static struct cam_ed *
4596 xpt_alloc_device(struct cam_eb *bus, struct cam_et *target, lun_id_t lun_id)
4597 {
4598 	struct	   cam_ed *device;
4599 	struct	   cam_devq *devq;
4600 	cam_status status;
4601 
4602 	/* Make space for us in the device queue on our bus */
4603 	if (bus->sim->devq == NULL)
4604 		return(NULL);
4605 	devq = bus->sim->devq;
4606 	status = cam_devq_resize(devq, devq->alloc_queue.array_size + 1);
4607 
4608 	if (status != CAM_REQ_CMP) {
4609 		device = NULL;
4610 	} else {
4611 		device = kmalloc(sizeof(*device), M_DEVBUF, M_INTWAIT);
4612 	}
4613 
4614 	if (device != NULL) {
4615 		struct cam_ed *cur_device;
4616 
4617 		cam_init_pinfo(&device->alloc_ccb_entry.pinfo);
4618 		device->alloc_ccb_entry.device = device;
4619 		cam_init_pinfo(&device->send_ccb_entry.pinfo);
4620 		device->send_ccb_entry.device = device;
4621 		device->target = target;
4622 		device->lun_id = lun_id;
4623 		/* Initialize our queues */
4624 		if (camq_init(&device->drvq, 0) != 0) {
4625 			kfree(device, M_DEVBUF);
4626 			return (NULL);
4627 		}
4628 		if (cam_ccbq_init(&device->ccbq,
4629 				  bus->sim->max_dev_openings) != 0) {
4630 			camq_fini(&device->drvq);
4631 			kfree(device, M_DEVBUF);
4632 			return (NULL);
4633 		}
4634 		SLIST_INIT(&device->asyncs);
4635 		SLIST_INIT(&device->periphs);
4636 		device->generation = 0;
4637 		device->owner = NULL;
4638 		/*
4639 		 * Take the default quirk entry until we have inquiry
4640 		 * data and can determine a better quirk to use.
4641 		 */
4642 		device->quirk = &xpt_quirk_table[xpt_quirk_table_size - 1];
4643 		bzero(&device->inq_data, sizeof(device->inq_data));
4644 		device->inq_flags = 0;
4645 		device->queue_flags = 0;
4646 		device->serial_num = NULL;
4647 		device->serial_num_len = 0;
4648 		device->qfrozen_cnt = 0;
4649 		device->flags = CAM_DEV_UNCONFIGURED;
4650 		device->tag_delay_count = 0;
4651 		device->refcount = 1;
4652 		callout_init(&device->c_handle);
4653 
4654 		/*
4655 		 * Hold a reference to our parent target so it
4656 		 * will not go away before we do.
4657 		 */
4658 		target->refcount++;
4659 
4660 		/*
4661 		 * XXX should be limited by number of CCBs this bus can
4662 		 * do.
4663 		 */
4664 		xpt_max_ccbs += device->ccbq.devq_openings;
4665 		/* Insertion sort into our target's device list */
4666 		cur_device = TAILQ_FIRST(&target->ed_entries);
4667 		while (cur_device != NULL && cur_device->lun_id < lun_id)
4668 			cur_device = TAILQ_NEXT(cur_device, links);
4669 		if (cur_device != NULL) {
4670 			TAILQ_INSERT_BEFORE(cur_device, device, links);
4671 		} else {
4672 			TAILQ_INSERT_TAIL(&target->ed_entries, device, links);
4673 		}
4674 		target->generation++;
4675 	}
4676 	return (device);
4677 }
4678 
4679 static void
4680 xpt_reference_device(struct cam_ed *device)
4681 {
4682 	++device->refcount;
4683 }
4684 
4685 static void
4686 xpt_release_device(struct cam_eb *bus, struct cam_et *target,
4687 		   struct cam_ed *device)
4688 {
4689 	struct cam_devq *devq;
4690 
4691 	crit_enter();
4692 	if (device->refcount == 1) {
4693 		KKASSERT(device->flags & CAM_DEV_UNCONFIGURED);
4694 
4695 		if (device->alloc_ccb_entry.pinfo.index != CAM_UNQUEUED_INDEX
4696 		 || device->send_ccb_entry.pinfo.index != CAM_UNQUEUED_INDEX)
4697 			panic("Removing device while still queued for ccbs");
4698 
4699 		if ((device->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
4700 			device->flags &= ~CAM_DEV_REL_TIMEOUT_PENDING;
4701 			callout_stop(&device->c_handle);
4702 		}
4703 
4704 		TAILQ_REMOVE(&target->ed_entries, device,links);
4705 		target->generation++;
4706 		xpt_max_ccbs -= device->ccbq.devq_openings;
4707 		/* Release our slot in the devq */
4708 		devq = bus->sim->devq;
4709 		cam_devq_resize(devq, devq->alloc_queue.array_size - 1);
4710 		xpt_release_target(bus, target);
4711 		KKASSERT(device->refcount == 1);
4712 		kfree(device, M_DEVBUF);
4713 	} else {
4714 		--device->refcount;
4715 	}
4716 	crit_exit();
4717 }
4718 
4719 static u_int32_t
4720 xpt_dev_ccbq_resize(struct cam_path *path, int newopenings)
4721 {
4722 	int	diff;
4723 	int	result;
4724 	struct	cam_ed *dev;
4725 
4726 	dev = path->device;
4727 
4728 	crit_enter();
4729 
4730 	diff = newopenings - (dev->ccbq.dev_active + dev->ccbq.dev_openings);
4731 	result = cam_ccbq_resize(&dev->ccbq, newopenings);
4732 	if (result == CAM_REQ_CMP && (diff < 0)) {
4733 		dev->flags |= CAM_DEV_RESIZE_QUEUE_NEEDED;
4734 	}
4735 	/* Adjust the global limit */
4736 	xpt_max_ccbs += diff;
4737 	crit_exit();
4738 	return (result);
4739 }
4740 
4741 static struct cam_eb *
4742 xpt_find_bus(path_id_t path_id)
4743 {
4744 	struct cam_eb *bus;
4745 
4746 	for (bus = TAILQ_FIRST(&xpt_busses);
4747 	     bus != NULL;
4748 	     bus = TAILQ_NEXT(bus, links)) {
4749 		if (bus->path_id == path_id) {
4750 			bus->refcount++;
4751 			break;
4752 		}
4753 	}
4754 	return (bus);
4755 }
4756 
4757 static struct cam_et *
4758 xpt_find_target(struct cam_eb *bus, target_id_t	target_id)
4759 {
4760 	struct cam_et *target;
4761 
4762 	for (target = TAILQ_FIRST(&bus->et_entries);
4763 	     target != NULL;
4764 	     target = TAILQ_NEXT(target, links)) {
4765 		if (target->target_id == target_id) {
4766 			target->refcount++;
4767 			break;
4768 		}
4769 	}
4770 	return (target);
4771 }
4772 
4773 static struct cam_ed *
4774 xpt_find_device(struct cam_et *target, lun_id_t lun_id)
4775 {
4776 	struct cam_ed *device;
4777 
4778 	for (device = TAILQ_FIRST(&target->ed_entries);
4779 	     device != NULL;
4780 	     device = TAILQ_NEXT(device, links)) {
4781 		if (device->lun_id == lun_id) {
4782 			device->refcount++;
4783 			break;
4784 		}
4785 	}
4786 	return (device);
4787 }
4788 
4789 typedef struct {
4790 	union	ccb *request_ccb;
4791 	struct 	ccb_pathinq *cpi;
4792 	int	pending_count;
4793 } xpt_scan_bus_info;
4794 
4795 /*
4796  * To start a scan, request_ccb is an XPT_SCAN_BUS ccb.
4797  * As the scan progresses, xpt_scan_bus is used as the
4798  * callback on completion function.
4799  */
4800 static void
4801 xpt_scan_bus(struct cam_periph *periph, union ccb *request_ccb)
4802 {
4803 	CAM_DEBUG(request_ccb->ccb_h.path, CAM_DEBUG_TRACE,
4804 		  ("xpt_scan_bus\n"));
4805 	switch (request_ccb->ccb_h.func_code) {
4806 	case XPT_SCAN_BUS:
4807 	{
4808 		xpt_scan_bus_info *scan_info;
4809 		union	ccb *work_ccb;
4810 		struct	cam_path *path;
4811 		u_int	i;
4812 		u_int	max_target;
4813 		u_int	initiator_id;
4814 
4815 		/* Find out the characteristics of the bus */
4816 		work_ccb = xpt_alloc_ccb();
4817 		xpt_setup_ccb(&work_ccb->ccb_h, request_ccb->ccb_h.path,
4818 			      request_ccb->ccb_h.pinfo.priority);
4819 		work_ccb->ccb_h.func_code = XPT_PATH_INQ;
4820 		xpt_action(work_ccb);
4821 		if (work_ccb->ccb_h.status != CAM_REQ_CMP) {
4822 			request_ccb->ccb_h.status = work_ccb->ccb_h.status;
4823 			xpt_free_ccb(work_ccb);
4824 			xpt_done(request_ccb);
4825 			return;
4826 		}
4827 
4828 		if ((work_ccb->cpi.hba_misc & PIM_NOINITIATOR) != 0) {
4829 			/*
4830 			 * Can't scan the bus on an adapter that
4831 			 * cannot perform the initiator role.
4832 			 */
4833 			request_ccb->ccb_h.status = CAM_REQ_CMP;
4834 			xpt_free_ccb(work_ccb);
4835 			xpt_done(request_ccb);
4836 			return;
4837 		}
4838 
4839 		/* Save some state for use while we probe for devices */
4840 		scan_info = (xpt_scan_bus_info *)
4841 		    kmalloc(sizeof(xpt_scan_bus_info), M_TEMP, M_INTWAIT);
4842 		scan_info->request_ccb = request_ccb;
4843 		scan_info->cpi = &work_ccb->cpi;
4844 
4845 		/* Cache on our stack so we can work asynchronously */
4846 		max_target = scan_info->cpi->max_target;
4847 		initiator_id = scan_info->cpi->initiator_id;
4848 
4849 		/*
4850 		 * Don't count the initiator if the
4851 		 * initiator is addressable.
4852 		 */
4853 		scan_info->pending_count = max_target + 1;
4854 		if (initiator_id <= max_target)
4855 			scan_info->pending_count--;
4856 
4857 		for (i = 0; i <= max_target; i++) {
4858 			cam_status status;
4859 		 	if (i == initiator_id)
4860 				continue;
4861 
4862 			status = xpt_create_path(&path, xpt_periph,
4863 						 request_ccb->ccb_h.path_id,
4864 						 i, 0);
4865 			if (status != CAM_REQ_CMP) {
4866 				kprintf("xpt_scan_bus: xpt_create_path failed"
4867 				       " with status %#x, bus scan halted\n",
4868 				       status);
4869 				break;
4870 			}
4871 			work_ccb = xpt_alloc_ccb();
4872 			xpt_setup_ccb(&work_ccb->ccb_h, path,
4873 				      request_ccb->ccb_h.pinfo.priority);
4874 			work_ccb->ccb_h.func_code = XPT_SCAN_LUN;
4875 			work_ccb->ccb_h.cbfcnp = xpt_scan_bus;
4876 			work_ccb->ccb_h.ppriv_ptr0 = scan_info;
4877 			work_ccb->crcn.flags = request_ccb->crcn.flags;
4878 #if 0
4879 			kprintf("xpt_scan_bus: probing %d:%d:%d\n",
4880 				request_ccb->ccb_h.path_id, i, 0);
4881 #endif
4882 			xpt_action(work_ccb);
4883 		}
4884 		break;
4885 	}
4886 	case XPT_SCAN_LUN:
4887 	{
4888 		xpt_scan_bus_info *scan_info;
4889 		path_id_t path_id;
4890 		target_id_t target_id;
4891 		lun_id_t lun_id;
4892 
4893 		/* Reuse the same CCB to query if a device was really found */
4894 		scan_info = (xpt_scan_bus_info *)request_ccb->ccb_h.ppriv_ptr0;
4895 		xpt_setup_ccb(&request_ccb->ccb_h, request_ccb->ccb_h.path,
4896 			      request_ccb->ccb_h.pinfo.priority);
4897 		request_ccb->ccb_h.func_code = XPT_GDEV_TYPE;
4898 
4899 		path_id = request_ccb->ccb_h.path_id;
4900 		target_id = request_ccb->ccb_h.target_id;
4901 		lun_id = request_ccb->ccb_h.target_lun;
4902 		xpt_action(request_ccb);
4903 
4904 #if 0
4905 		kprintf("xpt_scan_bus: got back probe from %d:%d:%d\n",
4906 			path_id, target_id, lun_id);
4907 #endif
4908 
4909 		if (request_ccb->ccb_h.status != CAM_REQ_CMP) {
4910 			struct cam_ed *device;
4911 			struct cam_et *target;
4912 			int phl;
4913 
4914 			/*
4915 			 * If we already probed lun 0 successfully, or
4916 			 * we have additional configured luns on this
4917 			 * target that might have "gone away", go onto
4918 			 * the next lun.
4919 			 */
4920 			target = request_ccb->ccb_h.path->target;
4921 			/*
4922 			 * We may touch devices that we don't
4923 			 * hold references too, so ensure they
4924 			 * don't disappear out from under us.
4925 			 * The target above is referenced by the
4926 			 * path in the request ccb.
4927 			 */
4928 			phl = 0;
4929 			crit_enter();
4930 			device = TAILQ_FIRST(&target->ed_entries);
4931 			if (device != NULL) {
4932 				phl = device->quirk->quirks & CAM_QUIRK_HILUNS;
4933 				if (device->lun_id == 0)
4934 					device = TAILQ_NEXT(device, links);
4935 			}
4936 			crit_exit();
4937 			if ((lun_id != 0) || (device != NULL)) {
4938 				if (lun_id < (CAM_SCSI2_MAXLUN-1) || phl)
4939 					lun_id++;
4940 			}
4941 		} else {
4942 			struct cam_ed *device;
4943 
4944 			device = request_ccb->ccb_h.path->device;
4945 
4946 			if ((device->quirk->quirks & CAM_QUIRK_NOLUNS) == 0) {
4947 				/* Try the next lun */
4948 				if (lun_id < (CAM_SCSI2_MAXLUN-1) ||
4949 				    (device->quirk->quirks & CAM_QUIRK_HILUNS))
4950 					lun_id++;
4951 			}
4952 		}
4953 
4954 		xpt_free_path(request_ccb->ccb_h.path);
4955 
4956 		/* Check Bounds */
4957 		if ((lun_id == request_ccb->ccb_h.target_lun)
4958 		 || lun_id > scan_info->cpi->max_lun) {
4959 			/* We're done */
4960 
4961 			xpt_free_ccb(request_ccb);
4962 			scan_info->pending_count--;
4963 			if (scan_info->pending_count == 0) {
4964 				xpt_free_ccb((union ccb *)scan_info->cpi);
4965 				request_ccb = scan_info->request_ccb;
4966 				kfree(scan_info, M_TEMP);
4967 				request_ccb->ccb_h.status = CAM_REQ_CMP;
4968 				xpt_done(request_ccb);
4969 			}
4970 		} else {
4971 			/* Try the next device */
4972 			struct cam_path *path;
4973 			cam_status status;
4974 
4975 			path = request_ccb->ccb_h.path;
4976 			status = xpt_create_path(&path, xpt_periph,
4977 						 path_id, target_id, lun_id);
4978 			if (status != CAM_REQ_CMP) {
4979 				kprintf("xpt_scan_bus: xpt_create_path failed "
4980 				       "with status %#x, halting LUN scan\n",
4981 			 	       status);
4982 				xpt_free_ccb(request_ccb);
4983 				scan_info->pending_count--;
4984 				if (scan_info->pending_count == 0) {
4985 					xpt_free_ccb(
4986 						(union ccb *)scan_info->cpi);
4987 					request_ccb = scan_info->request_ccb;
4988 					kfree(scan_info, M_TEMP);
4989 					request_ccb->ccb_h.status = CAM_REQ_CMP;
4990 					xpt_done(request_ccb);
4991 					break;
4992 				}
4993 			}
4994 			xpt_setup_ccb(&request_ccb->ccb_h, path,
4995 				      request_ccb->ccb_h.pinfo.priority);
4996 			request_ccb->ccb_h.func_code = XPT_SCAN_LUN;
4997 			request_ccb->ccb_h.cbfcnp = xpt_scan_bus;
4998 			request_ccb->ccb_h.ppriv_ptr0 = scan_info;
4999 			request_ccb->crcn.flags =
5000 				scan_info->request_ccb->crcn.flags;
5001 #if 0
5002 			xpt_print_path(path);
5003 			kprintf("xpt_scan bus probing\n");
5004 #endif
5005 			xpt_action(request_ccb);
5006 		}
5007 		break;
5008 	}
5009 	default:
5010 		break;
5011 	}
5012 }
5013 
5014 typedef enum {
5015 	PROBE_TUR,
5016 	PROBE_INQUIRY,
5017 	PROBE_FULL_INQUIRY,
5018 	PROBE_MODE_SENSE,
5019 	PROBE_SERIAL_NUM,
5020 	PROBE_TUR_FOR_NEGOTIATION
5021 } probe_action;
5022 
5023 typedef enum {
5024 	PROBE_INQUIRY_CKSUM	= 0x01,
5025 	PROBE_SERIAL_CKSUM	= 0x02,
5026 	PROBE_NO_ANNOUNCE	= 0x04
5027 } probe_flags;
5028 
5029 typedef struct {
5030 	TAILQ_HEAD(, ccb_hdr) request_ccbs;
5031 	probe_action	action;
5032 	union ccb	saved_ccb;
5033 	probe_flags	flags;
5034 	MD5_CTX		context;
5035 	u_int8_t	digest[16];
5036 } probe_softc;
5037 
5038 static void
5039 xpt_scan_lun(struct cam_periph *periph, struct cam_path *path,
5040 	     cam_flags flags, union ccb *request_ccb)
5041 {
5042 	struct ccb_pathinq cpi;
5043 	cam_status status;
5044 	struct cam_path *new_path;
5045 	struct cam_periph *old_periph;
5046 
5047 	CAM_DEBUG(request_ccb->ccb_h.path, CAM_DEBUG_TRACE,
5048 		  ("xpt_scan_lun\n"));
5049 
5050 	xpt_setup_ccb(&cpi.ccb_h, path, /*priority*/1);
5051 	cpi.ccb_h.func_code = XPT_PATH_INQ;
5052 	xpt_action((union ccb *)&cpi);
5053 
5054 	if (cpi.ccb_h.status != CAM_REQ_CMP) {
5055 		if (request_ccb != NULL) {
5056 			request_ccb->ccb_h.status = cpi.ccb_h.status;
5057 			xpt_done(request_ccb);
5058 		}
5059 		return;
5060 	}
5061 
5062 	if ((cpi.hba_misc & PIM_NOINITIATOR) != 0) {
5063 		/*
5064 		 * Can't scan the bus on an adapter that
5065 		 * cannot perform the initiator role.
5066 		 */
5067 		if (request_ccb != NULL) {
5068 			request_ccb->ccb_h.status = CAM_REQ_CMP;
5069 			xpt_done(request_ccb);
5070 		}
5071 		return;
5072 	}
5073 
5074 	if (request_ccb == NULL) {
5075 		request_ccb = kmalloc(sizeof(union ccb), M_TEMP, M_INTWAIT);
5076 		new_path = kmalloc(sizeof(*new_path), M_TEMP, M_INTWAIT);
5077 		status = xpt_compile_path(new_path, xpt_periph,
5078 					  path->bus->path_id,
5079 					  path->target->target_id,
5080 					  path->device->lun_id);
5081 
5082 		if (status != CAM_REQ_CMP) {
5083 			xpt_print_path(path);
5084 			kprintf("xpt_scan_lun: can't compile path, can't "
5085 			       "continue\n");
5086 			kfree(request_ccb, M_TEMP);
5087 			kfree(new_path, M_TEMP);
5088 			return;
5089 		}
5090 		xpt_setup_ccb(&request_ccb->ccb_h, new_path, /*priority*/ 1);
5091 		request_ccb->ccb_h.cbfcnp = xptscandone;
5092 		request_ccb->ccb_h.func_code = XPT_SCAN_LUN;
5093 		request_ccb->crcn.flags = flags;
5094 	}
5095 
5096 	crit_enter();
5097 	if ((old_periph = cam_periph_find(path, "probe")) != NULL) {
5098 		probe_softc *softc;
5099 
5100 		softc = (probe_softc *)old_periph->softc;
5101 		TAILQ_INSERT_TAIL(&softc->request_ccbs, &request_ccb->ccb_h,
5102 				  periph_links.tqe);
5103 	} else {
5104 		status = cam_periph_alloc(proberegister, NULL, probecleanup,
5105 					  probestart, "probe",
5106 					  CAM_PERIPH_BIO,
5107 					  request_ccb->ccb_h.path, NULL, 0,
5108 					  request_ccb);
5109 
5110 		if (status != CAM_REQ_CMP) {
5111 			xpt_print_path(path);
5112 			kprintf("xpt_scan_lun: cam_alloc_periph returned an "
5113 			       "error, can't continue probe\n");
5114 			request_ccb->ccb_h.status = status;
5115 			xpt_done(request_ccb);
5116 		}
5117 	}
5118 	crit_exit();
5119 }
5120 
5121 static void
5122 xptscandone(struct cam_periph *periph, union ccb *done_ccb)
5123 {
5124 	xpt_release_path(done_ccb->ccb_h.path);
5125 	kfree(done_ccb->ccb_h.path, M_TEMP);
5126 	kfree(done_ccb, M_TEMP);
5127 }
5128 
5129 static cam_status
5130 proberegister(struct cam_periph *periph, void *arg)
5131 {
5132 	union ccb *request_ccb;	/* CCB representing the probe request */
5133 	probe_softc *softc;
5134 
5135 	request_ccb = (union ccb *)arg;
5136 	if (periph == NULL) {
5137 		kprintf("proberegister: periph was NULL!!\n");
5138 		return(CAM_REQ_CMP_ERR);
5139 	}
5140 
5141 	if (request_ccb == NULL) {
5142 		kprintf("proberegister: no probe CCB, "
5143 		       "can't register device\n");
5144 		return(CAM_REQ_CMP_ERR);
5145 	}
5146 
5147 	softc = kmalloc(sizeof(*softc), M_TEMP, M_INTWAIT | M_ZERO);
5148 	TAILQ_INIT(&softc->request_ccbs);
5149 	TAILQ_INSERT_TAIL(&softc->request_ccbs, &request_ccb->ccb_h,
5150 			  periph_links.tqe);
5151 	softc->flags = 0;
5152 	periph->softc = softc;
5153 	cam_periph_acquire(periph);
5154 	/*
5155 	 * Ensure we've waited at least a bus settle
5156 	 * delay before attempting to probe the device.
5157 	 * For HBAs that don't do bus resets, this won't make a difference.
5158 	 */
5159 	cam_periph_freeze_after_event(periph, &periph->path->bus->last_reset,
5160 				      SCSI_DELAY);
5161 	probeschedule(periph);
5162 	return(CAM_REQ_CMP);
5163 }
5164 
5165 static void
5166 probeschedule(struct cam_periph *periph)
5167 {
5168 	struct ccb_pathinq cpi;
5169 	union ccb *ccb;
5170 	probe_softc *softc;
5171 
5172 	softc = (probe_softc *)periph->softc;
5173 	ccb = (union ccb *)TAILQ_FIRST(&softc->request_ccbs);
5174 
5175 	xpt_setup_ccb(&cpi.ccb_h, periph->path, /*priority*/1);
5176 	cpi.ccb_h.func_code = XPT_PATH_INQ;
5177 	xpt_action((union ccb *)&cpi);
5178 
5179 	/*
5180 	 * If a device has gone away and another device, or the same one,
5181 	 * is back in the same place, it should have a unit attention
5182 	 * condition pending.  It will not report the unit attention in
5183 	 * response to an inquiry, which may leave invalid transfer
5184 	 * negotiations in effect.  The TUR will reveal the unit attention
5185 	 * condition.  Only send the TUR for lun 0, since some devices
5186 	 * will get confused by commands other than inquiry to non-existent
5187 	 * luns.  If you think a device has gone away start your scan from
5188 	 * lun 0.  This will insure that any bogus transfer settings are
5189 	 * invalidated.
5190 	 *
5191 	 * If we haven't seen the device before and the controller supports
5192 	 * some kind of transfer negotiation, negotiate with the first
5193 	 * sent command if no bus reset was performed at startup.  This
5194 	 * ensures that the device is not confused by transfer negotiation
5195 	 * settings left over by loader or BIOS action.
5196 	 */
5197 	if (((ccb->ccb_h.path->device->flags & CAM_DEV_UNCONFIGURED) == 0)
5198 	 && (ccb->ccb_h.target_lun == 0)) {
5199 		softc->action = PROBE_TUR;
5200 	} else if ((cpi.hba_inquiry & (PI_WIDE_32|PI_WIDE_16|PI_SDTR_ABLE)) != 0
5201 	      && (cpi.hba_misc & PIM_NOBUSRESET) != 0) {
5202 		proberequestdefaultnegotiation(periph);
5203 		softc->action = PROBE_INQUIRY;
5204 	} else {
5205 		softc->action = PROBE_INQUIRY;
5206 	}
5207 
5208 	if (ccb->crcn.flags & CAM_EXPECT_INQ_CHANGE)
5209 		softc->flags |= PROBE_NO_ANNOUNCE;
5210 	else
5211 		softc->flags &= ~PROBE_NO_ANNOUNCE;
5212 
5213 	xpt_schedule(periph, ccb->ccb_h.pinfo.priority);
5214 }
5215 
5216 static void
5217 probestart(struct cam_periph *periph, union ccb *start_ccb)
5218 {
5219 	/* Probe the device that our peripheral driver points to */
5220 	struct ccb_scsiio *csio;
5221 	probe_softc *softc;
5222 
5223 	CAM_DEBUG(start_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("probestart\n"));
5224 
5225 	softc = (probe_softc *)periph->softc;
5226 	csio = &start_ccb->csio;
5227 
5228 	switch (softc->action) {
5229 	case PROBE_TUR:
5230 	case PROBE_TUR_FOR_NEGOTIATION:
5231 	{
5232 		scsi_test_unit_ready(csio,
5233 				     /*retries*/4,
5234 				     probedone,
5235 				     MSG_SIMPLE_Q_TAG,
5236 				     SSD_FULL_SIZE,
5237 				     /*timeout*/60000);
5238 		break;
5239 	}
5240 	case PROBE_INQUIRY:
5241 	case PROBE_FULL_INQUIRY:
5242 	{
5243 		u_int inquiry_len;
5244 		struct scsi_inquiry_data *inq_buf;
5245 
5246 		inq_buf = &periph->path->device->inq_data;
5247 		/*
5248 		 * If the device is currently configured, we calculate an
5249 		 * MD5 checksum of the inquiry data, and if the serial number
5250 		 * length is greater than 0, add the serial number data
5251 		 * into the checksum as well.  Once the inquiry and the
5252 		 * serial number check finish, we attempt to figure out
5253 		 * whether we still have the same device.
5254 		 */
5255 		if ((periph->path->device->flags & CAM_DEV_UNCONFIGURED) == 0) {
5256 
5257 			MD5Init(&softc->context);
5258 			MD5Update(&softc->context, (unsigned char *)inq_buf,
5259 				  sizeof(struct scsi_inquiry_data));
5260 			softc->flags |= PROBE_INQUIRY_CKSUM;
5261 			if (periph->path->device->serial_num_len > 0) {
5262 				MD5Update(&softc->context,
5263 					  periph->path->device->serial_num,
5264 					  periph->path->device->serial_num_len);
5265 				softc->flags |= PROBE_SERIAL_CKSUM;
5266 			}
5267 			MD5Final(softc->digest, &softc->context);
5268 		}
5269 
5270 		if (softc->action == PROBE_INQUIRY)
5271 			inquiry_len = SHORT_INQUIRY_LENGTH;
5272 		else
5273 			inquiry_len = inq_buf->additional_length + 5;
5274 
5275 		scsi_inquiry(csio,
5276 			     /*retries*/4,
5277 			     probedone,
5278 			     MSG_SIMPLE_Q_TAG,
5279 			     (u_int8_t *)inq_buf,
5280 			     inquiry_len,
5281 			     /*evpd*/FALSE,
5282 			     /*page_code*/0,
5283 			     SSD_MIN_SIZE,
5284 			     /*timeout*/60 * 1000);
5285 		break;
5286 	}
5287 	case PROBE_MODE_SENSE:
5288 	{
5289 		void  *mode_buf;
5290 		int    mode_buf_len;
5291 
5292 		mode_buf_len = sizeof(struct scsi_mode_header_6)
5293 			     + sizeof(struct scsi_mode_blk_desc)
5294 			     + sizeof(struct scsi_control_page);
5295 		mode_buf = kmalloc(mode_buf_len, M_TEMP, M_INTWAIT);
5296 		scsi_mode_sense(csio,
5297 				/*retries*/4,
5298 				probedone,
5299 				MSG_SIMPLE_Q_TAG,
5300 				/*dbd*/FALSE,
5301 				SMS_PAGE_CTRL_CURRENT,
5302 				SMS_CONTROL_MODE_PAGE,
5303 				mode_buf,
5304 				mode_buf_len,
5305 				SSD_FULL_SIZE,
5306 				/*timeout*/60000);
5307 		break;
5308 	}
5309 	case PROBE_SERIAL_NUM:
5310 	{
5311 		struct scsi_vpd_unit_serial_number *serial_buf;
5312 		struct cam_ed* device;
5313 
5314 		serial_buf = NULL;
5315 		device = periph->path->device;
5316 		device->serial_num = NULL;
5317 		device->serial_num_len = 0;
5318 
5319 		if ((device->quirk->quirks & CAM_QUIRK_NOSERIAL) == 0) {
5320 			serial_buf = kmalloc(sizeof(*serial_buf), M_TEMP,
5321 					    M_INTWAIT | M_ZERO);
5322 			scsi_inquiry(csio,
5323 				     /*retries*/4,
5324 				     probedone,
5325 				     MSG_SIMPLE_Q_TAG,
5326 				     (u_int8_t *)serial_buf,
5327 				     sizeof(*serial_buf),
5328 				     /*evpd*/TRUE,
5329 				     SVPD_UNIT_SERIAL_NUMBER,
5330 				     SSD_MIN_SIZE,
5331 				     /*timeout*/60 * 1000);
5332 			break;
5333 		}
5334 		/*
5335 		 * We'll have to do without, let our probedone
5336 		 * routine finish up for us.
5337 		 */
5338 		start_ccb->csio.data_ptr = NULL;
5339 		probedone(periph, start_ccb);
5340 		return;
5341 	}
5342 	}
5343 	xpt_action(start_ccb);
5344 }
5345 
5346 static void
5347 proberequestdefaultnegotiation(struct cam_periph *periph)
5348 {
5349 	struct ccb_trans_settings cts;
5350 
5351 	xpt_setup_ccb(&cts.ccb_h, periph->path, /*priority*/1);
5352 	cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
5353 	cts.flags = CCB_TRANS_USER_SETTINGS;
5354 	xpt_action((union ccb *)&cts);
5355 	cts.ccb_h.func_code = XPT_SET_TRAN_SETTINGS;
5356 	cts.flags &= ~CCB_TRANS_USER_SETTINGS;
5357 	cts.flags |= CCB_TRANS_CURRENT_SETTINGS;
5358 	xpt_action((union ccb *)&cts);
5359 }
5360 
5361 static void
5362 probedone(struct cam_periph *periph, union ccb *done_ccb)
5363 {
5364 	probe_softc *softc;
5365 	struct cam_path *path;
5366 	u_int32_t  priority;
5367 
5368 	CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("probedone\n"));
5369 
5370 	softc = (probe_softc *)periph->softc;
5371 	path = done_ccb->ccb_h.path;
5372 	priority = done_ccb->ccb_h.pinfo.priority;
5373 
5374 	switch (softc->action) {
5375 	case PROBE_TUR:
5376 	{
5377 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
5378 
5379 			if (cam_periph_error(done_ccb, 0,
5380 					     SF_NO_PRINT, NULL) == ERESTART)
5381 				return;
5382 			else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
5383 				/* Don't wedge the queue */
5384 				xpt_release_devq(done_ccb->ccb_h.path,
5385 						 /*count*/1,
5386 						 /*run_queue*/TRUE);
5387 		}
5388 		softc->action = PROBE_INQUIRY;
5389 		xpt_release_ccb(done_ccb);
5390 		xpt_schedule(periph, priority);
5391 		return;
5392 	}
5393 	case PROBE_INQUIRY:
5394 	case PROBE_FULL_INQUIRY:
5395 	{
5396 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
5397 			struct scsi_inquiry_data *inq_buf;
5398 			u_int8_t periph_qual;
5399 
5400 			path->device->flags |= CAM_DEV_INQUIRY_DATA_VALID;
5401 			inq_buf = &path->device->inq_data;
5402 
5403 			periph_qual = SID_QUAL(inq_buf);
5404 
5405 			switch(periph_qual) {
5406 			case SID_QUAL_LU_CONNECTED:
5407 			{
5408 				u_int8_t alen;
5409 
5410 				/*
5411 				 * We conservatively request only
5412 				 * SHORT_INQUIRY_LEN bytes of inquiry
5413 				 * information during our first try
5414 				 * at sending an INQUIRY. If the device
5415 				 * has more information to give,
5416 				 * perform a second request specifying
5417 				 * the amount of information the device
5418 				 * is willing to give.
5419 				 */
5420 				alen = inq_buf->additional_length;
5421 				if (softc->action == PROBE_INQUIRY
5422 				 && alen > (SHORT_INQUIRY_LENGTH - 5)) {
5423 					softc->action = PROBE_FULL_INQUIRY;
5424 					xpt_release_ccb(done_ccb);
5425 					xpt_schedule(periph, priority);
5426 					return;
5427 				}
5428 
5429 				xpt_find_quirk(path->device);
5430 
5431 				if ((inq_buf->flags & SID_CmdQue) != 0)
5432 					softc->action = PROBE_MODE_SENSE;
5433 				else
5434 					softc->action = PROBE_SERIAL_NUM;
5435 
5436 				path->device->flags &= ~CAM_DEV_UNCONFIGURED;
5437 				xpt_reference_device(path->device);
5438 
5439 				xpt_release_ccb(done_ccb);
5440 				xpt_schedule(periph, priority);
5441 				return;
5442 			}
5443 			default:
5444 				break;
5445 			}
5446 		} else if (cam_periph_error(done_ccb, 0,
5447 					    done_ccb->ccb_h.target_lun > 0
5448 					    ? SF_RETRY_UA|SF_QUIET_IR
5449 					    : SF_RETRY_UA,
5450 					    &softc->saved_ccb) == ERESTART) {
5451 			return;
5452 		} else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
5453 			/* Don't wedge the queue */
5454 			xpt_release_devq(done_ccb->ccb_h.path, /*count*/1,
5455 					 /*run_queue*/TRUE);
5456 		}
5457 		/*
5458 		 * If we get to this point, we got an error status back
5459 		 * from the inquiry and the error status doesn't require
5460 		 * automatically retrying the command.  Therefore, the
5461 		 * inquiry failed.  If we had inquiry information before
5462 		 * for this device, but this latest inquiry command failed,
5463 		 * the device has probably gone away.  If this device isn't
5464 		 * already marked unconfigured, notify the peripheral
5465 		 * drivers that this device is no more.
5466 		 */
5467 		if ((path->device->flags & CAM_DEV_UNCONFIGURED) == 0) {
5468 			/* Send the async notification. */
5469 			xpt_async(AC_LOST_DEVICE, path, NULL);
5470 		}
5471 
5472 		xpt_release_ccb(done_ccb);
5473 		break;
5474 	}
5475 	case PROBE_MODE_SENSE:
5476 	{
5477 		struct ccb_scsiio *csio;
5478 		struct scsi_mode_header_6 *mode_hdr;
5479 
5480 		csio = &done_ccb->csio;
5481 		mode_hdr = (struct scsi_mode_header_6 *)csio->data_ptr;
5482 		if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
5483 			struct scsi_control_page *page;
5484 			u_int8_t *offset;
5485 
5486 			offset = ((u_int8_t *)&mode_hdr[1])
5487 			    + mode_hdr->blk_desc_len;
5488 			page = (struct scsi_control_page *)offset;
5489 			path->device->queue_flags = page->queue_flags;
5490 		} else if (cam_periph_error(done_ccb, 0,
5491 					    SF_RETRY_UA|SF_NO_PRINT,
5492 					    &softc->saved_ccb) == ERESTART) {
5493 			return;
5494 		} else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
5495 			/* Don't wedge the queue */
5496 			xpt_release_devq(done_ccb->ccb_h.path,
5497 					 /*count*/1, /*run_queue*/TRUE);
5498 		}
5499 		xpt_release_ccb(done_ccb);
5500 		kfree(mode_hdr, M_TEMP);
5501 		softc->action = PROBE_SERIAL_NUM;
5502 		xpt_schedule(periph, priority);
5503 		return;
5504 	}
5505 	case PROBE_SERIAL_NUM:
5506 	{
5507 		struct ccb_scsiio *csio;
5508 		struct scsi_vpd_unit_serial_number *serial_buf;
5509 		u_int32_t  priority;
5510 		int changed;
5511 		int have_serialnum;
5512 
5513 		changed = 1;
5514 		have_serialnum = 0;
5515 		csio = &done_ccb->csio;
5516 		priority = done_ccb->ccb_h.pinfo.priority;
5517 		serial_buf =
5518 		    (struct scsi_vpd_unit_serial_number *)csio->data_ptr;
5519 
5520 		/* Clean up from previous instance of this device */
5521 		if (path->device->serial_num != NULL) {
5522 			kfree(path->device->serial_num, M_DEVBUF);
5523 			path->device->serial_num = NULL;
5524 			path->device->serial_num_len = 0;
5525 		}
5526 
5527 		if (serial_buf == NULL) {
5528 			/*
5529 			 * Don't process the command as it was never sent
5530 			 */
5531 		} else if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP
5532 			&& (serial_buf->length > 0)) {
5533 
5534 			have_serialnum = 1;
5535 			path->device->serial_num =
5536 				kmalloc((serial_buf->length + 1),
5537 				       M_DEVBUF, M_INTWAIT);
5538 			bcopy(serial_buf->serial_num,
5539 			      path->device->serial_num,
5540 			      serial_buf->length);
5541 			path->device->serial_num_len = serial_buf->length;
5542 			path->device->serial_num[serial_buf->length] = '\0';
5543 		} else if (cam_periph_error(done_ccb, 0,
5544 					    SF_RETRY_UA|SF_NO_PRINT,
5545 					    &softc->saved_ccb) == ERESTART) {
5546 			return;
5547 		} else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
5548 			/* Don't wedge the queue */
5549 			xpt_release_devq(done_ccb->ccb_h.path, /*count*/1,
5550 					 /*run_queue*/TRUE);
5551 		}
5552 
5553 		/*
5554 		 * Let's see if we have seen this device before.
5555 		 */
5556 		if ((softc->flags & PROBE_INQUIRY_CKSUM) != 0) {
5557 			MD5_CTX context;
5558 			u_int8_t digest[16];
5559 
5560 			MD5Init(&context);
5561 
5562 			MD5Update(&context,
5563 				  (unsigned char *)&path->device->inq_data,
5564 				  sizeof(struct scsi_inquiry_data));
5565 
5566 			if (have_serialnum)
5567 				MD5Update(&context, serial_buf->serial_num,
5568 					  serial_buf->length);
5569 
5570 			MD5Final(digest, &context);
5571 			if (bcmp(softc->digest, digest, 16) == 0)
5572 				changed = 0;
5573 
5574 			/*
5575 			 * XXX Do we need to do a TUR in order to ensure
5576 			 *     that the device really hasn't changed???
5577 			 */
5578 			if ((changed != 0)
5579 			 && ((softc->flags & PROBE_NO_ANNOUNCE) == 0))
5580 				xpt_async(AC_LOST_DEVICE, path, NULL);
5581 		}
5582 		if (serial_buf != NULL)
5583 			kfree(serial_buf, M_TEMP);
5584 
5585 		if (changed != 0) {
5586 			/*
5587 			 * Now that we have all the necessary
5588 			 * information to safely perform transfer
5589 			 * negotiations... Controllers don't perform
5590 			 * any negotiation or tagged queuing until
5591 			 * after the first XPT_SET_TRAN_SETTINGS ccb is
5592 			 * received.  So, on a new device, just retreive
5593 			 * the user settings, and set them as the current
5594 			 * settings to set the device up.
5595 			 */
5596 			proberequestdefaultnegotiation(periph);
5597 			xpt_release_ccb(done_ccb);
5598 
5599 			/*
5600 			 * Perform a TUR to allow the controller to
5601 			 * perform any necessary transfer negotiation.
5602 			 */
5603 			softc->action = PROBE_TUR_FOR_NEGOTIATION;
5604 			xpt_schedule(periph, priority);
5605 			return;
5606 		}
5607 		xpt_release_ccb(done_ccb);
5608 		break;
5609 	}
5610 	case PROBE_TUR_FOR_NEGOTIATION:
5611 		if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
5612 			/* Don't wedge the queue */
5613 			xpt_release_devq(done_ccb->ccb_h.path, /*count*/1,
5614 					 /*run_queue*/TRUE);
5615 		}
5616 
5617 		path->device->flags &= ~CAM_DEV_UNCONFIGURED;
5618 		xpt_reference_device(path->device);
5619 
5620 		if ((softc->flags & PROBE_NO_ANNOUNCE) == 0) {
5621 			/* Inform the XPT that a new device has been found */
5622 			done_ccb->ccb_h.func_code = XPT_GDEV_TYPE;
5623 			xpt_action(done_ccb);
5624 
5625 			xpt_async(AC_FOUND_DEVICE, xpt_periph->path, done_ccb);
5626 		}
5627 		xpt_release_ccb(done_ccb);
5628 		break;
5629 	}
5630 	done_ccb = (union ccb *)TAILQ_FIRST(&softc->request_ccbs);
5631 	TAILQ_REMOVE(&softc->request_ccbs, &done_ccb->ccb_h, periph_links.tqe);
5632 	done_ccb->ccb_h.status = CAM_REQ_CMP;
5633 	xpt_done(done_ccb);
5634 	if (TAILQ_FIRST(&softc->request_ccbs) == NULL) {
5635 		cam_periph_invalidate(periph);
5636 		cam_periph_release(periph);
5637 	} else {
5638 		probeschedule(periph);
5639 	}
5640 }
5641 
5642 static void
5643 probecleanup(struct cam_periph *periph)
5644 {
5645 	kfree(periph->softc, M_TEMP);
5646 }
5647 
5648 static void
5649 xpt_find_quirk(struct cam_ed *device)
5650 {
5651 	caddr_t	match;
5652 
5653 	match = cam_quirkmatch((caddr_t)&device->inq_data,
5654 			       (caddr_t)xpt_quirk_table,
5655 			       sizeof(xpt_quirk_table)/sizeof(*xpt_quirk_table),
5656 			       sizeof(*xpt_quirk_table), scsi_inquiry_match);
5657 
5658 	if (match == NULL)
5659 		panic("xpt_find_quirk: device didn't match wildcard entry!!");
5660 
5661 	device->quirk = (struct xpt_quirk_entry *)match;
5662 }
5663 
5664 static void
5665 xpt_set_transfer_settings(struct ccb_trans_settings *cts, struct cam_ed *device,
5666 			  int async_update)
5667 {
5668 	struct	cam_sim *sim;
5669 	int	qfrozen;
5670 
5671 	sim = cts->ccb_h.path->bus->sim;
5672 	if (async_update == FALSE) {
5673 		struct	scsi_inquiry_data *inq_data;
5674 		struct	ccb_pathinq cpi;
5675 		struct	ccb_trans_settings cur_cts;
5676 
5677 		if (device == NULL) {
5678 			cts->ccb_h.status = CAM_PATH_INVALID;
5679 			xpt_done((union ccb *)cts);
5680 			return;
5681 		}
5682 
5683 		/*
5684 		 * Perform sanity checking against what the
5685 		 * controller and device can do.
5686 		 */
5687 		xpt_setup_ccb(&cpi.ccb_h, cts->ccb_h.path, /*priority*/1);
5688 		cpi.ccb_h.func_code = XPT_PATH_INQ;
5689 		xpt_action((union ccb *)&cpi);
5690 		xpt_setup_ccb(&cur_cts.ccb_h, cts->ccb_h.path, /*priority*/1);
5691 		cur_cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
5692 		cur_cts.flags = CCB_TRANS_CURRENT_SETTINGS;
5693 		xpt_action((union ccb *)&cur_cts);
5694 		inq_data = &device->inq_data;
5695 
5696 		/* Fill in any gaps in what the user gave us */
5697 		if ((cts->valid & CCB_TRANS_SYNC_RATE_VALID) == 0)
5698 			cts->sync_period = cur_cts.sync_period;
5699 		if ((cts->valid & CCB_TRANS_SYNC_OFFSET_VALID) == 0)
5700 			cts->sync_offset = cur_cts.sync_offset;
5701 		if ((cts->valid & CCB_TRANS_BUS_WIDTH_VALID) == 0)
5702 			cts->bus_width = cur_cts.bus_width;
5703 		if ((cts->valid & CCB_TRANS_DISC_VALID) == 0) {
5704 			cts->flags &= ~CCB_TRANS_DISC_ENB;
5705 			cts->flags |= cur_cts.flags & CCB_TRANS_DISC_ENB;
5706 		}
5707 		if ((cts->valid & CCB_TRANS_TQ_VALID) == 0) {
5708 			cts->flags &= ~CCB_TRANS_TAG_ENB;
5709 			cts->flags |= cur_cts.flags & CCB_TRANS_TAG_ENB;
5710 		}
5711 
5712 		if (((device->flags & CAM_DEV_INQUIRY_DATA_VALID) != 0
5713 		  && (inq_data->flags & SID_Sync) == 0)
5714 		 || ((cpi.hba_inquiry & PI_SDTR_ABLE) == 0)
5715 		 || (cts->sync_offset == 0)
5716 		 || (cts->sync_period == 0)) {
5717 			/* Force async */
5718 			cts->sync_period = 0;
5719 			cts->sync_offset = 0;
5720 		} else if ((device->flags & CAM_DEV_INQUIRY_DATA_VALID) != 0) {
5721 
5722 			if ((inq_data->spi3data & SID_SPI_CLOCK_DT) == 0
5723 			 && cts->sync_period <= 0x9) {
5724 				/*
5725 				 * Don't allow DT transmission rates if the
5726 				 * device does not support it.
5727 				 */
5728 				cts->sync_period = 0xa;
5729 			}
5730 			if ((inq_data->spi3data & SID_SPI_IUS) == 0
5731 			 && cts->sync_period <= 0x8) {
5732 				/*
5733 				 * Don't allow PACE transmission rates
5734 				 * if the device does support packetized
5735 				 * transfers.
5736 				 */
5737 				cts->sync_period = 0x9;
5738 			}
5739 		}
5740 
5741 		switch (cts->bus_width) {
5742 		case MSG_EXT_WDTR_BUS_32_BIT:
5743 			if (((device->flags & CAM_DEV_INQUIRY_DATA_VALID) == 0
5744 			  || (inq_data->flags & SID_WBus32) != 0)
5745 			 && (cpi.hba_inquiry & PI_WIDE_32) != 0)
5746 				break;
5747 			/* Fall Through to 16-bit */
5748 		case MSG_EXT_WDTR_BUS_16_BIT:
5749 			if (((device->flags & CAM_DEV_INQUIRY_DATA_VALID) == 0
5750 			  || (inq_data->flags & SID_WBus16) != 0)
5751 			 && (cpi.hba_inquiry & PI_WIDE_16) != 0) {
5752 				cts->bus_width = MSG_EXT_WDTR_BUS_16_BIT;
5753 				break;
5754 			}
5755 			/* Fall Through to 8-bit */
5756 		default: /* New bus width?? */
5757 		case MSG_EXT_WDTR_BUS_8_BIT:
5758 			/* All targets can do this */
5759 			cts->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
5760 			break;
5761 		}
5762 
5763 		if ((cts->flags & CCB_TRANS_DISC_ENB) == 0) {
5764 			/*
5765 			 * Can't tag queue without disconnection.
5766 			 */
5767 			cts->flags &= ~CCB_TRANS_TAG_ENB;
5768 			cts->valid |= CCB_TRANS_TQ_VALID;
5769 		}
5770 
5771 		if ((cpi.hba_inquiry & PI_TAG_ABLE) == 0
5772 		 || (inq_data->flags & SID_CmdQue) == 0
5773 		 || (device->queue_flags & SCP_QUEUE_DQUE) != 0
5774 		 || (device->quirk->mintags == 0)) {
5775 			/*
5776 			 * Can't tag on hardware that doesn't support,
5777 			 * doesn't have it enabled, or has broken tag support.
5778 			 */
5779 			cts->flags &= ~CCB_TRANS_TAG_ENB;
5780 		}
5781 	}
5782 
5783 	qfrozen = FALSE;
5784 	if ((cts->valid & CCB_TRANS_TQ_VALID) != 0) {
5785 		int device_tagenb;
5786 
5787 		/*
5788 		 * If we are transitioning from tags to no-tags or
5789 		 * vice-versa, we need to carefully freeze and restart
5790 		 * the queue so that we don't overlap tagged and non-tagged
5791 		 * commands.  We also temporarily stop tags if there is
5792 		 * a change in transfer negotiation settings to allow
5793 		 * "tag-less" negotiation.
5794 		 */
5795 		if ((device->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
5796 		 || (device->inq_flags & SID_CmdQue) != 0)
5797 			device_tagenb = TRUE;
5798 		else
5799 			device_tagenb = FALSE;
5800 
5801 		if (((cts->flags & CCB_TRANS_TAG_ENB) != 0
5802 		  && device_tagenb == FALSE)
5803 		 || ((cts->flags & CCB_TRANS_TAG_ENB) == 0
5804 		  && device_tagenb == TRUE)) {
5805 
5806 			if ((cts->flags & CCB_TRANS_TAG_ENB) != 0) {
5807 				/*
5808 				 * Delay change to use tags until after a
5809 				 * few commands have gone to this device so
5810 				 * the controller has time to perform transfer
5811 				 * negotiations without tagged messages getting
5812 				 * in the way.
5813 				 */
5814 				device->tag_delay_count = CAM_TAG_DELAY_COUNT;
5815 				device->flags |= CAM_DEV_TAG_AFTER_COUNT;
5816 			} else {
5817 				xpt_freeze_devq(cts->ccb_h.path, /*count*/1);
5818 				qfrozen = TRUE;
5819 		  		device->inq_flags &= ~SID_CmdQue;
5820 				xpt_dev_ccbq_resize(cts->ccb_h.path,
5821 						    sim->max_dev_openings);
5822 				device->flags &= ~CAM_DEV_TAG_AFTER_COUNT;
5823 				device->tag_delay_count = 0;
5824 			}
5825 		}
5826 	}
5827 
5828 	if (async_update == FALSE) {
5829 		/*
5830 		 * If we are currently performing tagged transactions to
5831 		 * this device and want to change its negotiation parameters,
5832 		 * go non-tagged for a bit to give the controller a chance to
5833 		 * negotiate unhampered by tag messages.
5834 		 */
5835 		if ((device->inq_flags & SID_CmdQue) != 0
5836 		 && (cts->flags & (CCB_TRANS_SYNC_RATE_VALID|
5837 				   CCB_TRANS_SYNC_OFFSET_VALID|
5838 				   CCB_TRANS_BUS_WIDTH_VALID)) != 0)
5839 			xpt_toggle_tags(cts->ccb_h.path);
5840 
5841 		(*(sim->sim_action))(sim, (union ccb *)cts);
5842 	}
5843 
5844 	if (qfrozen) {
5845 		struct ccb_relsim crs;
5846 
5847 		xpt_setup_ccb(&crs.ccb_h, cts->ccb_h.path,
5848 			      /*priority*/1);
5849 		crs.ccb_h.func_code = XPT_REL_SIMQ;
5850 		crs.release_flags = RELSIM_RELEASE_AFTER_QEMPTY;
5851 		crs.openings
5852 		    = crs.release_timeout
5853 		    = crs.qfrozen_cnt
5854 		    = 0;
5855 		xpt_action((union ccb *)&crs);
5856 	}
5857 }
5858 
5859 static void
5860 xpt_toggle_tags(struct cam_path *path)
5861 {
5862 	struct cam_ed *dev;
5863 
5864 	/*
5865 	 * Give controllers a chance to renegotiate
5866 	 * before starting tag operations.  We
5867 	 * "toggle" tagged queuing off then on
5868 	 * which causes the tag enable command delay
5869 	 * counter to come into effect.
5870 	 */
5871 	dev = path->device;
5872 	if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
5873 	 || ((dev->inq_flags & SID_CmdQue) != 0
5874  	  && (dev->inq_flags & (SID_Sync|SID_WBus16|SID_WBus32)) != 0)) {
5875 		struct ccb_trans_settings cts;
5876 
5877 		xpt_setup_ccb(&cts.ccb_h, path, 1);
5878 		cts.flags = 0;
5879 		cts.valid = CCB_TRANS_TQ_VALID;
5880 		xpt_set_transfer_settings(&cts, path->device,
5881 					  /*async_update*/TRUE);
5882 		cts.flags = CCB_TRANS_TAG_ENB;
5883 		xpt_set_transfer_settings(&cts, path->device,
5884 					  /*async_update*/TRUE);
5885 	}
5886 }
5887 
5888 static void
5889 xpt_start_tags(struct cam_path *path)
5890 {
5891 	struct ccb_relsim crs;
5892 	struct cam_ed *device;
5893 	struct cam_sim *sim;
5894 	int    newopenings;
5895 
5896 	device = path->device;
5897 	sim = path->bus->sim;
5898 	device->flags &= ~CAM_DEV_TAG_AFTER_COUNT;
5899 	xpt_freeze_devq(path, /*count*/1);
5900 	device->inq_flags |= SID_CmdQue;
5901 	newopenings = min(device->quirk->maxtags, sim->max_tagged_dev_openings);
5902 	xpt_dev_ccbq_resize(path, newopenings);
5903 	xpt_setup_ccb(&crs.ccb_h, path, /*priority*/1);
5904 	crs.ccb_h.func_code = XPT_REL_SIMQ;
5905 	crs.release_flags = RELSIM_RELEASE_AFTER_QEMPTY;
5906 	crs.openings
5907 	    = crs.release_timeout
5908 	    = crs.qfrozen_cnt
5909 	    = 0;
5910 	xpt_action((union ccb *)&crs);
5911 }
5912 
5913 static int busses_to_config;
5914 static int busses_to_reset;
5915 
5916 static int
5917 xptconfigbuscountfunc(struct cam_eb *bus, void *arg)
5918 {
5919 	if (bus->path_id != CAM_XPT_PATH_ID) {
5920 		struct cam_path path;
5921 		struct ccb_pathinq cpi;
5922 		int can_negotiate;
5923 
5924 		busses_to_config++;
5925 		xpt_compile_path(&path, NULL, bus->path_id,
5926 				 CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
5927 		xpt_setup_ccb(&cpi.ccb_h, &path, /*priority*/1);
5928 		cpi.ccb_h.func_code = XPT_PATH_INQ;
5929 		xpt_action((union ccb *)&cpi);
5930 		can_negotiate = cpi.hba_inquiry;
5931 		can_negotiate &= (PI_WIDE_32|PI_WIDE_16|PI_SDTR_ABLE);
5932 		if ((cpi.hba_misc & PIM_NOBUSRESET) == 0
5933 		 && can_negotiate)
5934 			busses_to_reset++;
5935 		xpt_release_path(&path);
5936 	}
5937 
5938 	return(1);
5939 }
5940 
5941 static int
5942 xptconfigfunc(struct cam_eb *bus, void *arg)
5943 {
5944 	struct	cam_path *path;
5945 	union	ccb *work_ccb;
5946 
5947 	if (bus->path_id != CAM_XPT_PATH_ID) {
5948 		cam_status status;
5949 		int can_negotiate;
5950 
5951 		work_ccb = xpt_alloc_ccb();
5952 		if ((status = xpt_create_path(&path, xpt_periph, bus->path_id,
5953 					      CAM_TARGET_WILDCARD,
5954 					      CAM_LUN_WILDCARD)) !=CAM_REQ_CMP){
5955 			kprintf("xptconfigfunc: xpt_create_path failed with "
5956 			       "status %#x for bus %d\n", status, bus->path_id);
5957 			kprintf("xptconfigfunc: halting bus configuration\n");
5958 			xpt_free_ccb(work_ccb);
5959 			busses_to_config--;
5960 			xpt_finishconfig(xpt_periph, NULL);
5961 			return(0);
5962 		}
5963 		xpt_setup_ccb(&work_ccb->ccb_h, path, /*priority*/1);
5964 		work_ccb->ccb_h.func_code = XPT_PATH_INQ;
5965 		xpt_action(work_ccb);
5966 		if (work_ccb->ccb_h.status != CAM_REQ_CMP) {
5967 			kprintf("xptconfigfunc: CPI failed on bus %d "
5968 			       "with status %d\n", bus->path_id,
5969 			       work_ccb->ccb_h.status);
5970 			xpt_finishconfig(xpt_periph, work_ccb);
5971 			return(1);
5972 		}
5973 
5974 		can_negotiate = work_ccb->cpi.hba_inquiry;
5975 		can_negotiate &= (PI_WIDE_32|PI_WIDE_16|PI_SDTR_ABLE);
5976 		if ((work_ccb->cpi.hba_misc & PIM_NOBUSRESET) == 0
5977 		 && (can_negotiate != 0)) {
5978 			xpt_setup_ccb(&work_ccb->ccb_h, path, /*priority*/1);
5979 			work_ccb->ccb_h.func_code = XPT_RESET_BUS;
5980 			work_ccb->ccb_h.cbfcnp = NULL;
5981 			CAM_DEBUG(path, CAM_DEBUG_SUBTRACE,
5982 				  ("Resetting Bus\n"));
5983 			xpt_action(work_ccb);
5984 			xpt_finishconfig(xpt_periph, work_ccb);
5985 		} else {
5986 			/* Act as though we performed a successful BUS RESET */
5987 			work_ccb->ccb_h.func_code = XPT_RESET_BUS;
5988 			xpt_finishconfig(xpt_periph, work_ccb);
5989 		}
5990 	}
5991 
5992 	return(1);
5993 }
5994 
5995 static void
5996 xpt_config(void *arg)
5997 {
5998 	/* Now that interrupts are enabled, go find our devices */
5999 
6000 #ifdef CAMDEBUG
6001 	/* Setup debugging flags and path */
6002 #ifdef CAM_DEBUG_FLAGS
6003 	cam_dflags = CAM_DEBUG_FLAGS;
6004 #else /* !CAM_DEBUG_FLAGS */
6005 	cam_dflags = CAM_DEBUG_NONE;
6006 #endif /* CAM_DEBUG_FLAGS */
6007 #ifdef CAM_DEBUG_BUS
6008 	if (cam_dflags != CAM_DEBUG_NONE) {
6009 		if (xpt_create_path(&cam_dpath, xpt_periph,
6010 				    CAM_DEBUG_BUS, CAM_DEBUG_TARGET,
6011 				    CAM_DEBUG_LUN) != CAM_REQ_CMP) {
6012 			kprintf("xpt_config: xpt_create_path() failed for debug"
6013 			       " target %d:%d:%d, debugging disabled\n",
6014 			       CAM_DEBUG_BUS, CAM_DEBUG_TARGET, CAM_DEBUG_LUN);
6015 			cam_dflags = CAM_DEBUG_NONE;
6016 		}
6017 	} else
6018 		cam_dpath = NULL;
6019 #else /* !CAM_DEBUG_BUS */
6020 	cam_dpath = NULL;
6021 #endif /* CAM_DEBUG_BUS */
6022 #endif /* CAMDEBUG */
6023 
6024 	/*
6025 	 * Scan all installed busses.
6026 	 */
6027 	xpt_for_all_busses(xptconfigbuscountfunc, NULL);
6028 
6029 	if (busses_to_config == 0) {
6030 		/* Call manually because we don't have any busses */
6031 		xpt_finishconfig(xpt_periph, NULL);
6032 	} else  {
6033 		if (busses_to_reset > 0 && SCSI_DELAY >= 2000) {
6034 			kprintf("Waiting %d seconds for SCSI "
6035 			       "devices to settle\n", SCSI_DELAY/1000);
6036 		}
6037 		xpt_for_all_busses(xptconfigfunc, NULL);
6038 	}
6039 }
6040 
6041 /*
6042  * If the given device only has one peripheral attached to it, and if that
6043  * peripheral is the passthrough driver, announce it.  This insures that the
6044  * user sees some sort of announcement for every peripheral in their system.
6045  */
6046 static int
6047 xptpassannouncefunc(struct cam_ed *device, void *arg)
6048 {
6049 	struct cam_periph *periph;
6050 	int i;
6051 
6052 	for (periph = SLIST_FIRST(&device->periphs), i = 0; periph != NULL;
6053 	     periph = SLIST_NEXT(periph, periph_links), i++);
6054 
6055 	periph = SLIST_FIRST(&device->periphs);
6056 	if ((i == 1)
6057 	 && (strncmp(periph->periph_name, "pass", 4) == 0))
6058 		xpt_announce_periph(periph, NULL);
6059 
6060 	return(1);
6061 }
6062 
6063 static void
6064 xpt_finishconfig(struct cam_periph *periph, union ccb *done_ccb)
6065 {
6066 	struct	periph_driver **p_drv;
6067 
6068 	if (done_ccb != NULL) {
6069 		CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE,
6070 			  ("xpt_finishconfig\n"));
6071 		switch(done_ccb->ccb_h.func_code) {
6072 		case XPT_RESET_BUS:
6073 			if (done_ccb->ccb_h.status == CAM_REQ_CMP) {
6074 				done_ccb->ccb_h.func_code = XPT_SCAN_BUS;
6075 				done_ccb->ccb_h.cbfcnp = xpt_finishconfig;
6076 				xpt_action(done_ccb);
6077 				return;
6078 			}
6079 			/* FALLTHROUGH */
6080 		case XPT_SCAN_BUS:
6081 		default:
6082 			xpt_free_path(done_ccb->ccb_h.path);
6083 			busses_to_config--;
6084 			break;
6085 		}
6086 	}
6087 
6088 	if (busses_to_config == 0) {
6089 		/* Register all the peripheral drivers */
6090 		/* XXX This will have to change when we have loadable modules */
6091 		SET_FOREACH(p_drv, periphdriver_set) {
6092 			(*p_drv)->init();
6093 		}
6094 
6095 		/*
6096 		 * Check for devices with no "standard" peripheral driver
6097 		 * attached.  For any devices like that, announce the
6098 		 * passthrough driver so the user will see something.
6099 		 */
6100 		xpt_for_all_devices(xptpassannouncefunc, NULL);
6101 
6102 		/* Release our hook so that the boot can continue. */
6103 		config_intrhook_disestablish(xpt_config_hook);
6104 		kfree(xpt_config_hook, M_TEMP);
6105 		xpt_config_hook = NULL;
6106 	}
6107 	if (done_ccb != NULL)
6108 		xpt_free_ccb(done_ccb);
6109 }
6110 
6111 static void
6112 xptaction(struct cam_sim *sim, union ccb *work_ccb)
6113 {
6114 	CAM_DEBUG(work_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("xptaction\n"));
6115 
6116 	switch (work_ccb->ccb_h.func_code) {
6117 	/* Common cases first */
6118 	case XPT_PATH_INQ:		/* Path routing inquiry */
6119 	{
6120 		struct ccb_pathinq *cpi;
6121 
6122 		cpi = &work_ccb->cpi;
6123 		cpi->version_num = 1; /* XXX??? */
6124 		cpi->hba_inquiry = 0;
6125 		cpi->target_sprt = 0;
6126 		cpi->hba_misc = 0;
6127 		cpi->hba_eng_cnt = 0;
6128 		cpi->max_target = 0;
6129 		cpi->max_lun = 0;
6130 		cpi->initiator_id = 0;
6131 		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
6132 		strncpy(cpi->hba_vid, "", HBA_IDLEN);
6133 		strncpy(cpi->dev_name, sim->sim_name, DEV_IDLEN);
6134 		cpi->unit_number = sim->unit_number;
6135 		cpi->bus_id = sim->bus_id;
6136 		cpi->base_transfer_speed = 0;
6137 		cpi->ccb_h.status = CAM_REQ_CMP;
6138 		xpt_done(work_ccb);
6139 		break;
6140 	}
6141 	default:
6142 		work_ccb->ccb_h.status = CAM_REQ_INVALID;
6143 		xpt_done(work_ccb);
6144 		break;
6145 	}
6146 }
6147 
6148 /*
6149  * The xpt as a "controller" has no interrupt sources, so polling
6150  * is a no-op.
6151  */
6152 static void
6153 xptpoll(struct cam_sim *sim)
6154 {
6155 }
6156 
6157 /*
6158  * Should only be called by the machine interrupt dispatch routines,
6159  * so put these prototypes here instead of in the header.
6160  */
6161 
6162 static void
6163 swi_camnet(void *arg, void *frame)
6164 {
6165 	camisr(&cam_netq);
6166 }
6167 
6168 static void
6169 swi_cambio(void *arg, void *frame)
6170 {
6171 	camisr(&cam_bioq);
6172 }
6173 
6174 static void
6175 camisr(cam_isrq_t *queue)
6176 {
6177 	struct	ccb_hdr *ccb_h;
6178 
6179 	crit_enter();
6180 	while ((ccb_h = TAILQ_FIRST(queue)) != NULL) {
6181 		int	runq;
6182 
6183 		TAILQ_REMOVE(queue, ccb_h, sim_links.tqe);
6184 		ccb_h->pinfo.index = CAM_UNQUEUED_INDEX;
6185 		splz();
6186 
6187 		CAM_DEBUG(ccb_h->path, CAM_DEBUG_TRACE,
6188 			  ("camisr\n"));
6189 
6190 		runq = FALSE;
6191 
6192 		if (ccb_h->flags & CAM_HIGH_POWER) {
6193 			struct highpowerlist	*hphead;
6194 			struct cam_ed		*device;
6195 			union ccb		*send_ccb;
6196 
6197 			hphead = &highpowerq;
6198 
6199 			send_ccb = (union ccb *)STAILQ_FIRST(hphead);
6200 
6201 			/*
6202 			 * Increment the count since this command is done.
6203 			 */
6204 			num_highpower++;
6205 
6206 			/*
6207 			 * Any high powered commands queued up?
6208 			 */
6209 			if (send_ccb != NULL) {
6210 				device = send_ccb->ccb_h.path->device;
6211 
6212 				STAILQ_REMOVE_HEAD(hphead, xpt_links.stqe);
6213 
6214 				xpt_release_devq(send_ccb->ccb_h.path,
6215 						 /*count*/1, /*runqueue*/TRUE);
6216 			}
6217 		}
6218 		if ((ccb_h->func_code & XPT_FC_USER_CCB) == 0) {
6219 			struct cam_ed *dev;
6220 
6221 			dev = ccb_h->path->device;
6222 
6223 			cam_ccbq_ccb_done(&dev->ccbq, (union ccb *)ccb_h);
6224 
6225 			if (ccb_h->path->bus->sim->devq) {
6226 				ccb_h->path->bus->sim->devq->send_active--;
6227 				ccb_h->path->bus->sim->devq->send_openings++;
6228 			}
6229 
6230 			if ((dev->flags & CAM_DEV_REL_ON_COMPLETE) != 0
6231 			 || ((dev->flags & CAM_DEV_REL_ON_QUEUE_EMPTY) != 0
6232 			  && (dev->ccbq.dev_active == 0))) {
6233 
6234 				xpt_release_devq(ccb_h->path, /*count*/1,
6235 						 /*run_queue*/TRUE);
6236 			}
6237 
6238 			if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
6239 			 && (--dev->tag_delay_count == 0))
6240 				xpt_start_tags(ccb_h->path);
6241 
6242 			if ((dev->ccbq.queue.entries > 0)
6243 			 && (dev->qfrozen_cnt == 0)
6244 			 && (device_is_send_queued(dev) == 0)) {
6245 				runq = xpt_schedule_dev_sendq(ccb_h->path->bus,
6246 							      dev);
6247 			}
6248 		}
6249 
6250 		if (ccb_h->status & CAM_RELEASE_SIMQ) {
6251 			xpt_release_simq(ccb_h->path->bus->sim,
6252 					 /*run_queue*/TRUE);
6253 			ccb_h->status &= ~CAM_RELEASE_SIMQ;
6254 			runq = FALSE;
6255 		}
6256 
6257 		if ((ccb_h->flags & CAM_DEV_QFRZDIS)
6258 		 && (ccb_h->status & CAM_DEV_QFRZN)) {
6259 			xpt_release_devq(ccb_h->path, /*count*/1,
6260 					 /*run_queue*/TRUE);
6261 			ccb_h->status &= ~CAM_DEV_QFRZN;
6262 		} else if (runq) {
6263 			xpt_run_dev_sendq(ccb_h->path->bus);
6264 		}
6265 
6266 		/* Call the peripheral driver's callback */
6267 		(*ccb_h->cbfcnp)(ccb_h->path->periph, (union ccb *)ccb_h);
6268 	}
6269 	crit_exit();
6270 }
6271