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