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