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