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