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