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