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