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