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