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