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