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