Again, use offsetof() instead of a constant to enhance readability.
[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                 /*