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