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