1931836c209b48970577cbe48cb1a942b2cdf37c
[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.33 2006/12/20 18:14:33 dillon Exp $
31  */
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/types.h>
35 #include <sys/malloc.h>
36 #include <sys/kernel.h>
37 #include <sys/time.h>
38 #include <sys/conf.h>
39 #include <sys/device.h>
40 #include <sys/fcntl.h>
41 #include <sys/md5.h>
42 #include <sys/devicestat.h>
43 #include <sys/interrupt.h>
44 #include <sys/bus.h>
45 #include <sys/thread.h>
46 #include <sys/thread2.h>
47
48 #include <machine/clock.h>
49
50 #include "cam.h"
51 #include "cam_ccb.h"
52 #include "cam_periph.h"
53 #include "cam_sim.h"
54 #include "cam_xpt.h"
55 #include "cam_xpt_sim.h"
56 #include "cam_xpt_periph.h"
57 #include "cam_debug.h"
58
59 #include "scsi/scsi_all.h"
60 #include "scsi/scsi_message.h"
61 #include "scsi/scsi_pass.h"
62 #include "opt_cam.h"
63
64 /* Datastructures internal to the xpt layer */
65
66 /*
67  * Definition of an async handler callback block.  These are used to add
68  * SIMs and peripherals to the async callback lists.
69  */
70 struct async_node {
71         SLIST_ENTRY(async_node) links;
72         u_int32_t       event_enable;   /* Async Event enables */
73         void            (*callback)(void *arg, u_int32_t code,
74                                     struct cam_path *path, void *args);
75         void            *callback_arg;
76 };
77
78 SLIST_HEAD(async_list, async_node);
79 SLIST_HEAD(periph_list, cam_periph);
80 static STAILQ_HEAD(highpowerlist, ccb_hdr) highpowerq;
81
82 /*
83  * This is the maximum number of high powered commands (e.g. start unit)
84  * that can be outstanding at a particular time.
85  */
86 #ifndef CAM_MAX_HIGHPOWER
87 #define CAM_MAX_HIGHPOWER  4
88 #endif
89
90 /* number of high powered commands that can go through right now */
91 static int num_highpower = CAM_MAX_HIGHPOWER;
92
93 /*
94  * Structure for queueing a device in a run queue.
95  * There is one run queue for allocating new ccbs,
96  * and another for sending ccbs to the controller.
97  */
98 struct cam_ed_qinfo {
99         cam_pinfo pinfo;
100         struct    cam_ed *device;
101 };
102
103 /*
104  * The CAM EDT (Existing Device Table) contains the device information for
105  * all devices for all busses in the system.  The table contains a
106  * cam_ed structure for each device on the bus.
107  */
108 struct cam_ed {
109         TAILQ_ENTRY(cam_ed) links;
110         struct  cam_ed_qinfo alloc_ccb_entry;
111         struct  cam_ed_qinfo send_ccb_entry;
112         struct  cam_et   *target;
113         lun_id_t         lun_id;
114         struct  camq drvq;              /*
115                                          * Queue of type drivers wanting to do
116                                          * work on this device.
117                                          */
118         struct  cam_ccbq ccbq;          /* Queue of pending ccbs */
119         struct  async_list asyncs;      /* Async callback info for this B/T/L */
120         struct  periph_list periphs;    /* All attached devices */
121         u_int   generation;             /* Generation number */
122         struct  cam_periph *owner;      /* Peripheral driver's ownership tag */
123         struct  xpt_quirk_entry *quirk; /* Oddities about this device */
124                                         /* Storage for the inquiry data */
125         struct  scsi_inquiry_data inq_data;
126         u_int8_t         inq_flags;     /*
127                                          * Current settings for inquiry flags.
128                                          * This allows us to override settings
129                                          * like disconnection and tagged
130                                          * queuing for a device.
131                                          */
132         u_int8_t         queue_flags;   /* Queue flags from the control page */
133         u_int8_t         serial_num_len;
134         u_int8_t         *serial_num;
135         u_int32_t        qfrozen_cnt;
136         u_int32_t        flags;
137 #define CAM_DEV_UNCONFIGURED            0x01
138 #define CAM_DEV_REL_TIMEOUT_PENDING     0x02
139 #define CAM_DEV_REL_ON_COMPLETE         0x04
140 #define CAM_DEV_REL_ON_QUEUE_EMPTY      0x08
141 #define CAM_DEV_RESIZE_QUEUE_NEEDED     0x10
142 #define CAM_DEV_TAG_AFTER_COUNT         0x20
143 #define CAM_DEV_INQUIRY_DATA_VALID      0x40
144         u_int32_t        tag_delay_count;
145 #define CAM_TAG_DELAY_COUNT             5
146         u_int32_t        refcount;
147         struct           callout c_handle;
148 };
149
150 /*
151  * Each target is represented by an ET (Existing Target).  These
152  * entries are created when a target is successfully probed with an
153  * identify, and removed when a device fails to respond after a number
154  * of retries, or a bus rescan finds the device missing.
155  */
156 struct cam_et { 
157         TAILQ_HEAD(, cam_ed) ed_entries;
158         TAILQ_ENTRY(cam_et) links;
159         struct  cam_eb  *bus;   
160         target_id_t     target_id;
161         u_int32_t       refcount;       
162         u_int           generation;
163         struct          timeval last_reset;     /* uptime of last reset */
164 };
165
166 /*
167  * Each bus is represented by an EB (Existing Bus).  These entries
168  * are created by calls to xpt_bus_register and deleted by calls to
169  * xpt_bus_deregister.
170  */
171 struct cam_eb { 
172         TAILQ_HEAD(, cam_et) et_entries;
173         TAILQ_ENTRY(cam_eb)  links;
174         path_id_t            path_id;
175         struct cam_sim       *sim;
176         struct timeval       last_reset;        /* uptime of last reset */
177         u_int32_t            flags;
178 #define CAM_EB_RUNQ_SCHEDULED   0x01
179         u_int32_t            refcount;
180         u_int                generation;
181 };
182
183 struct cam_path {
184         struct cam_periph *periph;
185         struct cam_eb     *bus;
186         struct cam_et     *target;
187         struct cam_ed     *device;
188 };
189
190 struct xpt_quirk_entry {
191         struct scsi_inquiry_pattern inq_pat;
192         u_int8_t quirks;
193 #define CAM_QUIRK_NOLUNS        0x01
194 #define CAM_QUIRK_NOSERIAL      0x02
195 #define CAM_QUIRK_HILUNS        0x04
196         u_int mintags;
197         u_int maxtags;
198 };
199 #define CAM_SCSI2_MAXLUN        8
200
201 typedef enum {
202         XPT_FLAG_OPEN           = 0x01
203 } xpt_flags;
204
205 struct xpt_softc {
206         xpt_flags       flags;
207         u_int32_t       generation;
208 };
209
210 static const char quantum[] = "QUANTUM";
211 static const char sony[] = "SONY";
212 static const char west_digital[] = "WDIGTL";
213 static const char samsung[] = "SAMSUNG";
214 static const char seagate[] = "SEAGATE";
215 static const char microp[] = "MICROP";
216
217 static struct xpt_quirk_entry xpt_quirk_table[] = 
218 {
219         {
220                 /* Reports QUEUE FULL for temporary resource shortages */
221                 { T_DIRECT, SIP_MEDIA_FIXED, quantum, "XP39100*", "*" },
222                 /*quirks*/0, /*mintags*/24, /*maxtags*/32
223         },
224         {
225                 /* Reports QUEUE FULL for temporary resource shortages */
226                 { T_DIRECT, SIP_MEDIA_FIXED, quantum, "XP34550*", "*" },
227                 /*quirks*/0, /*mintags*/24, /*maxtags*/32
228         },
229         {
230                 /* Reports QUEUE FULL for temporary resource shortages */
231                 { T_DIRECT, SIP_MEDIA_FIXED, quantum, "XP32275*", "*" },
232                 /*quirks*/0, /*mintags*/24, /*maxtags*/32
233         },
234         {
235                 /* Broken tagged queuing drive */
236                 { T_DIRECT, SIP_MEDIA_FIXED, microp, "4421-07*", "*" },
237                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
238         },
239         {
240                 /* Broken tagged queuing drive */
241                 { T_DIRECT, SIP_MEDIA_FIXED, "HP", "C372*", "*" },
242                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
243         },
244         {
245                 /* Broken tagged queuing drive */
246                 { T_DIRECT, SIP_MEDIA_FIXED, microp, "3391*", "x43h" },
247                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
248         },
249         {
250                 /*
251                  * Unfortunately, the Quantum Atlas III has the same
252                  * problem as the Atlas II drives above.
253                  * Reported by: "Johan Granlund" <johan@granlund.nu>
254                  *
255                  * For future reference, the drive with the problem was:
256                  * QUANTUM QM39100TD-SW N1B0
257                  * 
258                  * It's possible that Quantum will fix the problem in later
259                  * firmware revisions.  If that happens, the quirk entry
260                  * will need to be made specific to the firmware revisions
261                  * with the problem.
262                  * 
263                  */
264                 /* Reports QUEUE FULL for temporary resource shortages */
265                 { T_DIRECT, SIP_MEDIA_FIXED, quantum, "QM39100*", "*" },
266                 /*quirks*/0, /*mintags*/24, /*maxtags*/32
267         },
268         {
269                 /*
270                  * 18 Gig Atlas III, same problem as the 9G version.
271                  * Reported by: Andre Albsmeier
272                  *              <andre.albsmeier@mchp.siemens.de>
273                  *
274                  * For future reference, the drive with the problem was:
275                  * QUANTUM QM318000TD-S N491
276                  */
277                 /* Reports QUEUE FULL for temporary resource shortages */
278                 { T_DIRECT, SIP_MEDIA_FIXED, quantum, "QM318000*", "*" },
279                 /*quirks*/0, /*mintags*/24, /*maxtags*/32
280         },
281         {
282                 /*
283                  * Broken tagged queuing drive
284                  * Reported by: Bret Ford <bford@uop.cs.uop.edu>
285                  *         and: Martin Renters <martin@tdc.on.ca>
286                  */
287                 { T_DIRECT, SIP_MEDIA_FIXED, seagate, "ST410800*", "71*" },
288                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
289         },
290                 /*
291                  * The Seagate Medalist Pro drives have very poor write
292                  * performance with anything more than 2 tags.
293                  * 
294                  * Reported by:  Paul van der Zwan <paulz@trantor.xs4all.nl>
295                  * Drive:  <SEAGATE ST36530N 1444>
296                  *
297                  * Reported by:  Jeremy Lea <reg@shale.csir.co.za>
298                  * Drive:  <SEAGATE ST34520W 1281>
299                  *
300                  * No one has actually reported that the 9G version
301                  * (ST39140*) of the Medalist Pro has the same problem, but
302                  * we're assuming that it does because the 4G and 6.5G
303                  * versions of the drive are broken.
304                  */
305         {
306                 { T_DIRECT, SIP_MEDIA_FIXED, seagate, "ST34520*", "*"},
307                 /*quirks*/0, /*mintags*/2, /*maxtags*/2
308         },
309         {
310                 { T_DIRECT, SIP_MEDIA_FIXED, seagate, "ST36530*", "*"},
311                 /*quirks*/0, /*mintags*/2, /*maxtags*/2
312         },
313         {
314                 { T_DIRECT, SIP_MEDIA_FIXED, seagate, "ST39140*", "*"},
315                 /*quirks*/0, /*mintags*/2, /*maxtags*/2
316         },
317         {
318                 /*
319                  * Slow when tagged queueing is enabled.  Write performance
320                  * steadily drops off with more and more concurrent
321                  * transactions.  Best sequential write performance with
322                  * tagged queueing turned off and write caching turned on.
323                  *
324                  * PR:  kern/10398
325                  * Submitted by:  Hideaki Okada <hokada@isl.melco.co.jp>
326                  * Drive:  DCAS-34330 w/ "S65A" firmware.
327                  *
328                  * The drive with the problem had the "S65A" firmware
329                  * revision, and has also been reported (by Stephen J.
330                  * Roznowski <sjr@home.net>) for a drive with the "S61A"
331                  * firmware revision.
332                  *
333                  * Although no one has reported problems with the 2 gig
334                  * version of the DCAS drive, the assumption is that it
335                  * has the same problems as the 4 gig version.  Therefore
336                  * this quirk entries disables tagged queueing for all
337                  * DCAS drives.
338                  */
339                 { T_DIRECT, SIP_MEDIA_FIXED, "IBM", "DCAS*", "*" },
340                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
341         },
342         {
343                 /* Broken tagged queuing drive */
344                 { T_DIRECT, SIP_MEDIA_REMOVABLE, "iomega", "jaz*", "*" },
345                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
346         },
347         {
348                 /* Broken tagged queuing drive */ 
349                 { T_DIRECT, SIP_MEDIA_FIXED, "CONNER", "CFP2107*", "*" },
350                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
351         },
352         {
353                 /*
354                  * Broken tagged queuing drive.
355                  * Submitted by:
356                  * NAKAJI Hiroyuki <nakaji@zeisei.dpri.kyoto-u.ac.jp>
357                  * in PR kern/9535
358                  */
359                 { T_DIRECT, SIP_MEDIA_FIXED, samsung, "WN34324U*", "*" },
360                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
361         },
362         {
363                 /*
364                  * Slow when tagged queueing is enabled. (1.5MB/sec versus
365                  * 8MB/sec.)
366                  * Submitted by: Andrew Gallatin <gallatin@cs.duke.edu>
367                  * Best performance with these drives is achieved with
368                  * tagged queueing turned off, and write caching turned on.
369                  */
370                 { T_DIRECT, SIP_MEDIA_FIXED, west_digital, "WDE*", "*" },
371                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
372         },
373         {
374                 /*
375                  * Slow when tagged queueing is enabled. (1.5MB/sec versus
376                  * 8MB/sec.)
377                  * Submitted by: Andrew Gallatin <gallatin@cs.duke.edu>
378                  * Best performance with these drives is achieved with
379                  * tagged queueing turned off, and write caching turned on.
380                  */
381                 { T_DIRECT, SIP_MEDIA_FIXED, west_digital, "ENTERPRISE", "*" },
382                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
383         },
384         {
385                 /*
386                  * Doesn't handle queue full condition correctly,
387                  * so we need to limit maxtags to what the device
388                  * can handle instead of determining this automatically.
389                  */
390                 { T_DIRECT, SIP_MEDIA_FIXED, samsung, "WN321010S*", "*" },
391                 /*quirks*/0, /*mintags*/2, /*maxtags*/32
392         },
393         {
394                 /* Really only one LUN */
395                 { T_ENCLOSURE, SIP_MEDIA_FIXED, "SUN", "SENA", "*" },
396                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
397         },
398         {
399                 /* I can't believe we need a quirk for DPT volumes. */
400                 { T_ANY, SIP_MEDIA_FIXED|SIP_MEDIA_REMOVABLE, "DPT", "*", "*" },
401                 CAM_QUIRK_NOSERIAL|CAM_QUIRK_NOLUNS,
402                 /*mintags*/0, /*maxtags*/255
403         },
404         {
405                 /*
406                  * Many Sony CDROM drives don't like multi-LUN probing.
407                  */
408                 { T_CDROM, SIP_MEDIA_REMOVABLE, sony, "CD-ROM CDU*", "*" },
409                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
410         },
411         {
412                 /*
413                  * This drive doesn't like multiple LUN probing.
414                  * Submitted by:  Parag Patel <parag@cgt.com>
415                  */
416                 { T_WORM, SIP_MEDIA_REMOVABLE, sony, "CD-R   CDU9*", "*" },
417                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
418         },
419         {
420                 { T_WORM, SIP_MEDIA_REMOVABLE, "YAMAHA", "CDR100*", "*" },
421                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
422         },
423         {
424                 /*
425                  * The 8200 doesn't like multi-lun probing, and probably
426                  * don't like serial number requests either.
427                  */
428                 {
429                         T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "EXABYTE",
430                         "EXB-8200*", "*"
431                 },
432                 CAM_QUIRK_NOSERIAL|CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
433         },
434         {
435                 /*
436                  * Let's try the same as above, but for a drive that says
437                  * it's an IPL-6860 but is actually an EXB 8200.
438                  */
439                 {
440                         T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "EXABYTE",
441                         "IPL-6860*", "*"
442                 },
443                 CAM_QUIRK_NOSERIAL|CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
444         },
445         {
446                 /*
447                  * These Hitachi drives don't like multi-lun probing.
448                  * The PR submitter has a DK319H, but says that the Linux
449                  * kernel has a similar work-around for the DK312 and DK314,
450                  * so all DK31* drives are quirked here.
451                  * PR:            misc/18793
452                  * Submitted by:  Paul Haddad <paul@pth.com>
453                  */
454                 { T_DIRECT, SIP_MEDIA_FIXED, "HITACHI", "DK31*", "*" },
455                 CAM_QUIRK_NOLUNS, /*mintags*/2, /*maxtags*/255
456         },
457         {
458                 /*
459                  * This old revision of the TDC3600 is also SCSI-1, and
460                  * hangs upon serial number probing.
461                  */
462                 {
463                         T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "TANDBERG",
464                         " TDC 3600", "U07:"
465                 },
466                 CAM_QUIRK_NOSERIAL, /*mintags*/0, /*maxtags*/0
467         },
468         {
469                 /*
470                  * Would repond to all LUNs if asked for.
471                  */
472                 {
473                         T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "CALIPER",
474                         "CP150", "*"
475                 },
476                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
477         },
478         {
479                 /*
480                  * Would repond to all LUNs if asked for.
481                  */
482                 {
483                         T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "KENNEDY",
484                         "96X2*", "*"
485                 },
486                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
487         },
488         {
489                 /* Submitted by: Matthew Dodd <winter@jurai.net> */
490                 { T_PROCESSOR, SIP_MEDIA_FIXED, "Cabletrn", "EA41*", "*" },
491                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
492         },
493         {
494                 /* Submitted by: Matthew Dodd <winter@jurai.net> */
495                 { T_PROCESSOR, SIP_MEDIA_FIXED, "CABLETRN", "EA41*", "*" },
496                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
497         },
498         {
499                 /* TeraSolutions special settings for TRC-22 RAID */
500                 { T_DIRECT, SIP_MEDIA_FIXED, "TERASOLU", "TRC-22", "*" },
501                   /*quirks*/0, /*mintags*/55, /*maxtags*/255
502         },
503         {
504                 /* Veritas Storage Appliance */
505                 { T_DIRECT, SIP_MEDIA_FIXED, "VERITAS", "*", "*" },
506                   CAM_QUIRK_HILUNS, /*mintags*/2, /*maxtags*/1024
507         },
508         {
509                 /*
510                  * Would respond to all LUNs.  Device type and removable
511                  * flag are jumper-selectable.
512                  */
513                 { T_ANY, SIP_MEDIA_REMOVABLE|SIP_MEDIA_FIXED, "MaxOptix",
514                   "Tahiti 1", "*"
515                 },
516                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
517         },
518         {
519                 /* Default tagged queuing parameters for all devices */
520                 {
521                   T_ANY, SIP_MEDIA_REMOVABLE|SIP_MEDIA_FIXED,
522                   /*vendor*/"*", /*product*/"*", /*revision*/"*"
523                 },
524                 /*quirks*/0, /*mintags*/2, /*maxtags*/255
525         },
526 };
527
528 static const int xpt_quirk_table_size =
529         sizeof(xpt_quirk_table) / sizeof(*xpt_quirk_table);
530
531 typedef enum {
532         DM_RET_COPY             = 0x01,
533         DM_RET_FLAG_MASK        = 0x0f,
534         DM_RET_NONE             = 0x00,
535         DM_RET_STOP             = 0x10,
536         DM_RET_DESCEND          = 0x20,
537         DM_RET_ERROR            = 0x30,
538         DM_RET_ACTION_MASK      = 0xf0
539 } dev_match_ret;
540
541 typedef enum {
542         XPT_DEPTH_BUS,
543         XPT_DEPTH_TARGET,
544         XPT_DEPTH_DEVICE,
545         XPT_DEPTH_PERIPH
546 } xpt_traverse_depth;
547
548 struct xpt_traverse_config {
549         xpt_traverse_depth      depth;
550         void                    *tr_func;
551         void                    *tr_arg;
552 };
553
554 typedef int     xpt_busfunc_t (struct cam_eb *bus, void *arg);
555 typedef int     xpt_targetfunc_t (struct cam_et *target, void *arg);
556 typedef int     xpt_devicefunc_t (struct cam_ed *device, void *arg);
557 typedef int     xpt_periphfunc_t (struct cam_periph *periph, void *arg);
558 typedef int     xpt_pdrvfunc_t (struct periph_driver **pdrv, void *arg);
559
560 /* Transport layer configuration information */
561 static struct xpt_softc xsoftc;
562
563 /* Queues for our software interrupt handler */
564 typedef TAILQ_HEAD(cam_isrq, ccb_hdr) cam_isrq_t;
565 static cam_isrq_t cam_bioq;
566 static cam_isrq_t cam_netq;
567
568 /* "Pool" of inactive ccbs managed by xpt_alloc_ccb and xpt_free_ccb */
569 static SLIST_HEAD(,ccb_hdr) ccb_freeq;
570 static u_int xpt_max_ccbs;      /*
571                                  * Maximum size of ccb pool.  Modified as
572                                  * devices are added/removed or have their
573                                  * opening counts changed.
574                                  */
575 static u_int xpt_ccb_count;     /* Current count of allocated ccbs */
576
577 struct cam_periph *xpt_periph;
578
579 static periph_init_t xpt_periph_init;
580
581 static periph_init_t probe_periph_init;
582
583 static struct periph_driver xpt_driver =
584 {
585         xpt_periph_init, "xpt",
586         TAILQ_HEAD_INITIALIZER(xpt_driver.units)
587 };
588
589 static struct periph_driver probe_driver =
590 {
591         probe_periph_init, "probe",
592         TAILQ_HEAD_INITIALIZER(probe_driver.units)
593 };
594
595 DATA_SET(periphdriver_set, xpt_driver);
596 DATA_SET(periphdriver_set, probe_driver);
597
598 #define XPT_CDEV_MAJOR 104
599
600 static d_open_t xptopen;
601 static d_close_t xptclose;
602 static d_ioctl_t xptioctl;
603
604 static struct dev_ops xpt_ops = {
605         { "xpt", XPT_CDEV_MAJOR, 0 },
606         .d_open = xptopen,
607         .d_close = xptclose,
608         .d_ioctl = xptioctl
609 };
610
611 static struct intr_config_hook *xpt_config_hook;
612
613 /* Registered busses */
614 static TAILQ_HEAD(,cam_eb) xpt_busses;
615 static u_int bus_generation;
616
617 /* Storage for debugging datastructures */
618 #ifdef  CAMDEBUG
619 struct cam_path *cam_dpath;
620 u_int32_t cam_dflags;
621 u_int32_t cam_debug_delay;
622 #endif
623
624 #if defined(CAM_DEBUG_FLAGS) && !defined(CAMDEBUG)
625 #error "You must have options CAMDEBUG to use options CAM_DEBUG_FLAGS"
626 #endif
627
628 /*
629  * In order to enable the CAM_DEBUG_* options, the user must have CAMDEBUG
630  * enabled.  Also, the user must have either none, or all of CAM_DEBUG_BUS,
631  * CAM_DEBUG_TARGET, and CAM_DEBUG_LUN specified.
632  */
633 #if defined(CAM_DEBUG_BUS) || defined(CAM_DEBUG_TARGET) \
634     || defined(CAM_DEBUG_LUN)
635 #ifdef CAMDEBUG
636 #if !defined(CAM_DEBUG_BUS) || !defined(CAM_DEBUG_TARGET) \
637     || !defined(CAM_DEBUG_LUN)
638 #error "You must define all or none of CAM_DEBUG_BUS, CAM_DEBUG_TARGET \
639         and CAM_DEBUG_LUN"
640 #endif /* !CAM_DEBUG_BUS || !CAM_DEBUG_TARGET || !CAM_DEBUG_LUN */
641 #else /* !CAMDEBUG */
642 #error "You must use options CAMDEBUG if you use the CAM_DEBUG_* options"
643 #endif /* CAMDEBUG */
644 #endif /* CAM_DEBUG_BUS || CAM_DEBUG_TARGET || CAM_DEBUG_LUN */
645
646 /* Our boot-time initialization hook */
647 static void     xpt_init(void *);
648 SYSINIT(cam, SI_SUB_CONFIGURE, SI_ORDER_SECOND, xpt_init, NULL);
649
650 static cam_status       xpt_compile_path(struct cam_path *new_path,
651                                          struct cam_periph *perph,
652                                          path_id_t path_id,
653                                          target_id_t target_id,
654                                          lun_id_t lun_id);
655
656 static void             xpt_release_path(struct cam_path *path);
657
658 static void             xpt_async_bcast(struct async_list *async_head,
659                                         u_int32_t async_code,
660                                         struct cam_path *path,
661                                         void *async_arg);
662 static void             xpt_dev_async(u_int32_t async_code,
663                                       struct cam_eb *bus,
664                                       struct cam_et *target,
665                                       struct cam_ed *device,
666                                       void *async_arg);
667 static path_id_t xptnextfreepathid(void);
668 static path_id_t xptpathid(const char *sim_name, int sim_unit, int sim_bus);
669 static union ccb *xpt_get_ccb(struct cam_ed *device);
670 static int       xpt_schedule_dev(struct camq *queue, cam_pinfo *dev_pinfo,
671                                   u_int32_t new_priority);
672 static void      xpt_run_dev_allocq(struct cam_eb *bus);
673 static void      xpt_run_dev_sendq(struct cam_eb *bus);
674 static timeout_t xpt_release_devq_timeout;
675 static void      xpt_release_bus(struct cam_eb *bus);
676 static void      xpt_release_devq_device(struct cam_ed *dev, u_int count,
677                                          int run_queue);
678 static struct cam_et*
679                  xpt_alloc_target(struct cam_eb *bus, target_id_t target_id);
680 static void      xpt_release_target(struct cam_eb *bus, struct cam_et *target);
681 static struct cam_ed*
682                  xpt_alloc_device(struct cam_eb *bus, struct cam_et *target,
683                                   lun_id_t lun_id);
684 static void      xpt_release_device(struct cam_eb *bus, struct cam_et *target,
685                                     struct cam_ed *device);
686 static u_int32_t xpt_dev_ccbq_resize(struct cam_path *path, int newopenings);
687 static struct cam_eb*
688                  xpt_find_bus(path_id_t path_id);
689 static struct cam_et*
690                  xpt_find_target(struct cam_eb *bus, target_id_t target_id);
691 static struct cam_ed*
692                  xpt_find_device(struct cam_et *target, lun_id_t lun_id);
693 static void      xpt_scan_bus(struct cam_periph *periph, union ccb *ccb);
694 static void      xpt_scan_lun(struct cam_periph *periph,
695                               struct cam_path *path, cam_flags flags,
696                               union ccb *ccb);
697 static void      xptscandone(struct cam_periph *periph, union ccb *done_ccb);
698 static xpt_busfunc_t    xptconfigbuscountfunc;
699 static xpt_busfunc_t    xptconfigfunc;
700 static void      xpt_config(void *arg);
701 static xpt_devicefunc_t xptpassannouncefunc;
702 static void      xpt_finishconfig(struct cam_periph *periph, union ccb *ccb);
703 static void      xptaction(struct cam_sim *sim, union ccb *work_ccb);
704 static void      xptpoll(struct cam_sim *sim);
705 static inthand2_t swi_camnet;
706 static inthand2_t swi_cambio;
707 static void      camisr(cam_isrq_t *queue);
708 #if 0
709 static void      xptstart(struct cam_periph *periph, union ccb *work_ccb);
710 static void      xptasync(struct cam_periph *periph,
711                           u_int32_t code, cam_path *path);
712 #endif
713 static dev_match_ret    xptbusmatch(struct dev_match_pattern *patterns,
714                                     int num_patterns, struct cam_eb *bus);
715 static dev_match_ret    xptdevicematch(struct dev_match_pattern *patterns,
716                                        int num_patterns, struct cam_ed *device);
717 static dev_match_ret    xptperiphmatch(struct dev_match_pattern *patterns,
718                                        int num_patterns,
719                                        struct cam_periph *periph);
720 static xpt_busfunc_t    xptedtbusfunc;
721 static xpt_targetfunc_t xptedttargetfunc;
722 static xpt_devicefunc_t xptedtdevicefunc;
723 static xpt_periphfunc_t xptedtperiphfunc;
724 static xpt_pdrvfunc_t   xptplistpdrvfunc;
725 static xpt_periphfunc_t xptplistperiphfunc;
726 static int              xptedtmatch(struct ccb_dev_match *cdm);
727 static int              xptperiphlistmatch(struct ccb_dev_match *cdm);
728 static int              xptbustraverse(struct cam_eb *start_bus,
729                                        xpt_busfunc_t *tr_func, void *arg);
730 static int              xpttargettraverse(struct cam_eb *bus,
731                                           struct cam_et *start_target,
732                                           xpt_targetfunc_t *tr_func, void *arg);
733 static int              xptdevicetraverse(struct cam_et *target,
734                                           struct cam_ed *start_device,
735                                           xpt_devicefunc_t *tr_func, void *arg);
736 static int              xptperiphtraverse(struct cam_ed *device,
737                                           struct cam_periph *start_periph,
738                                           xpt_periphfunc_t *tr_func, void *arg);
739 static int              xptpdrvtraverse(struct periph_driver **start_pdrv,
740                                         xpt_pdrvfunc_t *tr_func, void *arg);
741 static int              xptpdperiphtraverse(struct periph_driver **pdrv,
742                                             struct cam_periph *start_periph,
743                                             xpt_periphfunc_t *tr_func,
744                                             void *arg);
745 static xpt_busfunc_t    xptdefbusfunc;
746 static xpt_targetfunc_t xptdeftargetfunc;
747 static xpt_devicefunc_t xptdefdevicefunc;
748 static xpt_periphfunc_t xptdefperiphfunc;
749 static int              xpt_for_all_busses(xpt_busfunc_t *tr_func, void *arg);
750 #ifdef notusedyet
751 static int              xpt_for_all_targets(xpt_targetfunc_t *tr_func,
752                                             void *arg);
753 #endif
754 static int              xpt_for_all_devices(xpt_devicefunc_t *tr_func,
755                                             void *arg);
756 #ifdef notusedyet
757 static int              xpt_for_all_periphs(xpt_periphfunc_t *tr_func,
758                                             void *arg);
759 #endif
760 static xpt_devicefunc_t xptsetasyncfunc;
761 static xpt_busfunc_t    xptsetasyncbusfunc;
762 static cam_status       xptregister(struct cam_periph *periph,
763                                     void *arg);
764 static cam_status       proberegister(struct cam_periph *periph,
765                                       void *arg);
766 static void      probeschedule(struct cam_periph *probe_periph);
767 static void      probestart(struct cam_periph *periph, union ccb *start_ccb);
768 static void      proberequestdefaultnegotiation(struct cam_periph *periph);
769 static void      probedone(struct cam_periph *periph, union ccb *done_ccb);
770 static void      probecleanup(struct cam_periph *periph);
771 static void      xpt_find_quirk(struct cam_ed *device);
772 static void      xpt_set_transfer_settings(struct ccb_trans_settings *cts,
773                                            struct cam_ed *device,
774                                            int async_update);
775 static void      xpt_toggle_tags(struct cam_path *path);
776 static void      xpt_start_tags(struct cam_path *path);
777 static __inline int xpt_schedule_dev_allocq(struct cam_eb *bus,
778                                             struct cam_ed *dev);
779 static __inline int xpt_schedule_dev_sendq(struct cam_eb *bus,
780                                            struct cam_ed *dev);
781 static __inline int periph_is_queued(struct cam_periph *periph);
782 static __inline int device_is_alloc_queued(struct cam_ed *device);
783 static __inline int device_is_send_queued(struct cam_ed *device);
784 static __inline int dev_allocq_is_runnable(struct cam_devq *devq);
785
786 static __inline int
787 xpt_schedule_dev_allocq(struct cam_eb *bus, struct cam_ed *dev)
788 {
789         int retval;
790
791         if (bus->sim->devq && dev->ccbq.devq_openings > 0) {
792                 if ((dev->flags & CAM_DEV_RESIZE_QUEUE_NEEDED) != 0) {
793                         cam_ccbq_resize(&dev->ccbq,
794                                         dev->ccbq.dev_openings
795                                         + dev->ccbq.dev_active);
796                         dev->flags &= ~CAM_DEV_RESIZE_QUEUE_NEEDED;
797                 }
798                 /*
799                  * The priority of a device waiting for CCB resources
800                  * is that of the the highest priority peripheral driver
801                  * enqueued.
802                  */
803                 retval = xpt_schedule_dev(&bus->sim->devq->alloc_queue,
804                                           &dev->alloc_ccb_entry.pinfo,
805                                           CAMQ_GET_HEAD(&dev->drvq)->priority); 
806         } else {
807                 retval = 0;
808         }
809
810         return (retval);
811 }
812
813 static __inline int
814 xpt_schedule_dev_sendq(struct cam_eb *bus, struct cam_ed *dev)
815 {
816         int     retval;
817
818         if (bus->sim->devq && dev->ccbq.dev_openings > 0) {
819                 /*
820                  * The priority of a device waiting for controller
821                  * resources is that of the the highest priority CCB
822                  * enqueued.
823                  */
824                 retval =
825                     xpt_schedule_dev(&bus->sim->devq->send_queue,
826                                      &dev->send_ccb_entry.pinfo,
827                                      CAMQ_GET_HEAD(&dev->ccbq.queue)->priority);
828         } else {
829                 retval = 0;
830         }
831         return (retval);
832 }
833
834 static __inline int
835 periph_is_queued(struct cam_periph *periph)
836 {
837         return (periph->pinfo.index != CAM_UNQUEUED_INDEX);
838 }
839
840 static __inline int
841 device_is_alloc_queued(struct cam_ed *device)
842 {
843         return (device->alloc_ccb_entry.pinfo.index != CAM_UNQUEUED_INDEX);
844 }
845
846 static __inline int
847 device_is_send_queued(struct cam_ed *device)
848 {
849         return (device->send_ccb_entry.pinfo.index != CAM_UNQUEUED_INDEX);
850 }
851
852 static __inline int
853 dev_allocq_is_runnable(struct cam_devq *devq)
854 {
855         /*
856          * Have work to do.
857          * Have space to do more work.
858          * Allowed to do work.
859          */
860         return ((devq->alloc_queue.qfrozen_cnt == 0)
861              && (devq->alloc_queue.entries > 0)
862              && (devq->alloc_openings > 0));
863 }
864
865 static void
866 xpt_periph_init(void)
867 {
868         dev_ops_add(&xpt_ops, 0, 0);
869         make_dev(&xpt_ops, 0, UID_ROOT, GID_OPERATOR, 0600, "xpt0");
870 }
871
872 static void
873 probe_periph_init(void)
874 {
875 }
876
877
878 static void
879 xptdone(struct cam_periph *periph, union ccb *done_ccb)
880 {
881         /* Caller will release the CCB */
882         wakeup(&done_ccb->ccb_h.cbfcnp);
883 }
884
885 static int
886 xptopen(struct dev_open_args *ap)
887 {
888         cdev_t dev = ap->a_head.a_dev;
889         int unit;
890
891         unit = minor(dev) & 0xff;
892
893         /*
894          * Only allow read-write access.
895          */
896         if (((ap->a_oflags & FWRITE) == 0) || ((ap->a_oflags & FREAD) == 0))
897                 return(EPERM);
898
899         /*
900          * We don't allow nonblocking access.
901          */
902         if ((ap->a_oflags & O_NONBLOCK) != 0) {
903                 printf("xpt%d: can't do nonblocking access\n", unit);
904                 return(ENODEV);
905         }
906
907         /*
908          * We only have one transport layer right now.  If someone accesses
909          * us via something other than minor number 1, point out their
910          * mistake.
911          */
912         if (unit != 0) {
913                 printf("xptopen: got invalid xpt unit %d\n", unit);
914                 return(ENXIO);
915         }
916
917         /* Mark ourselves open */
918         xsoftc.flags |= XPT_FLAG_OPEN;
919         
920         return(0);
921 }
922
923 static int
924 xptclose(struct dev_close_args *ap)
925 {
926         cdev_t dev = ap->a_head.a_dev;
927         int unit;
928
929         unit = minor(dev) & 0xff;
930
931         /*
932          * We only have one transport layer right now.  If someone accesses
933          * us via something other than minor number 1, point out their
934          * mistake.
935          */
936         if (unit != 0) {
937                 printf("xptclose: got invalid xpt unit %d\n", unit);
938                 return(ENXIO);
939         }
940
941         /* Mark ourselves closed */
942         xsoftc.flags &= ~XPT_FLAG_OPEN;
943
944         return(0);
945 }
946
947 static int
948 xptioctl(struct dev_ioctl_args *ap)
949 {
950         cdev_t dev = ap->a_head.a_dev;
951         int unit, error;
952
953         error = 0;
954         unit = minor(dev) & 0xff;
955
956         /*
957          * We only have one transport layer right now.  If someone accesses
958          * us via something other than minor number 1, point out their
959          * mistake.
960          */
961         if (unit != 0) {
962                 printf("xptioctl: got invalid xpt unit %d\n", unit);
963                 return(ENXIO);
964         }
965
966         switch(ap->a_cmd) {
967         /*
968          * For the transport layer CAMIOCOMMAND ioctl, we really only want
969          * to accept CCB types that don't quite make sense to send through a
970          * passthrough driver.
971          */
972         case CAMIOCOMMAND: {
973                 union ccb *ccb;
974                 union ccb *inccb;
975
976                 inccb = (union ccb *)ap->a_data;
977
978                 switch(inccb->ccb_h.func_code) {
979                 case XPT_SCAN_BUS:
980                 case XPT_RESET_BUS:
981                         if ((inccb->ccb_h.target_id != CAM_TARGET_WILDCARD)
982                          || (inccb->ccb_h.target_lun != CAM_LUN_WILDCARD)) {
983                                 error = EINVAL;
984                                 break;
985                         }
986                         /* FALLTHROUGH */
987                 case XPT_PATH_INQ:
988                 case XPT_ENG_INQ:
989                 case XPT_SCAN_LUN:
990
991                         ccb = xpt_alloc_ccb();
992
993                         /*
994                          * Create a path using the bus, target, and lun the
995                          * user passed in.
996                          */
997                         if (xpt_create_path(&ccb->ccb_h.path, xpt_periph,
998                                             inccb->ccb_h.path_id,
999                                             inccb->ccb_h.target_id,
1000                                             inccb->ccb_h.target_lun) !=
1001                                             CAM_REQ_CMP){
1002                                 error = EINVAL;
1003                                 xpt_free_ccb(ccb);
1004                                 break;
1005                         }
1006                         /* Ensure all of our fields are correct */
1007                         xpt_setup_ccb(&ccb->ccb_h, ccb->ccb_h.path,
1008                                       inccb->ccb_h.pinfo.priority);
1009                         xpt_merge_ccb(ccb, inccb);
1010                         ccb->ccb_h.cbfcnp = xptdone;
1011                         cam_periph_runccb(ccb, NULL, 0, 0, NULL);
1012                         bcopy(ccb, inccb, sizeof(union ccb));
1013                         xpt_free_path(ccb->ccb_h.path);
1014                         xpt_free_ccb(ccb);
1015                         break;
1016
1017                 case XPT_DEBUG: {
1018                         union ccb ccb;
1019
1020                         /*
1021                          * This is an immediate CCB, so it's okay to
1022                          * allocate it on the stack.
1023                          */
1024
1025                         /*
1026                          * Create a path using the bus, target, and lun the
1027                          * user passed in.
1028                          */
1029                         if (xpt_create_path(&ccb.ccb_h.path, xpt_periph,
1030                                             inccb->ccb_h.path_id,
1031                                             inccb->ccb_h.target_id,
1032                                             inccb->ccb_h.target_lun) !=
1033                                             CAM_REQ_CMP){
1034                                 error = EINVAL;
1035                                 break;
1036                         }
1037                         /* Ensure all of our fields are correct */
1038                         xpt_setup_ccb(&ccb.ccb_h, ccb.ccb_h.path,
1039                                       inccb->ccb_h.pinfo.priority);
1040                         xpt_merge_ccb(&ccb, inccb);
1041                         ccb.ccb_h.cbfcnp = xptdone;
1042                         xpt_action(&ccb);
1043                         bcopy(&ccb, inccb, sizeof(union ccb));
1044                         xpt_free_path(ccb.ccb_h.path);
1045                         break;
1046
1047                 }
1048                 case XPT_DEV_MATCH: {
1049                         struct cam_periph_map_info mapinfo;
1050                         struct cam_path *old_path;
1051
1052                         /*
1053                          * We can't deal with physical addresses for this
1054                          * type of transaction.
1055                          */
1056                         if (inccb->ccb_h.flags & CAM_DATA_PHYS) {
1057                                 error = EINVAL;
1058                                 break;
1059                         }
1060
1061                         /*
1062                          * Save this in case the caller had it set to
1063                          * something in particular.
1064                          */
1065                         old_path = inccb->ccb_h.path;
1066
1067                         /*
1068                          * We really don't need a path for the matching
1069                          * code.  The path is needed because of the
1070                          * debugging statements in xpt_action().  They
1071                          * assume that the CCB has a valid path.
1072                          */
1073                         inccb->ccb_h.path = xpt_periph->path;
1074
1075                         bzero(&mapinfo, sizeof(mapinfo));
1076
1077                         /*
1078                          * Map the pattern and match buffers into kernel
1079                          * virtual address space.
1080                          */
1081                         error = cam_periph_mapmem(inccb, &mapinfo);
1082
1083                         if (error) {
1084                                 inccb->ccb_h.path = old_path;
1085                                 break;
1086                         }
1087
1088                         /*
1089                          * This is an immediate CCB, we can send it on directly.
1090                          */
1091                         xpt_action(inccb);
1092
1093                         /*
1094                          * Map the buffers back into user space.
1095                          */
1096                         cam_periph_unmapmem(inccb, &mapinfo);
1097
1098                         inccb->ccb_h.path = old_path;
1099
1100                         error = 0;
1101                         break;
1102                 }
1103                 default:
1104                         error = ENOTSUP;
1105                         break;
1106                 }
1107                 break;
1108         }
1109         /*
1110          * This is the getpassthru ioctl. It takes a XPT_GDEVLIST ccb as input,
1111          * with the periphal driver name and unit name filled in.  The other
1112          * fields don't really matter as input.  The passthrough driver name
1113          * ("pass"), and unit number are passed back in the ccb.  The current
1114          * device generation number, and the index into the device peripheral
1115          * driver list, and the status are also passed back.  Note that
1116          * since we do everything in one pass, unlike the XPT_GDEVLIST ccb,
1117          * we never return a status of CAM_GDEVLIST_LIST_CHANGED.  It is
1118          * (or rather should be) impossible for the device peripheral driver
1119          * list to change since we look at the whole thing in one pass, and
1120          * we do it within a critical section.
1121          * 
1122          */
1123         case CAMGETPASSTHRU: {
1124                 union ccb *ccb;
1125                 struct cam_periph *periph;
1126                 struct periph_driver **p_drv;
1127                 char   *name;
1128                 int unit;
1129                 int cur_generation;
1130                 int base_periph_found;
1131                 int splbreaknum;
1132
1133                 ccb = (union ccb *)ap->a_data;
1134                 unit = ccb->cgdl.unit_number;
1135                 name = ccb->cgdl.periph_name;
1136                 /*
1137                  * Every 100 devices, we want to call splz() to check for
1138                  * and allow the software interrupt handler a chance to run.
1139                  *
1140                  * Most systems won't run into this check, but this should
1141                  * avoid starvation in the software interrupt handler in
1142                  * large systems.
1143                  */
1144                 splbreaknum = 100;
1145
1146                 ccb = (union ccb *)ap->a_data;
1147
1148                 base_periph_found = 0;
1149
1150                 /*
1151                  * Sanity check -- make sure we don't get a null peripheral
1152                  * driver name.
1153                  */
1154                 if (*ccb->cgdl.periph_name == '\0') {
1155                         error = EINVAL;
1156                         break;
1157                 }
1158
1159                 /* Keep the list from changing while we traverse it */
1160                 crit_enter();
1161 ptstartover:
1162                 cur_generation = xsoftc.generation;
1163
1164                 /* first find our driver in the list of drivers */
1165                 SET_FOREACH(p_drv, periphdriver_set) {
1166                         if (strcmp((*p_drv)->driver_name, name) == 0)
1167                                 break;
1168                 }
1169
1170                 if (*p_drv == NULL) {
1171                         crit_exit();
1172                         ccb->ccb_h.status = CAM_REQ_CMP_ERR;
1173                         ccb->cgdl.status = CAM_GDEVLIST_ERROR;
1174                         *ccb->cgdl.periph_name = '\0';
1175                         ccb->cgdl.unit_number = 0;
1176                         error = ENOENT;
1177                         break;
1178                 }       
1179
1180                 /*
1181                  * Run through every peripheral instance of this driver
1182                  * and check to see whether it matches the unit passed
1183                  * in by the user.  If it does, get out of the loops and
1184                  * find the passthrough driver associated with that
1185                  * peripheral driver.
1186                  */
1187                 for (periph = TAILQ_FIRST(&(*p_drv)->units); periph != NULL;
1188                      periph = TAILQ_NEXT(periph, unit_links)) {
1189
1190                         if (periph->unit_number == unit) {
1191                                 break;
1192                         } else if (--splbreaknum == 0) {
1193                                 splz();
1194                                 splbreaknum = 100;
1195                                 if (cur_generation != xsoftc.generation)
1196                                        goto ptstartover;
1197                         }
1198                 }
1199                 /*
1200                  * If we found the peripheral driver that the user passed
1201                  * in, go through all of the peripheral drivers for that
1202                  * particular device and look for a passthrough driver.
1203                  */
1204                 if (periph != NULL) {
1205                         struct cam_ed *device;
1206                         int i;
1207
1208                         base_periph_found = 1;
1209                         device = periph->path->device;
1210                         for (i = 0, periph = device->periphs.slh_first;
1211                              periph != NULL;
1212                              periph = periph->periph_links.sle_next, i++) {
1213                                 /*
1214                                  * Check to see whether we have a
1215                                  * passthrough device or not. 
1216                                  */
1217                                 if (strcmp(periph->periph_name, "pass") == 0) {
1218                                         /*
1219                                          * Fill in the getdevlist fields.
1220                                          */
1221                                         strcpy(ccb->cgdl.periph_name,
1222                                                periph->periph_name);
1223                                         ccb->cgdl.unit_number =
1224                                                 periph->unit_number;
1225                                         if (periph->periph_links.sle_next)
1226                                                 ccb->cgdl.status =
1227                                                         CAM_GDEVLIST_MORE_DEVS;
1228                                         else
1229                                                 ccb->cgdl.status =
1230                                                        CAM_GDEVLIST_LAST_DEVICE;
1231                                         ccb->cgdl.generation =
1232                                                 device->generation;
1233                                         ccb->cgdl.index = i;
1234                                         /*
1235                                          * Fill in some CCB header fields
1236                                          * that the user may want.
1237                                          */
1238                                         ccb->ccb_h.path_id =
1239                                                 periph->path->bus->path_id;
1240                                         ccb->ccb_h.target_id =
1241                                                 periph->path->target->target_id;
1242                                         ccb->ccb_h.target_lun =
1243                                                 periph->path->device->lun_id;
1244                                         ccb->ccb_h.status = CAM_REQ_CMP;
1245                                         break;
1246                                 }
1247                         }
1248                 }
1249
1250                 /*
1251                  * If the periph is null here, one of two things has
1252                  * happened.  The first possibility is that we couldn't
1253                  * find the unit number of the particular peripheral driver
1254                  * that the user is asking about.  e.g. the user asks for
1255                  * the passthrough driver for "da11".  We find the list of
1256                  * "da" peripherals all right, but there is no unit 11.
1257                  * The other possibility is that we went through the list
1258                  * of peripheral drivers attached to the device structure,
1259                  * but didn't find one with the name "pass".  Either way,
1260                  * we return ENOENT, since we couldn't find something.
1261                  */
1262                 if (periph == NULL) {
1263                         ccb->ccb_h.status = CAM_REQ_CMP_ERR;
1264                         ccb->cgdl.status = CAM_GDEVLIST_ERROR;
1265                         *ccb->cgdl.periph_name = '\0';
1266                         ccb->cgdl.unit_number = 0;
1267                         error = ENOENT;
1268                         /*
1269                          * It is unfortunate that this is even necessary,
1270                          * but there are many, many clueless users out there.
1271                          * If this is true, the user is looking for the
1272                          * passthrough driver, but doesn't have one in his
1273                          * kernel.
1274                          */
1275                         if (base_periph_found == 1) {
1276                                 printf("xptioctl: pass driver is not in the "
1277                                        "kernel\n");
1278                                 printf("xptioctl: put \"device pass0\" in "
1279                                        "your kernel config file\n");
1280                         }
1281                 }
1282                 crit_exit();
1283                 break;
1284                 }
1285         default:
1286                 error = ENOTTY;
1287                 break;
1288         }
1289
1290         return(error);
1291 }
1292
1293 /* Functions accessed by the peripheral drivers */
1294 static void
1295 xpt_init(void *dummy)
1296 {
1297         struct cam_sim *xpt_sim;
1298         struct cam_path *path;
1299         struct cam_devq *devq;
1300         cam_status status;
1301
1302         TAILQ_INIT(&xpt_busses);
1303         TAILQ_INIT(&cam_bioq);
1304         TAILQ_INIT(&cam_netq);
1305         SLIST_INIT(&ccb_freeq);
1306         STAILQ_INIT(&highpowerq);
1307
1308         /*
1309          * The xpt layer is, itself, the equivelent of a SIM.
1310          * Allow 16 ccbs in the ccb pool for it.  This should
1311          * give decent parallelism when we probe busses and
1312          * perform other XPT functions.
1313          */
1314         devq = cam_simq_alloc(16);
1315         xpt_sim = cam_sim_alloc(xptaction,
1316                                 xptpoll,
1317                                 "xpt",
1318                                 /*softc*/NULL,
1319                                 /*unit*/0,
1320                                 /*max_dev_transactions*/0,
1321                                 /*max_tagged_dev_transactions*/0,
1322                                 devq);
1323         cam_simq_release(devq);
1324         xpt_max_ccbs = 16;
1325                                 
1326         xpt_bus_register(xpt_sim, /*bus #*/0);
1327
1328         /*
1329          * Looking at the XPT from the SIM layer, the XPT is
1330          * the equivelent of a peripheral driver.  Allocate
1331          * a peripheral driver entry for us.
1332          */
1333         if ((status = xpt_create_path(&path, NULL, CAM_XPT_PATH_ID,
1334                                       CAM_TARGET_WILDCARD,
1335                                       CAM_LUN_WILDCARD)) != CAM_REQ_CMP) {
1336                 printf("xpt_init: xpt_create_path failed with status %#x,"
1337                        " failing attach\n", status);
1338                 return;
1339         }
1340
1341         cam_periph_alloc(xptregister, NULL, NULL, NULL, "xpt", CAM_PERIPH_BIO,
1342                          path, NULL, 0, NULL);
1343         xpt_free_path(path);
1344
1345         xpt_sim->softc = xpt_periph;
1346
1347         /*
1348          * Register a callback for when interrupts are enabled.
1349          */
1350         xpt_config_hook = kmalloc(sizeof(struct intr_config_hook),
1351                                   M_TEMP, M_INTWAIT | M_ZERO);
1352         xpt_config_hook->ich_func = xpt_config;
1353         xpt_config_hook->ich_desc = "xpt";
1354         if (config_intrhook_establish(xpt_config_hook) != 0) {
1355                 kfree (xpt_config_hook, M_TEMP);
1356                 printf("xpt_init: config_intrhook_establish failed "
1357                        "- failing attach\n");
1358         }
1359
1360         /* Install our software interrupt handlers */
1361         register_swi(SWI_CAMNET, swi_camnet, NULL, "swi_camnet", NULL);
1362         register_swi(SWI_CAMBIO, swi_cambio, NULL, "swi_cambio", NULL);
1363 }
1364
1365 static cam_status
1366 xptregister(struct cam_periph *periph, void *arg)
1367 {
1368         if (periph == NULL) {
1369                 printf("xptregister: periph was NULL!!\n");
1370                 return(CAM_REQ_CMP_ERR);
1371         }
1372
1373         periph->softc = NULL;
1374
1375         xpt_periph = periph;
1376
1377         return(CAM_REQ_CMP);
1378 }
1379
1380 int32_t
1381 xpt_add_periph(struct cam_periph *periph)
1382 {
1383         struct cam_ed *device;
1384         int32_t  status;
1385         struct periph_list *periph_head;
1386
1387         device = periph->path->device;
1388
1389         periph_head = &device->periphs;
1390
1391         status = CAM_REQ_CMP;
1392
1393         if (device != NULL) {
1394                 /*
1395                  * Make room for this peripheral
1396                  * so it will fit in the queue
1397                  * when it's scheduled to run
1398                  */
1399                 crit_enter();
1400                 status = camq_resize(&device->drvq,
1401                                      device->drvq.array_size + 1);
1402
1403                 device->generation++;
1404
1405                 SLIST_INSERT_HEAD(periph_head, periph, periph_links);
1406                 crit_exit();
1407         }
1408
1409         xsoftc.generation++;
1410
1411         return (status);
1412 }
1413
1414 void
1415 xpt_remove_periph(struct cam_periph *periph)
1416 {
1417         struct cam_ed *device;
1418
1419         device = periph->path->device;
1420
1421         if (device != NULL) {
1422                 struct periph_list *periph_head;
1423
1424                 periph_head = &device->periphs;
1425                 
1426                 /* Release the slot for this peripheral */
1427                 crit_enter();
1428                 camq_resize(&device->drvq, device->drvq.array_size - 1);
1429
1430                 device->generation++;
1431
1432                 SLIST_REMOVE(periph_head, periph, cam_periph, periph_links);
1433                 crit_exit();
1434         }
1435
1436         xsoftc.generation++;
1437
1438 }
1439
1440 void
1441 xpt_announce_periph(struct cam_periph *periph, char *announce_string)
1442 {
1443         u_int mb;
1444         struct cam_path *path;
1445         struct ccb_trans_settings cts;
1446
1447         path = periph->path;
1448         /*
1449          * To ensure that this is printed in one piece,
1450          * mask out CAM interrupts.
1451          */
1452         crit_enter();
1453         printf("%s%d at %s%d bus %d target %d lun %d\n",
1454                periph->periph_name, periph->unit_number,
1455                path->bus->sim->sim_name,
1456                path->bus->sim->unit_number,
1457                path->bus->sim->bus_id,
1458                path->target->target_id,
1459                path->device->lun_id);
1460         printf("%s%d: ", periph->periph_name, periph->unit_number);
1461         scsi_print_inquiry(&path->device->inq_data);
1462         if ((bootverbose)
1463          && (path->device->serial_num_len > 0)) {
1464                 /* Don't wrap the screen  - print only the first 60 chars */
1465                 printf("%s%d: Serial Number %.60s\n", periph->periph_name,
1466                        periph->unit_number, path->device->serial_num);
1467         }
1468         xpt_setup_ccb(&cts.ccb_h, path, /*priority*/1);
1469         cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
1470         cts.flags = CCB_TRANS_CURRENT_SETTINGS;
1471         xpt_action((union ccb*)&cts);
1472         if (cts.ccb_h.status == CAM_REQ_CMP) {
1473                 u_int speed;
1474                 u_int freq;
1475
1476                 if ((cts.valid & CCB_TRANS_SYNC_OFFSET_VALID) != 0
1477                   && cts.sync_offset != 0) {
1478                         freq = scsi_calc_syncsrate(cts.sync_period);
1479                         speed = freq;
1480                 } else {
1481                         struct ccb_pathinq cpi;
1482
1483                         /* Ask the SIM for its base transfer speed */
1484                         xpt_setup_ccb(&cpi.ccb_h, path, /*priority*/1);
1485                         cpi.ccb_h.func_code = XPT_PATH_INQ;
1486                         xpt_action((union ccb *)&cpi);
1487
1488                         speed = cpi.base_transfer_speed;
1489                         freq = 0;
1490                 }
1491                 if ((cts.valid & CCB_TRANS_BUS_WIDTH_VALID) != 0)
1492                         speed *= (0x01 << cts.bus_width);
1493                 mb = speed / 1000;
1494                 if (mb > 0)
1495                         printf("%s%d: %d.%03dMB/s transfers",
1496                                periph->periph_name, periph->unit_number,
1497                                mb, speed % 1000);
1498                 else
1499                         printf("%s%d: %dKB/s transfers", periph->periph_name,
1500                                periph->unit_number, speed);
1501                 if ((cts.valid & CCB_TRANS_SYNC_OFFSET_VALID) != 0
1502                  && cts.sync_offset != 0) {
1503                         printf(" (%d.%03dMHz, offset %d", freq / 1000,
1504                                freq % 1000, cts.sync_offset);
1505                 }
1506                 if ((cts.valid & CCB_TRANS_BUS_WIDTH_VALID) != 0
1507                  && cts.bus_width > 0) {
1508                         if ((cts.valid & CCB_TRANS_SYNC_OFFSET_VALID) != 0
1509                          && cts.sync_offset != 0) {
1510                                 printf(", ");
1511                         } else {
1512                                 printf(" (");
1513                         }
1514                         printf("%dbit)", 8 * (0x01 << cts.bus_width));
1515                 } else if ((cts.valid & CCB_TRANS_SYNC_OFFSET_VALID) != 0
1516                         && cts.sync_offset != 0) {
1517                         printf(")");
1518                 }
1519
1520                 if (path->device->inq_flags & SID_CmdQue
1521                  || path->device->flags & CAM_DEV_TAG_AFTER_COUNT) {
1522                         printf(", Tagged Queueing Enabled");
1523                 }
1524
1525                 printf("\n");
1526         } else if (path->device->inq_flags & SID_CmdQue
1527                 || path->device->flags & CAM_DEV_TAG_AFTER_COUNT) {
1528                 printf("%s%d: Tagged Queueing Enabled\n",
1529                        periph->periph_name, periph->unit_number);
1530         }
1531
1532         /*
1533          * We only want to print the caller's announce string if they've
1534          * passed one in..
1535          */
1536         if (announce_string != NULL)
1537                 printf("%s%d: %s\n", periph->periph_name,
1538                        periph->unit_number, announce_string);
1539         crit_exit();
1540 }
1541
1542
1543 static dev_match_ret
1544 xptbusmatch(struct dev_match_pattern *patterns, int num_patterns,
1545             struct cam_eb *bus)
1546 {
1547         dev_match_ret retval;
1548         int i;
1549
1550         retval = DM_RET_NONE;
1551
1552         /*
1553          * If we aren't given something to match against, that's an error.
1554          */
1555         if (bus == NULL)
1556                 return(DM_RET_ERROR);
1557
1558         /*
1559          * If there are no match entries, then this bus matches no
1560          * matter what.
1561          */
1562         if ((patterns == NULL) || (num_patterns == 0))
1563                 return(DM_RET_DESCEND | DM_RET_COPY);
1564
1565         for (i = 0; i < num_patterns; i++) {
1566                 struct bus_match_pattern *cur_pattern;
1567
1568                 /*
1569                  * If the pattern in question isn't for a bus node, we
1570                  * aren't interested.  However, we do indicate to the
1571                  * calling routine that we should continue descending the
1572                  * tree, since the user wants to match against lower-level
1573                  * EDT elements.
1574                  */
1575                 if (patterns[i].type != DEV_MATCH_BUS) {
1576                         if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1577                                 retval |= DM_RET_DESCEND;
1578                         continue;
1579                 }
1580
1581                 cur_pattern = &patterns[i].pattern.bus_pattern;
1582
1583                 /*
1584                  * If they want to match any bus node, we give them any
1585                  * device node.
1586                  */
1587                 if (cur_pattern->flags == BUS_MATCH_ANY) {
1588                         /* set the copy flag */
1589                         retval |= DM_RET_COPY;
1590
1591                         /*
1592                          * If we've already decided on an action, go ahead
1593                          * and return.
1594                          */
1595                         if ((retval & DM_RET_ACTION_MASK) != DM_RET_NONE)
1596                                 return(retval);
1597                 }
1598
1599                 /*
1600                  * Not sure why someone would do this...
1601                  */
1602                 if (cur_pattern->flags == BUS_MATCH_NONE)
1603                         continue;
1604
1605                 if (((cur_pattern->flags & BUS_MATCH_PATH) != 0)
1606                  && (cur_pattern->path_id != bus->path_id))
1607                         continue;
1608
1609                 if (((cur_pattern->flags & BUS_MATCH_BUS_ID) != 0)
1610                  && (cur_pattern->bus_id != bus->sim->bus_id))
1611                         continue;
1612
1613                 if (((cur_pattern->flags & BUS_MATCH_UNIT) != 0)
1614                  && (cur_pattern->unit_number != bus->sim->unit_number))
1615                         continue;
1616
1617                 if (((cur_pattern->flags & BUS_MATCH_NAME) != 0)
1618                  && (strncmp(cur_pattern->dev_name, bus->sim->sim_name,
1619                              DEV_IDLEN) != 0))
1620                         continue;
1621
1622                 /*
1623                  * If we get to this point, the user definitely wants 
1624                  * information on this bus.  So tell the caller to copy the
1625                  * data out.
1626                  */
1627                 retval |= DM_RET_COPY;
1628
1629                 /*
1630                  * If the return action has been set to descend, then we
1631                  * know that we've already seen a non-bus matching
1632                  * expression, therefore we need to further descend the tree.
1633                  * This won't change by continuing around the loop, so we
1634                  * go ahead and return.  If we haven't seen a non-bus
1635                  * matching expression, we keep going around the loop until
1636                  * we exhaust the matching expressions.  We'll set the stop
1637                  * flag once we fall out of the loop.
1638                  */
1639                 if ((retval & DM_RET_ACTION_MASK) == DM_RET_DESCEND)
1640                         return(retval);
1641         }
1642
1643         /*
1644          * If the return action hasn't been set to descend yet, that means
1645          * we haven't seen anything other than bus matching patterns.  So
1646          * tell the caller to stop descending the tree -- the user doesn't
1647          * want to match against lower level tree elements.
1648          */
1649         if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1650                 retval |= DM_RET_STOP;
1651
1652         return(retval);
1653 }
1654
1655 static dev_match_ret
1656 xptdevicematch(struct dev_match_pattern *patterns, int num_patterns,
1657                struct cam_ed *device)
1658 {
1659         dev_match_ret retval;
1660         int i;
1661
1662         retval = DM_RET_NONE;
1663
1664         /*
1665          * If we aren't given something to match against, that's an error.
1666          */
1667         if (device == NULL)
1668                 return(DM_RET_ERROR);
1669
1670         /*
1671          * If there are no match entries, then this device matches no
1672          * matter what.
1673          */
1674         if ((patterns == NULL) || (patterns == 0))
1675                 return(DM_RET_DESCEND | DM_RET_COPY);
1676
1677         for (i = 0; i < num_patterns; i++) {
1678                 struct device_match_pattern *cur_pattern;
1679
1680                 /*
1681                  * If the pattern in question isn't for a device node, we
1682                  * aren't interested.
1683                  */
1684                 if (patterns[i].type != DEV_MATCH_DEVICE) {
1685                         if ((patterns[i].type == DEV_MATCH_PERIPH)
1686                          && ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE))
1687                                 retval |= DM_RET_DESCEND;
1688                         continue;
1689                 }
1690
1691                 cur_pattern = &patterns[i].pattern.device_pattern;
1692
1693                 /*
1694                  * If they want to match any device node, we give them any
1695                  * device node.
1696                  */
1697                 if (cur_pattern->flags == DEV_MATCH_ANY) {
1698                         /* set the copy flag */
1699                         retval |= DM_RET_COPY;
1700
1701                         
1702                         /*
1703                          * If we've already decided on an action, go ahead
1704                          * and return.
1705                          */
1706                         if ((retval & DM_RET_ACTION_MASK) != DM_RET_NONE)
1707                                 return(retval);
1708                 }
1709
1710                 /*
1711                  * Not sure why someone would do this...
1712                  */
1713                 if (cur_pattern->flags == DEV_MATCH_NONE)
1714                         continue;
1715
1716                 if (((cur_pattern->flags & DEV_MATCH_PATH) != 0)
1717                  && (cur_pattern->path_id != device->target->bus->path_id))
1718                         continue;
1719
1720                 if (((cur_pattern->flags & DEV_MATCH_TARGET) != 0)
1721                  && (cur_pattern->target_id != device->target->target_id))
1722                         continue;
1723
1724                 if (((cur_pattern->flags & DEV_MATCH_LUN) != 0)
1725                  && (cur_pattern->target_lun != device->lun_id))
1726                         continue;
1727
1728                 if (((cur_pattern->flags & DEV_MATCH_INQUIRY) != 0)
1729                  && (cam_quirkmatch((caddr_t)&device->inq_data,
1730                                     (caddr_t)&cur_pattern->inq_pat,
1731                                     1, sizeof(cur_pattern->inq_pat),
1732                                     scsi_static_inquiry_match) == NULL))
1733                         continue;
1734
1735                 /*
1736                  * If we get to this point, the user definitely wants 
1737                  * information on this device.  So tell the caller to copy
1738                  * the data out.
1739                  */
1740                 retval |= DM_RET_COPY;
1741
1742                 /*
1743                  * If the return action has been set to descend, then we
1744                  * know that we've already seen a peripheral matching
1745                  * expression, therefore we need to further descend the tree.
1746                  * This won't change by continuing around the loop, so we
1747                  * go ahead and return.  If we haven't seen a peripheral
1748                  * matching expression, we keep going around the loop until
1749                  * we exhaust the matching expressions.  We'll set the stop
1750                  * flag once we fall out of the loop.
1751                  */
1752                 if ((retval & DM_RET_ACTION_MASK) == DM_RET_DESCEND)
1753                         return(retval);
1754         }
1755
1756         /*
1757          * If the return action hasn't been set to descend yet, that means
1758          * we haven't seen any peripheral matching patterns.  So tell the
1759          * caller to stop descending the tree -- the user doesn't want to
1760          * match against lower level tree elements.
1761          */
1762         if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1763                 retval |= DM_RET_STOP;
1764
1765         return(retval);
1766 }
1767
1768 /*
1769  * Match a single peripheral against any number of match patterns.
1770  */
1771 static dev_match_ret
1772 xptperiphmatch(struct dev_match_pattern *patterns, int num_patterns,
1773                struct cam_periph *periph)
1774 {
1775         dev_match_ret retval;
1776         int i;
1777
1778         /*
1779          * If we aren't given something to match against, that's an error.
1780          */
1781         if (periph == NULL)
1782                 return(DM_RET_ERROR);
1783
1784         /*
1785          * If there are no match entries, then this peripheral matches no
1786          * matter what.
1787          */
1788         if ((patterns == NULL) || (num_patterns == 0))
1789                 return(DM_RET_STOP | DM_RET_COPY);
1790
1791         /*
1792          * There aren't any nodes below a peripheral node, so there's no
1793          * reason to descend the tree any further.
1794          */
1795         retval = DM_RET_STOP;
1796
1797         for (i = 0; i < num_patterns; i++) {
1798                 struct periph_match_pattern *cur_pattern;
1799
1800                 /*
1801                  * If the pattern in question isn't for a peripheral, we
1802                  * aren't interested.
1803                  */
1804                 if (patterns[i].type != DEV_MATCH_PERIPH)
1805                         continue;
1806
1807                 cur_pattern = &patterns[i].pattern.periph_pattern;
1808
1809                 /*
1810                  * If they want to match on anything, then we will do so.
1811                  */
1812                 if (cur_pattern->flags == PERIPH_MATCH_ANY) {
1813                         /* set the copy flag */
1814                         retval |= DM_RET_COPY;
1815
1816                         /*
1817                          * We've already set the return action to stop,
1818                          * since there are no nodes below peripherals in
1819                          * the tree.
1820                          */
1821                         return(retval);
1822                 }
1823
1824                 /*
1825                  * Not sure why someone would do this...
1826                  */
1827                 if (cur_pattern->flags == PERIPH_MATCH_NONE)
1828                         continue;
1829
1830                 if (((cur_pattern->flags & PERIPH_MATCH_PATH) != 0)
1831                  && (cur_pattern->path_id != periph->path->bus->path_id))
1832                         continue;
1833
1834                 /*
1835                  * For the target and lun id's, we have to make sure the
1836                  * target and lun pointers aren't NULL.  The xpt peripheral
1837                  * has a wildcard target and device.
1838                  */
1839                 if (((cur_pattern->flags & PERIPH_MATCH_TARGET) != 0)
1840                  && ((periph->path->target == NULL)
1841                  ||(cur_pattern->target_id != periph->path->target->target_id)))
1842                         continue;
1843
1844                 if (((cur_pattern->flags & PERIPH_MATCH_LUN) != 0)
1845                  && ((periph->path->device == NULL)
1846                  || (cur_pattern->target_lun != periph->path->device->lun_id)))
1847                         continue;
1848
1849                 if (((cur_pattern->flags & PERIPH_MATCH_UNIT) != 0)
1850                  && (cur_pattern->unit_number != periph->unit_number))
1851                         continue;
1852
1853                 if (((cur_pattern->flags & PERIPH_MATCH_NAME) != 0)
1854                  && (strncmp(cur_pattern->periph_name, periph->periph_name,
1855                              DEV_IDLEN) != 0))
1856                         continue;
1857
1858                 /*
1859                  * If we get to this point, the user definitely wants 
1860                  * information on this peripheral.  So tell the caller to
1861                  * copy the data out.
1862                  */
1863                 retval |= DM_RET_COPY;
1864
1865                 /*
1866                  * The return action has already been set to stop, since
1867                  * peripherals don't have any nodes below them in the EDT.
1868                  */
1869                 return(retval);
1870         }
1871
1872         /*
1873          * If we get to this point, the peripheral that was passed in
1874          * doesn't match any of the patterns.
1875          */
1876         return(retval);
1877 }
1878
1879 static int
1880 xptedtbusfunc(struct cam_eb *bus, void *arg)
1881 {
1882         struct ccb_dev_match *cdm;
1883         dev_match_ret retval;
1884
1885         cdm = (struct ccb_dev_match *)arg;
1886
1887         /*
1888          * If our position is for something deeper in the tree, that means
1889          * that we've already seen this node.  So, we keep going down.
1890          */
1891         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1892          && (cdm->pos.cookie.bus == bus)
1893          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1894          && (cdm->pos.cookie.target != NULL))
1895                 retval = DM_RET_DESCEND;
1896         else
1897                 retval = xptbusmatch(cdm->patterns, cdm->num_patterns, bus);
1898
1899         /*
1900          * If we got an error, bail out of the search.
1901          */
1902         if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
1903                 cdm->status = CAM_DEV_MATCH_ERROR;
1904                 return(0);
1905         }
1906
1907         /*
1908          * If the copy flag is set, copy this bus out.
1909          */
1910         if (retval & DM_RET_COPY) {
1911                 int spaceleft, j;
1912
1913                 spaceleft = cdm->match_buf_len - (cdm->num_matches *
1914                         sizeof(struct dev_match_result));
1915
1916                 /*
1917                  * If we don't have enough space to put in another
1918                  * match result, save our position and tell the
1919                  * user there are more devices to check.
1920                  */
1921                 if (spaceleft < sizeof(struct dev_match_result)) {
1922                         bzero(&cdm->pos, sizeof(cdm->pos));
1923                         cdm->pos.position_type = 
1924                                 CAM_DEV_POS_EDT | CAM_DEV_POS_BUS;
1925
1926                         cdm->pos.cookie.bus = bus;
1927                         cdm->pos.generations[CAM_BUS_GENERATION]=
1928                                 bus_generation;
1929                         cdm->status = CAM_DEV_MATCH_MORE;
1930                         return(0);
1931                 }
1932                 j = cdm->num_matches;
1933                 cdm->num_matches++;
1934                 cdm->matches[j].type = DEV_MATCH_BUS;
1935                 cdm->matches[j].result.bus_result.path_id = bus->path_id;
1936                 cdm->matches[j].result.bus_result.bus_id = bus->sim->bus_id;
1937                 cdm->matches[j].result.bus_result.unit_number =
1938                         bus->sim->unit_number;
1939                 strncpy(cdm->matches[j].result.bus_result.dev_name,
1940                         bus->sim->sim_name, DEV_IDLEN);
1941         }
1942
1943         /*
1944          * If the user is only interested in busses, there's no
1945          * reason to descend to the next level in the tree.
1946          */
1947         if ((retval & DM_RET_ACTION_MASK) == DM_RET_STOP)
1948                 return(1);
1949
1950         /*
1951          * If there is a target generation recorded, check it to
1952          * make sure the target list hasn't changed.
1953          */
1954         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1955          && (bus == cdm->pos.cookie.bus)
1956          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1957          && (cdm->pos.generations[CAM_TARGET_GENERATION] != 0)
1958          && (cdm->pos.generations[CAM_TARGET_GENERATION] !=
1959              bus->generation)) {
1960                 cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1961                 return(0);
1962         }
1963
1964         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1965          && (cdm->pos.cookie.bus == bus)
1966          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1967          && (cdm->pos.cookie.target != NULL))
1968                 return(xpttargettraverse(bus,
1969                                         (struct cam_et *)cdm->pos.cookie.target,
1970                                          xptedttargetfunc, arg));
1971         else
1972                 return(xpttargettraverse(bus, NULL, xptedttargetfunc, arg));
1973 }
1974
1975 static int
1976 xptedttargetfunc(struct cam_et *target, void *arg)
1977 {
1978         struct ccb_dev_match *cdm;
1979
1980         cdm = (struct ccb_dev_match *)arg;
1981
1982         /*
1983          * If there is a device list generation recorded, check it to
1984          * make sure the device list hasn't changed.
1985          */
1986         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1987          && (cdm->pos.cookie.bus == target->bus)
1988          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1989          && (cdm->pos.cookie.target == target)
1990          && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
1991          && (cdm->pos.generations[CAM_DEV_GENERATION] != 0)
1992          && (cdm->pos.generations[CAM_DEV_GENERATION] !=
1993              target->generation)) {
1994                 cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1995                 return(0);
1996         }
1997
1998         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1999          && (cdm->pos.cookie.bus == target->bus)
2000          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2001          && (cdm->pos.cookie.target == target)
2002          && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
2003          && (cdm->pos.cookie.device != NULL))
2004                 return(xptdevicetraverse(target,
2005                                         (struct cam_ed *)cdm->pos.cookie.device,
2006                                          xptedtdevicefunc, arg));
2007         else
2008                 return(xptdevicetraverse(target, NULL, xptedtdevicefunc, arg));
2009 }
2010
2011 static int
2012 xptedtdevicefunc(struct cam_ed *device, void *arg)
2013 {
2014
2015         struct ccb_dev_match *cdm;
2016         dev_match_ret retval;
2017
2018         cdm = (struct ccb_dev_match *)arg;
2019
2020         /*
2021          * If our position is for something deeper in the tree, that means
2022          * that we've already seen this node.  So, we keep going down.
2023          */
2024         if ((cdm->pos.position_type & CAM_DEV_POS_DEVICE)
2025          && (cdm->pos.cookie.device == device)
2026          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2027          && (cdm->pos.cookie.periph != NULL))
2028                 retval = DM_RET_DESCEND;
2029         else
2030                 retval = xptdevicematch(cdm->patterns, cdm->num_patterns,
2031                                         device);
2032
2033         if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
2034                 cdm->status = CAM_DEV_MATCH_ERROR;
2035                 return(0);
2036         }
2037
2038         /*
2039          * If the copy flag is set, copy this device out.
2040          */
2041         if (retval & DM_RET_COPY) {
2042                 int spaceleft, j;
2043
2044                 spaceleft = cdm->match_buf_len - (cdm->num_matches *
2045                         sizeof(struct dev_match_result));
2046
2047                 /*
2048                  * If we don't have enough space to put in another
2049                  * match result, save our position and tell the
2050                  * user there are more devices to check.
2051                  */
2052                 if (spaceleft < sizeof(struct dev_match_result)) {
2053                         bzero(&cdm->pos, sizeof(cdm->pos));
2054                         cdm->pos.position_type = 
2055                                 CAM_DEV_POS_EDT | CAM_DEV_POS_BUS |
2056                                 CAM_DEV_POS_TARGET | CAM_DEV_POS_DEVICE;
2057
2058                         cdm->pos.cookie.bus = device->target->bus;
2059                         cdm->pos.generations[CAM_BUS_GENERATION]=
2060                                 bus_generation;
2061                         cdm->pos.cookie.target = device->target;
2062                         cdm->pos.generations[CAM_TARGET_GENERATION] =
2063                                 device->target->bus->generation;
2064                         cdm->pos.cookie.device = device;
2065                         cdm->pos.generations[CAM_DEV_GENERATION] = 
2066                                 device->target->generation;
2067                         cdm->status = CAM_DEV_MATCH_MORE;
2068                         return(0);
2069                 }
2070                 j = cdm->num_matches;
2071                 cdm->num_matches++;
2072                 cdm->matches[j].type = DEV_MATCH_DEVICE;
2073                 cdm->matches[j].result.device_result.path_id =
2074                         device->target->bus->path_id;
2075                 cdm->matches[j].result.device_result.target_id =
2076                         device->target->target_id;
2077                 cdm->matches[j].result.device_result.target_lun =
2078                         device->lun_id;
2079                 bcopy(&device->inq_data,
2080                       &cdm->matches[j].result.device_result.inq_data,
2081                       sizeof(struct scsi_inquiry_data));
2082
2083                 /* Let the user know whether this device is unconfigured */
2084                 if (device->flags & CAM_DEV_UNCONFIGURED)
2085                         cdm->matches[j].result.device_result.flags =
2086                                 DEV_RESULT_UNCONFIGURED;
2087                 else
2088                         cdm->matches[j].result.device_result.flags =
2089                                 DEV_RESULT_NOFLAG;
2090         }
2091
2092         /*
2093          * If the user isn't interested in peripherals, don't descend
2094          * the tree any further.
2095          */
2096         if ((retval & DM_RET_ACTION_MASK) == DM_RET_STOP)
2097                 return(1);
2098
2099         /*
2100          * If there is a peripheral list generation recorded, make sure
2101          * it hasn't changed.
2102          */
2103         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2104          && (device->target->bus == cdm->pos.cookie.bus)
2105          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2106          && (device->target == cdm->pos.cookie.target)
2107          && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
2108          && (device == cdm->pos.cookie.device)
2109          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2110          && (cdm->pos.generations[CAM_PERIPH_GENERATION] != 0)
2111          && (cdm->pos.generations[CAM_PERIPH_GENERATION] !=
2112              device->generation)){
2113                 cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
2114                 return(0);
2115         }
2116
2117         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2118          && (cdm->pos.cookie.bus == device->target->bus)
2119          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2120          && (cdm->pos.cookie.target == device->target)
2121          && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
2122          && (cdm->pos.cookie.device == device)
2123          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2124          && (cdm->pos.cookie.periph != NULL))
2125                 return(xptperiphtraverse(device,
2126                                 (struct cam_periph *)cdm->pos.cookie.periph,
2127                                 xptedtperiphfunc, arg));
2128         else
2129                 return(xptperiphtraverse(device, NULL, xptedtperiphfunc, arg));
2130 }
2131
2132 static int
2133 xptedtperiphfunc(struct cam_periph *periph, void *arg)
2134 {
2135         struct ccb_dev_match *cdm;
2136         dev_match_ret retval;
2137
2138         cdm = (struct ccb_dev_match *)arg;
2139
2140         retval = xptperiphmatch(cdm->patterns, cdm->num_patterns, periph);
2141
2142         if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
2143                 cdm->status = CAM_DEV_MATCH_ERROR;
2144                 return(0);
2145         }
2146
2147         /*
2148          * If the copy flag is set, copy this peripheral out.
2149          */
2150         if (retval & DM_RET_COPY) {
2151                 int spaceleft, j;
2152
2153                 spaceleft = cdm->match_buf_len - (cdm->num_matches *
2154                         sizeof(struct dev_match_result));
2155
2156                 /*
2157                  * If we don't have enough space to put in another
2158                  * match result, save our position and tell the
2159                  * user there are more devices to check.
2160                  */
2161                 if (spaceleft < sizeof(struct dev_match_result)) {
2162                         bzero(&cdm->pos, sizeof(cdm->pos));
2163                         cdm->pos.position_type = 
2164                                 CAM_DEV_POS_EDT | CAM_DEV_POS_BUS |
2165                                 CAM_DEV_POS_TARGET | CAM_DEV_POS_DEVICE |
2166                                 CAM_DEV_POS_PERIPH;
2167
2168                         cdm->pos.cookie.bus = periph->path->bus;
2169                         cdm->pos.generations[CAM_BUS_GENERATION]=
2170                                 bus_generation;
2171                         cdm->pos.cookie.target = periph->path->target;
2172                         cdm->pos.generations[CAM_TARGET_GENERATION] =
2173                                 periph->path->bus->generation;
2174                         cdm->pos.cookie.device = periph->path->device;
2175                         cdm->pos.generations[CAM_DEV_GENERATION] = 
2176                                 periph->path->target->generation;
2177                         cdm->pos.cookie.periph = periph;
2178                         cdm->pos.generations[CAM_PERIPH_GENERATION] =
2179                                 periph->path->device->generation;
2180                         cdm->status = CAM_DEV_MATCH_MORE;
2181                         return(0);
2182                 }
2183
2184                 j = cdm->num_matches;
2185                 cdm->num_matches++;
2186                 cdm->matches[j].type = DEV_MATCH_PERIPH;
2187                 cdm->matches[j].result.periph_result.path_id =
2188                         periph->path->bus->path_id;
2189                 cdm->matches[j].result.periph_result.target_id =
2190                         periph->path->target->target_id;
2191                 cdm->matches[j].result.periph_result.target_lun =
2192                         periph->path->device->lun_id;
2193                 cdm->matches[j].result.periph_result.unit_number =
2194                         periph->unit_number;
2195                 strncpy(cdm->matches[j].result.periph_result.periph_name,
2196                         periph->periph_name, DEV_IDLEN);
2197         }
2198
2199         return(1);
2200 }
2201
2202 static int
2203 xptedtmatch(struct ccb_dev_match *cdm)
2204 {
2205         int ret;
2206
2207         cdm->num_matches = 0;
2208
2209         /*
2210          * Check the bus list generation.  If it has changed, the user
2211          * needs to reset everything and start over.
2212          */
2213         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2214          && (cdm->pos.generations[CAM_BUS_GENERATION] != 0)
2215          && (cdm->pos.generations[CAM_BUS_GENERATION] != bus_generation)) {
2216                 cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
2217                 return(0);
2218         }
2219
2220         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2221          && (cdm->pos.cookie.bus != NULL))
2222                 ret = xptbustraverse((struct cam_eb *)cdm->pos.cookie.bus,
2223                                      xptedtbusfunc, cdm);
2224         else
2225                 ret = xptbustraverse(NULL, xptedtbusfunc, cdm);
2226
2227         /*
2228          * If we get back 0, that means that we had to stop before fully
2229          * traversing the EDT.  It also means that one of the subroutines
2230          * has set the status field to the proper value.  If we get back 1,
2231          * we've fully traversed the EDT and copied out any matching entries.
2232          */
2233         if (ret == 1)
2234                 cdm->status = CAM_DEV_MATCH_LAST;
2235
2236         return(ret);
2237 }
2238
2239 static int
2240 xptplistpdrvfunc(struct periph_driver **pdrv, void *arg)
2241 {
2242         struct ccb_dev_match *cdm;
2243
2244         cdm = (struct ccb_dev_match *)arg;
2245
2246         if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
2247          && (cdm->pos.cookie.pdrv == pdrv)
2248          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2249          && (cdm->pos.generations[CAM_PERIPH_GENERATION] != 0)
2250          && (cdm->pos.generations[CAM_PERIPH_GENERATION] !=
2251              (*pdrv)->generation)) {
2252                 cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
2253                 return(0);
2254         }
2255
2256         if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
2257          && (cdm->pos.cookie.pdrv == pdrv)
2258          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2259          && (cdm->pos.cookie.periph != NULL))
2260                 return(xptpdperiphtraverse(pdrv,
2261                                 (struct cam_periph *)cdm->pos.cookie.periph,
2262                                 xptplistperiphfunc, arg));
2263         else
2264                 return(xptpdperiphtraverse(pdrv, NULL,xptplistperiphfunc, arg));
2265 }
2266
2267 static int
2268 xptplistperiphfunc(struct cam_periph *periph, void *arg)
2269 {
2270         struct ccb_dev_match *cdm;
2271         dev_match_ret retval;
2272
2273         cdm = (struct ccb_dev_match *)arg;
2274
2275         retval = xptperiphmatch(cdm->patterns, cdm->num_patterns, periph);
2276
2277         if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
2278                 cdm->status = CAM_DEV_MATCH_ERROR;
2279                 return(0);
2280         }
2281
2282         /*
2283          * If the copy flag is set, copy this peripheral out.
2284          */
2285         if (retval & DM_RET_COPY) {
2286                 int spaceleft, j;
2287
2288                 spaceleft = cdm->match_buf_len - (cdm->num_matches *
2289                         sizeof(struct dev_match_result));
2290
2291                 /*
2292                  * If we don't have enough space to put in another
2293                  * match result, save our position and tell the
2294                  * user there are more devices to check.
2295                  */
2296                 if (spaceleft < sizeof(struct dev_match_result)) {
2297                         struct periph_driver **pdrv;
2298
2299                         pdrv = NULL;
2300                         bzero(&cdm->pos, sizeof(cdm->pos));
2301                         cdm->pos.position_type = 
2302                                 CAM_DEV_POS_PDRV | CAM_DEV_POS_PDPTR |
2303                                 CAM_DEV_POS_PERIPH;
2304
2305                         /*
2306                          * This may look a bit non-sensical, but it is
2307                          * actually quite logical.  There are very few
2308                          * peripheral drivers, and bloating every peripheral
2309                          * structure with a pointer back to its parent
2310                          * peripheral driver linker set entry would cost
2311                          * more in the long run than doing this quick lookup.
2312                          */
2313                         SET_FOREACH(pdrv, periphdriver_set) {
2314                                 if (strcmp((*pdrv)->driver_name,
2315                                     periph->periph_name) == 0)
2316                                         break;
2317                         }
2318
2319                         if (*pdrv == NULL) {
2320                                 cdm->status = CAM_DEV_MATCH_ERROR;
2321                                 return(0);
2322                         }
2323
2324                         cdm->pos.cookie.pdrv = pdrv;
2325                         /*
2326                          * The periph generation slot does double duty, as
2327                          * does the periph pointer slot.  They are used for
2328                          * both edt and pdrv lookups and positioning.
2329                          */
2330                         cdm->pos.cookie.periph = periph;
2331                         cdm->pos.generations[CAM_PERIPH_GENERATION] =
2332                                 (*pdrv)->generation;
2333                         cdm->status = CAM_DEV_MATCH_MORE;
2334                         return(0);
2335                 }
2336
2337                 j = cdm->num_matches;
2338                 cdm->num_matches++;
2339                 cdm->matches[j].type = DEV_MATCH_PERIPH;
2340                 cdm->matches[j].result.periph_result.path_id =
2341                         periph->path->bus->path_id;
2342
2343                 /*
2344                  * The transport layer peripheral doesn't have a target or
2345                  * lun.
2346                  */
2347                 if (periph->path->target)
2348                         cdm->matches[j].result.periph_result.target_id =
2349                                 periph->path->target->target_id;
2350                 else
2351                         cdm->matches[j].result.periph_result.target_id = -1;
2352
2353                 if (periph->path->device)
2354                         cdm->matches[j].result.periph_result.target_lun =
2355                                 periph->path->device->lun_id;
2356                 else
2357                         cdm->matches[j].result.periph_result.target_lun = -1;
2358
2359                 cdm->matches[j].result.periph_result.unit_number =
2360                         periph->unit_number;
2361                 strncpy(cdm->matches[j].result.periph_result.periph_name,
2362                         periph->periph_name, DEV_IDLEN);
2363         }
2364
2365         return(1);
2366 }
2367
2368 static int
2369 xptperiphlistmatch(struct ccb_dev_match *cdm)
2370 {
2371         int ret;
2372
2373         cdm->num_matches = 0;
2374
2375         /*
2376          * At this point in the edt traversal function, we check the bus
2377          * list generation to make sure that no busses have been added or
2378          * removed since the user last sent a XPT_DEV_MATCH ccb through.
2379          * For the peripheral driver list traversal function, however, we
2380          * don't have to worry about new peripheral driver types coming or
2381          * going; they're in a linker set, and therefore can't change
2382          * without a recompile.
2383          */
2384
2385         if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
2386          && (cdm->pos.cookie.pdrv != NULL))
2387                 ret = xptpdrvtraverse(
2388                                 (struct periph_driver **)cdm->pos.cookie.pdrv,
2389                                 xptplistpdrvfunc, cdm);
2390         else
2391                 ret = xptpdrvtraverse(NULL, xptplistpdrvfunc, cdm);
2392
2393         /*
2394          * If we get back 0, that means that we had to stop before fully
2395          * traversing the peripheral driver tree.  It also means that one of
2396          * the subroutines has set the status field to the proper value.  If
2397          * we get back 1, we've fully traversed the EDT and copied out any
2398          * matching entries.
2399          */
2400         if (ret == 1)
2401                 cdm->status = CAM_DEV_MATCH_LAST;
2402
2403         return(ret);
2404 }
2405
2406 static int
2407 xptbustraverse(struct cam_eb *start_bus, xpt_busfunc_t *tr_func, void *arg)
2408 {
2409         struct cam_eb *bus, *next_bus;
2410         int retval;
2411
2412         retval = 1;
2413
2414         for (bus = (start_bus ? start_bus : TAILQ_FIRST(&xpt_busses));
2415              bus != NULL;
2416              bus = next_bus) {
2417                 next_bus = TAILQ_NEXT(bus, links);
2418
2419                 retval = tr_func(bus, arg);
2420                 if (retval == 0)
2421                         return(retval);
2422         }
2423
2424         return(retval);
2425 }
2426
2427 static int
2428 xpttargettraverse(struct cam_eb *bus, struct cam_et *start_target,
2429                   xpt_targetfunc_t *tr_func, void *arg)
2430 {
2431         struct cam_et *target, *next_target;
2432         int retval;
2433
2434         retval = 1;
2435         for (target = (start_target ? start_target :
2436                        TAILQ_FIRST(&bus->et_entries));
2437              target != NULL; target = next_target) {
2438
2439                 next_target = TAILQ_NEXT(target, links);
2440
2441                 retval = tr_func(target, arg);
2442
2443                 if (retval == 0)
2444                         return(retval);
2445         }
2446
2447         return(retval);
2448 }
2449
2450 static int
2451 xptdevicetraverse(struct cam_et *target, struct cam_ed *start_device,
2452                   xpt_devicefunc_t *tr_func, void *arg)
2453 {
2454         struct cam_ed *device, *next_device;
2455         int retval;
2456
2457         retval = 1;
2458         for (device = (start_device ? start_device :
2459                        TAILQ_FIRST(&target->ed_entries));
2460              device != NULL;
2461              device = next_device) {
2462
2463                 next_device = TAILQ_NEXT(device, links);
2464
2465                 retval = tr_func(device, arg);
2466
2467                 if (retval == 0)
2468                         return(retval);
2469         }
2470
2471         return(retval);
2472 }
2473
2474 static int
2475 xptperiphtraverse(struct cam_ed *device, struct cam_periph *start_periph,
2476                   xpt_periphfunc_t *tr_func, void *arg)
2477 {
2478         struct cam_periph *periph, *next_periph;
2479         int retval;
2480
2481         retval = 1;
2482
2483         for (periph = (start_periph ? start_periph :
2484                        SLIST_FIRST(&device->periphs));
2485              periph != NULL;
2486              periph = next_periph) {
2487
2488                 next_periph = SLIST_NEXT(periph, periph_links);
2489
2490                 retval = tr_func(periph, arg);
2491                 if (retval == 0)
2492                         return(retval);
2493         }
2494
2495         return(retval);
2496 }
2497
2498 static int
2499 xptpdrvtraverse(struct periph_driver **start_pdrv,
2500                 xpt_pdrvfunc_t *tr_func, void *arg)
2501 {
2502         struct periph_driver **pdrv;
2503         int retval;
2504
2505         retval = 1;
2506
2507         /*
2508          * We don't traverse the peripheral driver list like we do the
2509          * other lists, because it is a linker set, and therefore cannot be
2510          * changed during runtime.  If the peripheral driver list is ever
2511          * re-done to be something other than a linker set (i.e. it can
2512          * change while the system is running), the list traversal should
2513          * be modified to work like the other traversal functions.
2514          */
2515         SET_FOREACH(pdrv, periphdriver_set) {
2516                 if (start_pdrv == NULL || start_pdrv == pdrv) {
2517                         retval = tr_func(pdrv, arg);
2518                         if (retval == 0)
2519                                 return(retval);
2520                         start_pdrv = NULL; /* traverse remainder */
2521                 }
2522         }
2523         return(retval);
2524 }
2525
2526 static int
2527 xptpdperiphtraverse(struct periph_driver **pdrv,
2528                     struct cam_periph *start_periph,
2529                     xpt_periphfunc_t *tr_func, void *arg)
2530 {
2531         struct cam_periph *periph, *next_periph;
2532         int retval;
2533
2534         retval = 1;
2535
2536         for (periph = (start_periph ? start_periph :
2537              TAILQ_FIRST(&(*pdrv)->units)); periph != NULL;
2538              periph = next_periph) {
2539
2540                 next_periph = TAILQ_NEXT(periph, unit_links);
2541
2542                 retval = tr_func(periph, arg);
2543                 if (retval == 0)
2544                         return(retval);
2545         }
2546         return(retval);
2547 }
2548
2549 static int
2550 xptdefbusfunc(struct cam_eb *bus, void *arg)
2551 {
2552         struct xpt_traverse_config *tr_config;
2553
2554         tr_config = (struct xpt_traverse_config *)arg;
2555
2556         if (tr_config->depth == XPT_DEPTH_BUS) {
2557                 xpt_busfunc_t *tr_func;
2558
2559                 tr_func = (xpt_busfunc_t *)tr_config->tr_func;
2560
2561                 return(tr_func(bus, tr_config->tr_arg));
2562         } else
2563                 return(xpttargettraverse(bus, NULL, xptdeftargetfunc, arg));
2564 }
2565
2566 static int
2567 xptdeftargetfunc(struct cam_et *target, void *arg)
2568 {
2569         struct xpt_traverse_config *tr_config;
2570
2571         tr_config = (struct xpt_traverse_config *)arg;
2572
2573         if (tr_config->depth == XPT_DEPTH_TARGET) {
2574                 xpt_targetfunc_t *tr_func;
2575
2576                 tr_func = (xpt_targetfunc_t *)tr_config->tr_func;
2577
2578                 return(tr_func(target, tr_config->tr_arg));
2579         } else
2580                 return(xptdevicetraverse(target, NULL, xptdefdevicefunc, arg));
2581 }
2582
2583 static int
2584 xptdefdevicefunc(struct cam_ed *device, void *arg)
2585 {
2586         struct xpt_traverse_config *tr_config;
2587
2588         tr_config = (struct xpt_traverse_config *)arg;
2589
2590         if (tr_config->depth == XPT_DEPTH_DEVICE) {
2591                 xpt_devicefunc_t *tr_func;
2592
2593                 tr_func = (xpt_devicefunc_t *)tr_config->tr_func;
2594
2595                 return(tr_func(device, tr_config->tr_arg));
2596         } else
2597                 return(xptperiphtraverse(device, NULL, xptdefperiphfunc, arg));
2598 }
2599
2600 static int
2601 xptdefperiphfunc(struct cam_periph *periph, void *arg)
2602 {
2603         struct xpt_traverse_config *tr_config;
2604         xpt_periphfunc_t *tr_func;
2605
2606         tr_config = (struct xpt_traverse_config *)arg;
2607
2608         tr_func = (xpt_periphfunc_t *)tr_config->tr_func;
2609
2610         /*
2611          * Unlike the other default functions, we don't check for depth
2612          * here.  The peripheral driver level is the last level in the EDT,
2613          * so if we're here, we should execute the function in question.
2614          */
2615         return(tr_func(periph, tr_config->tr_arg));
2616 }
2617
2618 /*
2619  * Execute the given function for every bus in the EDT.
2620  */
2621 static int
2622 xpt_for_all_busses(xpt_busfunc_t *tr_func, void *arg)
2623 {
2624         struct xpt_traverse_config tr_config;
2625
2626         tr_config.depth = XPT_DEPTH_BUS;
2627         tr_config.tr_func = tr_func;
2628         tr_config.tr_arg = arg;
2629
2630         return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2631 }
2632
2633 #ifdef notusedyet
2634 /*
2635  * Execute the given function for every target in the EDT.
2636  */
2637 static int
2638 xpt_for_all_targets(xpt_targetfunc_t *tr_func, void *arg)
2639 {
2640         struct xpt_traverse_config tr_config;
2641
2642         tr_config.depth = XPT_DEPTH_TARGET;
2643         tr_config.tr_func = tr_func;
2644         tr_config.tr_arg = arg;
2645
2646         return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2647 }
2648 #endif /* notusedyet */
2649
2650 /*
2651  * Execute the given function for every device in the EDT.
2652  */
2653 static int
2654 xpt_for_all_devices(xpt_devicefunc_t *tr_func, void *arg)
2655 {
2656         struct xpt_traverse_config tr_config;
2657
2658         tr_config.depth = XPT_DEPTH_DEVICE;
2659         tr_config.tr_func = tr_func;
2660         tr_config.tr_arg = arg;
2661
2662         return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2663 }
2664
2665 #ifdef notusedyet
2666 /*
2667  * Execute the given function for every peripheral in the EDT.
2668  */
2669 static int
2670 xpt_for_all_periphs(xpt_periphfunc_t *tr_func, void *arg)
2671 {
2672         struct xpt_traverse_config tr_config;
2673
2674         tr_config.depth = XPT_DEPTH_PERIPH;
2675         tr_config.tr_func = tr_func;
2676         tr_config.tr_arg = arg;
2677
2678         return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2679 }
2680 #endif /* notusedyet */
2681
2682 static int
2683 xptsetasyncfunc(struct cam_ed *device, void *arg)
2684 {
2685         struct cam_path path;
2686         struct ccb_getdev cgd;
2687         struct async_node *cur_entry;
2688
2689         cur_entry = (struct async_node *)arg;
2690
2691         /*
2692          * Don't report unconfigured devices (Wildcard devs,
2693          * devices only for target mode, device instances
2694          * that have been invalidated but are waiting for
2695          * their last reference count to be released).
2696          */
2697         if ((device->flags & CAM_DEV_UNCONFIGURED) != 0)
2698                 return (1);
2699
2700         xpt_compile_path(&path,
2701                          NULL,
2702                          device->target->bus->path_id,
2703                          device->target->target_id,
2704                          device->lun_id);
2705         xpt_setup_ccb(&cgd.ccb_h, &path, /*priority*/1);
2706         cgd.ccb_h.func_code = XPT_GDEV_TYPE;
2707         xpt_action((union ccb *)&cgd);
2708         cur_entry->callback(cur_entry->callback_arg,
2709                             AC_FOUND_DEVICE,
2710                             &path, &cgd);
2711         xpt_release_path(&path);
2712
2713         return(1);
2714 }
2715
2716 static int
2717 xptsetasyncbusfunc(struct cam_eb *bus, void *arg)
2718 {
2719         struct cam_path path;
2720         struct ccb_pathinq cpi;
2721         struct async_node *cur_entry;
2722
2723         cur_entry = (struct async_node *)arg;
2724
2725         xpt_compile_path(&path, /*periph*/NULL,
2726                          bus->sim->path_id,
2727                          CAM_TARGET_WILDCARD,
2728                          CAM_LUN_WILDCARD);
2729         xpt_setup_ccb(&cpi.ccb_h, &path, /*priority*/1);
2730         cpi.ccb_h.func_code = XPT_PATH_INQ;
2731         xpt_action((union ccb *)&cpi);
2732         cur_entry->callback(cur_entry->callback_arg,
2733                             AC_PATH_REGISTERED,
2734                             &path, &cpi);
2735         xpt_release_path(&path);
2736
2737         return(1);
2738 }
2739
2740 void
2741 xpt_action(union ccb *start_ccb)
2742 {
2743         CAM_DEBUG(start_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("xpt_action\n"));
2744
2745         start_ccb->ccb_h.status = CAM_REQ_INPROG;
2746
2747         crit_enter();
2748
2749         switch (start_ccb->ccb_h.func_code) {
2750         case XPT_SCSI_IO:
2751         {
2752 #ifdef CAMDEBUG
2753                 char cdb_str[(SCSI_MAX_CDBLEN * 3) + 1];
2754                 struct cam_path *path;
2755
2756                 path = start_ccb->ccb_h.path;
2757 #endif
2758
2759                 /*
2760                  * For the sake of compatibility with SCSI-1
2761                  * devices that may not understand the identify
2762                  * message, we include lun information in the
2763                  * second byte of all commands.  SCSI-1 specifies
2764                  * that luns are a 3 bit value and reserves only 3
2765                  * bits for lun information in the CDB.  Later
2766                  * revisions of the SCSI spec allow for more than 8
2767                  * luns, but have deprecated lun information in the
2768                  * CDB.  So, if the lun won't fit, we must omit.
2769                  *
2770                  * Also be aware that during initial probing for devices,
2771                  * the inquiry information is unknown but initialized to 0.
2772                  * This means that this code will be exercised while probing
2773                  * devices with an ANSI revision greater than 2.
2774                  */
2775                 if (SID_ANSI_REV(&start_ccb->ccb_h.path->device->inq_data) <= 2
2776                  && start_ccb->ccb_h.target_lun < 8
2777                  && (start_ccb->ccb_h.flags & CAM_CDB_POINTER) == 0) {
2778
2779                         start_ccb->csio.cdb_io.cdb_bytes[1] |=
2780                             start_ccb->ccb_h.target_lun << 5;
2781                 }
2782                 start_ccb->csio.scsi_status = SCSI_STATUS_OK;
2783                 CAM_DEBUG(path, CAM_DEBUG_CDB,("%s. CDB: %s\n",
2784                           scsi_op_desc(start_ccb->csio.cdb_io.cdb_bytes[0],
2785                                        &path->device->inq_data),
2786                           scsi_cdb_string(start_ccb->csio.cdb_io.cdb_bytes,
2787                                           cdb_str, sizeof(cdb_str))));
2788                 /* FALLTHROUGH */
2789         }
2790         case XPT_TARGET_IO:
2791         case XPT_CONT_TARGET_IO:
2792                 start_ccb->csio.sense_resid = 0;
2793                 start_ccb->csio.resid = 0;
2794                 /* FALLTHROUGH */
2795         case XPT_RESET_DEV:
2796         case XPT_ENG_EXEC:
2797         {
2798                 struct cam_path *path;
2799                 int runq;
2800
2801                 path = start_ccb->ccb_h.path;
2802
2803                 cam_ccbq_insert_ccb(&path->device->ccbq, start_ccb);
2804                 if (path->device->qfrozen_cnt == 0)
2805                         runq = xpt_schedule_dev_sendq(path->bus, path->device);
2806                 else
2807                         runq = 0;
2808                 if (runq != 0)
2809                         xpt_run_dev_sendq(path->bus);
2810                 break;
2811         }
2812         case XPT_SET_TRAN_SETTINGS:
2813         {
2814                 xpt_set_transfer_settings(&start_ccb->cts,
2815                                           start_ccb->ccb_h.path->device,
2816                                           /*async_update*/FALSE);
2817                 break;
2818         }
2819         case XPT_CALC_GEOMETRY:
2820         {
2821                 struct cam_sim *sim;
2822
2823                 /* Filter out garbage */
2824                 if (start_ccb->ccg.block_size == 0
2825                  || start_ccb->ccg.volume_size == 0) {
2826                         start_ccb->ccg.cylinders = 0;
2827                         start_ccb->ccg.heads = 0;
2828                         start_ccb->ccg.secs_per_track = 0;
2829                         start_ccb->ccb_h.status = CAM_REQ_CMP;
2830                         break;
2831                 }
2832                 sim = start_ccb->ccb_h.path->bus->sim;
2833                 (*(sim->sim_action))(sim, start_ccb);
2834                 break;
2835         }
2836         case XPT_ABORT:
2837         {
2838                 union ccb* abort_ccb;
2839
2840                 abort_ccb = start_ccb->cab.abort_ccb;
2841                 if (XPT_FC_IS_DEV_QUEUED(abort_ccb)) {
2842
2843                         if (abort_ccb->ccb_h.pinfo.index >= 0) {
2844                                 struct cam_ccbq *ccbq;
2845
2846                                 ccbq = &abort_ccb->ccb_h.path->device->ccbq;
2847                                 cam_ccbq_remove_ccb(ccbq, abort_ccb);
2848                                 abort_ccb->ccb_h.status =
2849                                     CAM_REQ_ABORTED|CAM_DEV_QFRZN;
2850                                 xpt_freeze_devq(abort_ccb->ccb_h.path, 1);
2851                                 xpt_done(abort_ccb);
2852                                 start_ccb->ccb_h.status = CAM_REQ_CMP;
2853                                 break;
2854                         }
2855                         if (abort_ccb->ccb_h.pinfo.index == CAM_UNQUEUED_INDEX
2856                          && (abort_ccb->ccb_h.status & CAM_SIM_QUEUED) == 0) {
2857                                 /*
2858                                  * We've caught this ccb en route to
2859                                  * the SIM.  Flag it for abort and the
2860                                  * SIM will do so just before starting
2861                                  * real work on the CCB.
2862                                  */
2863                                 abort_ccb->ccb_h.status =
2864                                     CAM_REQ_ABORTED|CAM_DEV_QFRZN;
2865                                 xpt_freeze_devq(abort_ccb->ccb_h.path, 1);
2866                                 start_ccb->ccb_h.status = CAM_REQ_CMP;
2867                                 break;
2868                         }
2869                 } 
2870                 if (XPT_FC_IS_QUEUED(abort_ccb)
2871                  && (abort_ccb->ccb_h.pinfo.index == CAM_DONEQ_INDEX)) {
2872                         /*
2873                          * It's already completed but waiting
2874                          * for our SWI to get to it.
2875                          */
2876                         start_ccb->ccb_h.status = CAM_UA_ABORT;
2877                         break;
2878                 }
2879                 /*
2880                  * If we weren't able to take care of the abort request
2881                  * in the XPT, pass the request down to the SIM for processing.
2882                  */
2883                 /* FALLTHROUGH */
2884         }
2885         case XPT_ACCEPT_TARGET_IO:
2886         case XPT_EN_LUN:
2887         case XPT_IMMED_NOTIFY:
2888         case XPT_NOTIFY_ACK:
2889         case XPT_GET_TRAN_SETTINGS:
2890         case XPT_RESET_BUS:
2891         {
2892                 struct cam_sim *sim;
2893
2894                 sim = start_ccb->ccb_h.path->bus->sim;
2895                 (*(sim->sim_action))(sim, start_ccb);
2896                 break;
2897         }
2898         case XPT_PATH_INQ:
2899         {
2900                 struct cam_sim *sim;
2901
2902                 sim = start_ccb->ccb_h.path->bus->sim;
2903                 (*(sim->sim_action))(sim, start_ccb);
2904                 break;
2905         }
2906         case XPT_PATH_STATS:
2907                 start_ccb->cpis.last_reset =
2908                         start_ccb->ccb_h.path->bus->last_reset;
2909                 start_ccb->ccb_h.status = CAM_REQ_CMP;
2910                 break;
2911         case XPT_GDEV_TYPE:
2912         {
2913                 struct cam_ed *dev;
2914
2915                 dev = start_ccb->ccb_h.path->device;
2916                 if ((dev->flags & CAM_DEV_UNCONFIGURED) != 0) {
2917                         start_ccb->ccb_h.status = CAM_DEV_NOT_THERE;
2918                 } else {
2919                         struct ccb_getdev *cgd;
2920                         struct cam_eb *bus;
2921                         struct cam_et *tar;
2922
2923                         cgd = &start_ccb->cgd;
2924                         bus = cgd->ccb_h.path->bus;
2925                         tar = cgd->ccb_h.path->target;
2926                         cgd->inq_data = dev->inq_data;
2927                         cgd->ccb_h.status = CAM_REQ_CMP;
2928                         cgd->serial_num_len = dev->serial_num_len;
2929                         if ((dev->serial_num_len > 0)
2930                          && (dev->serial_num != NULL))
2931                                 bcopy(dev->serial_num, cgd->serial_num,
2932                                       dev->serial_num_len);
2933                 }
2934                 break; 
2935         }
2936         case XPT_GDEV_STATS:
2937         {
2938                 struct cam_ed *dev;
2939
2940                 dev = start_ccb->ccb_h.path->device;
2941                 if ((dev->flags & CAM_DEV_UNCONFIGURED) != 0) {
2942                         start_ccb->ccb_h.status = CAM_DEV_NOT_THERE;
2943                 } else {
2944                         struct ccb_getdevstats *cgds;
2945                         struct cam_eb *bus;
2946                         struct cam_et *tar;
2947
2948                         cgds = &start_ccb->cgds;
2949                         bus = cgds->ccb_h.path->bus;
2950                         tar = cgds->ccb_h.path->target;
2951                         cgds->dev_openings = dev->ccbq.dev_openings;
2952                         cgds->dev_active = dev->ccbq.dev_active;
2953                         cgds->devq_openings = dev->ccbq.devq_openings;
2954                         cgds->devq_queued = dev->ccbq.queue.entries;
2955                         cgds->held = dev->ccbq.held;
2956                         cgds->last_reset = tar->last_reset;
2957                         cgds->maxtags = dev->quirk->maxtags;
2958                         cgds->mintags = dev->quirk->mintags;
2959                         if (timevalcmp(&tar->last_reset, &bus->last_reset, <))
2960                                 cgds->last_reset = bus->last_reset;
2961                         cgds->ccb_h.status = CAM_REQ_CMP;
2962                 }
2963                 break;
2964         }
2965         case XPT_GDEVLIST:
2966         {
2967                 struct cam_periph       *nperiph;
2968                 struct periph_list      *periph_head;
2969                 struct ccb_getdevlist   *cgdl;
2970                 int                     i;
2971                 struct cam_ed           *device;
2972                 int                     found;
2973
2974
2975                 found = 0;
2976
2977                 /*
2978                  * Don't want anyone mucking with our data.
2979                  */
2980                 device = start_ccb->ccb_h.path->device;
2981                 periph_head = &device->periphs;
2982                 cgdl = &start_ccb->cgdl;
2983
2984                 /*
2985                  * Check and see if the list has changed since the user
2986                  * last requested a list member.  If so, tell them that the
2987                  * list has changed, and therefore they need to start over 
2988                  * from the beginning.
2989                  */
2990                 if ((cgdl->index != 0) && 
2991                     (cgdl->generation != device->generation)) {
2992                         cgdl->status = CAM_GDEVLIST_LIST_CHANGED;
2993                         break;
2994                 }
2995
2996                 /*
2997                  * Traverse the list of peripherals and attempt to find 
2998                  * the requested peripheral.
2999                  */
3000                 for (nperiph = periph_head->slh_first, i = 0;
3001                      (nperiph != NULL) && (i <= cgdl->index);
3002                      nperiph = nperiph->periph_links.sle_next, i++) {
3003                         if (i == cgdl->index) {
3004                                 strncpy(cgdl->periph_name,
3005                                         nperiph->periph_name,
3006                                         DEV_IDLEN);
3007                                 cgdl->unit_number = nperiph->unit_number;
3008                                 found = 1;
3009                         }
3010                 }
3011                 if (found == 0) {
3012                         cgdl->status = CAM_GDEVLIST_ERROR;
3013                         break;
3014                 }
3015
3016                 if (nperiph == NULL)
3017                         cgdl->status = CAM_GDEVLIST_LAST_DEVICE;
3018                 else
3019                         cgdl->status = CAM_GDEVLIST_MORE_DEVS;
3020
3021                 cgdl->index++;
3022                 cgdl->generation = device->generation;
3023
3024                 cgdl->ccb_h.status = CAM_REQ_CMP;
3025                 break;
3026         }
3027         case XPT_DEV_MATCH:
3028         {
3029                 dev_pos_type position_type;
3030                 struct ccb_dev_match *cdm;
3031                 int ret;
3032
3033                 cdm = &start_ccb->cdm;
3034
3035                 /*
3036                  * Prevent EDT changes while we traverse it.
3037                  */
3038                 /*
3039                  * There are two ways of getting at information in the EDT.
3040                  * The first way is via the primary EDT tree.  It starts
3041                  * with a list of busses, then a list of targets on a bus,
3042                  * then devices/luns on a target, and then peripherals on a
3043                  * device/lun.  The "other" way is by the peripheral driver
3044                  * lists.  The peripheral driver lists are organized by
3045                  * peripheral driver.  (obviously)  So it makes sense to
3046                  * use the peripheral driver list if the user is looking
3047                  * for something like "da1", or all "da" devices.  If the
3048                  * user is looking for something on a particular bus/target
3049                  * or lun, it's generally better to go through the EDT tree.
3050                  */
3051
3052                 if (cdm->pos.position_type != CAM_DEV_POS_NONE)
3053                         position_type = cdm->pos.position_type;
3054                 else {
3055                         int i;
3056
3057                         position_type = CAM_DEV_POS_NONE;
3058
3059                         for (i = 0; i < cdm->num_patterns; i++) {
3060                                 if ((cdm->patterns[i].type == DEV_MATCH_BUS)
3061                                  ||(cdm->patterns[i].type == DEV_MATCH_DEVICE)){
3062                                         position_type = CAM_DEV_POS_EDT;
3063                                         break;
3064                                 }
3065                         }
3066
3067                         if (cdm->num_patterns == 0)
3068                                 position_type = CAM_DEV_POS_EDT;
3069                         else if (position_type == CAM_DEV_POS_NONE)
3070                                 position_type = CAM_DEV_POS_PDRV;
3071                 }
3072
3073                 switch(position_type & CAM_DEV_POS_TYPEMASK) {
3074                 case CAM_DEV_POS_EDT:
3075                         ret = xptedtmatch(cdm);
3076                         break;
3077                 case CAM_DEV_POS_PDRV:
3078                         ret = xptperiphlistmatch(cdm);
3079                         break;
3080                 default:
3081                         cdm->status = CAM_DEV_MATCH_ERROR;
3082                         break;
3083                 }
3084
3085                 if (cdm->status == CAM_DEV_MATCH_ERROR)
3086                         start_ccb->ccb_h.status = CAM_REQ_CMP_ERR;
3087                 else
3088                         start_ccb->ccb_h.status = CAM_REQ_CMP;
3089
3090                 break;
3091         }
3092         case XPT_SASYNC_CB:
3093         {
3094                 struct ccb_setasync *csa;
3095                 struct async_node *cur_entry;
3096                 struct async_list *async_head;
3097                 u_int32_t added;
3098
3099                 csa = &start_ccb->csa;
3100                 added = csa->event_enable;
3101                 async_head = &csa->ccb_h.path->device->asyncs;
3102
3103                 /*
3104                  * If there is already an entry for us, simply
3105                  * update it.
3106                  */
3107                 cur_entry = SLIST_FIRST(async_head);
3108                 while (cur_entry != NULL) {
3109                         if ((cur_entry->callback_arg == csa->callback_arg)
3110                          && (cur_entry->callback == csa->callback))
3111                                 break;
3112                         cur_entry = SLIST_NEXT(cur_entry, links);
3113                 }
3114
3115                 if (cur_entry != NULL) {
3116                         /*
3117                          * If the request has no flags set,
3118                          * remove the entry.
3119                          */
3120                         added &= ~cur_entry->event_enable;
3121                         if (csa->event_enable == 0) {
3122                                 SLIST_REMOVE(async_head, cur_entry,
3123                                              async_node, links);
3124                                 csa->ccb_h.path->device->refcount--;
3125                                 kfree(cur_entry, M_DEVBUF);
3126                         } else {
3127                                 cur_entry->event_enable = csa->event_enable;
3128                         }
3129                 } else {
3130                         cur_entry = kmalloc(sizeof(*cur_entry), 
3131                                             M_DEVBUF, M_INTWAIT);
3132                         cur_entry->event_enable = csa->event_enable;
3133                         cur_entry->callback_arg = csa->callback_arg;
3134                         cur_entry->callback = csa->callback;
3135                         SLIST_INSERT_HEAD(async_head, cur_entry, links);
3136                         csa->ccb_h.path->device->refcount++;
3137                 }
3138
3139                 if ((added & AC_FOUND_DEVICE) != 0) {
3140                         /*
3141                          * Get this peripheral up to date with all
3142                          * the currently existing devices.
3143                          */
3144                         xpt_for_all_devices(xptsetasyncfunc, cur_entry);
3145                 }
3146                 if ((added & AC_PATH_REGISTERED) != 0) {
3147                         /*
3148                          * Get this peripheral up to date with all
3149                          * the currently existing busses.
3150                          */
3151                         xpt_for_all_busses(xptsetasyncbusfunc, cur_entry);
3152                 }
3153                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3154                 break;
3155         }
3156         case XPT_REL_SIMQ:
3157         {
3158                 struct ccb_relsim *crs;
3159                 struct cam_ed *dev;
3160
3161                 crs = &start_ccb->crs;
3162                 dev = crs->ccb_h.path->device;
3163                 if (dev == NULL) {
3164
3165                         crs->ccb_h.status = CAM_DEV_NOT_THERE;
3166                         break;
3167                 }
3168
3169                 if ((crs->release_flags & RELSIM_ADJUST_OPENINGS) != 0) {
3170
3171                         if ((dev->inq_data.flags & SID_CmdQue) != 0) {
3172
3173                                 /* Don't ever go below one opening */
3174                                 if (crs->openings > 0) {
3175                                         xpt_dev_ccbq_resize(crs->ccb_h.path,
3176                                                             crs->openings);
3177
3178                                         if (bootverbose) {
3179                                                 xpt_print_path(crs->ccb_h.path);
3180                                                 printf("tagged openings "
3181                                                        "now %d\n",
3182                                                        crs->openings);
3183                                         }
3184                                 }
3185                         }
3186                 }
3187
3188                 if ((crs->release_flags & RELSIM_RELEASE_AFTER_TIMEOUT) != 0) {
3189
3190                         if ((dev->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
3191
3192                                 /*
3193                                  * Just extend the old timeout and decrement
3194                                  * the freeze count so that a single timeout
3195                                  * is sufficient for releasing the queue.
3196                                  */
3197                                 start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
3198                                 callout_stop(&dev->c_handle);
3199                         } else {
3200
3201                                 start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
3202                         }
3203
3204                         callout_reset(&dev->c_handle,
3205                                       (crs->release_timeout * hz) / 1000, 
3206                                       xpt_release_devq_timeout, dev);
3207
3208                         dev->flags |= CAM_DEV_REL_TIMEOUT_PENDING;
3209
3210                 }
3211
3212                 if ((crs->release_flags & RELSIM_RELEASE_AFTER_CMDCMPLT) != 0) {
3213
3214                         if ((dev->flags & CAM_DEV_REL_ON_COMPLETE) != 0) {
3215                                 /*
3216                                  * Decrement the freeze count so that a single
3217                                  * completion is still sufficient to unfreeze
3218                                  * the queue.
3219                                  */
3220                                 start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
3221                         } else {
3222                                 
3223                                 dev->flags |= CAM_DEV_REL_ON_COMPLETE;
3224                                 start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
3225                         }
3226                 }
3227
3228                 if ((crs->release_flags & RELSIM_RELEASE_AFTER_QEMPTY) != 0) {
3229
3230                         if ((dev->flags & CAM_DEV_REL_ON_QUEUE_EMPTY) != 0
3231                          || (dev->ccbq.dev_active == 0)) {
3232
3233                                 start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
3234                         } else {
3235                                 
3236                                 dev->flags |= CAM_DEV_REL_ON_QUEUE_EMPTY;
3237                                 start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
3238                         }
3239                 }
3240                 
3241                 if ((start_ccb->ccb_h.flags & CAM_DEV_QFREEZE) == 0) {
3242
3243                         xpt_release_devq(crs->ccb_h.path, /*count*/1,
3244                                          /*run_queue*/TRUE);
3245                 }
3246                 start_ccb->crs.qfrozen_cnt = dev->qfrozen_cnt;
3247                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3248                 break;
3249         }
3250         case XPT_SCAN_BUS:
3251                 xpt_scan_bus(start_ccb->ccb_h.path->periph, start_ccb);
3252                 break;
3253         case XPT_SCAN_LUN:
3254                 xpt_scan_lun(start_ccb->ccb_h.path->periph,
3255                              start_ccb->ccb_h.path, start_ccb->crcn.flags,
3256                              start_ccb);
3257                 break;
3258         case XPT_DEBUG: {
3259 #ifdef CAMDEBUG
3260 #ifdef CAM_DEBUG_DELAY
3261                 cam_debug_delay = CAM_DEBUG_DELAY;
3262 #endif
3263                 cam_dflags = start_ccb->cdbg.flags;
3264                 if (cam_dpath != NULL) {
3265                         xpt_free_path(cam_dpath);
3266                         cam_dpath = NULL;
3267                 }
3268
3269                 if (cam_dflags != CAM_DEBUG_NONE) {
3270                         if (xpt_create_path(&cam_dpath, xpt_periph,
3271                                             start_ccb->ccb_h.path_id,
3272                                             start_ccb->ccb_h.target_id,
3273                                             start_ccb->ccb_h.target_lun) !=
3274                                             CAM_REQ_CMP) {
3275                                 start_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
3276                                 cam_dflags = CAM_DEBUG_NONE;
3277                         } else {
3278                                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3279                                 xpt_print_path(cam_dpath);
3280                                 printf("debugging flags now %x\n", cam_dflags);
3281                         }
3282                 } else {
3283                         cam_dpath = NULL;
3284                         start_ccb->ccb_h.status = CAM_REQ_CMP;
3285                 }
3286 #else /* !CAMDEBUG */
3287                 start_ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
3288 #endif /* CAMDEBUG */
3289                 break;
3290         }
3291         case XPT_NOOP:
3292                 if ((start_ccb->ccb_h.flags & CAM_DEV_QFREEZE) != 0)
3293                         xpt_freeze_devq(start_ccb->ccb_h.path, 1);
3294                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3295                 break;
3296         default:
3297         case XPT_SDEV_TYPE:
3298         case XPT_TERM_IO:
3299         case XPT_ENG_INQ:
3300                 /* XXX Implement */
3301                 start_ccb->ccb_h.status = CAM_PROVIDE_FAIL;
3302                 break;
3303         }
3304         crit_exit();
3305 }
3306
3307 void
3308 xpt_polled_action(union ccb *start_ccb)
3309 {
3310         u_int32_t timeout;
3311         struct    cam_sim *sim; 
3312         struct    cam_devq *devq;
3313         struct    cam_ed *dev;
3314
3315         timeout = start_ccb->ccb_h.timeout;
3316         sim = start_ccb->ccb_h.path->bus->sim;
3317         devq = sim->devq;
3318         dev = start_ccb->ccb_h.path->device;
3319
3320         crit_enter();
3321
3322         /*
3323          * Steal an opening so that no other queued requests
3324          * can get it before us while we simulate interrupts.
3325          */
3326         dev->ccbq.devq_openings--;
3327         dev->ccbq.dev_openings--;       
3328         
3329         while(((devq && devq->send_openings <= 0) || dev->ccbq.dev_openings < 0)
3330            && (--timeout > 0)) {
3331                 DELAY(1000);
3332                 (*(sim->sim_poll))(sim);
3333                 swi_camnet(NULL, NULL);
3334                 swi_cambio(NULL, NULL);         
3335         }
3336         
3337         dev->ccbq.devq_openings++;
3338         dev->ccbq.dev_openings++;
3339         
3340         if (timeout != 0) {
3341                 xpt_action(start_ccb);
3342                 while(--timeout > 0) {
3343                         (*(sim->sim_poll))(sim);
3344                         swi_camnet(NULL, NULL);
3345                         swi_cambio(NULL, NULL);
3346                         if ((start_ccb->ccb_h.status  & CAM_STATUS_MASK)
3347                             != CAM_REQ_INPROG)
3348                                 break;
3349                         DELAY(1000);
3350                 }
3351                 if (timeout == 0) {
3352                         /*
3353                          * XXX Is it worth adding a sim_timeout entry
3354                          * point so we can attempt recovery?  If
3355                          * this is only used for dumps, I don't think
3356                          * it is.
3357                          */
3358                         start_ccb->ccb_h.status = CAM_CMD_TIMEOUT;
3359                 }
3360         } else {
3361                 start_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
3362         }
3363         crit_exit();
3364 }
3365         
3366 /*
3367  * Schedule a peripheral driver to receive a ccb when it's
3368  * target device has space for more transactions.
3369  */
3370 void
3371 xpt_schedule(struct cam_periph *perph, u_int32_t new_priority)
3372 {
3373         struct cam_ed *device;
3374         int runq;
3375
3376         CAM_DEBUG(perph->path, CAM_DEBUG_TRACE, ("xpt_schedule\n"));
3377         device = perph->path->device;
3378         crit_enter();
3379         if (periph_is_queued(perph)) {
3380                 /* Simply reorder based on new priority */
3381                 CAM_DEBUG(perph->path, CAM_DEBUG_SUBTRACE,
3382                           ("   change priority to %d\n", new_priority));
3383                 if (new_priority < perph->pinfo.priority) {
3384                         camq_change_priority(&device->drvq,
3385                                              perph->pinfo.index,
3386                                              new_priority);
3387                 }
3388                 runq = 0;
3389         } else {
3390                 /* New entry on the queue */
3391                 CAM_DEBUG(perph->path, CAM_DEBUG_SUBTRACE,
3392                           ("   added periph to queue\n"));
3393                 perph->pinfo.priority = new_priority;
3394                 perph->pinfo.generation = ++device->drvq.generation;
3395                 camq_insert(&device->drvq, &perph->pinfo);
3396                 runq = xpt_schedule_dev_allocq(perph->path->bus, device);
3397         }
3398         crit_exit();
3399         if (runq != 0) {
3400                 CAM_DEBUG(perph->path, CAM_DEBUG_SUBTRACE,
3401                           ("   calling xpt_run_devq\n"));
3402                 xpt_run_dev_allocq(perph->path->bus);
3403         }
3404 }
3405
3406
3407 /*
3408  * Schedule a device to run on a given queue.
3409  * If the device was inserted as a new entry on the queue,
3410  * return 1 meaning the device queue should be run. If we
3411  * were already queued, implying someone else has already
3412  * started the queue, return 0 so the caller doesn't attempt
3413  * to run the queue.  Must be run in a critical section.
3414  */
3415 static int
3416 xpt_schedule_dev(struct camq *queue, cam_pinfo *pinfo,
3417                  u_int32_t new_priority)
3418 {
3419         int retval;
3420         u_int32_t old_priority;
3421
3422         CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_schedule_dev\n"));
3423
3424         old_priority = pinfo->priority;
3425
3426         /*
3427          * Are we already queued?
3428          */
3429         if (pinfo->index != CAM_UNQUEUED_INDEX) {
3430                 /* Simply reorder based on new priority */
3431                 if (new_priority < old_priority) {
3432                         camq_change_priority(queue, pinfo->index,
3433                                              new_priority);
3434                         CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3435                                         ("changed priority to %d\n",
3436                                          new_priority));
3437                 }
3438                 retval = 0;
3439         } else {
3440                 /* New entry on the queue */
3441                 if (new_priority < old_priority)
3442                         pinfo->priority = new_priority;
3443
3444                 CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3445                                 ("Inserting onto queue\n"));
3446                 pinfo->generation = ++queue->generation;
3447                 camq_insert(queue, pinfo);
3448                 retval = 1;
3449         }
3450         return (retval);
3451 }
3452
3453 static void
3454 xpt_run_dev_allocq(struct cam_eb *bus)
3455 {
3456         struct  cam_devq *devq;
3457
3458         if ((devq = bus->sim->devq) == NULL) {
3459                 CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_dev_allocq: NULL devq\n"));
3460                 return;
3461         }
3462         CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_dev_allocq\n"));
3463
3464         CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3465                         ("   qfrozen_cnt == 0x%x, entries == %d, "
3466                          "openings == %d, active == %d\n",
3467                          devq->alloc_queue.qfrozen_cnt,
3468                          devq->alloc_queue.entries,
3469                          devq->alloc_openings,
3470                          devq->alloc_active));
3471
3472         crit_enter();
3473         devq->alloc_queue.qfrozen_cnt++;
3474         while ((devq->alloc_queue.entries > 0)
3475             && (devq->alloc_openings > 0)
3476             && (devq->alloc_queue.qfrozen_cnt <= 1)) {
3477                 struct  cam_ed_qinfo *qinfo;
3478                 struct  cam_ed *device;
3479                 union   ccb *work_ccb;
3480                 struct  cam_periph *drv;
3481                 struct  camq *drvq;
3482                 
3483                 qinfo = (struct cam_ed_qinfo *)camq_remove(&devq->alloc_queue,
3484                                                            CAMQ_HEAD);
3485                 device = qinfo->device;
3486
3487                 CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3488                                 ("running device %p\n", device));
3489
3490                 drvq = &device->drvq;
3491
3492 #ifdef CAMDEBUG
3493                 if (drvq->entries <= 0) {
3494                         panic("xpt_run_dev_allocq: "
3495                               "Device on queue without any work to do");
3496                 }
3497 #endif
3498                 if ((work_ccb = xpt_get_ccb(device)) != NULL) {
3499                         devq->alloc_openings--;
3500                         devq->alloc_active++;
3501                         drv = (struct cam_periph*)camq_remove(drvq, CAMQ_HEAD);
3502                         crit_exit();
3503                         xpt_setup_ccb(&work_ccb->ccb_h, drv->path,
3504                                       drv->pinfo.priority);
3505                         CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3506                                         ("calling periph start\n"));
3507                         drv->periph_start(drv, work_ccb);
3508                 } else {
3509                         /*
3510                          * Malloc failure in alloc_ccb
3511                          */
3512                         /*
3513                          * XXX add us to a list to be run from free_ccb
3514                          * if we don't have any ccbs active on this
3515                          * device queue otherwise we may never get run
3516                          * again.
3517                          */
3518                         break;
3519                 }
3520         
3521                 /* Raise IPL for possible insertion and test at top of loop */
3522                 crit_enter();
3523
3524                 if (drvq->entries > 0) {
3525                         /* We have more work.  Attempt to reschedule */
3526                         xpt_schedule_dev_allocq(bus, device);
3527                 }
3528         }
3529         devq->alloc_queue.qfrozen_cnt--;
3530         crit_exit();
3531 }
3532
3533 static void
3534 xpt_run_dev_sendq(struct cam_eb *bus)
3535 {
3536         struct  cam_devq *devq;
3537
3538         if ((devq = bus->sim->devq) == NULL) {
3539                 CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_dev_sendq: NULL devq\n"));
3540                 return;
3541         }
3542         CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_dev_sendq\n"));
3543
3544         crit_enter();
3545         devq->send_queue.qfrozen_cnt++;
3546         while ((devq->send_queue.entries > 0)
3547             && (devq->send_openings > 0)) {
3548                 struct  cam_ed_qinfo *qinfo;
3549                 struct  cam_ed *device;
3550                 union ccb *work_ccb;
3551                 struct  cam_sim *sim;
3552
3553                 if (devq->send_queue.qfrozen_cnt > 1) {
3554                         break;
3555                 }
3556
3557                 qinfo = (struct cam_ed_qinfo *)camq_remove(&devq->send_queue,
3558                                                            CAMQ_HEAD);
3559                 device = qinfo->device;
3560
3561                 /*
3562                  * If the device has been "frozen", don't attempt
3563                  * to run it.
3564                  */
3565                 if (device->qfrozen_cnt > 0) {
3566                         continue;
3567                 }
3568
3569                 CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3570                                 ("running device %p\n", device));
3571
3572                 work_ccb = cam_ccbq_peek_ccb(&device->ccbq, CAMQ_HEAD);
3573                 if (work_ccb == NULL) {
3574                         printf("device on run queue with no ccbs???\n");
3575                         continue;
3576                 }
3577
3578                 if ((work_ccb->ccb_h.flags & CAM_HIGH_POWER) != 0) {
3579
3580                         if (num_highpower <= 0) {
3581                                 /*
3582                                  * We got a high power command, but we
3583                                  * don't have any available slots.  Freeze
3584                                  * the device queue until we have a slot
3585                                  * available.
3586                                  */
3587                                 device->qfrozen_cnt++;
3588                                 STAILQ_INSERT_TAIL(&highpowerq, 
3589                                                    &work_ccb->ccb_h, 
3590                                                    xpt_links.stqe);
3591
3592                                 continue;
3593                         } else {
3594                                 /*
3595                                  * Consume a high power slot while
3596                                  * this ccb runs.
3597                                  */
3598                                 num_highpower--;
3599                         }
3600                 }
3601                 devq->active_dev = device;
3602                 cam_ccbq_remove_ccb(&device->ccbq, work_ccb);
3603
3604                 cam_ccbq_send_ccb(&device->ccbq, work_ccb);
3605
3606                 devq->send_openings--;
3607                 devq->send_active++;            
3608                 
3609                 if (device->ccbq.queue.entries > 0)
3610                         xpt_schedule_dev_sendq(bus, device);
3611
3612                 if (work_ccb && (work_ccb->ccb_h.flags & CAM_DEV_QFREEZE) != 0){
3613                         /*
3614                          * The client wants to freeze the queue
3615                          * after this CCB is sent.
3616                          */
3617                         device->qfrozen_cnt++;
3618                 }
3619
3620                 /* In Target mode, the peripheral driver knows best... */
3621                 if (work_ccb->ccb_h.func_code == XPT_SCSI_IO) {
3622                         if ((device->inq_flags & SID_CmdQue) != 0
3623                          && work_ccb->csio.tag_action != CAM_TAG_ACTION_NONE)
3624                                 work_ccb->ccb_h.flags |= CAM_TAG_ACTION_VALID;
3625                         else
3626                                 /*
3627                                  * Clear this in case of a retried CCB that
3628                                  * failed due to a rejected tag.
3629                                  */
3630                                 work_ccb->ccb_h.flags &= ~CAM_TAG_ACTION_VALID;
3631                 }
3632
3633                 /*
3634                  * Device queues can be shared among multiple sim instances
3635                  * that reside on different busses.  Use the SIM in the queue
3636                  * CCB's path, rather than the one in the bus that was passed
3637                  * into this function.
3638                  */
3639                 sim = work_ccb->ccb_h.path->bus->sim;
3640                 (*(sim->sim_action))(sim, work_ccb);
3641
3642                 devq->active_dev = NULL;
3643                 /* Raise IPL for possible insertion and test at top of loop */
3644         }
3645         devq->send_queue.qfrozen_cnt--;
3646         crit_exit();
3647 }
3648
3649 /*
3650  * This function merges stuff from the slave ccb into the master ccb, while
3651  * keeping important fields in the master ccb constant.
3652  */
3653 void
3654 xpt_merge_ccb(union ccb *master_ccb, union ccb *slave_ccb)
3655 {
3656         /*
3657          * Pull fields that are valid for peripheral drivers to set
3658          * into the master CCB along with the CCB "payload".
3659          */
3660         master_ccb->ccb_h.retry_count = slave_ccb->ccb_h.retry_count;
3661         master_ccb->ccb_h.func_code = slave_ccb->ccb_h.func_code;
3662         master_ccb->ccb_h.timeout = slave_ccb->ccb_h.timeout;
3663         master_ccb->ccb_h.flags = slave_ccb->ccb_h.flags;
3664         bcopy(&(&slave_ccb->ccb_h)[1], &(&master_ccb->ccb_h)[1],
3665               sizeof(union ccb) - sizeof(struct ccb_hdr));
3666 }
3667
3668 void
3669 xpt_setup_ccb(struct ccb_hdr *ccb_h, struct cam_path *path, u_int32_t priority)
3670 {
3671         CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_setup_ccb\n"));
3672         callout_init(&ccb_h->timeout_ch);
3673         ccb_h->pinfo.priority = priority;
3674         ccb_h->path = path;
3675         ccb_h->path_id = path->bus->path_id;
3676         if (path->target)
3677                 ccb_h->target_id = path->target->target_id;
3678         else
3679                 ccb_h->target_id = CAM_TARGET_WILDCARD;
3680         if (path->device) {
3681                 ccb_h->target_lun = path->device->lun_id;
3682                 ccb_h->pinfo.generation = ++path->device->ccbq.queue.generation;
3683         } else {
3684                 ccb_h->target_lun = CAM_TARGET_WILDCARD;
3685         }
3686         ccb_h->pinfo.index = CAM_UNQUEUED_INDEX;
3687         ccb_h->flags = 0;
3688 }
3689
3690 /* Path manipulation functions */
3691 cam_status
3692 xpt_create_path(struct cam_path **new_path_ptr, struct cam_periph *perph,
3693                 path_id_t path_id, target_id_t target_id, lun_id_t lun_id)
3694 {
3695         struct     cam_path *path;
3696         cam_status status;
3697
3698         path = kmalloc(sizeof(*path), M_DEVBUF, M_INTWAIT);
3699         status = xpt_compile_path(path, perph, path_id, target_id, lun_id);
3700         if (status != CAM_REQ_CMP) {
3701                 kfree(path, M_DEVBUF);
3702                 path = NULL;
3703         }
3704         *new_path_ptr = path;
3705         return (status);
3706 }
3707
3708 static cam_status
3709 xpt_compile_path(struct cam_path *new_path, struct cam_periph *perph,
3710                  path_id_t path_id, target_id_t target_id, lun_id_t lun_id)
3711 {
3712         struct       cam_eb *bus;
3713         struct       cam_et *target;
3714         struct       cam_ed *device;
3715         cam_status   status;
3716
3717         status = CAM_REQ_CMP;   /* Completed without error */
3718         target = NULL;          /* Wildcarded */
3719         device = NULL;          /* Wildcarded */
3720
3721         /*
3722          * We will potentially modify the EDT, so block interrupts
3723          * that may attempt to create cam paths.
3724          */
3725         crit_enter();
3726         bus = xpt_find_bus(path_id);
3727         if (bus == NULL) {
3728                 status = CAM_PATH_INVALID;
3729         } else {
3730                 target = xpt_find_target(bus, target_id);
3731                 if (target == NULL) {
3732                         /* Create one */
3733                         struct cam_et *new_target;
3734
3735                         new_target = xpt_alloc_target(bus, target_id);
3736                         if (new_target == NULL) {
3737                                 status = CAM_RESRC_UNAVAIL;
3738                         } else {
3739                                 target = new_target;
3740                         }
3741                 }
3742                 if (target != NULL) {
3743                         device = xpt_find_device(target, lun_id);
3744                         if (device == NULL) {
3745                                 /* Create one */
3746                                 struct cam_ed *new_device;
3747
3748                                 new_device = xpt_alloc_device(bus,
3749                                                               target,
3750                                                               lun_id);
3751                                 if (new_device == NULL) {
3752                                         status = CAM_RESRC_UNAVAIL;
3753                                 } else {
3754                                         device = new_device;
3755                                 }
3756                         }
3757                 }
3758         }
3759         crit_exit();
3760
3761         /*
3762          * Only touch the user's data if we are successful.
3763          */
3764         if (status == CAM_REQ_CMP) {
3765                 new_path->periph = perph;
3766                 new_path->bus = bus;
3767                 new_path->target = target;
3768                 new_path->device = device;
3769                 CAM_DEBUG(new_path, CAM_DEBUG_TRACE, ("xpt_compile_path\n"));
3770         } else {
3771                 if (device != NULL)
3772                         xpt_release_device(bus, target, device);
3773                 if (target != NULL)
3774                         xpt_release_target(bus, target);
3775                 if (bus != NULL)
3776                         xpt_release_bus(bus);
3777         }
3778         return (status);
3779 }
3780
3781 static void
3782 xpt_release_path(struct cam_path *path)
3783 {
3784         CAM_DEBUG(path,