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