xref: /freebsd/sys/cam/cam_xpt.c (revision 6607310b740c499e273ae5bbf1f308ed91b61c05)
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 				continue;
3866 			} else {
3867 				/*
3868 				 * Consume a high power slot while
3869 				 * this ccb runs.
3870 				 */
3871 				xsoftc.num_highpower--;
3872 			}
3873 			mtx_unlock(&xsoftc.xpt_lock);
3874 		}
3875 		devq->active_dev = device;
3876 		cam_ccbq_remove_ccb(&device->ccbq, work_ccb);
3877 
3878 		cam_ccbq_send_ccb(&device->ccbq, work_ccb);
3879 
3880 		devq->send_openings--;
3881 		devq->send_active++;
3882 
3883 		if (device->ccbq.queue.entries > 0)
3884 			xpt_schedule_dev_sendq(bus, device);
3885 
3886 		if (work_ccb && (work_ccb->ccb_h.flags & CAM_DEV_QFREEZE) != 0){
3887 			/*
3888 			 * The client wants to freeze the queue
3889 			 * after this CCB is sent.
3890 			 */
3891 			device->qfrozen_cnt++;
3892 		}
3893 
3894 		/* In Target mode, the peripheral driver knows best... */
3895 		if (work_ccb->ccb_h.func_code == XPT_SCSI_IO) {
3896 			if ((device->inq_flags & SID_CmdQue) != 0
3897 			 && work_ccb->csio.tag_action != CAM_TAG_ACTION_NONE)
3898 				work_ccb->ccb_h.flags |= CAM_TAG_ACTION_VALID;
3899 			else
3900 				/*
3901 				 * Clear this in case of a retried CCB that
3902 				 * failed due to a rejected tag.
3903 				 */
3904 				work_ccb->ccb_h.flags &= ~CAM_TAG_ACTION_VALID;
3905 		}
3906 
3907 		/*
3908 		 * Device queues can be shared among multiple sim instances
3909 		 * that reside on different busses.  Use the SIM in the queue
3910 		 * CCB's path, rather than the one in the bus that was passed
3911 		 * into this function.
3912 		 */
3913 		sim = work_ccb->ccb_h.path->bus->sim;
3914 		(*(sim->sim_action))(sim, work_ccb);
3915 
3916 		devq->active_dev = NULL;
3917 	}
3918 	devq->send_queue.qfrozen_cnt--;
3919 }
3920 
3921 /*
3922  * This function merges stuff from the slave ccb into the master ccb, while
3923  * keeping important fields in the master ccb constant.
3924  */
3925 void
3926 xpt_merge_ccb(union ccb *master_ccb, union ccb *slave_ccb)
3927 {
3928 
3929 	/*
3930 	 * Pull fields that are valid for peripheral drivers to set
3931 	 * into the master CCB along with the CCB "payload".
3932 	 */
3933 	master_ccb->ccb_h.retry_count = slave_ccb->ccb_h.retry_count;
3934 	master_ccb->ccb_h.func_code = slave_ccb->ccb_h.func_code;
3935 	master_ccb->ccb_h.timeout = slave_ccb->ccb_h.timeout;
3936 	master_ccb->ccb_h.flags = slave_ccb->ccb_h.flags;
3937 	bcopy(&(&slave_ccb->ccb_h)[1], &(&master_ccb->ccb_h)[1],
3938 	      sizeof(union ccb) - sizeof(struct ccb_hdr));
3939 }
3940 
3941 void
3942 xpt_setup_ccb(struct ccb_hdr *ccb_h, struct cam_path *path, u_int32_t priority)
3943 {
3944 
3945 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_setup_ccb\n"));
3946 	ccb_h->pinfo.priority = priority;
3947 	ccb_h->path = path;
3948 	ccb_h->path_id = path->bus->path_id;
3949 	if (path->target)
3950 		ccb_h->target_id = path->target->target_id;
3951 	else
3952 		ccb_h->target_id = CAM_TARGET_WILDCARD;
3953 	if (path->device) {
3954 		ccb_h->target_lun = path->device->lun_id;
3955 		ccb_h->pinfo.generation = ++path->device->ccbq.queue.generation;
3956 	} else {
3957 		ccb_h->target_lun = CAM_TARGET_WILDCARD;
3958 	}
3959 	ccb_h->pinfo.index = CAM_UNQUEUED_INDEX;
3960 	ccb_h->flags = 0;
3961 }
3962 
3963 /* Path manipulation functions */
3964 cam_status
3965 xpt_create_path(struct cam_path **new_path_ptr, struct cam_periph *perph,
3966 		path_id_t path_id, target_id_t target_id, lun_id_t lun_id)
3967 {
3968 	struct	   cam_path *path;
3969 	cam_status status;
3970 
3971 	path = (struct cam_path *)malloc(sizeof(*path), M_CAMXPT, M_NOWAIT);
3972 
3973 	if (path == NULL) {
3974 		status = CAM_RESRC_UNAVAIL;
3975 		return(status);
3976 	}
3977 	status = xpt_compile_path(path, perph, path_id, target_id, lun_id);
3978 	if (status != CAM_REQ_CMP) {
3979 		free(path, M_CAMXPT);
3980 		path = NULL;
3981 	}
3982 	*new_path_ptr = path;
3983 	return (status);
3984 }
3985 
3986 cam_status
3987 xpt_create_path_unlocked(struct cam_path **new_path_ptr,
3988 			 struct cam_periph *periph, path_id_t path_id,
3989 			 target_id_t target_id, lun_id_t lun_id)
3990 {
3991 	struct	   cam_path *path;
3992 	struct	   cam_eb *bus = NULL;
3993 	cam_status status;
3994 	int	   need_unlock = 0;
3995 
3996 	path = (struct cam_path *)malloc(sizeof(*path), M_CAMXPT, M_WAITOK);
3997 
3998 	if (path_id != CAM_BUS_WILDCARD) {
3999 		bus = xpt_find_bus(path_id);
4000 		if (bus != NULL) {
4001 			need_unlock = 1;
4002 			CAM_SIM_LOCK(bus->sim);
4003 		}
4004 	}
4005 	status = xpt_compile_path(path, periph, path_id, target_id, lun_id);
4006 	if (need_unlock)
4007 		CAM_SIM_UNLOCK(bus->sim);
4008 	if (status != CAM_REQ_CMP) {
4009 		free(path, M_CAMXPT);
4010 		path = NULL;
4011 	}
4012 	*new_path_ptr = path;
4013 	return (status);
4014 }
4015 
4016 static cam_status
4017 xpt_compile_path(struct cam_path *new_path, struct cam_periph *perph,
4018 		 path_id_t path_id, target_id_t target_id, lun_id_t lun_id)
4019 {
4020 	struct	     cam_eb *bus;
4021 	struct	     cam_et *target;
4022 	struct	     cam_ed *device;
4023 	cam_status   status;
4024 
4025 	status = CAM_REQ_CMP;	/* Completed without error */
4026 	target = NULL;		/* Wildcarded */
4027 	device = NULL;		/* Wildcarded */
4028 
4029 	/*
4030 	 * We will potentially modify the EDT, so block interrupts
4031 	 * that may attempt to create cam paths.
4032 	 */
4033 	bus = xpt_find_bus(path_id);
4034 	if (bus == NULL) {
4035 		status = CAM_PATH_INVALID;
4036 	} else {
4037 		target = xpt_find_target(bus, target_id);
4038 		if (target == NULL) {
4039 			/* Create one */
4040 			struct cam_et *new_target;
4041 
4042 			new_target = xpt_alloc_target(bus, target_id);
4043 			if (new_target == NULL) {
4044 				status = CAM_RESRC_UNAVAIL;
4045 			} else {
4046 				target = new_target;
4047 			}
4048 		}
4049 		if (target != NULL) {
4050 			device = xpt_find_device(target, lun_id);
4051 			if (device == NULL) {
4052 				/* Create one */
4053 				struct cam_ed *new_device;
4054 
4055 				new_device = xpt_alloc_device(bus,
4056 							      target,
4057 							      lun_id);
4058 				if (new_device == NULL) {
4059 					status = CAM_RESRC_UNAVAIL;
4060 				} else {
4061 					device = new_device;
4062 				}
4063 			}
4064 		}
4065 	}
4066 
4067 	/*
4068 	 * Only touch the user's data if we are successful.
4069 	 */
4070 	if (status == CAM_REQ_CMP) {
4071 		new_path->periph = perph;
4072 		new_path->bus = bus;
4073 		new_path->target = target;
4074 		new_path->device = device;
4075 		CAM_DEBUG(new_path, CAM_DEBUG_TRACE, ("xpt_compile_path\n"));
4076 	} else {
4077 		if (device != NULL)
4078 			xpt_release_device(bus, target, device);
4079 		if (target != NULL)
4080 			xpt_release_target(bus, target);
4081 		if (bus != NULL)
4082 			xpt_release_bus(bus);
4083 	}
4084 	return (status);
4085 }
4086 
4087 static void
4088 xpt_release_path(struct cam_path *path)
4089 {
4090 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_release_path\n"));
4091 	if (path->device != NULL) {
4092 		xpt_release_device(path->bus, path->target, path->device);
4093 		path->device = NULL;
4094 	}
4095 	if (path->target != NULL) {
4096 		xpt_release_target(path->bus, path->target);
4097 		path->target = NULL;
4098 	}
4099 	if (path->bus != NULL) {
4100 		xpt_release_bus(path->bus);
4101 		path->bus = NULL;
4102 	}
4103 }
4104 
4105 void
4106 xpt_free_path(struct cam_path *path)
4107 {
4108 
4109 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_free_path\n"));
4110 	xpt_release_path(path);
4111 	free(path, M_CAMXPT);
4112 }
4113 
4114 
4115 /*
4116  * Return -1 for failure, 0 for exact match, 1 for match with wildcards
4117  * in path1, 2 for match with wildcards in path2.
4118  */
4119 int
4120 xpt_path_comp(struct cam_path *path1, struct cam_path *path2)
4121 {
4122 	int retval = 0;
4123 
4124 	if (path1->bus != path2->bus) {
4125 		if (path1->bus->path_id == CAM_BUS_WILDCARD)
4126 			retval = 1;
4127 		else if (path2->bus->path_id == CAM_BUS_WILDCARD)
4128 			retval = 2;
4129 		else
4130 			return (-1);
4131 	}
4132 	if (path1->target != path2->target) {
4133 		if (path1->target->target_id == CAM_TARGET_WILDCARD) {
4134 			if (retval == 0)
4135 				retval = 1;
4136 		} else if (path2->target->target_id == CAM_TARGET_WILDCARD)
4137 			retval = 2;
4138 		else
4139 			return (-1);
4140 	}
4141 	if (path1->device != path2->device) {
4142 		if (path1->device->lun_id == CAM_LUN_WILDCARD) {
4143 			if (retval == 0)
4144 				retval = 1;
4145 		} else if (path2->device->lun_id == CAM_LUN_WILDCARD)
4146 			retval = 2;
4147 		else
4148 			return (-1);
4149 	}
4150 	return (retval);
4151 }
4152 
4153 void
4154 xpt_print_path(struct cam_path *path)
4155 {
4156 
4157 	if (path == NULL)
4158 		printf("(nopath): ");
4159 	else {
4160 		if (path->periph != NULL)
4161 			printf("(%s%d:", path->periph->periph_name,
4162 			       path->periph->unit_number);
4163 		else
4164 			printf("(noperiph:");
4165 
4166 		if (path->bus != NULL)
4167 			printf("%s%d:%d:", path->bus->sim->sim_name,
4168 			       path->bus->sim->unit_number,
4169 			       path->bus->sim->bus_id);
4170 		else
4171 			printf("nobus:");
4172 
4173 		if (path->target != NULL)
4174 			printf("%d:", path->target->target_id);
4175 		else
4176 			printf("X:");
4177 
4178 		if (path->device != NULL)
4179 			printf("%d): ", path->device->lun_id);
4180 		else
4181 			printf("X): ");
4182 	}
4183 }
4184 
4185 void
4186 xpt_print(struct cam_path *path, const char *fmt, ...)
4187 {
4188 	va_list ap;
4189 	xpt_print_path(path);
4190 	va_start(ap, fmt);
4191 	vprintf(fmt, ap);
4192 	va_end(ap);
4193 }
4194 
4195 int
4196 xpt_path_string(struct cam_path *path, char *str, size_t str_len)
4197 {
4198 	struct sbuf sb;
4199 
4200 	mtx_assert(path->bus->sim->mtx, MA_OWNED);
4201 
4202 	sbuf_new(&sb, str, str_len, 0);
4203 
4204 	if (path == NULL)
4205 		sbuf_printf(&sb, "(nopath): ");
4206 	else {
4207 		if (path->periph != NULL)
4208 			sbuf_printf(&sb, "(%s%d:", path->periph->periph_name,
4209 				    path->periph->unit_number);
4210 		else
4211 			sbuf_printf(&sb, "(noperiph:");
4212 
4213 		if (path->bus != NULL)
4214 			sbuf_printf(&sb, "%s%d:%d:", path->bus->sim->sim_name,
4215 				    path->bus->sim->unit_number,
4216 				    path->bus->sim->bus_id);
4217 		else
4218 			sbuf_printf(&sb, "nobus:");
4219 
4220 		if (path->target != NULL)
4221 			sbuf_printf(&sb, "%d:", path->target->target_id);
4222 		else
4223 			sbuf_printf(&sb, "X:");
4224 
4225 		if (path->device != NULL)
4226 			sbuf_printf(&sb, "%d): ", path->device->lun_id);
4227 		else
4228 			sbuf_printf(&sb, "X): ");
4229 	}
4230 	sbuf_finish(&sb);
4231 
4232 	return(sbuf_len(&sb));
4233 }
4234 
4235 path_id_t
4236 xpt_path_path_id(struct cam_path *path)
4237 {
4238 	mtx_assert(path->bus->sim->mtx, MA_OWNED);
4239 
4240 	return(path->bus->path_id);
4241 }
4242 
4243 target_id_t
4244 xpt_path_target_id(struct cam_path *path)
4245 {
4246 	mtx_assert(path->bus->sim->mtx, MA_OWNED);
4247 
4248 	if (path->target != NULL)
4249 		return (path->target->target_id);
4250 	else
4251 		return (CAM_TARGET_WILDCARD);
4252 }
4253 
4254 lun_id_t
4255 xpt_path_lun_id(struct cam_path *path)
4256 {
4257 	mtx_assert(path->bus->sim->mtx, MA_OWNED);
4258 
4259 	if (path->device != NULL)
4260 		return (path->device->lun_id);
4261 	else
4262 		return (CAM_LUN_WILDCARD);
4263 }
4264 
4265 struct cam_sim *
4266 xpt_path_sim(struct cam_path *path)
4267 {
4268 
4269 	return (path->bus->sim);
4270 }
4271 
4272 struct cam_periph*
4273 xpt_path_periph(struct cam_path *path)
4274 {
4275 	mtx_assert(path->bus->sim->mtx, MA_OWNED);
4276 
4277 	return (path->periph);
4278 }
4279 
4280 /*
4281  * Release a CAM control block for the caller.  Remit the cost of the structure
4282  * to the device referenced by the path.  If the this device had no 'credits'
4283  * and peripheral drivers have registered async callbacks for this notification
4284  * call them now.
4285  */
4286 void
4287 xpt_release_ccb(union ccb *free_ccb)
4288 {
4289 	struct	 cam_path *path;
4290 	struct	 cam_ed *device;
4291 	struct	 cam_eb *bus;
4292 	struct   cam_sim *sim;
4293 
4294 	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_release_ccb\n"));
4295 	path = free_ccb->ccb_h.path;
4296 	device = path->device;
4297 	bus = path->bus;
4298 	sim = bus->sim;
4299 
4300 	mtx_assert(sim->mtx, MA_OWNED);
4301 
4302 	cam_ccbq_release_opening(&device->ccbq);
4303 	if (sim->ccb_count > sim->max_ccbs) {
4304 		xpt_free_ccb(free_ccb);
4305 		sim->ccb_count--;
4306 	} else {
4307 		SLIST_INSERT_HEAD(&sim->ccb_freeq, &free_ccb->ccb_h,
4308 		    xpt_links.sle);
4309 	}
4310 	if (sim->devq == NULL) {
4311 		return;
4312 	}
4313 	sim->devq->alloc_openings++;
4314 	sim->devq->alloc_active--;
4315 	/* XXX Turn this into an inline function - xpt_run_device?? */
4316 	if ((device_is_alloc_queued(device) == 0)
4317 	 && (device->drvq.entries > 0)) {
4318 		xpt_schedule_dev_allocq(bus, device);
4319 	}
4320 	if (dev_allocq_is_runnable(sim->devq))
4321 		xpt_run_dev_allocq(bus);
4322 }
4323 
4324 /* Functions accessed by SIM drivers */
4325 
4326 /*
4327  * A sim structure, listing the SIM entry points and instance
4328  * identification info is passed to xpt_bus_register to hook the SIM
4329  * into the CAM framework.  xpt_bus_register creates a cam_eb entry
4330  * for this new bus and places it in the array of busses and assigns
4331  * it a path_id.  The path_id may be influenced by "hard wiring"
4332  * information specified by the user.  Once interrupt services are
4333  * availible, the bus will be probed.
4334  */
4335 int32_t
4336 xpt_bus_register(struct cam_sim *sim, device_t parent, u_int32_t bus)
4337 {
4338 	struct cam_eb *new_bus;
4339 	struct cam_eb *old_bus;
4340 	struct ccb_pathinq cpi;
4341 
4342 	mtx_assert(sim->mtx, MA_OWNED);
4343 
4344 	sim->bus_id = bus;
4345 	new_bus = (struct cam_eb *)malloc(sizeof(*new_bus),
4346 					  M_CAMXPT, M_NOWAIT);
4347 	if (new_bus == NULL) {
4348 		/* Couldn't satisfy request */
4349 		return (CAM_RESRC_UNAVAIL);
4350 	}
4351 
4352 	if (strcmp(sim->sim_name, "xpt") != 0) {
4353 
4354 		sim->path_id =
4355 		    xptpathid(sim->sim_name, sim->unit_number, sim->bus_id);
4356 	}
4357 
4358 	TAILQ_INIT(&new_bus->et_entries);
4359 	new_bus->path_id = sim->path_id;
4360 	new_bus->sim = sim;
4361 	timevalclear(&new_bus->last_reset);
4362 	new_bus->flags = 0;
4363 	new_bus->refcount = 1;	/* Held until a bus_deregister event */
4364 	new_bus->generation = 0;
4365 	mtx_lock(&xsoftc.xpt_topo_lock);
4366 	old_bus = TAILQ_FIRST(&xsoftc.xpt_busses);
4367 	while (old_bus != NULL
4368 	    && old_bus->path_id < new_bus->path_id)
4369 		old_bus = TAILQ_NEXT(old_bus, links);
4370 	if (old_bus != NULL)
4371 		TAILQ_INSERT_BEFORE(old_bus, new_bus, links);
4372 	else
4373 		TAILQ_INSERT_TAIL(&xsoftc.xpt_busses, new_bus, links);
4374 	xsoftc.bus_generation++;
4375 	mtx_unlock(&xsoftc.xpt_topo_lock);
4376 
4377 	/* Notify interested parties */
4378 	if (sim->path_id != CAM_XPT_PATH_ID) {
4379 		struct cam_path path;
4380 
4381 		xpt_compile_path(&path, /*periph*/NULL, sim->path_id,
4382 			         CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
4383 		xpt_setup_ccb(&cpi.ccb_h, &path, /*priority*/1);
4384 		cpi.ccb_h.func_code = XPT_PATH_INQ;
4385 		xpt_action((union ccb *)&cpi);
4386 		xpt_async(AC_PATH_REGISTERED, &path, &cpi);
4387 		xpt_release_path(&path);
4388 	}
4389 	return (CAM_SUCCESS);
4390 }
4391 
4392 int32_t
4393 xpt_bus_deregister(path_id_t pathid)
4394 {
4395 	struct cam_path bus_path;
4396 	struct cam_ed *device;
4397 	struct cam_ed_qinfo *qinfo;
4398 	struct cam_devq *devq;
4399 	struct cam_periph *periph;
4400 	struct cam_sim *ccbsim;
4401 	union ccb *work_ccb;
4402 	cam_status status;
4403 
4404 
4405 	status = xpt_compile_path(&bus_path, NULL, pathid,
4406 				  CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
4407 	if (status != CAM_REQ_CMP)
4408 		return (status);
4409 
4410 	xpt_async(AC_LOST_DEVICE, &bus_path, NULL);
4411 	xpt_async(AC_PATH_DEREGISTERED, &bus_path, NULL);
4412 
4413 	/* The SIM may be gone, so use a dummy SIM for any stray operations. */
4414 	devq = bus_path.bus->sim->devq;
4415 	ccbsim = bus_path.bus->sim;
4416 	bus_path.bus->sim = &cam_dead_sim;
4417 
4418 	/* Execute any pending operations now. */
4419 	while ((qinfo = (struct cam_ed_qinfo *)camq_remove(&devq->send_queue,
4420 	    CAMQ_HEAD)) != NULL ||
4421 	    (qinfo = (struct cam_ed_qinfo *)camq_remove(&devq->alloc_queue,
4422 	    CAMQ_HEAD)) != NULL) {
4423 		do {
4424 			device = qinfo->device;
4425 			work_ccb = cam_ccbq_peek_ccb(&device->ccbq, CAMQ_HEAD);
4426 			if (work_ccb != NULL) {
4427 				devq->active_dev = device;
4428 				cam_ccbq_remove_ccb(&device->ccbq, work_ccb);
4429 				cam_ccbq_send_ccb(&device->ccbq, work_ccb);
4430 				(*(ccbsim->sim_action))(ccbsim, work_ccb);
4431 			}
4432 
4433 			periph = (struct cam_periph *)camq_remove(&device->drvq,
4434 			    CAMQ_HEAD);
4435 			if (periph != NULL)
4436 				xpt_schedule(periph, periph->pinfo.priority);
4437 		} while (work_ccb != NULL || periph != NULL);
4438 	}
4439 
4440 	/* Make sure all completed CCBs are processed. */
4441 	while (!TAILQ_EMPTY(&ccbsim->sim_doneq)) {
4442 		camisr_runqueue(&ccbsim->sim_doneq);
4443 
4444 		/* Repeat the async's for the benefit of any new devices. */
4445 		xpt_async(AC_LOST_DEVICE, &bus_path, NULL);
4446 		xpt_async(AC_PATH_DEREGISTERED, &bus_path, NULL);
4447 	}
4448 
4449 	/* Release the reference count held while registered. */
4450 	xpt_release_bus(bus_path.bus);
4451 	xpt_release_path(&bus_path);
4452 
4453 	return (CAM_REQ_CMP);
4454 }
4455 
4456 static path_id_t
4457 xptnextfreepathid(void)
4458 {
4459 	struct cam_eb *bus;
4460 	path_id_t pathid;
4461 	const char *strval;
4462 
4463 	pathid = 0;
4464 	mtx_lock(&xsoftc.xpt_topo_lock);
4465 	bus = TAILQ_FIRST(&xsoftc.xpt_busses);
4466 retry:
4467 	/* Find an unoccupied pathid */
4468 	while (bus != NULL && bus->path_id <= pathid) {
4469 		if (bus->path_id == pathid)
4470 			pathid++;
4471 		bus = TAILQ_NEXT(bus, links);
4472 	}
4473 	mtx_unlock(&xsoftc.xpt_topo_lock);
4474 
4475 	/*
4476 	 * Ensure that this pathid is not reserved for
4477 	 * a bus that may be registered in the future.
4478 	 */
4479 	if (resource_string_value("scbus", pathid, "at", &strval) == 0) {
4480 		++pathid;
4481 		/* Start the search over */
4482 		mtx_lock(&xsoftc.xpt_topo_lock);
4483 		goto retry;
4484 	}
4485 	return (pathid);
4486 }
4487 
4488 static path_id_t
4489 xptpathid(const char *sim_name, int sim_unit, int sim_bus)
4490 {
4491 	path_id_t pathid;
4492 	int i, dunit, val;
4493 	char buf[32];
4494 	const char *dname;
4495 
4496 	pathid = CAM_XPT_PATH_ID;
4497 	snprintf(buf, sizeof(buf), "%s%d", sim_name, sim_unit);
4498 	i = 0;
4499 	while ((resource_find_match(&i, &dname, &dunit, "at", buf)) == 0) {
4500 		if (strcmp(dname, "scbus")) {
4501 			/* Avoid a bit of foot shooting. */
4502 			continue;
4503 		}
4504 		if (dunit < 0)		/* unwired?! */
4505 			continue;
4506 		if (resource_int_value("scbus", dunit, "bus", &val) == 0) {
4507 			if (sim_bus == val) {
4508 				pathid = dunit;
4509 				break;
4510 			}
4511 		} else if (sim_bus == 0) {
4512 			/* Unspecified matches bus 0 */
4513 			pathid = dunit;
4514 			break;
4515 		} else {
4516 			printf("Ambiguous scbus configuration for %s%d "
4517 			       "bus %d, cannot wire down.  The kernel "
4518 			       "config entry for scbus%d should "
4519 			       "specify a controller bus.\n"
4520 			       "Scbus will be assigned dynamically.\n",
4521 			       sim_name, sim_unit, sim_bus, dunit);
4522 			break;
4523 		}
4524 	}
4525 
4526 	if (pathid == CAM_XPT_PATH_ID)
4527 		pathid = xptnextfreepathid();
4528 	return (pathid);
4529 }
4530 
4531 void
4532 xpt_async(u_int32_t async_code, struct cam_path *path, void *async_arg)
4533 {
4534 	struct cam_eb *bus;
4535 	struct cam_et *target, *next_target;
4536 	struct cam_ed *device, *next_device;
4537 
4538 	mtx_assert(path->bus->sim->mtx, MA_OWNED);
4539 
4540 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_async\n"));
4541 
4542 	/*
4543 	 * Most async events come from a CAM interrupt context.  In
4544 	 * a few cases, the error recovery code at the peripheral layer,
4545 	 * which may run from our SWI or a process context, may signal
4546 	 * deferred events with a call to xpt_async.
4547 	 */
4548 
4549 	bus = path->bus;
4550 
4551 	if (async_code == AC_BUS_RESET) {
4552 		/* Update our notion of when the last reset occurred */
4553 		microtime(&bus->last_reset);
4554 	}
4555 
4556 	for (target = TAILQ_FIRST(&bus->et_entries);
4557 	     target != NULL;
4558 	     target = next_target) {
4559 
4560 		next_target = TAILQ_NEXT(target, links);
4561 
4562 		if (path->target != target
4563 		 && path->target->target_id != CAM_TARGET_WILDCARD
4564 		 && target->target_id != CAM_TARGET_WILDCARD)
4565 			continue;
4566 
4567 		if (async_code == AC_SENT_BDR) {
4568 			/* Update our notion of when the last reset occurred */
4569 			microtime(&path->target->last_reset);
4570 		}
4571 
4572 		for (device = TAILQ_FIRST(&target->ed_entries);
4573 		     device != NULL;
4574 		     device = next_device) {
4575 
4576 			next_device = TAILQ_NEXT(device, links);
4577 
4578 			if (path->device != device
4579 			 && path->device->lun_id != CAM_LUN_WILDCARD
4580 			 && device->lun_id != CAM_LUN_WILDCARD)
4581 				continue;
4582 
4583 			xpt_dev_async(async_code, bus, target,
4584 				      device, async_arg);
4585 
4586 			xpt_async_bcast(&device->asyncs, async_code,
4587 					path, async_arg);
4588 		}
4589 	}
4590 
4591 	/*
4592 	 * If this wasn't a fully wildcarded async, tell all
4593 	 * clients that want all async events.
4594 	 */
4595 	if (bus != xpt_periph->path->bus)
4596 		xpt_async_bcast(&xpt_periph->path->device->asyncs, async_code,
4597 				path, async_arg);
4598 }
4599 
4600 static void
4601 xpt_async_bcast(struct async_list *async_head,
4602 		u_int32_t async_code,
4603 		struct cam_path *path, void *async_arg)
4604 {
4605 	struct async_node *cur_entry;
4606 
4607 	cur_entry = SLIST_FIRST(async_head);
4608 	while (cur_entry != NULL) {
4609 		struct async_node *next_entry;
4610 		/*
4611 		 * Grab the next list entry before we call the current
4612 		 * entry's callback.  This is because the callback function
4613 		 * can delete its async callback entry.
4614 		 */
4615 		next_entry = SLIST_NEXT(cur_entry, links);
4616 		if ((cur_entry->event_enable & async_code) != 0)
4617 			cur_entry->callback(cur_entry->callback_arg,
4618 					    async_code, path,
4619 					    async_arg);
4620 		cur_entry = next_entry;
4621 	}
4622 }
4623 
4624 /*
4625  * Handle any per-device event notifications that require action by the XPT.
4626  */
4627 static void
4628 xpt_dev_async(u_int32_t async_code, struct cam_eb *bus, struct cam_et *target,
4629 	      struct cam_ed *device, void *async_arg)
4630 {
4631 	cam_status status;
4632 	struct cam_path newpath;
4633 
4634 	/*
4635 	 * We only need to handle events for real devices.
4636 	 */
4637 	if (target->target_id == CAM_TARGET_WILDCARD
4638 	 || device->lun_id == CAM_LUN_WILDCARD)
4639 		return;
4640 
4641 	/*
4642 	 * We need our own path with wildcards expanded to
4643 	 * handle certain types of events.
4644 	 */
4645 	if ((async_code == AC_SENT_BDR)
4646 	 || (async_code == AC_BUS_RESET)
4647 	 || (async_code == AC_INQ_CHANGED))
4648 		status = xpt_compile_path(&newpath, NULL,
4649 					  bus->path_id,
4650 					  target->target_id,
4651 					  device->lun_id);
4652 	else
4653 		status = CAM_REQ_CMP_ERR;
4654 
4655 	if (status == CAM_REQ_CMP) {
4656 
4657 		/*
4658 		 * Allow transfer negotiation to occur in a
4659 		 * tag free environment.
4660 		 */
4661 		if (async_code == AC_SENT_BDR
4662 		 || async_code == AC_BUS_RESET)
4663 			xpt_toggle_tags(&newpath);
4664 
4665 		if (async_code == AC_INQ_CHANGED) {
4666 			/*
4667 			 * We've sent a start unit command, or
4668 			 * something similar to a device that
4669 			 * may have caused its inquiry data to
4670 			 * change. So we re-scan the device to
4671 			 * refresh the inquiry data for it.
4672 			 */
4673 			xpt_scan_lun(newpath.periph, &newpath,
4674 				     CAM_EXPECT_INQ_CHANGE, NULL);
4675 		}
4676 		xpt_release_path(&newpath);
4677 	} else if (async_code == AC_LOST_DEVICE) {
4678 		device->flags |= CAM_DEV_UNCONFIGURED;
4679 	} else if (async_code == AC_TRANSFER_NEG) {
4680 		struct ccb_trans_settings *settings;
4681 
4682 		settings = (struct ccb_trans_settings *)async_arg;
4683 		xpt_set_transfer_settings(settings, device,
4684 					  /*async_update*/TRUE);
4685 	}
4686 }
4687 
4688 u_int32_t
4689 xpt_freeze_devq(struct cam_path *path, u_int count)
4690 {
4691 	struct ccb_hdr *ccbh;
4692 
4693 	mtx_assert(path->bus->sim->mtx, MA_OWNED);
4694 
4695 	path->device->qfrozen_cnt += count;
4696 
4697 	/*
4698 	 * Mark the last CCB in the queue as needing
4699 	 * to be requeued if the driver hasn't
4700 	 * changed it's state yet.  This fixes a race
4701 	 * where a ccb is just about to be queued to
4702 	 * a controller driver when it's interrupt routine
4703 	 * freezes the queue.  To completly close the
4704 	 * hole, controller drives must check to see
4705 	 * if a ccb's status is still CAM_REQ_INPROG
4706 	 * just before they queue
4707 	 * the CCB.  See ahc_action/ahc_freeze_devq for
4708 	 * an example.
4709 	 */
4710 	ccbh = TAILQ_LAST(&path->device->ccbq.active_ccbs, ccb_hdr_tailq);
4711 	if (ccbh && ccbh->status == CAM_REQ_INPROG)
4712 		ccbh->status = CAM_REQUEUE_REQ;
4713 	return (path->device->qfrozen_cnt);
4714 }
4715 
4716 u_int32_t
4717 xpt_freeze_simq(struct cam_sim *sim, u_int count)
4718 {
4719 	mtx_assert(sim->mtx, MA_OWNED);
4720 
4721 	sim->devq->send_queue.qfrozen_cnt += count;
4722 	if (sim->devq->active_dev != NULL) {
4723 		struct ccb_hdr *ccbh;
4724 
4725 		ccbh = TAILQ_LAST(&sim->devq->active_dev->ccbq.active_ccbs,
4726 				  ccb_hdr_tailq);
4727 		if (ccbh && ccbh->status == CAM_REQ_INPROG)
4728 			ccbh->status = CAM_REQUEUE_REQ;
4729 	}
4730 	return (sim->devq->send_queue.qfrozen_cnt);
4731 }
4732 
4733 static void
4734 xpt_release_devq_timeout(void *arg)
4735 {
4736 	struct cam_ed *device;
4737 
4738 	device = (struct cam_ed *)arg;
4739 
4740 	xpt_release_devq_device(device, /*count*/1, /*run_queue*/TRUE);
4741 }
4742 
4743 void
4744 xpt_release_devq(struct cam_path *path, u_int count, int run_queue)
4745 {
4746 	mtx_assert(path->bus->sim->mtx, MA_OWNED);
4747 
4748 	xpt_release_devq_device(path->device, count, run_queue);
4749 }
4750 
4751 static void
4752 xpt_release_devq_device(struct cam_ed *dev, u_int count, int run_queue)
4753 {
4754 	int	rundevq;
4755 
4756 	rundevq = 0;
4757 	if (dev->qfrozen_cnt > 0) {
4758 
4759 		count = (count > dev->qfrozen_cnt) ? dev->qfrozen_cnt : count;
4760 		dev->qfrozen_cnt -= count;
4761 		if (dev->qfrozen_cnt == 0) {
4762 
4763 			/*
4764 			 * No longer need to wait for a successful
4765 			 * command completion.
4766 			 */
4767 			dev->flags &= ~CAM_DEV_REL_ON_COMPLETE;
4768 
4769 			/*
4770 			 * Remove any timeouts that might be scheduled
4771 			 * to release this queue.
4772 			 */
4773 			if ((dev->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
4774 				callout_stop(&dev->callout);
4775 				dev->flags &= ~CAM_DEV_REL_TIMEOUT_PENDING;
4776 			}
4777 
4778 			/*
4779 			 * Now that we are unfrozen schedule the
4780 			 * device so any pending transactions are
4781 			 * run.
4782 			 */
4783 			if ((dev->ccbq.queue.entries > 0)
4784 			 && (xpt_schedule_dev_sendq(dev->target->bus, dev))
4785 			 && (run_queue != 0)) {
4786 				rundevq = 1;
4787 			}
4788 		}
4789 	}
4790 	if (rundevq != 0)
4791 		xpt_run_dev_sendq(dev->target->bus);
4792 }
4793 
4794 void
4795 xpt_release_simq(struct cam_sim *sim, int run_queue)
4796 {
4797 	struct	camq *sendq;
4798 
4799 	mtx_assert(sim->mtx, MA_OWNED);
4800 
4801 	sendq = &(sim->devq->send_queue);
4802 	if (sendq->qfrozen_cnt > 0) {
4803 
4804 		sendq->qfrozen_cnt--;
4805 		if (sendq->qfrozen_cnt == 0) {
4806 			struct cam_eb *bus;
4807 
4808 			/*
4809 			 * If there is a timeout scheduled to release this
4810 			 * sim queue, remove it.  The queue frozen count is
4811 			 * already at 0.
4812 			 */
4813 			if ((sim->flags & CAM_SIM_REL_TIMEOUT_PENDING) != 0){
4814 				callout_stop(&sim->callout);
4815 				sim->flags &= ~CAM_SIM_REL_TIMEOUT_PENDING;
4816 			}
4817 			bus = xpt_find_bus(sim->path_id);
4818 
4819 			if (run_queue) {
4820 				/*
4821 				 * Now that we are unfrozen run the send queue.
4822 				 */
4823 				xpt_run_dev_sendq(bus);
4824 			}
4825 			xpt_release_bus(bus);
4826 		}
4827 	}
4828 }
4829 
4830 /*
4831  * XXX Appears to be unused.
4832  */
4833 static void
4834 xpt_release_simq_timeout(void *arg)
4835 {
4836 	struct cam_sim *sim;
4837 
4838 	sim = (struct cam_sim *)arg;
4839 	xpt_release_simq(sim, /* run_queue */ TRUE);
4840 }
4841 
4842 void
4843 xpt_done(union ccb *done_ccb)
4844 {
4845 	struct cam_sim *sim;
4846 
4847 	CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("xpt_done\n"));
4848 	if ((done_ccb->ccb_h.func_code & XPT_FC_QUEUED) != 0) {
4849 		/*
4850 		 * Queue up the request for handling by our SWI handler
4851 		 * any of the "non-immediate" type of ccbs.
4852 		 */
4853 		sim = done_ccb->ccb_h.path->bus->sim;
4854 		switch (done_ccb->ccb_h.path->periph->type) {
4855 		case CAM_PERIPH_BIO:
4856 			TAILQ_INSERT_TAIL(&sim->sim_doneq, &done_ccb->ccb_h,
4857 					  sim_links.tqe);
4858 			done_ccb->ccb_h.pinfo.index = CAM_DONEQ_INDEX;
4859 			if ((sim->flags & CAM_SIM_ON_DONEQ) == 0) {
4860 				mtx_lock(&cam_simq_lock);
4861 				TAILQ_INSERT_TAIL(&cam_simq, sim,
4862 						  links);
4863 				sim->flags |= CAM_SIM_ON_DONEQ;
4864 				mtx_unlock(&cam_simq_lock);
4865 			}
4866 			if ((done_ccb->ccb_h.path->periph->flags &
4867 			    CAM_PERIPH_POLLED) == 0)
4868 				swi_sched(cambio_ih, 0);
4869 			break;
4870 		default:
4871 			panic("unknown periph type %d",
4872 			    done_ccb->ccb_h.path->periph->type);
4873 		}
4874 	}
4875 }
4876 
4877 union ccb *
4878 xpt_alloc_ccb()
4879 {
4880 	union ccb *new_ccb;
4881 
4882 	new_ccb = malloc(sizeof(*new_ccb), M_CAMXPT, M_ZERO|M_WAITOK);
4883 	return (new_ccb);
4884 }
4885 
4886 union ccb *
4887 xpt_alloc_ccb_nowait()
4888 {
4889 	union ccb *new_ccb;
4890 
4891 	new_ccb = malloc(sizeof(*new_ccb), M_CAMXPT, M_ZERO|M_NOWAIT);
4892 	return (new_ccb);
4893 }
4894 
4895 void
4896 xpt_free_ccb(union ccb *free_ccb)
4897 {
4898 	free(free_ccb, M_CAMXPT);
4899 }
4900 
4901 
4902 
4903 /* Private XPT functions */
4904 
4905 /*
4906  * Get a CAM control block for the caller. Charge the structure to the device
4907  * referenced by the path.  If the this device has no 'credits' then the
4908  * device already has the maximum number of outstanding operations under way
4909  * and we return NULL. If we don't have sufficient resources to allocate more
4910  * ccbs, we also return NULL.
4911  */
4912 static union ccb *
4913 xpt_get_ccb(struct cam_ed *device)
4914 {
4915 	union ccb *new_ccb;
4916 	struct cam_sim *sim;
4917 
4918 	sim = device->sim;
4919 	if ((new_ccb = (union ccb *)SLIST_FIRST(&sim->ccb_freeq)) == NULL) {
4920 		new_ccb = xpt_alloc_ccb_nowait();
4921                 if (new_ccb == NULL) {
4922 			return (NULL);
4923 		}
4924 		if ((sim->flags & CAM_SIM_MPSAFE) == 0)
4925 			callout_handle_init(&new_ccb->ccb_h.timeout_ch);
4926 		SLIST_INSERT_HEAD(&sim->ccb_freeq, &new_ccb->ccb_h,
4927 				  xpt_links.sle);
4928 		sim->ccb_count++;
4929 	}
4930 	cam_ccbq_take_opening(&device->ccbq);
4931 	SLIST_REMOVE_HEAD(&sim->ccb_freeq, xpt_links.sle);
4932 	return (new_ccb);
4933 }
4934 
4935 static void
4936 xpt_release_bus(struct cam_eb *bus)
4937 {
4938 
4939 	if ((--bus->refcount == 0)
4940 	 && (TAILQ_FIRST(&bus->et_entries) == NULL)) {
4941 		mtx_lock(&xsoftc.xpt_topo_lock);
4942 		TAILQ_REMOVE(&xsoftc.xpt_busses, bus, links);
4943 		xsoftc.bus_generation++;
4944 		mtx_unlock(&xsoftc.xpt_topo_lock);
4945 		free(bus, M_CAMXPT);
4946 	}
4947 }
4948 
4949 static struct cam_et *
4950 xpt_alloc_target(struct cam_eb *bus, target_id_t target_id)
4951 {
4952 	struct cam_et *target;
4953 
4954 	target = (struct cam_et *)malloc(sizeof(*target), M_CAMXPT, M_NOWAIT);
4955 	if (target != NULL) {
4956 		struct cam_et *cur_target;
4957 
4958 		TAILQ_INIT(&target->ed_entries);
4959 		target->bus = bus;
4960 		target->target_id = target_id;
4961 		target->refcount = 1;
4962 		target->generation = 0;
4963 		timevalclear(&target->last_reset);
4964 		/*
4965 		 * Hold a reference to our parent bus so it
4966 		 * will not go away before we do.
4967 		 */
4968 		bus->refcount++;
4969 
4970 		/* Insertion sort into our bus's target list */
4971 		cur_target = TAILQ_FIRST(&bus->et_entries);
4972 		while (cur_target != NULL && cur_target->target_id < target_id)
4973 			cur_target = TAILQ_NEXT(cur_target, links);
4974 
4975 		if (cur_target != NULL) {
4976 			TAILQ_INSERT_BEFORE(cur_target, target, links);
4977 		} else {
4978 			TAILQ_INSERT_TAIL(&bus->et_entries, target, links);
4979 		}
4980 		bus->generation++;
4981 	}
4982 	return (target);
4983 }
4984 
4985 static void
4986 xpt_release_target(struct cam_eb *bus, struct cam_et *target)
4987 {
4988 
4989 	if ((--target->refcount == 0)
4990 	 && (TAILQ_FIRST(&target->ed_entries) == NULL)) {
4991 		TAILQ_REMOVE(&bus->et_entries, target, links);
4992 		bus->generation++;
4993 		free(target, M_CAMXPT);
4994 		xpt_release_bus(bus);
4995 	}
4996 }
4997 
4998 static struct cam_ed *
4999 xpt_alloc_device(struct cam_eb *bus, struct cam_et *target, lun_id_t lun_id)
5000 {
5001 	struct	   cam_path path;
5002 	struct	   cam_ed *device;
5003 	struct	   cam_devq *devq;
5004 	cam_status status;
5005 
5006 	if (SIM_DEAD(bus->sim))
5007 		return (NULL);
5008 
5009 	/* Make space for us in the device queue on our bus */
5010 	devq = bus->sim->devq;
5011 	status = cam_devq_resize(devq, devq->alloc_queue.array_size + 1);
5012 
5013 	if (status != CAM_REQ_CMP) {
5014 		device = NULL;
5015 	} else {
5016 		device = (struct cam_ed *)malloc(sizeof(*device),
5017 						 M_CAMXPT, M_NOWAIT);
5018 	}
5019 
5020 	if (device != NULL) {
5021 		struct cam_ed *cur_device;
5022 
5023 		cam_init_pinfo(&device->alloc_ccb_entry.pinfo);
5024 		device->alloc_ccb_entry.device = device;
5025 		cam_init_pinfo(&device->send_ccb_entry.pinfo);
5026 		device->send_ccb_entry.device = device;
5027 		device->target = target;
5028 		device->lun_id = lun_id;
5029 		device->sim = bus->sim;
5030 		/* Initialize our queues */
5031 		if (camq_init(&device->drvq, 0) != 0) {
5032 			free(device, M_CAMXPT);
5033 			return (NULL);
5034 		}
5035 		if (cam_ccbq_init(&device->ccbq,
5036 				  bus->sim->max_dev_openings) != 0) {
5037 			camq_fini(&device->drvq);
5038 			free(device, M_CAMXPT);
5039 			return (NULL);
5040 		}
5041 		SLIST_INIT(&device->asyncs);
5042 		SLIST_INIT(&device->periphs);
5043 		device->generation = 0;
5044 		device->owner = NULL;
5045 		/*
5046 		 * Take the default quirk entry until we have inquiry
5047 		 * data and can determine a better quirk to use.
5048 		 */
5049 		device->quirk = &xpt_quirk_table[xpt_quirk_table_size - 1];
5050 		bzero(&device->inq_data, sizeof(device->inq_data));
5051 		device->inq_flags = 0;
5052 		device->queue_flags = 0;
5053 		device->serial_num = NULL;
5054 		device->serial_num_len = 0;
5055 		device->qfrozen_cnt = 0;
5056 		device->flags = CAM_DEV_UNCONFIGURED;
5057 		device->tag_delay_count = 0;
5058 		device->tag_saved_openings = 0;
5059 		device->refcount = 1;
5060 		if (bus->sim->flags & CAM_SIM_MPSAFE)
5061 			callout_init_mtx(&device->callout, bus->sim->mtx, 0);
5062 		else
5063 			callout_init_mtx(&device->callout, &Giant, 0);
5064 
5065 		/*
5066 		 * Hold a reference to our parent target so it
5067 		 * will not go away before we do.
5068 		 */
5069 		target->refcount++;
5070 
5071 		/*
5072 		 * XXX should be limited by number of CCBs this bus can
5073 		 * do.
5074 		 */
5075 		bus->sim->max_ccbs += device->ccbq.devq_openings;
5076 		/* Insertion sort into our target's device list */
5077 		cur_device = TAILQ_FIRST(&target->ed_entries);
5078 		while (cur_device != NULL && cur_device->lun_id < lun_id)
5079 			cur_device = TAILQ_NEXT(cur_device, links);
5080 		if (cur_device != NULL) {
5081 			TAILQ_INSERT_BEFORE(cur_device, device, links);
5082 		} else {
5083 			TAILQ_INSERT_TAIL(&target->ed_entries, device, links);
5084 		}
5085 		target->generation++;
5086 		if (lun_id != CAM_LUN_WILDCARD) {
5087 			xpt_compile_path(&path,
5088 					 NULL,
5089 					 bus->path_id,
5090 					 target->target_id,
5091 					 lun_id);
5092 			xpt_devise_transport(&path);
5093 			xpt_release_path(&path);
5094 		}
5095 	}
5096 	return (device);
5097 }
5098 
5099 static void
5100 xpt_release_device(struct cam_eb *bus, struct cam_et *target,
5101 		   struct cam_ed *device)
5102 {
5103 
5104 	if ((--device->refcount == 0)
5105 	 && ((device->flags & CAM_DEV_UNCONFIGURED) != 0)) {
5106 		struct cam_devq *devq;
5107 
5108 		if (device->alloc_ccb_entry.pinfo.index != CAM_UNQUEUED_INDEX
5109 		 || device->send_ccb_entry.pinfo.index != CAM_UNQUEUED_INDEX)
5110 			panic("Removing device while still queued for ccbs");
5111 
5112 		if ((device->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0)
5113 				callout_stop(&device->callout);
5114 
5115 		TAILQ_REMOVE(&target->ed_entries, device,links);
5116 		target->generation++;
5117 		bus->sim->max_ccbs -= device->ccbq.devq_openings;
5118 		if (!SIM_DEAD(bus->sim)) {
5119 			/* Release our slot in the devq */
5120 			devq = bus->sim->devq;
5121 			cam_devq_resize(devq, devq->alloc_queue.array_size - 1);
5122 		}
5123 		camq_fini(&device->drvq);
5124 		camq_fini(&device->ccbq.queue);
5125 		free(device, M_CAMXPT);
5126 		xpt_release_target(bus, target);
5127 	}
5128 }
5129 
5130 static u_int32_t
5131 xpt_dev_ccbq_resize(struct cam_path *path, int newopenings)
5132 {
5133 	int	diff;
5134 	int	result;
5135 	struct	cam_ed *dev;
5136 
5137 	dev = path->device;
5138 
5139 	diff = newopenings - (dev->ccbq.dev_active + dev->ccbq.dev_openings);
5140 	result = cam_ccbq_resize(&dev->ccbq, newopenings);
5141 	if (result == CAM_REQ_CMP && (diff < 0)) {
5142 		dev->flags |= CAM_DEV_RESIZE_QUEUE_NEEDED;
5143 	}
5144 	if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
5145 	 || (dev->inq_flags & SID_CmdQue) != 0)
5146 		dev->tag_saved_openings = newopenings;
5147 	/* Adjust the global limit */
5148 	dev->sim->max_ccbs += diff;
5149 	return (result);
5150 }
5151 
5152 static struct cam_eb *
5153 xpt_find_bus(path_id_t path_id)
5154 {
5155 	struct cam_eb *bus;
5156 
5157 	mtx_lock(&xsoftc.xpt_topo_lock);
5158 	for (bus = TAILQ_FIRST(&xsoftc.xpt_busses);
5159 	     bus != NULL;
5160 	     bus = TAILQ_NEXT(bus, links)) {
5161 		if (bus->path_id == path_id) {
5162 			bus->refcount++;
5163 			break;
5164 		}
5165 	}
5166 	mtx_unlock(&xsoftc.xpt_topo_lock);
5167 	return (bus);
5168 }
5169 
5170 static struct cam_et *
5171 xpt_find_target(struct cam_eb *bus, target_id_t	target_id)
5172 {
5173 	struct cam_et *target;
5174 
5175 	for (target = TAILQ_FIRST(&bus->et_entries);
5176 	     target != NULL;
5177 	     target = TAILQ_NEXT(target, links)) {
5178 		if (target->target_id == target_id) {
5179 			target->refcount++;
5180 			break;
5181 		}
5182 	}
5183 	return (target);
5184 }
5185 
5186 static struct cam_ed *
5187 xpt_find_device(struct cam_et *target, lun_id_t lun_id)
5188 {
5189 	struct cam_ed *device;
5190 
5191 	for (device = TAILQ_FIRST(&target->ed_entries);
5192 	     device != NULL;
5193 	     device = TAILQ_NEXT(device, links)) {
5194 		if (device->lun_id == lun_id) {
5195 			device->refcount++;
5196 			break;
5197 		}
5198 	}
5199 	return (device);
5200 }
5201 
5202 typedef struct {
5203 	union	ccb *request_ccb;
5204 	struct 	ccb_pathinq *cpi;
5205 	int	counter;
5206 } xpt_scan_bus_info;
5207 
5208 /*
5209  * To start a scan, request_ccb is an XPT_SCAN_BUS ccb.
5210  * As the scan progresses, xpt_scan_bus is used as the
5211  * callback on completion function.
5212  */
5213 static void
5214 xpt_scan_bus(struct cam_periph *periph, union ccb *request_ccb)
5215 {
5216 	CAM_DEBUG(request_ccb->ccb_h.path, CAM_DEBUG_TRACE,
5217 		  ("xpt_scan_bus\n"));
5218 	switch (request_ccb->ccb_h.func_code) {
5219 	case XPT_SCAN_BUS:
5220 	{
5221 		xpt_scan_bus_info *scan_info;
5222 		union	ccb *work_ccb;
5223 		struct	cam_path *path;
5224 		u_int	i;
5225 		u_int	max_target;
5226 		u_int	initiator_id;
5227 
5228 		/* Find out the characteristics of the bus */
5229 		work_ccb = xpt_alloc_ccb_nowait();
5230 		if (work_ccb == NULL) {
5231 			request_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
5232 			xpt_done(request_ccb);
5233 			return;
5234 		}
5235 		xpt_setup_ccb(&work_ccb->ccb_h, request_ccb->ccb_h.path,
5236 			      request_ccb->ccb_h.pinfo.priority);
5237 		work_ccb->ccb_h.func_code = XPT_PATH_INQ;
5238 		xpt_action(work_ccb);
5239 		if (work_ccb->ccb_h.status != CAM_REQ_CMP) {
5240 			request_ccb->ccb_h.status = work_ccb->ccb_h.status;
5241 			xpt_free_ccb(work_ccb);
5242 			xpt_done(request_ccb);
5243 			return;
5244 		}
5245 
5246 		if ((work_ccb->cpi.hba_misc & PIM_NOINITIATOR) != 0) {
5247 			/*
5248 			 * Can't scan the bus on an adapter that
5249 			 * cannot perform the initiator role.
5250 			 */
5251 			request_ccb->ccb_h.status = CAM_REQ_CMP;
5252 			xpt_free_ccb(work_ccb);
5253 			xpt_done(request_ccb);
5254 			return;
5255 		}
5256 
5257 		/* Save some state for use while we probe for devices */
5258 		scan_info = (xpt_scan_bus_info *)
5259 		    malloc(sizeof(xpt_scan_bus_info), M_CAMXPT, M_NOWAIT);
5260 		scan_info->request_ccb = request_ccb;
5261 		scan_info->cpi = &work_ccb->cpi;
5262 
5263 		/* Cache on our stack so we can work asynchronously */
5264 		max_target = scan_info->cpi->max_target;
5265 		initiator_id = scan_info->cpi->initiator_id;
5266 
5267 
5268 		/*
5269 		 * We can scan all targets in parallel, or do it sequentially.
5270 		 */
5271 		if (scan_info->cpi->hba_misc & PIM_SEQSCAN) {
5272 			max_target = 0;
5273 			scan_info->counter = 0;
5274 		} else {
5275 			scan_info->counter = scan_info->cpi->max_target + 1;
5276 			if (scan_info->cpi->initiator_id < scan_info->counter) {
5277 				scan_info->counter--;
5278 			}
5279 		}
5280 
5281 		for (i = 0; i <= max_target; i++) {
5282 			cam_status status;
5283 			if (i == initiator_id)
5284 				continue;
5285 
5286 			status = xpt_create_path(&path, xpt_periph,
5287 						 request_ccb->ccb_h.path_id,
5288 						 i, 0);
5289 			if (status != CAM_REQ_CMP) {
5290 				printf("xpt_scan_bus: xpt_create_path failed"
5291 				       " with status %#x, bus scan halted\n",
5292 				       status);
5293 				free(scan_info, M_CAMXPT);
5294 				request_ccb->ccb_h.status = status;
5295 				xpt_free_ccb(work_ccb);
5296 				xpt_done(request_ccb);
5297 				break;
5298 			}
5299 			work_ccb = xpt_alloc_ccb_nowait();
5300 			if (work_ccb == NULL) {
5301 				free(scan_info, M_CAMXPT);
5302 				xpt_free_path(path);
5303 				request_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
5304 				xpt_done(request_ccb);
5305 				break;
5306 			}
5307 			xpt_setup_ccb(&work_ccb->ccb_h, path,
5308 				      request_ccb->ccb_h.pinfo.priority);
5309 			work_ccb->ccb_h.func_code = XPT_SCAN_LUN;
5310 			work_ccb->ccb_h.cbfcnp = xpt_scan_bus;
5311 			work_ccb->ccb_h.ppriv_ptr0 = scan_info;
5312 			work_ccb->crcn.flags = request_ccb->crcn.flags;
5313 			xpt_action(work_ccb);
5314 		}
5315 		break;
5316 	}
5317 	case XPT_SCAN_LUN:
5318 	{
5319 		cam_status status;
5320 		struct cam_path *path;
5321 		xpt_scan_bus_info *scan_info;
5322 		path_id_t path_id;
5323 		target_id_t target_id;
5324 		lun_id_t lun_id;
5325 
5326 		/* Reuse the same CCB to query if a device was really found */
5327 		scan_info = (xpt_scan_bus_info *)request_ccb->ccb_h.ppriv_ptr0;
5328 		xpt_setup_ccb(&request_ccb->ccb_h, request_ccb->ccb_h.path,
5329 			      request_ccb->ccb_h.pinfo.priority);
5330 		request_ccb->ccb_h.func_code = XPT_GDEV_TYPE;
5331 
5332 		path_id = request_ccb->ccb_h.path_id;
5333 		target_id = request_ccb->ccb_h.target_id;
5334 		lun_id = request_ccb->ccb_h.target_lun;
5335 		xpt_action(request_ccb);
5336 
5337 		if (request_ccb->ccb_h.status != CAM_REQ_CMP) {
5338 			struct cam_ed *device;
5339 			struct cam_et *target;
5340 			int phl;
5341 
5342 			/*
5343 			 * If we already probed lun 0 successfully, or
5344 			 * we have additional configured luns on this
5345 			 * target that might have "gone away", go onto
5346 			 * the next lun.
5347 			 */
5348 			target = request_ccb->ccb_h.path->target;
5349 			/*
5350 			 * We may touch devices that we don't
5351 			 * hold references too, so ensure they
5352 			 * don't disappear out from under us.
5353 			 * The target above is referenced by the
5354 			 * path in the request ccb.
5355 			 */
5356 			phl = 0;
5357 			device = TAILQ_FIRST(&target->ed_entries);
5358 			if (device != NULL) {
5359 				phl = CAN_SRCH_HI_SPARSE(device);
5360 				if (device->lun_id == 0)
5361 					device = TAILQ_NEXT(device, links);
5362 			}
5363 			if ((lun_id != 0) || (device != NULL)) {
5364 				if (lun_id < (CAM_SCSI2_MAXLUN-1) || phl)
5365 					lun_id++;
5366 			}
5367 		} else {
5368 			struct cam_ed *device;
5369 
5370 			device = request_ccb->ccb_h.path->device;
5371 
5372 			if ((device->quirk->quirks & CAM_QUIRK_NOLUNS) == 0) {
5373 				/* Try the next lun */
5374 				if (lun_id < (CAM_SCSI2_MAXLUN-1)
5375 				  || CAN_SRCH_HI_DENSE(device))
5376 					lun_id++;
5377 			}
5378 		}
5379 
5380 		/*
5381 		 * Free the current request path- we're done with it.
5382 		 */
5383 		xpt_free_path(request_ccb->ccb_h.path);
5384 
5385 		/*
5386 		 * Check to see if we scan any further luns.
5387 		 */
5388 		if (lun_id == request_ccb->ccb_h.target_lun
5389                  || lun_id > scan_info->cpi->max_lun) {
5390 			int done;
5391 
5392  hop_again:
5393 			done = 0;
5394 			if (scan_info->cpi->hba_misc & PIM_SEQSCAN) {
5395 				scan_info->counter++;
5396 				if (scan_info->counter ==
5397 				    scan_info->cpi->initiator_id) {
5398 					scan_info->counter++;
5399 				}
5400 				if (scan_info->counter >=
5401 				    scan_info->cpi->max_target+1) {
5402 					done = 1;
5403 				}
5404 			} else {
5405 				scan_info->counter--;
5406 				if (scan_info->counter == 0) {
5407 					done = 1;
5408 				}
5409 			}
5410 			if (done) {
5411 				xpt_free_ccb(request_ccb);
5412 				xpt_free_ccb((union ccb *)scan_info->cpi);
5413 				request_ccb = scan_info->request_ccb;
5414 				free(scan_info, M_CAMXPT);
5415 				request_ccb->ccb_h.status = CAM_REQ_CMP;
5416 				xpt_done(request_ccb);
5417 				break;
5418 			}
5419 
5420 			if ((scan_info->cpi->hba_misc & PIM_SEQSCAN) == 0) {
5421 				break;
5422 			}
5423 			status = xpt_create_path(&path, xpt_periph,
5424 			    scan_info->request_ccb->ccb_h.path_id,
5425 			    scan_info->counter, 0);
5426 			if (status != CAM_REQ_CMP) {
5427 				printf("xpt_scan_bus: xpt_create_path failed"
5428 				    " with status %#x, bus scan halted\n",
5429 			       	    status);
5430 				xpt_free_ccb(request_ccb);
5431 				xpt_free_ccb((union ccb *)scan_info->cpi);
5432 				request_ccb = scan_info->request_ccb;
5433 				free(scan_info, M_CAMXPT);
5434 				request_ccb->ccb_h.status = status;
5435 				xpt_done(request_ccb);
5436 				break;
5437 			}
5438 			xpt_setup_ccb(&request_ccb->ccb_h, path,
5439 			    request_ccb->ccb_h.pinfo.priority);
5440 			request_ccb->ccb_h.func_code = XPT_SCAN_LUN;
5441 			request_ccb->ccb_h.cbfcnp = xpt_scan_bus;
5442 			request_ccb->ccb_h.ppriv_ptr0 = scan_info;
5443 			request_ccb->crcn.flags =
5444 			    scan_info->request_ccb->crcn.flags;
5445 		} else {
5446 			status = xpt_create_path(&path, xpt_periph,
5447 						 path_id, target_id, lun_id);
5448 			if (status != CAM_REQ_CMP) {
5449 				printf("xpt_scan_bus: xpt_create_path failed "
5450 				       "with status %#x, halting LUN scan\n",
5451 			 	       status);
5452 				goto hop_again;
5453 			}
5454 			xpt_setup_ccb(&request_ccb->ccb_h, path,
5455 				      request_ccb->ccb_h.pinfo.priority);
5456 			request_ccb->ccb_h.func_code = XPT_SCAN_LUN;
5457 			request_ccb->ccb_h.cbfcnp = xpt_scan_bus;
5458 			request_ccb->ccb_h.ppriv_ptr0 = scan_info;
5459 			request_ccb->crcn.flags =
5460 				scan_info->request_ccb->crcn.flags;
5461 		}
5462 		xpt_action(request_ccb);
5463 		break;
5464 	}
5465 	default:
5466 		break;
5467 	}
5468 }
5469 
5470 typedef enum {
5471 	PROBE_TUR,
5472 	PROBE_INQUIRY,	/* this counts as DV0 for Basic Domain Validation */
5473 	PROBE_FULL_INQUIRY,
5474 	PROBE_MODE_SENSE,
5475 	PROBE_SERIAL_NUM,
5476 	PROBE_TUR_FOR_NEGOTIATION,
5477 	PROBE_INQUIRY_BASIC_DV1,
5478 	PROBE_INQUIRY_BASIC_DV2,
5479 	PROBE_DV_EXIT
5480 } probe_action;
5481 
5482 typedef enum {
5483 	PROBE_INQUIRY_CKSUM	= 0x01,
5484 	PROBE_SERIAL_CKSUM	= 0x02,
5485 	PROBE_NO_ANNOUNCE	= 0x04
5486 } probe_flags;
5487 
5488 typedef struct {
5489 	TAILQ_HEAD(, ccb_hdr) request_ccbs;
5490 	probe_action	action;
5491 	union ccb	saved_ccb;
5492 	probe_flags	flags;
5493 	MD5_CTX		context;
5494 	u_int8_t	digest[16];
5495 } probe_softc;
5496 
5497 static void
5498 xpt_scan_lun(struct cam_periph *periph, struct cam_path *path,
5499 	     cam_flags flags, union ccb *request_ccb)
5500 {
5501 	struct ccb_pathinq cpi;
5502 	cam_status status;
5503 	struct cam_path *new_path;
5504 	struct cam_periph *old_periph;
5505 
5506 	CAM_DEBUG(request_ccb->ccb_h.path, CAM_DEBUG_TRACE,
5507 		  ("xpt_scan_lun\n"));
5508 
5509 	xpt_setup_ccb(&cpi.ccb_h, path, /*priority*/1);
5510 	cpi.ccb_h.func_code = XPT_PATH_INQ;
5511 	xpt_action((union ccb *)&cpi);
5512 
5513 	if (cpi.ccb_h.status != CAM_REQ_CMP) {
5514 		if (request_ccb != NULL) {
5515 			request_ccb->ccb_h.status = cpi.ccb_h.status;
5516 			xpt_done(request_ccb);
5517 		}
5518 		return;
5519 	}
5520 
5521 	if ((cpi.hba_misc & PIM_NOINITIATOR) != 0) {
5522 		/*
5523 		 * Can't scan the bus on an adapter that
5524 		 * cannot perform the initiator role.
5525 		 */
5526 		if (request_ccb != NULL) {
5527 			request_ccb->ccb_h.status = CAM_REQ_CMP;
5528 			xpt_done(request_ccb);
5529 		}
5530 		return;
5531 	}
5532 
5533 	if (request_ccb == NULL) {
5534 		request_ccb = malloc(sizeof(union ccb), M_CAMXPT, M_NOWAIT);
5535 		if (request_ccb == NULL) {
5536 			xpt_print(path, "xpt_scan_lun: can't allocate CCB, "
5537 			    "can't continue\n");
5538 			return;
5539 		}
5540 		new_path = malloc(sizeof(*new_path), M_CAMXPT, M_NOWAIT);
5541 		if (new_path == NULL) {
5542 			xpt_print(path, "xpt_scan_lun: can't allocate path, "
5543 			    "can't continue\n");
5544 			free(request_ccb, M_CAMXPT);
5545 			return;
5546 		}
5547 		status = xpt_compile_path(new_path, xpt_periph,
5548 					  path->bus->path_id,
5549 					  path->target->target_id,
5550 					  path->device->lun_id);
5551 
5552 		if (status != CAM_REQ_CMP) {
5553 			xpt_print(path, "xpt_scan_lun: can't compile path, "
5554 			    "can't continue\n");
5555 			free(request_ccb, M_CAMXPT);
5556 			free(new_path, M_CAMXPT);
5557 			return;
5558 		}
5559 		xpt_setup_ccb(&request_ccb->ccb_h, new_path, /*priority*/ 1);
5560 		request_ccb->ccb_h.cbfcnp = xptscandone;
5561 		request_ccb->ccb_h.func_code = XPT_SCAN_LUN;
5562 		request_ccb->crcn.flags = flags;
5563 	}
5564 
5565 	if ((old_periph = cam_periph_find(path, "probe")) != NULL) {
5566 		probe_softc *softc;
5567 
5568 		softc = (probe_softc *)old_periph->softc;
5569 		TAILQ_INSERT_TAIL(&softc->request_ccbs, &request_ccb->ccb_h,
5570 				  periph_links.tqe);
5571 	} else {
5572 		status = cam_periph_alloc(proberegister, NULL, probecleanup,
5573 					  probestart, "probe",
5574 					  CAM_PERIPH_BIO,
5575 					  request_ccb->ccb_h.path, NULL, 0,
5576 					  request_ccb);
5577 
5578 		if (status != CAM_REQ_CMP) {
5579 			xpt_print(path, "xpt_scan_lun: cam_alloc_periph "
5580 			    "returned an error, can't continue probe\n");
5581 			request_ccb->ccb_h.status = status;
5582 			xpt_done(request_ccb);
5583 		}
5584 	}
5585 }
5586 
5587 static void
5588 xptscandone(struct cam_periph *periph, union ccb *done_ccb)
5589 {
5590 	xpt_release_path(done_ccb->ccb_h.path);
5591 	free(done_ccb->ccb_h.path, M_CAMXPT);
5592 	free(done_ccb, M_CAMXPT);
5593 }
5594 
5595 static cam_status
5596 proberegister(struct cam_periph *periph, void *arg)
5597 {
5598 	union ccb *request_ccb;	/* CCB representing the probe request */
5599 	cam_status status;
5600 	probe_softc *softc;
5601 
5602 	request_ccb = (union ccb *)arg;
5603 	if (periph == NULL) {
5604 		printf("proberegister: periph was NULL!!\n");
5605 		return(CAM_REQ_CMP_ERR);
5606 	}
5607 
5608 	if (request_ccb == NULL) {
5609 		printf("proberegister: no probe CCB, "
5610 		       "can't register device\n");
5611 		return(CAM_REQ_CMP_ERR);
5612 	}
5613 
5614 	softc = (probe_softc *)malloc(sizeof(*softc), M_CAMXPT, M_NOWAIT);
5615 
5616 	if (softc == NULL) {
5617 		printf("proberegister: Unable to probe new device. "
5618 		       "Unable to allocate softc\n");
5619 		return(CAM_REQ_CMP_ERR);
5620 	}
5621 	TAILQ_INIT(&softc->request_ccbs);
5622 	TAILQ_INSERT_TAIL(&softc->request_ccbs, &request_ccb->ccb_h,
5623 			  periph_links.tqe);
5624 	softc->flags = 0;
5625 	periph->softc = softc;
5626 	status = cam_periph_acquire(periph);
5627 	if (status != CAM_REQ_CMP) {
5628 		return (status);
5629 	}
5630 
5631 
5632 	/*
5633 	 * Ensure we've waited at least a bus settle
5634 	 * delay before attempting to probe the device.
5635 	 * For HBAs that don't do bus resets, this won't make a difference.
5636 	 */
5637 	cam_periph_freeze_after_event(periph, &periph->path->bus->last_reset,
5638 				      scsi_delay);
5639 	probeschedule(periph);
5640 	return(CAM_REQ_CMP);
5641 }
5642 
5643 static void
5644 probeschedule(struct cam_periph *periph)
5645 {
5646 	struct ccb_pathinq cpi;
5647 	union ccb *ccb;
5648 	probe_softc *softc;
5649 
5650 	softc = (probe_softc *)periph->softc;
5651 	ccb = (union ccb *)TAILQ_FIRST(&softc->request_ccbs);
5652 
5653 	xpt_setup_ccb(&cpi.ccb_h, periph->path, /*priority*/1);
5654 	cpi.ccb_h.func_code = XPT_PATH_INQ;
5655 	xpt_action((union ccb *)&cpi);
5656 
5657 	/*
5658 	 * If a device has gone away and another device, or the same one,
5659 	 * is back in the same place, it should have a unit attention
5660 	 * condition pending.  It will not report the unit attention in
5661 	 * response to an inquiry, which may leave invalid transfer
5662 	 * negotiations in effect.  The TUR will reveal the unit attention
5663 	 * condition.  Only send the TUR for lun 0, since some devices
5664 	 * will get confused by commands other than inquiry to non-existent
5665 	 * luns.  If you think a device has gone away start your scan from
5666 	 * lun 0.  This will insure that any bogus transfer settings are
5667 	 * invalidated.
5668 	 *
5669 	 * If we haven't seen the device before and the controller supports
5670 	 * some kind of transfer negotiation, negotiate with the first
5671 	 * sent command if no bus reset was performed at startup.  This
5672 	 * ensures that the device is not confused by transfer negotiation
5673 	 * settings left over by loader or BIOS action.
5674 	 */
5675 	if (((ccb->ccb_h.path->device->flags & CAM_DEV_UNCONFIGURED) == 0)
5676 	 && (ccb->ccb_h.target_lun == 0)) {
5677 		softc->action = PROBE_TUR;
5678 	} else if ((cpi.hba_inquiry & (PI_WIDE_32|PI_WIDE_16|PI_SDTR_ABLE)) != 0
5679 	      && (cpi.hba_misc & PIM_NOBUSRESET) != 0) {
5680 		proberequestdefaultnegotiation(periph);
5681 		softc->action = PROBE_INQUIRY;
5682 	} else {
5683 		softc->action = PROBE_INQUIRY;
5684 	}
5685 
5686 	if (ccb->crcn.flags & CAM_EXPECT_INQ_CHANGE)
5687 		softc->flags |= PROBE_NO_ANNOUNCE;
5688 	else
5689 		softc->flags &= ~PROBE_NO_ANNOUNCE;
5690 
5691 	xpt_schedule(periph, ccb->ccb_h.pinfo.priority);
5692 }
5693 
5694 static void
5695 probestart(struct cam_periph *periph, union ccb *start_ccb)
5696 {
5697 	/* Probe the device that our peripheral driver points to */
5698 	struct ccb_scsiio *csio;
5699 	probe_softc *softc;
5700 
5701 	CAM_DEBUG(start_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("probestart\n"));
5702 
5703 	softc = (probe_softc *)periph->softc;
5704 	csio = &start_ccb->csio;
5705 
5706 	switch (softc->action) {
5707 	case PROBE_TUR:
5708 	case PROBE_TUR_FOR_NEGOTIATION:
5709 	case PROBE_DV_EXIT:
5710 	{
5711 		scsi_test_unit_ready(csio,
5712 				     /*retries*/4,
5713 				     probedone,
5714 				     MSG_SIMPLE_Q_TAG,
5715 				     SSD_FULL_SIZE,
5716 				     /*timeout*/60000);
5717 		break;
5718 	}
5719 	case PROBE_INQUIRY:
5720 	case PROBE_FULL_INQUIRY:
5721 	case PROBE_INQUIRY_BASIC_DV1:
5722 	case PROBE_INQUIRY_BASIC_DV2:
5723 	{
5724 		u_int inquiry_len;
5725 		struct scsi_inquiry_data *inq_buf;
5726 
5727 		inq_buf = &periph->path->device->inq_data;
5728 
5729 		/*
5730 		 * If the device is currently configured, we calculate an
5731 		 * MD5 checksum of the inquiry data, and if the serial number
5732 		 * length is greater than 0, add the serial number data
5733 		 * into the checksum as well.  Once the inquiry and the
5734 		 * serial number check finish, we attempt to figure out
5735 		 * whether we still have the same device.
5736 		 */
5737 		if ((periph->path->device->flags & CAM_DEV_UNCONFIGURED) == 0) {
5738 
5739 			MD5Init(&softc->context);
5740 			MD5Update(&softc->context, (unsigned char *)inq_buf,
5741 				  sizeof(struct scsi_inquiry_data));
5742 			softc->flags |= PROBE_INQUIRY_CKSUM;
5743 			if (periph->path->device->serial_num_len > 0) {
5744 				MD5Update(&softc->context,
5745 					  periph->path->device->serial_num,
5746 					  periph->path->device->serial_num_len);
5747 				softc->flags |= PROBE_SERIAL_CKSUM;
5748 			}
5749 			MD5Final(softc->digest, &softc->context);
5750 		}
5751 
5752 		if (softc->action == PROBE_INQUIRY)
5753 			inquiry_len = SHORT_INQUIRY_LENGTH;
5754 		else
5755 			inquiry_len = SID_ADDITIONAL_LENGTH(inq_buf);
5756 
5757 		/*
5758 		 * Some parallel SCSI devices fail to send an
5759 		 * ignore wide residue message when dealing with
5760 		 * odd length inquiry requests.  Round up to be
5761 		 * safe.
5762 		 */
5763 		inquiry_len = roundup2(inquiry_len, 2);
5764 
5765 		if (softc->action == PROBE_INQUIRY_BASIC_DV1
5766 		 || softc->action == PROBE_INQUIRY_BASIC_DV2) {
5767 			inq_buf = malloc(inquiry_len, M_CAMXPT, M_NOWAIT);
5768 		}
5769 		if (inq_buf == NULL) {
5770 			xpt_print(periph->path, "malloc failure- skipping Basic"
5771 			    "Domain Validation\n");
5772 			softc->action = PROBE_DV_EXIT;
5773 			scsi_test_unit_ready(csio,
5774 					     /*retries*/4,
5775 					     probedone,
5776 					     MSG_SIMPLE_Q_TAG,
5777 					     SSD_FULL_SIZE,
5778 					     /*timeout*/60000);
5779 			break;
5780 		}
5781 		scsi_inquiry(csio,
5782 			     /*retries*/4,
5783 			     probedone,
5784 			     MSG_SIMPLE_Q_TAG,
5785 			     (u_int8_t *)inq_buf,
5786 			     inquiry_len,
5787 			     /*evpd*/FALSE,
5788 			     /*page_code*/0,
5789 			     SSD_MIN_SIZE,
5790 			     /*timeout*/60 * 1000);
5791 		break;
5792 	}
5793 	case PROBE_MODE_SENSE:
5794 	{
5795 		void  *mode_buf;
5796 		int    mode_buf_len;
5797 
5798 		mode_buf_len = sizeof(struct scsi_mode_header_6)
5799 			     + sizeof(struct scsi_mode_blk_desc)
5800 			     + sizeof(struct scsi_control_page);
5801 		mode_buf = malloc(mode_buf_len, M_CAMXPT, M_NOWAIT);
5802 		if (mode_buf != NULL) {
5803 	                scsi_mode_sense(csio,
5804 					/*retries*/4,
5805 					probedone,
5806 					MSG_SIMPLE_Q_TAG,
5807 					/*dbd*/FALSE,
5808 					SMS_PAGE_CTRL_CURRENT,
5809 					SMS_CONTROL_MODE_PAGE,
5810 					mode_buf,
5811 					mode_buf_len,
5812 					SSD_FULL_SIZE,
5813 					/*timeout*/60000);
5814 			break;
5815 		}
5816 		xpt_print(periph->path, "Unable to mode sense control page - "
5817 		    "malloc failure\n");
5818 		softc->action = PROBE_SERIAL_NUM;
5819 	}
5820 	/* FALLTHROUGH */
5821 	case PROBE_SERIAL_NUM:
5822 	{
5823 		struct scsi_vpd_unit_serial_number *serial_buf;
5824 		struct cam_ed* device;
5825 
5826 		serial_buf = NULL;
5827 		device = periph->path->device;
5828 		device->serial_num = NULL;
5829 		device->serial_num_len = 0;
5830 
5831 		if ((device->quirk->quirks & CAM_QUIRK_NOSERIAL) == 0)
5832 			serial_buf = (struct scsi_vpd_unit_serial_number *)
5833 				malloc(sizeof(*serial_buf), M_CAMXPT,
5834 					M_NOWAIT | M_ZERO);
5835 
5836 		if (serial_buf != NULL) {
5837 			scsi_inquiry(csio,
5838 				     /*retries*/4,
5839 				     probedone,
5840 				     MSG_SIMPLE_Q_TAG,
5841 				     (u_int8_t *)serial_buf,
5842 				     sizeof(*serial_buf),
5843 				     /*evpd*/TRUE,
5844 				     SVPD_UNIT_SERIAL_NUMBER,
5845 				     SSD_MIN_SIZE,
5846 				     /*timeout*/60 * 1000);
5847 			break;
5848 		}
5849 		/*
5850 		 * We'll have to do without, let our probedone
5851 		 * routine finish up for us.
5852 		 */
5853 		start_ccb->csio.data_ptr = NULL;
5854 		probedone(periph, start_ccb);
5855 		return;
5856 	}
5857 	}
5858 	xpt_action(start_ccb);
5859 }
5860 
5861 static void
5862 proberequestdefaultnegotiation(struct cam_periph *periph)
5863 {
5864 	struct ccb_trans_settings cts;
5865 
5866 	xpt_setup_ccb(&cts.ccb_h, periph->path, /*priority*/1);
5867 	cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
5868 	cts.type = CTS_TYPE_USER_SETTINGS;
5869 	xpt_action((union ccb *)&cts);
5870 	if ((cts.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
5871 		return;
5872 	}
5873 	cts.ccb_h.func_code = XPT_SET_TRAN_SETTINGS;
5874 	cts.type = CTS_TYPE_CURRENT_SETTINGS;
5875 	xpt_action((union ccb *)&cts);
5876 }
5877 
5878 /*
5879  * Backoff Negotiation Code- only pertinent for SPI devices.
5880  */
5881 static int
5882 proberequestbackoff(struct cam_periph *periph, struct cam_ed *device)
5883 {
5884 	struct ccb_trans_settings cts;
5885 	struct ccb_trans_settings_spi *spi;
5886 
5887 	memset(&cts, 0, sizeof (cts));
5888 	xpt_setup_ccb(&cts.ccb_h, periph->path, /*priority*/1);
5889 	cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
5890 	cts.type = CTS_TYPE_CURRENT_SETTINGS;
5891 	xpt_action((union ccb *)&cts);
5892 	if ((cts.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
5893 		if (bootverbose) {
5894 			xpt_print(periph->path,
5895 			    "failed to get current device settings\n");
5896 		}
5897 		return (0);
5898 	}
5899 	if (cts.transport != XPORT_SPI) {
5900 		if (bootverbose) {
5901 			xpt_print(periph->path, "not SPI transport\n");
5902 		}
5903 		return (0);
5904 	}
5905 	spi = &cts.xport_specific.spi;
5906 
5907 	/*
5908 	 * We cannot renegotiate sync rate if we don't have one.
5909 	 */
5910 	if ((spi->valid & CTS_SPI_VALID_SYNC_RATE) == 0) {
5911 		if (bootverbose) {
5912 			xpt_print(periph->path, "no sync rate known\n");
5913 		}
5914 		return (0);
5915 	}
5916 
5917 	/*
5918 	 * We'll assert that we don't have to touch PPR options- the
5919 	 * SIM will see what we do with period and offset and adjust
5920 	 * the PPR options as appropriate.
5921 	 */
5922 
5923 	/*
5924 	 * A sync rate with unknown or zero offset is nonsensical.
5925 	 * A sync period of zero means Async.
5926 	 */
5927 	if ((spi->valid & CTS_SPI_VALID_SYNC_OFFSET) == 0
5928 	 || spi->sync_offset == 0 || spi->sync_period == 0) {
5929 		if (bootverbose) {
5930 			xpt_print(periph->path, "no sync rate available\n");
5931 		}
5932 		return (0);
5933 	}
5934 
5935 	if (device->flags & CAM_DEV_DV_HIT_BOTTOM) {
5936 		CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
5937 		    ("hit async: giving up on DV\n"));
5938 		return (0);
5939 	}
5940 
5941 
5942 	/*
5943 	 * Jump sync_period up by one, but stop at 5MHz and fall back to Async.
5944 	 * We don't try to remember 'last' settings to see if the SIM actually
5945 	 * gets into the speed we want to set. We check on the SIM telling
5946 	 * us that a requested speed is bad, but otherwise don't try and
5947 	 * check the speed due to the asynchronous and handshake nature
5948 	 * of speed setting.
5949 	 */
5950 	spi->valid = CTS_SPI_VALID_SYNC_RATE | CTS_SPI_VALID_SYNC_OFFSET;
5951 	for (;;) {
5952 		spi->sync_period++;
5953 		if (spi->sync_period >= 0xf) {
5954 			spi->sync_period = 0;
5955 			spi->sync_offset = 0;
5956 			CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
5957 			    ("setting to async for DV\n"));
5958 			/*
5959 			 * Once we hit async, we don't want to try
5960 			 * any more settings.
5961 			 */
5962 			device->flags |= CAM_DEV_DV_HIT_BOTTOM;
5963 		} else if (bootverbose) {
5964 			CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
5965 			    ("DV: period 0x%x\n", spi->sync_period));
5966 			printf("setting period to 0x%x\n", spi->sync_period);
5967 		}
5968 		cts.ccb_h.func_code = XPT_SET_TRAN_SETTINGS;
5969 		cts.type = CTS_TYPE_CURRENT_SETTINGS;
5970 		xpt_action((union ccb *)&cts);
5971 		if ((cts.ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
5972 			break;
5973 		}
5974 		CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
5975 		    ("DV: failed to set period 0x%x\n", spi->sync_period));
5976 		if (spi->sync_period == 0) {
5977 			return (0);
5978 		}
5979 	}
5980 	return (1);
5981 }
5982 
5983 static void
5984 probedone(struct cam_periph *periph, union ccb *done_ccb)
5985 {
5986 	probe_softc *softc;
5987 	struct cam_path *path;
5988 	u_int32_t  priority;
5989 
5990 	CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("probedone\n"));
5991 
5992 	softc = (probe_softc *)periph->softc;
5993 	path = done_ccb->ccb_h.path;
5994 	priority = done_ccb->ccb_h.pinfo.priority;
5995 
5996 	switch (softc->action) {
5997 	case PROBE_TUR:
5998 	{
5999 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
6000 
6001 			if (cam_periph_error(done_ccb, 0,
6002 					     SF_NO_PRINT, NULL) == ERESTART)
6003 				return;
6004 			else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
6005 				/* Don't wedge the queue */
6006 				xpt_release_devq(done_ccb->ccb_h.path,
6007 						 /*count*/1,
6008 						 /*run_queue*/TRUE);
6009 		}
6010 		softc->action = PROBE_INQUIRY;
6011 		xpt_release_ccb(done_ccb);
6012 		xpt_schedule(periph, priority);
6013 		return;
6014 	}
6015 	case PROBE_INQUIRY:
6016 	case PROBE_FULL_INQUIRY:
6017 	{
6018 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
6019 			struct scsi_inquiry_data *inq_buf;
6020 			u_int8_t periph_qual;
6021 
6022 			path->device->flags |= CAM_DEV_INQUIRY_DATA_VALID;
6023 			inq_buf = &path->device->inq_data;
6024 
6025 			periph_qual = SID_QUAL(inq_buf);
6026 
6027 			switch(periph_qual) {
6028 			case SID_QUAL_LU_CONNECTED:
6029 			{
6030 				u_int8_t len;
6031 
6032 				/*
6033 				 * We conservatively request only
6034 				 * SHORT_INQUIRY_LEN bytes of inquiry
6035 				 * information during our first try
6036 				 * at sending an INQUIRY. If the device
6037 				 * has more information to give,
6038 				 * perform a second request specifying
6039 				 * the amount of information the device
6040 				 * is willing to give.
6041 				 */
6042 				len = inq_buf->additional_length
6043 				    + offsetof(struct scsi_inquiry_data,
6044                                                additional_length) + 1;
6045 				if (softc->action == PROBE_INQUIRY
6046 				 && len > SHORT_INQUIRY_LENGTH) {
6047 					softc->action = PROBE_FULL_INQUIRY;
6048 					xpt_release_ccb(done_ccb);
6049 					xpt_schedule(periph, priority);
6050 					return;
6051 				}
6052 
6053 				xpt_find_quirk(path->device);
6054 
6055 				xpt_devise_transport(path);
6056 				if (INQ_DATA_TQ_ENABLED(inq_buf))
6057 					softc->action = PROBE_MODE_SENSE;
6058 				else
6059 					softc->action = PROBE_SERIAL_NUM;
6060 
6061 				path->device->flags &= ~CAM_DEV_UNCONFIGURED;
6062 
6063 				xpt_release_ccb(done_ccb);
6064 				xpt_schedule(periph, priority);
6065 				return;
6066 			}
6067 			default:
6068 				break;
6069 			}
6070 		} else if (cam_periph_error(done_ccb, 0,
6071 					    done_ccb->ccb_h.target_lun > 0
6072 					    ? SF_RETRY_UA|SF_QUIET_IR
6073 					    : SF_RETRY_UA,
6074 					    &softc->saved_ccb) == ERESTART) {
6075 			return;
6076 		} else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
6077 			/* Don't wedge the queue */
6078 			xpt_release_devq(done_ccb->ccb_h.path, /*count*/1,
6079 					 /*run_queue*/TRUE);
6080 		}
6081 		/*
6082 		 * If we get to this point, we got an error status back
6083 		 * from the inquiry and the error status doesn't require
6084 		 * automatically retrying the command.  Therefore, the
6085 		 * inquiry failed.  If we had inquiry information before
6086 		 * for this device, but this latest inquiry command failed,
6087 		 * the device has probably gone away.  If this device isn't
6088 		 * already marked unconfigured, notify the peripheral
6089 		 * drivers that this device is no more.
6090 		 */
6091 		if ((path->device->flags & CAM_DEV_UNCONFIGURED) == 0)
6092 			/* Send the async notification. */
6093 			xpt_async(AC_LOST_DEVICE, path, NULL);
6094 
6095 		xpt_release_ccb(done_ccb);
6096 		break;
6097 	}
6098 	case PROBE_MODE_SENSE:
6099 	{
6100 		struct ccb_scsiio *csio;
6101 		struct scsi_mode_header_6 *mode_hdr;
6102 
6103 		csio = &done_ccb->csio;
6104 		mode_hdr = (struct scsi_mode_header_6 *)csio->data_ptr;
6105 		if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
6106 			struct scsi_control_page *page;
6107 			u_int8_t *offset;
6108 
6109 			offset = ((u_int8_t *)&mode_hdr[1])
6110 			    + mode_hdr->blk_desc_len;
6111 			page = (struct scsi_control_page *)offset;
6112 			path->device->queue_flags = page->queue_flags;
6113 		} else if (cam_periph_error(done_ccb, 0,
6114 					    SF_RETRY_UA|SF_NO_PRINT,
6115 					    &softc->saved_ccb) == ERESTART) {
6116 			return;
6117 		} else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
6118 			/* Don't wedge the queue */
6119 			xpt_release_devq(done_ccb->ccb_h.path,
6120 					 /*count*/1, /*run_queue*/TRUE);
6121 		}
6122 		xpt_release_ccb(done_ccb);
6123 		free(mode_hdr, M_CAMXPT);
6124 		softc->action = PROBE_SERIAL_NUM;
6125 		xpt_schedule(periph, priority);
6126 		return;
6127 	}
6128 	case PROBE_SERIAL_NUM:
6129 	{
6130 		struct ccb_scsiio *csio;
6131 		struct scsi_vpd_unit_serial_number *serial_buf;
6132 		u_int32_t  priority;
6133 		int changed;
6134 		int have_serialnum;
6135 
6136 		changed = 1;
6137 		have_serialnum = 0;
6138 		csio = &done_ccb->csio;
6139 		priority = done_ccb->ccb_h.pinfo.priority;
6140 		serial_buf =
6141 		    (struct scsi_vpd_unit_serial_number *)csio->data_ptr;
6142 
6143 		/* Clean up from previous instance of this device */
6144 		if (path->device->serial_num != NULL) {
6145 			free(path->device->serial_num, M_CAMXPT);
6146 			path->device->serial_num = NULL;
6147 			path->device->serial_num_len = 0;
6148 		}
6149 
6150 		if (serial_buf == NULL) {
6151 			/*
6152 			 * Don't process the command as it was never sent
6153 			 */
6154 		} else if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP
6155 			&& (serial_buf->length > 0)) {
6156 
6157 			have_serialnum = 1;
6158 			path->device->serial_num =
6159 				(u_int8_t *)malloc((serial_buf->length + 1),
6160 						   M_CAMXPT, M_NOWAIT);
6161 			if (path->device->serial_num != NULL) {
6162 				bcopy(serial_buf->serial_num,
6163 				      path->device->serial_num,
6164 				      serial_buf->length);
6165 				path->device->serial_num_len =
6166 				    serial_buf->length;
6167 				path->device->serial_num[serial_buf->length]
6168 				    = '\0';
6169 			}
6170 		} else if (cam_periph_error(done_ccb, 0,
6171 					    SF_RETRY_UA|SF_NO_PRINT,
6172 					    &softc->saved_ccb) == ERESTART) {
6173 			return;
6174 		} else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
6175 			/* Don't wedge the queue */
6176 			xpt_release_devq(done_ccb->ccb_h.path, /*count*/1,
6177 					 /*run_queue*/TRUE);
6178 		}
6179 
6180 		/*
6181 		 * Let's see if we have seen this device before.
6182 		 */
6183 		if ((softc->flags & PROBE_INQUIRY_CKSUM) != 0) {
6184 			MD5_CTX context;
6185 			u_int8_t digest[16];
6186 
6187 			MD5Init(&context);
6188 
6189 			MD5Update(&context,
6190 				  (unsigned char *)&path->device->inq_data,
6191 				  sizeof(struct scsi_inquiry_data));
6192 
6193 			if (have_serialnum)
6194 				MD5Update(&context, serial_buf->serial_num,
6195 					  serial_buf->length);
6196 
6197 			MD5Final(digest, &context);
6198 			if (bcmp(softc->digest, digest, 16) == 0)
6199 				changed = 0;
6200 
6201 			/*
6202 			 * XXX Do we need to do a TUR in order to ensure
6203 			 *     that the device really hasn't changed???
6204 			 */
6205 			if ((changed != 0)
6206 			 && ((softc->flags & PROBE_NO_ANNOUNCE) == 0))
6207 				xpt_async(AC_LOST_DEVICE, path, NULL);
6208 		}
6209 		if (serial_buf != NULL)
6210 			free(serial_buf, M_CAMXPT);
6211 
6212 		if (changed != 0) {
6213 			/*
6214 			 * Now that we have all the necessary
6215 			 * information to safely perform transfer
6216 			 * negotiations... Controllers don't perform
6217 			 * any negotiation or tagged queuing until
6218 			 * after the first XPT_SET_TRAN_SETTINGS ccb is
6219 			 * received.  So, on a new device, just retrieve
6220 			 * the user settings, and set them as the current
6221 			 * settings to set the device up.
6222 			 */
6223 			proberequestdefaultnegotiation(periph);
6224 			xpt_release_ccb(done_ccb);
6225 
6226 			/*
6227 			 * Perform a TUR to allow the controller to
6228 			 * perform any necessary transfer negotiation.
6229 			 */
6230 			softc->action = PROBE_TUR_FOR_NEGOTIATION;
6231 			xpt_schedule(periph, priority);
6232 			return;
6233 		}
6234 		xpt_release_ccb(done_ccb);
6235 		break;
6236 	}
6237 	case PROBE_TUR_FOR_NEGOTIATION:
6238 	case PROBE_DV_EXIT:
6239 		if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
6240 			/* Don't wedge the queue */
6241 			xpt_release_devq(done_ccb->ccb_h.path, /*count*/1,
6242 					 /*run_queue*/TRUE);
6243 		}
6244 		/*
6245 		 * Do Domain Validation for lun 0 on devices that claim
6246 		 * to support Synchronous Transfer modes.
6247 		 */
6248 	 	if (softc->action == PROBE_TUR_FOR_NEGOTIATION
6249 		 && done_ccb->ccb_h.target_lun == 0
6250 		 && (path->device->inq_data.flags & SID_Sync) != 0
6251                  && (path->device->flags & CAM_DEV_IN_DV) == 0) {
6252 			CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
6253 			    ("Begin Domain Validation\n"));
6254 			path->device->flags |= CAM_DEV_IN_DV;
6255 			xpt_release_ccb(done_ccb);
6256 			softc->action = PROBE_INQUIRY_BASIC_DV1;
6257 			xpt_schedule(periph, priority);
6258 			return;
6259 		}
6260 		if (softc->action == PROBE_DV_EXIT) {
6261 			CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
6262 			    ("Leave Domain Validation\n"));
6263 		}
6264 		path->device->flags &=
6265 		    ~(CAM_DEV_UNCONFIGURED|CAM_DEV_IN_DV|CAM_DEV_DV_HIT_BOTTOM);
6266 		if ((softc->flags & PROBE_NO_ANNOUNCE) == 0) {
6267 			/* Inform the XPT that a new device has been found */
6268 			done_ccb->ccb_h.func_code = XPT_GDEV_TYPE;
6269 			xpt_action(done_ccb);
6270 			xpt_async(AC_FOUND_DEVICE, done_ccb->ccb_h.path,
6271 				  done_ccb);
6272 		}
6273 		xpt_release_ccb(done_ccb);
6274 		break;
6275 	case PROBE_INQUIRY_BASIC_DV1:
6276 	case PROBE_INQUIRY_BASIC_DV2:
6277 	{
6278 		struct scsi_inquiry_data *nbuf;
6279 		struct ccb_scsiio *csio;
6280 
6281 		if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
6282 			/* Don't wedge the queue */
6283 			xpt_release_devq(done_ccb->ccb_h.path, /*count*/1,
6284 					 /*run_queue*/TRUE);
6285 		}
6286 		csio = &done_ccb->csio;
6287 		nbuf = (struct scsi_inquiry_data *)csio->data_ptr;
6288 		if (bcmp(nbuf, &path->device->inq_data, SHORT_INQUIRY_LENGTH)) {
6289 			xpt_print(path,
6290 			    "inquiry data fails comparison at DV%d step\n",
6291 			    softc->action == PROBE_INQUIRY_BASIC_DV1? 1 : 2);
6292 			if (proberequestbackoff(periph, path->device)) {
6293 				path->device->flags &= ~CAM_DEV_IN_DV;
6294 				softc->action = PROBE_TUR_FOR_NEGOTIATION;
6295 			} else {
6296 				/* give up */
6297 				softc->action = PROBE_DV_EXIT;
6298 			}
6299 			free(nbuf, M_CAMXPT);
6300 			xpt_release_ccb(done_ccb);
6301 			xpt_schedule(periph, priority);
6302 			return;
6303 		}
6304 		free(nbuf, M_CAMXPT);
6305 		if (softc->action == PROBE_INQUIRY_BASIC_DV1) {
6306 			softc->action = PROBE_INQUIRY_BASIC_DV2;
6307 			xpt_release_ccb(done_ccb);
6308 			xpt_schedule(periph, priority);
6309 			return;
6310 		}
6311 		if (softc->action == PROBE_DV_EXIT) {
6312 			CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
6313 			    ("Leave Domain Validation Successfully\n"));
6314 		}
6315 		path->device->flags &=
6316 		    ~(CAM_DEV_UNCONFIGURED|CAM_DEV_IN_DV|CAM_DEV_DV_HIT_BOTTOM);
6317 		if ((softc->flags & PROBE_NO_ANNOUNCE) == 0) {
6318 			/* Inform the XPT that a new device has been found */
6319 			done_ccb->ccb_h.func_code = XPT_GDEV_TYPE;
6320 			xpt_action(done_ccb);
6321 			xpt_async(AC_FOUND_DEVICE, done_ccb->ccb_h.path,
6322 				  done_ccb);
6323 		}
6324 		xpt_release_ccb(done_ccb);
6325 		break;
6326 	}
6327 	}
6328 	done_ccb = (union ccb *)TAILQ_FIRST(&softc->request_ccbs);
6329 	TAILQ_REMOVE(&softc->request_ccbs, &done_ccb->ccb_h, periph_links.tqe);
6330 	done_ccb->ccb_h.status = CAM_REQ_CMP;
6331 	xpt_done(done_ccb);
6332 	if (TAILQ_FIRST(&softc->request_ccbs) == NULL) {
6333 		cam_periph_invalidate(periph);
6334 		cam_periph_release(periph);
6335 	} else {
6336 		probeschedule(periph);
6337 	}
6338 }
6339 
6340 static void
6341 probecleanup(struct cam_periph *periph)
6342 {
6343 	free(periph->softc, M_CAMXPT);
6344 }
6345 
6346 static void
6347 xpt_find_quirk(struct cam_ed *device)
6348 {
6349 	caddr_t	match;
6350 
6351 	match = cam_quirkmatch((caddr_t)&device->inq_data,
6352 			       (caddr_t)xpt_quirk_table,
6353 			       sizeof(xpt_quirk_table)/sizeof(*xpt_quirk_table),
6354 			       sizeof(*xpt_quirk_table), scsi_inquiry_match);
6355 
6356 	if (match == NULL)
6357 		panic("xpt_find_quirk: device didn't match wildcard entry!!");
6358 
6359 	device->quirk = (struct xpt_quirk_entry *)match;
6360 }
6361 
6362 static int
6363 sysctl_cam_search_luns(SYSCTL_HANDLER_ARGS)
6364 {
6365 	int error, bool;
6366 
6367 	bool = cam_srch_hi;
6368 	error = sysctl_handle_int(oidp, &bool, 0, req);
6369 	if (error != 0 || req->newptr == NULL)
6370 		return (error);
6371 	if (bool == 0 || bool == 1) {
6372 		cam_srch_hi = bool;
6373 		return (0);
6374 	} else {
6375 		return (EINVAL);
6376 	}
6377 }
6378 
6379 
6380 static void
6381 xpt_devise_transport(struct cam_path *path)
6382 {
6383 	struct ccb_pathinq cpi;
6384 	struct ccb_trans_settings cts;
6385 	struct scsi_inquiry_data *inq_buf;
6386 
6387 	/* Get transport information from the SIM */
6388 	xpt_setup_ccb(&cpi.ccb_h, path, /*priority*/1);
6389 	cpi.ccb_h.func_code = XPT_PATH_INQ;
6390 	xpt_action((union ccb *)&cpi);
6391 
6392 	inq_buf = NULL;
6393 	if ((path->device->flags & CAM_DEV_INQUIRY_DATA_VALID) != 0)
6394 		inq_buf = &path->device->inq_data;
6395 	path->device->protocol = PROTO_SCSI;
6396 	path->device->protocol_version =
6397 	    inq_buf != NULL ? SID_ANSI_REV(inq_buf) : cpi.protocol_version;
6398 	path->device->transport = cpi.transport;
6399 	path->device->transport_version = cpi.transport_version;
6400 
6401 	/*
6402 	 * Any device not using SPI3 features should
6403 	 * be considered SPI2 or lower.
6404 	 */
6405 	if (inq_buf != NULL) {
6406 		if (path->device->transport == XPORT_SPI
6407 		 && (inq_buf->spi3data & SID_SPI_MASK) == 0
6408 		 && path->device->transport_version > 2)
6409 			path->device->transport_version = 2;
6410 	} else {
6411 		struct cam_ed* otherdev;
6412 
6413 		for (otherdev = TAILQ_FIRST(&path->target->ed_entries);
6414 		     otherdev != NULL;
6415 		     otherdev = TAILQ_NEXT(otherdev, links)) {
6416 			if (otherdev != path->device)
6417 				break;
6418 		}
6419 
6420 		if (otherdev != NULL) {
6421 			/*
6422 			 * Initially assume the same versioning as
6423 			 * prior luns for this target.
6424 			 */
6425 			path->device->protocol_version =
6426 			    otherdev->protocol_version;
6427 			path->device->transport_version =
6428 			    otherdev->transport_version;
6429 		} else {
6430 			/* Until we know better, opt for safty */
6431 			path->device->protocol_version = 2;
6432 			if (path->device->transport == XPORT_SPI)
6433 				path->device->transport_version = 2;
6434 			else
6435 				path->device->transport_version = 0;
6436 		}
6437 	}
6438 
6439 	/*
6440 	 * XXX
6441 	 * For a device compliant with SPC-2 we should be able
6442 	 * to determine the transport version supported by
6443 	 * scrutinizing the version descriptors in the
6444 	 * inquiry buffer.
6445 	 */
6446 
6447 	/* Tell the controller what we think */
6448 	xpt_setup_ccb(&cts.ccb_h, path, /*priority*/1);
6449 	cts.ccb_h.func_code = XPT_SET_TRAN_SETTINGS;
6450 	cts.type = CTS_TYPE_CURRENT_SETTINGS;
6451 	cts.transport = path->device->transport;
6452 	cts.transport_version = path->device->transport_version;
6453 	cts.protocol = path->device->protocol;
6454 	cts.protocol_version = path->device->protocol_version;
6455 	cts.proto_specific.valid = 0;
6456 	cts.xport_specific.valid = 0;
6457 	xpt_action((union ccb *)&cts);
6458 }
6459 
6460 static void
6461 xpt_set_transfer_settings(struct ccb_trans_settings *cts, struct cam_ed *device,
6462 			  int async_update)
6463 {
6464 	struct	ccb_pathinq cpi;
6465 	struct	ccb_trans_settings cur_cts;
6466 	struct	ccb_trans_settings_scsi *scsi;
6467 	struct	ccb_trans_settings_scsi *cur_scsi;
6468 	struct	cam_sim *sim;
6469 	struct	scsi_inquiry_data *inq_data;
6470 
6471 	if (device == NULL) {
6472 		cts->ccb_h.status = CAM_PATH_INVALID;
6473 		xpt_done((union ccb *)cts);
6474 		return;
6475 	}
6476 
6477 	if (cts->protocol == PROTO_UNKNOWN
6478 	 || cts->protocol == PROTO_UNSPECIFIED) {
6479 		cts->protocol = device->protocol;
6480 		cts->protocol_version = device->protocol_version;
6481 	}
6482 
6483 	if (cts->protocol_version == PROTO_VERSION_UNKNOWN
6484 	 || cts->protocol_version == PROTO_VERSION_UNSPECIFIED)
6485 		cts->protocol_version = device->protocol_version;
6486 
6487 	if (cts->protocol != device->protocol) {
6488 		xpt_print(cts->ccb_h.path, "Uninitialized Protocol %x:%x?\n",
6489 		       cts->protocol, device->protocol);
6490 		cts->protocol = device->protocol;
6491 	}
6492 
6493 	if (cts->protocol_version > device->protocol_version) {
6494 		if (bootverbose) {
6495 			xpt_print(cts->ccb_h.path, "Down reving Protocol "
6496 			    "Version from %d to %d?\n", cts->protocol_version,
6497 			    device->protocol_version);
6498 		}
6499 		cts->protocol_version = device->protocol_version;
6500 	}
6501 
6502 	if (cts->transport == XPORT_UNKNOWN
6503 	 || cts->transport == XPORT_UNSPECIFIED) {
6504 		cts->transport = device->transport;
6505 		cts->transport_version = device->transport_version;
6506 	}
6507 
6508 	if (cts->transport_version == XPORT_VERSION_UNKNOWN
6509 	 || cts->transport_version == XPORT_VERSION_UNSPECIFIED)
6510 		cts->transport_version = device->transport_version;
6511 
6512 	if (cts->transport != device->transport) {
6513 		xpt_print(cts->ccb_h.path, "Uninitialized Transport %x:%x?\n",
6514 		    cts->transport, device->transport);
6515 		cts->transport = device->transport;
6516 	}
6517 
6518 	if (cts->transport_version > device->transport_version) {
6519 		if (bootverbose) {
6520 			xpt_print(cts->ccb_h.path, "Down reving Transport "
6521 			    "Version from %d to %d?\n", cts->transport_version,
6522 			    device->transport_version);
6523 		}
6524 		cts->transport_version = device->transport_version;
6525 	}
6526 
6527 	sim = cts->ccb_h.path->bus->sim;
6528 
6529 	/*
6530 	 * Nothing more of interest to do unless
6531 	 * this is a device connected via the
6532 	 * SCSI protocol.
6533 	 */
6534 	if (cts->protocol != PROTO_SCSI) {
6535 		if (async_update == FALSE)
6536 			(*(sim->sim_action))(sim, (union ccb *)cts);
6537 		return;
6538 	}
6539 
6540 	inq_data = &device->inq_data;
6541 	scsi = &cts->proto_specific.scsi;
6542 	xpt_setup_ccb(&cpi.ccb_h, cts->ccb_h.path, /*priority*/1);
6543 	cpi.ccb_h.func_code = XPT_PATH_INQ;
6544 	xpt_action((union ccb *)&cpi);
6545 
6546 	/* SCSI specific sanity checking */
6547 	if ((cpi.hba_inquiry & PI_TAG_ABLE) == 0
6548 	 || (INQ_DATA_TQ_ENABLED(inq_data)) == 0
6549 	 || (device->queue_flags & SCP_QUEUE_DQUE) != 0
6550 	 || (device->quirk->mintags == 0)) {
6551 		/*
6552 		 * Can't tag on hardware that doesn't support tags,
6553 		 * doesn't have it enabled, or has broken tag support.
6554 		 */
6555 		scsi->flags &= ~CTS_SCSI_FLAGS_TAG_ENB;
6556 	}
6557 
6558 	if (async_update == FALSE) {
6559 		/*
6560 		 * Perform sanity checking against what the
6561 		 * controller and device can do.
6562 		 */
6563 		xpt_setup_ccb(&cur_cts.ccb_h, cts->ccb_h.path, /*priority*/1);
6564 		cur_cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
6565 		cur_cts.type = cts->type;
6566 		xpt_action((union ccb *)&cur_cts);
6567 		if ((cur_cts.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
6568 			return;
6569 		}
6570 		cur_scsi = &cur_cts.proto_specific.scsi;
6571 		if ((scsi->valid & CTS_SCSI_VALID_TQ) == 0) {
6572 			scsi->flags &= ~CTS_SCSI_FLAGS_TAG_ENB;
6573 			scsi->flags |= cur_scsi->flags & CTS_SCSI_FLAGS_TAG_ENB;
6574 		}
6575 		if ((cur_scsi->valid & CTS_SCSI_VALID_TQ) == 0)
6576 			scsi->flags &= ~CTS_SCSI_FLAGS_TAG_ENB;
6577 	}
6578 
6579 	/* SPI specific sanity checking */
6580 	if (cts->transport == XPORT_SPI && async_update == FALSE) {
6581 		u_int spi3caps;
6582 		struct ccb_trans_settings_spi *spi;
6583 		struct ccb_trans_settings_spi *cur_spi;
6584 
6585 		spi = &cts->xport_specific.spi;
6586 
6587 		cur_spi = &cur_cts.xport_specific.spi;
6588 
6589 		/* Fill in any gaps in what the user gave us */
6590 		if ((spi->valid & CTS_SPI_VALID_SYNC_RATE) == 0)
6591 			spi->sync_period = cur_spi->sync_period;
6592 		if ((cur_spi->valid & CTS_SPI_VALID_SYNC_RATE) == 0)
6593 			spi->sync_period = 0;
6594 		if ((spi->valid & CTS_SPI_VALID_SYNC_OFFSET) == 0)
6595 			spi->sync_offset = cur_spi->sync_offset;
6596 		if ((cur_spi->valid & CTS_SPI_VALID_SYNC_OFFSET) == 0)
6597 			spi->sync_offset = 0;
6598 		if ((spi->valid & CTS_SPI_VALID_PPR_OPTIONS) == 0)
6599 			spi->ppr_options = cur_spi->ppr_options;
6600 		if ((cur_spi->valid & CTS_SPI_VALID_PPR_OPTIONS) == 0)
6601 			spi->ppr_options = 0;
6602 		if ((spi->valid & CTS_SPI_VALID_BUS_WIDTH) == 0)
6603 			spi->bus_width = cur_spi->bus_width;
6604 		if ((cur_spi->valid & CTS_SPI_VALID_BUS_WIDTH) == 0)
6605 			spi->bus_width = 0;
6606 		if ((spi->valid & CTS_SPI_VALID_DISC) == 0) {
6607 			spi->flags &= ~CTS_SPI_FLAGS_DISC_ENB;
6608 			spi->flags |= cur_spi->flags & CTS_SPI_FLAGS_DISC_ENB;
6609 		}
6610 		if ((cur_spi->valid & CTS_SPI_VALID_DISC) == 0)
6611 			spi->flags &= ~CTS_SPI_FLAGS_DISC_ENB;
6612 		if (((device->flags & CAM_DEV_INQUIRY_DATA_VALID) != 0
6613 		  && (inq_data->flags & SID_Sync) == 0
6614 		  && cts->type == CTS_TYPE_CURRENT_SETTINGS)
6615 		 || ((cpi.hba_inquiry & PI_SDTR_ABLE) == 0)
6616 		 || (spi->sync_offset == 0)
6617 		 || (spi->sync_period == 0)) {
6618 			/* Force async */
6619 			spi->sync_period = 0;
6620 			spi->sync_offset = 0;
6621 		}
6622 
6623 		switch (spi->bus_width) {
6624 		case MSG_EXT_WDTR_BUS_32_BIT:
6625 			if (((device->flags & CAM_DEV_INQUIRY_DATA_VALID) == 0
6626 			  || (inq_data->flags & SID_WBus32) != 0
6627 			  || cts->type == CTS_TYPE_USER_SETTINGS)
6628 			 && (cpi.hba_inquiry & PI_WIDE_32) != 0)
6629 				break;
6630 			/* Fall Through to 16-bit */
6631 		case MSG_EXT_WDTR_BUS_16_BIT:
6632 			if (((device->flags & CAM_DEV_INQUIRY_DATA_VALID) == 0
6633 			  || (inq_data->flags & SID_WBus16) != 0
6634 			  || cts->type == CTS_TYPE_USER_SETTINGS)
6635 			 && (cpi.hba_inquiry & PI_WIDE_16) != 0) {
6636 				spi->bus_width = MSG_EXT_WDTR_BUS_16_BIT;
6637 				break;
6638 			}
6639 			/* Fall Through to 8-bit */
6640 		default: /* New bus width?? */
6641 		case MSG_EXT_WDTR_BUS_8_BIT:
6642 			/* All targets can do this */
6643 			spi->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
6644 			break;
6645 		}
6646 
6647 		spi3caps = cpi.xport_specific.spi.ppr_options;
6648 		if ((device->flags & CAM_DEV_INQUIRY_DATA_VALID) != 0
6649 		 && cts->type == CTS_TYPE_CURRENT_SETTINGS)
6650 			spi3caps &= inq_data->spi3data;
6651 
6652 		if ((spi3caps & SID_SPI_CLOCK_DT) == 0)
6653 			spi->ppr_options &= ~MSG_EXT_PPR_DT_REQ;
6654 
6655 		if ((spi3caps & SID_SPI_IUS) == 0)
6656 			spi->ppr_options &= ~MSG_EXT_PPR_IU_REQ;
6657 
6658 		if ((spi3caps & SID_SPI_QAS) == 0)
6659 			spi->ppr_options &= ~MSG_EXT_PPR_QAS_REQ;
6660 
6661 		/* No SPI Transfer settings are allowed unless we are wide */
6662 		if (spi->bus_width == 0)
6663 			spi->ppr_options = 0;
6664 
6665 		if ((spi->flags & CTS_SPI_FLAGS_DISC_ENB) == 0) {
6666 			/*
6667 			 * Can't tag queue without disconnection.
6668 			 */
6669 			scsi->flags &= ~CTS_SCSI_FLAGS_TAG_ENB;
6670 			scsi->valid |= CTS_SCSI_VALID_TQ;
6671 		}
6672 
6673 		/*
6674 		 * If we are currently performing tagged transactions to
6675 		 * this device and want to change its negotiation parameters,
6676 		 * go non-tagged for a bit to give the controller a chance to
6677 		 * negotiate unhampered by tag messages.
6678 		 */
6679 		if (cts->type == CTS_TYPE_CURRENT_SETTINGS
6680 		 && (device->inq_flags & SID_CmdQue) != 0
6681 		 && (scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) != 0
6682 		 && (spi->flags & (CTS_SPI_VALID_SYNC_RATE|
6683 				   CTS_SPI_VALID_SYNC_OFFSET|
6684 				   CTS_SPI_VALID_BUS_WIDTH)) != 0)
6685 			xpt_toggle_tags(cts->ccb_h.path);
6686 	}
6687 
6688 	if (cts->type == CTS_TYPE_CURRENT_SETTINGS
6689 	 && (scsi->valid & CTS_SCSI_VALID_TQ) != 0) {
6690 		int device_tagenb;
6691 
6692 		/*
6693 		 * If we are transitioning from tags to no-tags or
6694 		 * vice-versa, we need to carefully freeze and restart
6695 		 * the queue so that we don't overlap tagged and non-tagged
6696 		 * commands.  We also temporarily stop tags if there is
6697 		 * a change in transfer negotiation settings to allow
6698 		 * "tag-less" negotiation.
6699 		 */
6700 		if ((device->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
6701 		 || (device->inq_flags & SID_CmdQue) != 0)
6702 			device_tagenb = TRUE;
6703 		else
6704 			device_tagenb = FALSE;
6705 
6706 		if (((scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) != 0
6707 		  && device_tagenb == FALSE)
6708 		 || ((scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) == 0
6709 		  && device_tagenb == TRUE)) {
6710 
6711 			if ((scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) != 0) {
6712 				/*
6713 				 * Delay change to use tags until after a
6714 				 * few commands have gone to this device so
6715 				 * the controller has time to perform transfer
6716 				 * negotiations without tagged messages getting
6717 				 * in the way.
6718 				 */
6719 				device->tag_delay_count = CAM_TAG_DELAY_COUNT;
6720 				device->flags |= CAM_DEV_TAG_AFTER_COUNT;
6721 			} else {
6722 				struct ccb_relsim crs;
6723 
6724 				xpt_freeze_devq(cts->ccb_h.path, /*count*/1);
6725 		  		device->inq_flags &= ~SID_CmdQue;
6726 				xpt_dev_ccbq_resize(cts->ccb_h.path,
6727 						    sim->max_dev_openings);
6728 				device->flags &= ~CAM_DEV_TAG_AFTER_COUNT;
6729 				device->tag_delay_count = 0;
6730 
6731 				xpt_setup_ccb(&crs.ccb_h, cts->ccb_h.path,
6732 					      /*priority*/1);
6733 				crs.ccb_h.func_code = XPT_REL_SIMQ;
6734 				crs.release_flags = RELSIM_RELEASE_AFTER_QEMPTY;
6735 				crs.openings
6736 				    = crs.release_timeout
6737 				    = crs.qfrozen_cnt
6738 				    = 0;
6739 				xpt_action((union ccb *)&crs);
6740 			}
6741 		}
6742 	}
6743 	if (async_update == FALSE)
6744 		(*(sim->sim_action))(sim, (union ccb *)cts);
6745 }
6746 
6747 
6748 static void
6749 xpt_toggle_tags(struct cam_path *path)
6750 {
6751 	struct cam_ed *dev;
6752 
6753 	/*
6754 	 * Give controllers a chance to renegotiate
6755 	 * before starting tag operations.  We
6756 	 * "toggle" tagged queuing off then on
6757 	 * which causes the tag enable command delay
6758 	 * counter to come into effect.
6759 	 */
6760 	dev = path->device;
6761 	if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
6762 	 || ((dev->inq_flags & SID_CmdQue) != 0
6763  	  && (dev->inq_flags & (SID_Sync|SID_WBus16|SID_WBus32)) != 0)) {
6764 		struct ccb_trans_settings cts;
6765 
6766 		xpt_setup_ccb(&cts.ccb_h, path, 1);
6767 		cts.protocol = PROTO_SCSI;
6768 		cts.protocol_version = PROTO_VERSION_UNSPECIFIED;
6769 		cts.transport = XPORT_UNSPECIFIED;
6770 		cts.transport_version = XPORT_VERSION_UNSPECIFIED;
6771 		cts.proto_specific.scsi.flags = 0;
6772 		cts.proto_specific.scsi.valid = CTS_SCSI_VALID_TQ;
6773 		xpt_set_transfer_settings(&cts, path->device,
6774 					  /*async_update*/TRUE);
6775 		cts.proto_specific.scsi.flags = CTS_SCSI_FLAGS_TAG_ENB;
6776 		xpt_set_transfer_settings(&cts, path->device,
6777 					  /*async_update*/TRUE);
6778 	}
6779 }
6780 
6781 static void
6782 xpt_start_tags(struct cam_path *path)
6783 {
6784 	struct ccb_relsim crs;
6785 	struct cam_ed *device;
6786 	struct cam_sim *sim;
6787 	int    newopenings;
6788 
6789 	device = path->device;
6790 	sim = path->bus->sim;
6791 	device->flags &= ~CAM_DEV_TAG_AFTER_COUNT;
6792 	xpt_freeze_devq(path, /*count*/1);
6793 	device->inq_flags |= SID_CmdQue;
6794 	if (device->tag_saved_openings != 0)
6795 		newopenings = device->tag_saved_openings;
6796 	else
6797 		newopenings = min(device->quirk->maxtags,
6798 				  sim->max_tagged_dev_openings);
6799 	xpt_dev_ccbq_resize(path, newopenings);
6800 	xpt_setup_ccb(&crs.ccb_h, path, /*priority*/1);
6801 	crs.ccb_h.func_code = XPT_REL_SIMQ;
6802 	crs.release_flags = RELSIM_RELEASE_AFTER_QEMPTY;
6803 	crs.openings
6804 	    = crs.release_timeout
6805 	    = crs.qfrozen_cnt
6806 	    = 0;
6807 	xpt_action((union ccb *)&crs);
6808 }
6809 
6810 static int busses_to_config;
6811 static int busses_to_reset;
6812 
6813 static int
6814 xptconfigbuscountfunc(struct cam_eb *bus, void *arg)
6815 {
6816 
6817 	mtx_assert(bus->sim->mtx, MA_OWNED);
6818 
6819 	if (bus->path_id != CAM_XPT_PATH_ID) {
6820 		struct cam_path path;
6821 		struct ccb_pathinq cpi;
6822 		int can_negotiate;
6823 
6824 		busses_to_config++;
6825 		xpt_compile_path(&path, NULL, bus->path_id,
6826 				 CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
6827 		xpt_setup_ccb(&cpi.ccb_h, &path, /*priority*/1);
6828 		cpi.ccb_h.func_code = XPT_PATH_INQ;
6829 		xpt_action((union ccb *)&cpi);
6830 		can_negotiate = cpi.hba_inquiry;
6831 		can_negotiate &= (PI_WIDE_32|PI_WIDE_16|PI_SDTR_ABLE);
6832 		if ((cpi.hba_misc & PIM_NOBUSRESET) == 0
6833 		 && can_negotiate)
6834 			busses_to_reset++;
6835 		xpt_release_path(&path);
6836 	}
6837 
6838 	return(1);
6839 }
6840 
6841 static int
6842 xptconfigfunc(struct cam_eb *bus, void *arg)
6843 {
6844 	struct	cam_path *path;
6845 	union	ccb *work_ccb;
6846 
6847 	mtx_assert(bus->sim->mtx, MA_OWNED);
6848 
6849 	if (bus->path_id != CAM_XPT_PATH_ID) {
6850 		cam_status status;
6851 		int can_negotiate;
6852 
6853 		work_ccb = xpt_alloc_ccb_nowait();
6854 		if (work_ccb == NULL) {
6855 			busses_to_config--;
6856 			xpt_finishconfig(xpt_periph, NULL);
6857 			return(0);
6858 		}
6859 		if ((status = xpt_create_path(&path, xpt_periph, bus->path_id,
6860 					      CAM_TARGET_WILDCARD,
6861 					      CAM_LUN_WILDCARD)) !=CAM_REQ_CMP){
6862 			printf("xptconfigfunc: xpt_create_path failed with "
6863 			       "status %#x for bus %d\n", status, bus->path_id);
6864 			printf("xptconfigfunc: halting bus configuration\n");
6865 			xpt_free_ccb(work_ccb);
6866 			busses_to_config--;
6867 			xpt_finishconfig(xpt_periph, NULL);
6868 			return(0);
6869 		}
6870 		xpt_setup_ccb(&work_ccb->ccb_h, path, /*priority*/1);
6871 		work_ccb->ccb_h.func_code = XPT_PATH_INQ;
6872 		xpt_action(work_ccb);
6873 		if (work_ccb->ccb_h.status != CAM_REQ_CMP) {
6874 			printf("xptconfigfunc: CPI failed on bus %d "
6875 			       "with status %d\n", bus->path_id,
6876 			       work_ccb->ccb_h.status);
6877 			xpt_finishconfig(xpt_periph, work_ccb);
6878 			return(1);
6879 		}
6880 
6881 		can_negotiate = work_ccb->cpi.hba_inquiry;
6882 		can_negotiate &= (PI_WIDE_32|PI_WIDE_16|PI_SDTR_ABLE);
6883 		if ((work_ccb->cpi.hba_misc & PIM_NOBUSRESET) == 0
6884 		 && (can_negotiate != 0)) {
6885 			xpt_setup_ccb(&work_ccb->ccb_h, path, /*priority*/1);
6886 			work_ccb->ccb_h.func_code = XPT_RESET_BUS;
6887 			work_ccb->ccb_h.cbfcnp = NULL;
6888 			CAM_DEBUG(path, CAM_DEBUG_SUBTRACE,
6889 				  ("Resetting Bus\n"));
6890 			xpt_action(work_ccb);
6891 			xpt_finishconfig(xpt_periph, work_ccb);
6892 		} else {
6893 			/* Act as though we performed a successful BUS RESET */
6894 			work_ccb->ccb_h.func_code = XPT_RESET_BUS;
6895 			xpt_finishconfig(xpt_periph, work_ccb);
6896 		}
6897 	}
6898 
6899 	return(1);
6900 }
6901 
6902 static void
6903 xpt_config(void *arg)
6904 {
6905 	/*
6906 	 * Now that interrupts are enabled, go find our devices
6907 	 */
6908 
6909 #ifdef CAMDEBUG
6910 	/* Setup debugging flags and path */
6911 #ifdef CAM_DEBUG_FLAGS
6912 	cam_dflags = CAM_DEBUG_FLAGS;
6913 #else /* !CAM_DEBUG_FLAGS */
6914 	cam_dflags = CAM_DEBUG_NONE;
6915 #endif /* CAM_DEBUG_FLAGS */
6916 #ifdef CAM_DEBUG_BUS
6917 	if (cam_dflags != CAM_DEBUG_NONE) {
6918 		/*
6919 		 * Locking is specifically omitted here.  No SIMs have
6920 		 * registered yet, so xpt_create_path will only be searching
6921 		 * empty lists of targets and devices.
6922 		 */
6923 		if (xpt_create_path(&cam_dpath, xpt_periph,
6924 				    CAM_DEBUG_BUS, CAM_DEBUG_TARGET,
6925 				    CAM_DEBUG_LUN) != CAM_REQ_CMP) {
6926 			printf("xpt_config: xpt_create_path() failed for debug"
6927 			       " target %d:%d:%d, debugging disabled\n",
6928 			       CAM_DEBUG_BUS, CAM_DEBUG_TARGET, CAM_DEBUG_LUN);
6929 			cam_dflags = CAM_DEBUG_NONE;
6930 		}
6931 	} else
6932 		cam_dpath = NULL;
6933 #else /* !CAM_DEBUG_BUS */
6934 	cam_dpath = NULL;
6935 #endif /* CAM_DEBUG_BUS */
6936 #endif /* CAMDEBUG */
6937 
6938 	/*
6939 	 * Scan all installed busses.
6940 	 */
6941 	xpt_for_all_busses(xptconfigbuscountfunc, NULL);
6942 
6943 	if (busses_to_config == 0) {
6944 		/* Call manually because we don't have any busses */
6945 		xpt_finishconfig(xpt_periph, NULL);
6946 	} else  {
6947 		if (busses_to_reset > 0 && scsi_delay >= 2000) {
6948 			printf("Waiting %d seconds for SCSI "
6949 			       "devices to settle\n", scsi_delay/1000);
6950 		}
6951 		xpt_for_all_busses(xptconfigfunc, NULL);
6952 	}
6953 }
6954 
6955 /*
6956  * If the given device only has one peripheral attached to it, and if that
6957  * peripheral is the passthrough driver, announce it.  This insures that the
6958  * user sees some sort of announcement for every peripheral in their system.
6959  */
6960 static int
6961 xptpassannouncefunc(struct cam_ed *device, void *arg)
6962 {
6963 	struct cam_periph *periph;
6964 	int i;
6965 
6966 	for (periph = SLIST_FIRST(&device->periphs), i = 0; periph != NULL;
6967 	     periph = SLIST_NEXT(periph, periph_links), i++);
6968 
6969 	periph = SLIST_FIRST(&device->periphs);
6970 	if ((i == 1)
6971 	 && (strncmp(periph->periph_name, "pass", 4) == 0))
6972 		xpt_announce_periph(periph, NULL);
6973 
6974 	return(1);
6975 }
6976 
6977 static void
6978 xpt_finishconfig_task(void *context, int pending)
6979 {
6980 	struct	periph_driver **p_drv;
6981 	int	i;
6982 
6983 	if (busses_to_config == 0) {
6984 		/* Register all the peripheral drivers */
6985 		/* XXX This will have to change when we have loadable modules */
6986 		p_drv = periph_drivers;
6987 		for (i = 0; p_drv[i] != NULL; i++) {
6988 			(*p_drv[i]->init)();
6989 		}
6990 
6991 		/*
6992 		 * Check for devices with no "standard" peripheral driver
6993 		 * attached.  For any devices like that, announce the
6994 		 * passthrough driver so the user will see something.
6995 		 */
6996 		xpt_for_all_devices(xptpassannouncefunc, NULL);
6997 
6998 		/* Release our hook so that the boot can continue. */
6999 		config_intrhook_disestablish(xsoftc.xpt_config_hook);
7000 		free(xsoftc.xpt_config_hook, M_CAMXPT);
7001 		xsoftc.xpt_config_hook = NULL;
7002 	}
7003 
7004 	free(context, M_CAMXPT);
7005 }
7006 
7007 static void
7008 xpt_finishconfig(struct cam_periph *periph, union ccb *done_ccb)
7009 {
7010 	struct	xpt_task *task;
7011 
7012 	if (done_ccb != NULL) {
7013 		CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE,
7014 			  ("xpt_finishconfig\n"));
7015 		switch(done_ccb->ccb_h.func_code) {
7016 		case XPT_RESET_BUS:
7017 			if (done_ccb->ccb_h.status == CAM_REQ_CMP) {
7018 				done_ccb->ccb_h.func_code = XPT_SCAN_BUS;
7019 				done_ccb->ccb_h.cbfcnp = xpt_finishconfig;
7020 				done_ccb->crcn.flags = 0;
7021 				xpt_action(done_ccb);
7022 				return;
7023 			}
7024 			/* FALLTHROUGH */
7025 		case XPT_SCAN_BUS:
7026 		default:
7027 			xpt_free_path(done_ccb->ccb_h.path);
7028 			busses_to_config--;
7029 			break;
7030 		}
7031 	}
7032 
7033 	if (busses_to_config == 0) {
7034 		task = malloc(sizeof(struct xpt_task), M_CAMXPT, M_NOWAIT);
7035 		if (task != NULL) {
7036 			TASK_INIT(&task->task, 0, xpt_finishconfig_task, task);
7037 			taskqueue_enqueue(taskqueue_thread, &task->task);
7038 		}
7039 	}
7040 
7041 	if (done_ccb != NULL)
7042 		xpt_free_ccb(done_ccb);
7043 }
7044 
7045 cam_status
7046 xpt_register_async(int event, ac_callback_t *cbfunc, void *cbarg,
7047 		   struct cam_path *path)
7048 {
7049 	struct ccb_setasync csa;
7050 	cam_status status;
7051 	int xptpath = 0;
7052 
7053 	if (path == NULL) {
7054 		mtx_lock(&xsoftc.xpt_lock);
7055 		status = xpt_create_path(&path, /*periph*/NULL, CAM_XPT_PATH_ID,
7056 					 CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
7057 		if (status != CAM_REQ_CMP) {
7058 			mtx_unlock(&xsoftc.xpt_lock);
7059 			return (status);
7060 		}
7061 		xptpath = 1;
7062 	}
7063 
7064 	xpt_setup_ccb(&csa.ccb_h, path, /*priority*/5);
7065 	csa.ccb_h.func_code = XPT_SASYNC_CB;
7066 	csa.event_enable = event;
7067 	csa.callback = cbfunc;
7068 	csa.callback_arg = cbarg;
7069 	xpt_action((union ccb *)&csa);
7070 	status = csa.ccb_h.status;
7071 	if (xptpath) {
7072 		xpt_free_path(path);
7073 		mtx_unlock(&xsoftc.xpt_lock);
7074 	}
7075 	return (status);
7076 }
7077 
7078 static void
7079 xptaction(struct cam_sim *sim, union ccb *work_ccb)
7080 {
7081 	CAM_DEBUG(work_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("xptaction\n"));
7082 
7083 	switch (work_ccb->ccb_h.func_code) {
7084 	/* Common cases first */
7085 	case XPT_PATH_INQ:		/* Path routing inquiry */
7086 	{
7087 		struct ccb_pathinq *cpi;
7088 
7089 		cpi = &work_ccb->cpi;
7090 		cpi->version_num = 1; /* XXX??? */
7091 		cpi->hba_inquiry = 0;
7092 		cpi->target_sprt = 0;
7093 		cpi->hba_misc = 0;
7094 		cpi->hba_eng_cnt = 0;
7095 		cpi->max_target = 0;
7096 		cpi->max_lun = 0;
7097 		cpi->initiator_id = 0;
7098 		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
7099 		strncpy(cpi->hba_vid, "", HBA_IDLEN);
7100 		strncpy(cpi->dev_name, sim->sim_name, DEV_IDLEN);
7101 		cpi->unit_number = sim->unit_number;
7102 		cpi->bus_id = sim->bus_id;
7103 		cpi->base_transfer_speed = 0;
7104 		cpi->protocol = PROTO_UNSPECIFIED;
7105 		cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
7106 		cpi->transport = XPORT_UNSPECIFIED;
7107 		cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
7108 		cpi->ccb_h.status = CAM_REQ_CMP;
7109 		xpt_done(work_ccb);
7110 		break;
7111 	}
7112 	default:
7113 		work_ccb->ccb_h.status = CAM_REQ_INVALID;
7114 		xpt_done(work_ccb);
7115 		break;
7116 	}
7117 }
7118 
7119 /*
7120  * The xpt as a "controller" has no interrupt sources, so polling
7121  * is a no-op.
7122  */
7123 static void
7124 xptpoll(struct cam_sim *sim)
7125 {
7126 }
7127 
7128 void
7129 xpt_lock_buses(void)
7130 {
7131 	mtx_lock(&xsoftc.xpt_topo_lock);
7132 }
7133 
7134 void
7135 xpt_unlock_buses(void)
7136 {
7137 	mtx_unlock(&xsoftc.xpt_topo_lock);
7138 }
7139 
7140 static void
7141 camisr(void *dummy)
7142 {
7143 	cam_simq_t queue;
7144 	struct cam_sim *sim;
7145 
7146 	mtx_lock(&cam_simq_lock);
7147 	TAILQ_INIT(&queue);
7148 	TAILQ_CONCAT(&queue, &cam_simq, links);
7149 	mtx_unlock(&cam_simq_lock);
7150 
7151 	while ((sim = TAILQ_FIRST(&queue)) != NULL) {
7152 		TAILQ_REMOVE(&queue, sim, links);
7153 		CAM_SIM_LOCK(sim);
7154 		sim->flags &= ~CAM_SIM_ON_DONEQ;
7155 		camisr_runqueue(&sim->sim_doneq);
7156 		CAM_SIM_UNLOCK(sim);
7157 	}
7158 }
7159 
7160 static void
7161 camisr_runqueue(void *V_queue)
7162 {
7163 	cam_isrq_t *queue = V_queue;
7164 	struct	ccb_hdr *ccb_h;
7165 
7166 	while ((ccb_h = TAILQ_FIRST(queue)) != NULL) {
7167 		int	runq;
7168 
7169 		TAILQ_REMOVE(queue, ccb_h, sim_links.tqe);
7170 		ccb_h->pinfo.index = CAM_UNQUEUED_INDEX;
7171 
7172 		CAM_DEBUG(ccb_h->path, CAM_DEBUG_TRACE,
7173 			  ("camisr\n"));
7174 
7175 		runq = FALSE;
7176 
7177 		if (ccb_h->flags & CAM_HIGH_POWER) {
7178 			struct highpowerlist	*hphead;
7179 			union ccb		*send_ccb;
7180 
7181 			mtx_lock(&xsoftc.xpt_lock);
7182 			hphead = &xsoftc.highpowerq;
7183 
7184 			send_ccb = (union ccb *)STAILQ_FIRST(hphead);
7185 
7186 			/*
7187 			 * Increment the count since this command is done.
7188 			 */
7189 			xsoftc.num_highpower++;
7190 
7191 			/*
7192 			 * Any high powered commands queued up?
7193 			 */
7194 			if (send_ccb != NULL) {
7195 
7196 				STAILQ_REMOVE_HEAD(hphead, xpt_links.stqe);
7197 				mtx_unlock(&xsoftc.xpt_lock);
7198 
7199 				xpt_release_devq(send_ccb->ccb_h.path,
7200 						 /*count*/1, /*runqueue*/TRUE);
7201 			} else
7202 				mtx_unlock(&xsoftc.xpt_lock);
7203 		}
7204 
7205 		if ((ccb_h->func_code & XPT_FC_USER_CCB) == 0) {
7206 			struct cam_ed *dev;
7207 
7208 			dev = ccb_h->path->device;
7209 
7210 			cam_ccbq_ccb_done(&dev->ccbq, (union ccb *)ccb_h);
7211 
7212 			if (!SIM_DEAD(ccb_h->path->bus->sim)) {
7213 				ccb_h->path->bus->sim->devq->send_active--;
7214 				ccb_h->path->bus->sim->devq->send_openings++;
7215 			}
7216 
7217 			if (((dev->flags & CAM_DEV_REL_ON_COMPLETE) != 0
7218 			  && (ccb_h->status&CAM_STATUS_MASK) != CAM_REQUEUE_REQ)
7219 			 || ((dev->flags & CAM_DEV_REL_ON_QUEUE_EMPTY) != 0
7220 			  && (dev->ccbq.dev_active == 0))) {
7221 
7222 				xpt_release_devq(ccb_h->path, /*count*/1,
7223 						 /*run_queue*/TRUE);
7224 			}
7225 
7226 			if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
7227 			 && (--dev->tag_delay_count == 0))
7228 				xpt_start_tags(ccb_h->path);
7229 
7230 			if ((dev->ccbq.queue.entries > 0)
7231 			 && (dev->qfrozen_cnt == 0)
7232 			 && (device_is_send_queued(dev) == 0)) {
7233 				runq = xpt_schedule_dev_sendq(ccb_h->path->bus,
7234 							      dev);
7235 			}
7236 		}
7237 
7238 		if (ccb_h->status & CAM_RELEASE_SIMQ) {
7239 			xpt_release_simq(ccb_h->path->bus->sim,
7240 					 /*run_queue*/TRUE);
7241 			ccb_h->status &= ~CAM_RELEASE_SIMQ;
7242 			runq = FALSE;
7243 		}
7244 
7245 		if ((ccb_h->flags & CAM_DEV_QFRZDIS)
7246 		 && (ccb_h->status & CAM_DEV_QFRZN)) {
7247 			xpt_release_devq(ccb_h->path, /*count*/1,
7248 					 /*run_queue*/TRUE);
7249 			ccb_h->status &= ~CAM_DEV_QFRZN;
7250 		} else if (runq) {
7251 			xpt_run_dev_sendq(ccb_h->path->bus);
7252 		}
7253 
7254 		/* Call the peripheral driver's callback */
7255 		(*ccb_h->cbfcnp)(ccb_h->path->periph, (union ccb *)ccb_h);
7256 	}
7257 }
7258 
7259 static void
7260 dead_sim_action(struct cam_sim *sim, union ccb *ccb)
7261 {
7262 
7263 	ccb->ccb_h.status = CAM_DEV_NOT_THERE;
7264 	xpt_done(ccb);
7265 }
7266 
7267 static void
7268 dead_sim_poll(struct cam_sim *sim)
7269 {
7270 }
7271