Rewrite of the CAM error recovery code.
[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.40 2007/11/18 17:53:01 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)
1502          && (path->device->serial_num_len > 0)) {
1503                 /* Don't wrap the screen  - print only the first 60 chars */
1504                 printf("%s%d: Serial Number %.60s\n", periph->periph_name,
1505                        periph->unit_number, path->device->serial_num);
1506         }
1507         xpt_setup_ccb(&cts.ccb_h, path, /*priority*/1);
1508         cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
1509         cts.type = CTS_TYPE_CURRENT_SETTINGS;
1510         xpt_action((union ccb*)&cts);
1511
1512         /* Ask the SIM for its base transfer speed */
1513         xpt_setup_ccb(&cpi.ccb_h, path, /*priority*/1);
1514         cpi.ccb_h.func_code = XPT_PATH_INQ;
1515         xpt_action((union ccb *)&cpi);
1516
1517         speed = cpi.base_transfer_speed;
1518         freq = 0;
1519         if (cts.ccb_h.status == CAM_REQ_CMP
1520          && cts.transport == XPORT_SPI) {
1521                 struct  ccb_trans_settings_spi *spi;
1522
1523                 spi = &cts.xport_specific.spi;
1524                 if ((spi->valid & CTS_SPI_VALID_SYNC_OFFSET) != 0
1525                   && spi->sync_offset != 0) {
1526                         freq = scsi_calc_syncsrate(spi->sync_period);
1527                         speed = freq;
1528                 }
1529
1530                 if ((spi->valid & CTS_SPI_VALID_BUS_WIDTH) != 0)
1531                         speed *= (0x01 << spi->bus_width);
1532         }
1533
1534         mb = speed / 1000;
1535         if (mb > 0)
1536                 printf("%s%d: %d.%03dMB/s transfers",
1537                        periph->periph_name, periph->unit_number,
1538                        mb, speed % 1000);
1539         else
1540                 printf("%s%d: %dKB/s transfers", periph->periph_name,
1541                        periph->unit_number, speed);
1542         /* Report additional information about SPI connections */
1543         if (cts.ccb_h.status == CAM_REQ_CMP
1544          && cts.transport == XPORT_SPI) {
1545                 struct  ccb_trans_settings_spi *spi;
1546
1547                 spi = &cts.xport_specific.spi;
1548                 if (freq != 0) {
1549                         printf(" (%d.%03dMHz%s, offset %d", freq / 1000,
1550                                freq % 1000,
1551                                (spi->ppr_options & MSG_EXT_PPR_DT_REQ) != 0
1552                              ? " DT" : "",
1553                                spi->sync_offset);
1554                 }
1555                 if ((spi->valid & CTS_SPI_VALID_BUS_WIDTH) != 0
1556                  && spi->bus_width > 0) {
1557                         if (freq != 0) {
1558                                 printf(", ");
1559                         } else {
1560                                 printf(" (");
1561                         }
1562                         printf("%dbit)", 8 * (0x01 << spi->bus_width));
1563                 } else if (freq != 0) {
1564                         printf(")");
1565                 }
1566         }
1567
1568         if (path->device->inq_flags & SID_CmdQue
1569          || path->device->flags & CAM_DEV_TAG_AFTER_COUNT) {
1570                 printf("\n%s%d: Tagged Queueing Enabled",
1571                        periph->periph_name, periph->unit_number);
1572         }
1573         printf("\n");
1574
1575         /*
1576          * We only want to print the caller's announce string if they've
1577          * passed one in..
1578          */
1579         if (announce_string != NULL)
1580                 printf("%s%d: %s\n", periph->periph_name,
1581                        periph->unit_number, announce_string);
1582         crit_exit();
1583 }
1584 #else /* CAM_NEW_TRAN_CODE */
1585 void
1586 xpt_announce_periph(struct cam_periph *periph, char *announce_string)
1587 {
1588         u_int mb;
1589         struct cam_path *path;
1590         struct ccb_trans_settings cts;
1591
1592         path = periph->path;
1593         /*
1594          * To ensure that this is printed in one piece,
1595          * mask out CAM interrupts.
1596          */
1597         crit_enter();
1598         kprintf("%s%d at %s%d bus %d target %d lun %d\n",
1599                periph->periph_name, periph->unit_number,
1600                path->bus->sim->sim_name,
1601                path->bus->sim->unit_number,
1602                path->bus->sim->bus_id,
1603                path->target->target_id,
1604                path->device->lun_id);
1605         kprintf("%s%d: ", periph->periph_name, periph->unit_number);
1606         scsi_print_inquiry(&path->device->inq_data);
1607         if ((bootverbose)
1608          && (path->device->serial_num_len > 0)) {
1609                 /* Don't wrap the screen  - print only the first 60 chars */
1610                 kprintf("%s%d: Serial Number %.60s\n", periph->periph_name,
1611                        periph->unit_number, path->device->serial_num);
1612         }
1613         xpt_setup_ccb(&cts.ccb_h, path, /*priority*/1);
1614         cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
1615         cts.flags = CCB_TRANS_CURRENT_SETTINGS;
1616         xpt_action((union ccb*)&cts);
1617         if (cts.ccb_h.status == CAM_REQ_CMP) {
1618                 u_int speed;
1619                 u_int freq;
1620
1621                 if ((cts.valid & CCB_TRANS_SYNC_OFFSET_VALID) != 0
1622                   && cts.sync_offset != 0) {
1623                         freq = scsi_calc_syncsrate(cts.sync_period);
1624                         speed = freq;
1625                 } else {
1626                         struct ccb_pathinq cpi;
1627
1628                         /* Ask the SIM for its base transfer speed */
1629                         xpt_setup_ccb(&cpi.ccb_h, path, /*priority*/1);
1630                         cpi.ccb_h.func_code = XPT_PATH_INQ;
1631                         xpt_action((union ccb *)&cpi);
1632
1633                         speed = cpi.base_transfer_speed;
1634                         freq = 0;
1635                 }
1636                 if ((cts.valid & CCB_TRANS_BUS_WIDTH_VALID) != 0)
1637                         speed *= (0x01 << cts.bus_width);
1638                 mb = speed / 1000;
1639                 if (mb > 0)
1640                         kprintf("%s%d: %d.%03dMB/s transfers",
1641                                periph->periph_name, periph->unit_number,
1642                                mb, speed % 1000);
1643                 else
1644                         kprintf("%s%d: %dKB/s transfers", periph->periph_name,
1645                                periph->unit_number, speed);
1646                 if ((cts.valid & CCB_TRANS_SYNC_OFFSET_VALID) != 0
1647                  && cts.sync_offset != 0) {
1648                         kprintf(" (%d.%03dMHz, offset %d", freq / 1000,
1649                                freq % 1000, cts.sync_offset);
1650                 }
1651                 if ((cts.valid & CCB_TRANS_BUS_WIDTH_VALID) != 0
1652                  && cts.bus_width > 0) {
1653                         if ((cts.valid & CCB_TRANS_SYNC_OFFSET_VALID) != 0
1654                          && cts.sync_offset != 0) {
1655                                 kprintf(", ");
1656                         } else {
1657                                 kprintf(" (");
1658                         }
1659                         kprintf("%dbit)", 8 * (0x01 << cts.bus_width));
1660                 } else if ((cts.valid & CCB_TRANS_SYNC_OFFSET_VALID) != 0
1661                         && cts.sync_offset != 0) {
1662                         kprintf(")");
1663                 }
1664
1665                 if (path->device->inq_flags & SID_CmdQue
1666                  || path->device->flags & CAM_DEV_TAG_AFTER_COUNT) {
1667                         kprintf(", Tagged Queueing Enabled");
1668                 }
1669
1670                 kprintf("\n");
1671         } else if (path->device->inq_flags & SID_CmdQue
1672                 || path->device->flags & CAM_DEV_TAG_AFTER_COUNT) {
1673                 kprintf("%s%d: Tagged Queueing Enabled\n",
1674                        periph->periph_name, periph->unit_number);
1675         }
1676
1677         /*
1678          * We only want to print the caller's announce string if they've
1679          * passed one in..
1680          */
1681         if (announce_string != NULL)
1682                 kprintf("%s%d: %s\n", periph->periph_name,
1683                        periph->unit_number, announce_string);
1684         crit_exit();
1685 }
1686
1687 #endif /* CAM_NEW_TRAN_CODE */
1688
1689 static dev_match_ret
1690 xptbusmatch(struct dev_match_pattern *patterns, u_int num_patterns,
1691             struct cam_eb *bus)
1692 {
1693         dev_match_ret retval;
1694         int i;
1695
1696         retval = DM_RET_NONE;
1697
1698         /*
1699          * If we aren't given something to match against, that's an error.
1700          */
1701         if (bus == NULL)
1702                 return(DM_RET_ERROR);
1703
1704         /*
1705          * If there are no match entries, then this bus matches no
1706          * matter what.
1707          */
1708         if ((patterns == NULL) || (num_patterns == 0))
1709                 return(DM_RET_DESCEND | DM_RET_COPY);
1710
1711         for (i = 0; i < num_patterns; i++) {
1712                 struct bus_match_pattern *cur_pattern;
1713
1714                 /*
1715                  * If the pattern in question isn't for a bus node, we
1716                  * aren't interested.  However, we do indicate to the
1717                  * calling routine that we should continue descending the
1718                  * tree, since the user wants to match against lower-level
1719                  * EDT elements.
1720                  */
1721                 if (patterns[i].type != DEV_MATCH_BUS) {
1722                         if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1723                                 retval |= DM_RET_DESCEND;
1724                         continue;
1725                 }
1726
1727                 cur_pattern = &patterns[i].pattern.bus_pattern;
1728
1729                 /*
1730                  * If they want to match any bus node, we give them any
1731                  * device node.
1732                  */
1733                 if (cur_pattern->flags == BUS_MATCH_ANY) {
1734                         /* set the copy flag */
1735                         retval |= DM_RET_COPY;
1736
1737                         /*
1738                          * If we've already decided on an action, go ahead
1739                          * and return.
1740                          */
1741                         if ((retval & DM_RET_ACTION_MASK) != DM_RET_NONE)
1742                                 return(retval);
1743                 }
1744
1745                 /*
1746                  * Not sure why someone would do this...
1747                  */
1748                 if (cur_pattern->flags == BUS_MATCH_NONE)
1749                         continue;
1750
1751                 if (((cur_pattern->flags & BUS_MATCH_PATH) != 0)
1752                  && (cur_pattern->path_id != bus->path_id))
1753                         continue;
1754
1755                 if (((cur_pattern->flags & BUS_MATCH_BUS_ID) != 0)
1756                  && (cur_pattern->bus_id != bus->sim->bus_id))
1757                         continue;
1758
1759                 if (((cur_pattern->flags & BUS_MATCH_UNIT) != 0)
1760                  && (cur_pattern->unit_number != bus->sim->unit_number))
1761                         continue;
1762
1763                 if (((cur_pattern->flags & BUS_MATCH_NAME) != 0)
1764                  && (strncmp(cur_pattern->dev_name, bus->sim->sim_name,
1765                              DEV_IDLEN) != 0))
1766                         continue;
1767
1768                 /*
1769                  * If we get to this point, the user definitely wants 
1770                  * information on this bus.  So tell the caller to copy the
1771                  * data out.
1772                  */
1773                 retval |= DM_RET_COPY;
1774
1775                 /*
1776                  * If the return action has been set to descend, then we
1777                  * know that we've already seen a non-bus matching
1778                  * expression, therefore we need to further descend the tree.
1779                  * This won't change by continuing around the loop, so we
1780                  * go ahead and return.  If we haven't seen a non-bus
1781                  * matching expression, we keep going around the loop until
1782                  * we exhaust the matching expressions.  We'll set the stop
1783                  * flag once we fall out of the loop.
1784                  */
1785                 if ((retval & DM_RET_ACTION_MASK) == DM_RET_DESCEND)
1786                         return(retval);
1787         }
1788
1789         /*
1790          * If the return action hasn't been set to descend yet, that means
1791          * we haven't seen anything other than bus matching patterns.  So
1792          * tell the caller to stop descending the tree -- the user doesn't
1793          * want to match against lower level tree elements.
1794          */
1795         if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1796                 retval |= DM_RET_STOP;
1797
1798         return(retval);
1799 }
1800
1801 static dev_match_ret
1802 xptdevicematch(struct dev_match_pattern *patterns, u_int num_patterns,
1803                struct cam_ed *device)
1804 {
1805         dev_match_ret retval;
1806         int i;
1807
1808         retval = DM_RET_NONE;
1809
1810         /*
1811          * If we aren't given something to match against, that's an error.
1812          */
1813         if (device == NULL)
1814                 return(DM_RET_ERROR);
1815
1816         /*
1817          * If there are no match entries, then this device matches no
1818          * matter what.
1819          */
1820         if ((patterns == NULL) || (patterns == 0))
1821                 return(DM_RET_DESCEND | DM_RET_COPY);
1822
1823         for (i = 0; i < num_patterns; i++) {
1824                 struct device_match_pattern *cur_pattern;
1825
1826                 /*
1827                  * If the pattern in question isn't for a device node, we
1828                  * aren't interested.
1829                  */
1830                 if (patterns[i].type != DEV_MATCH_DEVICE) {
1831                         if ((patterns[i].type == DEV_MATCH_PERIPH)
1832                          && ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE))
1833                                 retval |= DM_RET_DESCEND;
1834                         continue;
1835                 }
1836
1837                 cur_pattern = &patterns[i].pattern.device_pattern;
1838
1839                 /*
1840                  * If they want to match any device node, we give them any
1841                  * device node.
1842                  */
1843                 if (cur_pattern->flags == DEV_MATCH_ANY) {
1844                         /* set the copy flag */
1845                         retval |= DM_RET_COPY;
1846
1847                         
1848                         /*
1849                          * If we've already decided on an action, go ahead
1850                          * and return.
1851                          */
1852                         if ((retval & DM_RET_ACTION_MASK) != DM_RET_NONE)
1853                                 return(retval);
1854                 }
1855
1856                 /*
1857                  * Not sure why someone would do this...
1858                  */
1859                 if (cur_pattern->flags == DEV_MATCH_NONE)
1860                         continue;
1861
1862                 if (((cur_pattern->flags & DEV_MATCH_PATH) != 0)
1863                  && (cur_pattern->path_id != device->target->bus->path_id))
1864                         continue;
1865
1866                 if (((cur_pattern->flags & DEV_MATCH_TARGET) != 0)
1867                  && (cur_pattern->target_id != device->target->target_id))
1868                         continue;
1869
1870                 if (((cur_pattern->flags & DEV_MATCH_LUN) != 0)
1871                  && (cur_pattern->target_lun != device->lun_id))
1872                         continue;
1873
1874                 if (((cur_pattern->flags & DEV_MATCH_INQUIRY) != 0)
1875                  && (cam_quirkmatch((caddr_t)&device->inq_data,
1876                                     (caddr_t)&cur_pattern->inq_pat,
1877                                     1, sizeof(cur_pattern->inq_pat),
1878                                     scsi_static_inquiry_match) == NULL))
1879                         continue;
1880
1881                 /*
1882                  * If we get to this point, the user definitely wants 
1883                  * information on this device.  So tell the caller to copy
1884                  * the data out.
1885                  */
1886                 retval |= DM_RET_COPY;
1887
1888                 /*
1889                  * If the return action has been set to descend, then we
1890                  * know that we've already seen a peripheral matching
1891                  * expression, therefore we need to further descend the tree.
1892                  * This won't change by continuing around the loop, so we
1893                  * go ahead and return.  If we haven't seen a peripheral
1894                  * matching expression, we keep going around the loop until
1895                  * we exhaust the matching expressions.  We'll set the stop
1896                  * flag once we fall out of the loop.
1897                  */
1898                 if ((retval & DM_RET_ACTION_MASK) == DM_RET_DESCEND)
1899                         return(retval);
1900         }
1901
1902         /*
1903          * If the return action hasn't been set to descend yet, that means
1904          * we haven't seen any peripheral matching patterns.  So tell the
1905          * caller to stop descending the tree -- the user doesn't want to
1906          * match against lower level tree elements.
1907          */
1908         if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1909                 retval |= DM_RET_STOP;
1910
1911         return(retval);
1912 }
1913
1914 /*
1915  * Match a single peripheral against any number of match patterns.
1916  */
1917 static dev_match_ret
1918 xptperiphmatch(struct dev_match_pattern *patterns, u_int num_patterns,
1919                struct cam_periph *periph)
1920 {
1921         dev_match_ret retval;
1922         int i;
1923
1924         /*
1925          * If we aren't given something to match against, that's an error.
1926          */
1927         if (periph == NULL)
1928                 return(DM_RET_ERROR);
1929
1930         /*
1931          * If there are no match entries, then this peripheral matches no
1932          * matter what.
1933          */
1934         if ((patterns == NULL) || (num_patterns == 0))
1935                 return(DM_RET_STOP | DM_RET_COPY);
1936
1937         /*
1938          * There aren't any nodes below a peripheral node, so there's no
1939          * reason to descend the tree any further.
1940          */
1941         retval = DM_RET_STOP;
1942
1943         for (i = 0; i < num_patterns; i++) {
1944                 struct periph_match_pattern *cur_pattern;
1945
1946                 /*
1947                  * If the pattern in question isn't for a peripheral, we
1948                  * aren't interested.
1949                  */
1950                 if (patterns[i].type != DEV_MATCH_PERIPH)
1951                         continue;
1952
1953                 cur_pattern = &patterns[i].pattern.periph_pattern;
1954
1955                 /*
1956                  * If they want to match on anything, then we will do so.
1957                  */
1958                 if (cur_pattern->flags == PERIPH_MATCH_ANY) {
1959                         /* set the copy flag */
1960                         retval |= DM_RET_COPY;
1961
1962                         /*
1963                          * We've already set the return action to stop,
1964                          * since there are no nodes below peripherals in
1965                          * the tree.
1966                          */
1967                         return(retval);
1968                 }
1969
1970                 /*
1971                  * Not sure why someone would do this...
1972                  */
1973                 if (cur_pattern->flags == PERIPH_MATCH_NONE)
1974                         continue;
1975
1976                 if (((cur_pattern->flags & PERIPH_MATCH_PATH) != 0)
1977                  && (cur_pattern->path_id != periph->path->bus->path_id))
1978                         continue;
1979
1980                 /*
1981                  * For the target and lun id's, we have to make sure the
1982                  * target and lun pointers aren't NULL.  The xpt peripheral
1983                  * has a wildcard target and device.
1984                  */
1985                 if (((cur_pattern->flags & PERIPH_MATCH_TARGET) != 0)
1986                  && ((periph->path->target == NULL)
1987                  ||(cur_pattern->target_id != periph->path->target->target_id)))
1988                         continue;
1989
1990                 if (((cur_pattern->flags & PERIPH_MATCH_LUN) != 0)
1991                  && ((periph->path->device == NULL)
1992                  || (cur_pattern->target_lun != periph->path->device->lun_id)))
1993                         continue;
1994
1995                 if (((cur_pattern->flags & PERIPH_MATCH_UNIT) != 0)
1996                  && (cur_pattern->unit_number != periph->unit_number))
1997                         continue;
1998
1999                 if (((cur_pattern->flags & PERIPH_MATCH_NAME) != 0)
2000                  && (strncmp(cur_pattern->periph_name, periph->periph_name,
2001                              DEV_IDLEN) != 0))
2002                         continue;
2003
2004                 /*
2005                  * If we get to this point, the user definitely wants 
2006                  * information on this peripheral.  So tell the caller to
2007                  * copy the data out.
2008                  */
2009                 retval |= DM_RET_COPY;
2010
2011                 /*
2012                  * The return action has already been set to stop, since
2013                  * peripherals don't have any nodes below them in the EDT.
2014                  */
2015                 return(retval);
2016         }
2017
2018         /*
2019          * If we get to this point, the peripheral that was passed in
2020          * doesn't match any of the patterns.
2021          */
2022         return(retval);
2023 }
2024
2025 static int
2026 xptedtbusfunc(struct cam_eb *bus, void *arg)
2027 {
2028         struct ccb_dev_match *cdm;
2029         dev_match_ret retval;
2030
2031         cdm = (struct ccb_dev_match *)arg;
2032
2033         /*
2034          * If our position is for something deeper in the tree, that means
2035          * that we've already seen this node.  So, we keep going down.
2036          */
2037         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2038          && (cdm->pos.cookie.bus == bus)
2039          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2040          && (cdm->pos.cookie.target != NULL))
2041                 retval = DM_RET_DESCEND;
2042         else
2043                 retval = xptbusmatch(cdm->patterns, cdm->num_patterns, bus);
2044
2045         /*
2046          * If we got an error, bail out of the search.
2047          */
2048         if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
2049                 cdm->status = CAM_DEV_MATCH_ERROR;
2050                 return(0);
2051         }
2052
2053         /*
2054          * If the copy flag is set, copy this bus out.
2055          */
2056         if (retval & DM_RET_COPY) {
2057                 int spaceleft, j;
2058
2059                 spaceleft = cdm->match_buf_len - (cdm->num_matches *
2060                         sizeof(struct dev_match_result));
2061
2062                 /*
2063                  * If we don't have enough space to put in another
2064                  * match result, save our position and tell the
2065                  * user there are more devices to check.
2066                  */
2067                 if (spaceleft < sizeof(struct dev_match_result)) {
2068                         bzero(&cdm->pos, sizeof(cdm->pos));
2069                         cdm->pos.position_type = 
2070                                 CAM_DEV_POS_EDT | CAM_DEV_POS_BUS;
2071
2072                         cdm->pos.cookie.bus = bus;
2073                         cdm->pos.generations[CAM_BUS_GENERATION]=
2074                                 bus_generation;
2075                         cdm->status = CAM_DEV_MATCH_MORE;
2076                         return(0);
2077                 }
2078                 j = cdm->num_matches;
2079                 cdm->num_matches++;
2080                 cdm->matches[j].type = DEV_MATCH_BUS;
2081                 cdm->matches[j].result.bus_result.path_id = bus->path_id;
2082                 cdm->matches[j].result.bus_result.bus_id = bus->sim->bus_id;
2083                 cdm->matches[j].result.bus_result.unit_number =
2084                         bus->sim->unit_number;
2085                 strncpy(cdm->matches[j].result.bus_result.dev_name,
2086                         bus->sim->sim_name, DEV_IDLEN);
2087         }
2088
2089         /*
2090          * If the user is only interested in busses, there's no
2091          * reason to descend to the next level in the tree.
2092          */
2093         if ((retval & DM_RET_ACTION_MASK) == DM_RET_STOP)
2094                 return(1);
2095
2096         /*
2097          * If there is a target generation recorded, check it to
2098          * make sure the target list hasn't changed.
2099          */
2100         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2101          && (bus == cdm->pos.cookie.bus)
2102          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2103          && (cdm->pos.generations[CAM_TARGET_GENERATION] != 0)
2104          && (cdm->pos.generations[CAM_TARGET_GENERATION] !=
2105              bus->generation)) {
2106                 cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
2107                 return(0);
2108         }
2109
2110         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2111          && (cdm->pos.cookie.bus == bus)
2112          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2113          && (cdm->pos.cookie.target != NULL))
2114                 return(xpttargettraverse(bus,
2115                                         (struct cam_et *)cdm->pos.cookie.target,
2116                                          xptedttargetfunc, arg));
2117         else
2118                 return(xpttargettraverse(bus, NULL, xptedttargetfunc, arg));
2119 }
2120
2121 static int
2122 xptedttargetfunc(struct cam_et *target, void *arg)
2123 {
2124         struct ccb_dev_match *cdm;
2125
2126         cdm = (struct ccb_dev_match *)arg;
2127
2128         /*
2129          * If there is a device list generation recorded, check it to
2130          * make sure the device list hasn't changed.
2131          */
2132         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2133          && (cdm->pos.cookie.bus == target->bus)
2134          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2135          && (cdm->pos.cookie.target == target)
2136          && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
2137          && (cdm->pos.generations[CAM_DEV_GENERATION] != 0)
2138          && (cdm->pos.generations[CAM_DEV_GENERATION] !=
2139              target->generation)) {
2140                 cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
2141                 return(0);
2142         }
2143
2144         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2145          && (cdm->pos.cookie.bus == target->bus)
2146          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2147          && (cdm->pos.cookie.target == target)
2148          && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
2149          && (cdm->pos.cookie.device != NULL))
2150                 return(xptdevicetraverse(target,
2151                                         (struct cam_ed *)cdm->pos.cookie.device,
2152                                          xptedtdevicefunc, arg));
2153         else
2154                 return(xptdevicetraverse(target, NULL, xptedtdevicefunc, arg));
2155 }
2156
2157 static int
2158 xptedtdevicefunc(struct cam_ed *device, void *arg)
2159 {
2160
2161         struct ccb_dev_match *cdm;
2162         dev_match_ret retval;
2163
2164         cdm = (struct ccb_dev_match *)arg;
2165
2166         /*
2167          * If our position is for something deeper in the tree, that means
2168          * that we've already seen this node.  So, we keep going down.
2169          */
2170         if ((cdm->pos.position_type & CAM_DEV_POS_DEVICE)
2171          && (cdm->pos.cookie.device == device)
2172          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2173          && (cdm->pos.cookie.periph != NULL))
2174                 retval = DM_RET_DESCEND;
2175         else
2176                 retval = xptdevicematch(cdm->patterns, cdm->num_patterns,
2177                                         device);
2178
2179         if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
2180                 cdm->status = CAM_DEV_MATCH_ERROR;
2181                 return(0);
2182         }
2183
2184         /*
2185          * If the copy flag is set, copy this device out.
2186          */
2187         if (retval & DM_RET_COPY) {
2188                 int spaceleft, j;
2189
2190                 spaceleft = cdm->match_buf_len - (cdm->num_matches *
2191                         sizeof(struct dev_match_result));
2192
2193                 /*
2194                  * If we don't have enough space to put in another
2195                  * match result, save our position and tell the
2196                  * user there are more devices to check.
2197                  */
2198                 if (spaceleft < sizeof(struct dev_match_result)) {
2199                         bzero(&cdm->pos, sizeof(cdm->pos));
2200                         cdm->pos.position_type = 
2201                                 CAM_DEV_POS_EDT | CAM_DEV_POS_BUS |
2202                                 CAM_DEV_POS_TARGET | CAM_DEV_POS_DEVICE;
2203
2204                         cdm->pos.cookie.bus = device->target->bus;
2205                         cdm->pos.generations[CAM_BUS_GENERATION]=
2206                                 bus_generation;
2207                         cdm->pos.cookie.target = device->target;
2208                         cdm->pos.generations[CAM_TARGET_GENERATION] =
2209                                 device->target->bus->generation;
2210                         cdm->pos.cookie.device = device;
2211                         cdm->pos.generations[CAM_DEV_GENERATION] = 
2212                                 device->target->generation;
2213                         cdm->status = CAM_DEV_MATCH_MORE;
2214                         return(0);
2215                 }
2216                 j = cdm->num_matches;
2217                 cdm->num_matches++;
2218                 cdm->matches[j].type = DEV_MATCH_DEVICE;
2219                 cdm->matches[j].result.device_result.path_id =
2220                         device->target->bus->path_id;
2221                 cdm->matches[j].result.device_result.target_id =
2222                         device->target->target_id;
2223                 cdm->matches[j].result.device_result.target_lun =
2224                         device->lun_id;
2225                 bcopy(&device->inq_data,
2226                       &cdm->matches[j].result.device_result.inq_data,
2227                       sizeof(struct scsi_inquiry_data));
2228
2229                 /* Let the user know whether this device is unconfigured */
2230                 if (device->flags & CAM_DEV_UNCONFIGURED)
2231                         cdm->matches[j].result.device_result.flags =
2232                                 DEV_RESULT_UNCONFIGURED;
2233                 else
2234                         cdm->matches[j].result.device_result.flags =
2235                                 DEV_RESULT_NOFLAG;
2236         }
2237
2238         /*
2239          * If the user isn't interested in peripherals, don't descend
2240          * the tree any further.
2241          */
2242         if ((retval & DM_RET_ACTION_MASK) == DM_RET_STOP)
2243                 return(1);
2244
2245         /*
2246          * If there is a peripheral list generation recorded, make sure
2247          * it hasn't changed.
2248          */
2249         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2250          && (device->target->bus == cdm->pos.cookie.bus)
2251          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2252          && (device->target == cdm->pos.cookie.target)
2253          && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
2254          && (device == cdm->pos.cookie.device)
2255          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2256          && (cdm->pos.generations[CAM_PERIPH_GENERATION] != 0)
2257          && (cdm->pos.generations[CAM_PERIPH_GENERATION] !=
2258              device->generation)){
2259                 cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
2260                 return(0);
2261         }
2262
2263         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2264          && (cdm->pos.cookie.bus == device->target->bus)
2265          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2266          && (cdm->pos.cookie.target == device->target)
2267          && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
2268          && (cdm->pos.cookie.device == device)
2269          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2270          && (cdm->pos.cookie.periph != NULL))
2271                 return(xptperiphtraverse(device,
2272                                 (struct cam_periph *)cdm->pos.cookie.periph,
2273                                 xptedtperiphfunc, arg));
2274         else
2275                 return(xptperiphtraverse(device, NULL, xptedtperiphfunc, arg));
2276 }
2277
2278 static int
2279 xptedtperiphfunc(struct cam_periph *periph, void *arg)
2280 {
2281         struct ccb_dev_match *cdm;
2282         dev_match_ret retval;
2283
2284         cdm = (struct ccb_dev_match *)arg;
2285
2286         retval = xptperiphmatch(cdm->patterns, cdm->num_patterns, periph);
2287
2288         if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
2289                 cdm->status = CAM_DEV_MATCH_ERROR;
2290                 return(0);
2291         }
2292
2293         /*
2294          * If the copy flag is set, copy this peripheral out.
2295          */
2296         if (retval & DM_RET_COPY) {
2297                 int spaceleft, j;
2298
2299                 spaceleft = cdm->match_buf_len - (cdm->num_matches *
2300                         sizeof(struct dev_match_result));
2301
2302                 /*
2303                  * If we don't have enough space to put in another
2304                  * match result, save our position and tell the
2305                  * user there are more devices to check.
2306                  */
2307                 if (spaceleft < sizeof(struct dev_match_result)) {
2308                         bzero(&cdm->pos, sizeof(cdm->pos));
2309                         cdm->pos.position_type = 
2310                                 CAM_DEV_POS_EDT | CAM_DEV_POS_BUS |
2311                                 CAM_DEV_POS_TARGET | CAM_DEV_POS_DEVICE |
2312                                 CAM_DEV_POS_PERIPH;
2313
2314                         cdm->pos.cookie.bus = periph->path->bus;
2315                         cdm->pos.generations[CAM_BUS_GENERATION]=
2316                                 bus_generation;
2317                         cdm->pos.cookie.target = periph->path->target;
2318                         cdm->pos.generations[CAM_TARGET_GENERATION] =
2319                                 periph->path->bus->generation;
2320                         cdm->pos.cookie.device = periph->path->device;
2321                         cdm->pos.generations[CAM_DEV_GENERATION] = 
2322                                 periph->path->target->generation;
2323                         cdm->pos.cookie.periph = periph;
2324                         cdm->pos.generations[CAM_PERIPH_GENERATION] =
2325                                 periph->path->device->generation;
2326                         cdm->status = CAM_DEV_MATCH_MORE;
2327                         return(0);
2328                 }
2329
2330                 j = cdm->num_matches;
2331                 cdm->num_matches++;
2332                 cdm->matches[j].type = DEV_MATCH_PERIPH;
2333                 cdm->matches[j].result.periph_result.path_id =
2334                         periph->path->bus->path_id;
2335                 cdm->matches[j].result.periph_result.target_id =
2336                         periph->path->target->target_id;
2337                 cdm->matches[j].result.periph_result.target_lun =
2338                         periph->path->device->lun_id;
2339                 cdm->matches[j].result.periph_result.unit_number =
2340                         periph->unit_number;
2341                 strncpy(cdm->matches[j].result.periph_result.periph_name,
2342                         periph->periph_name, DEV_IDLEN);
2343         }
2344
2345         return(1);
2346 }
2347
2348 static int
2349 xptedtmatch(struct ccb_dev_match *cdm)
2350 {
2351         int ret;
2352
2353         cdm->num_matches = 0;
2354
2355         /*
2356          * Check the bus list generation.  If it has changed, the user
2357          * needs to reset everything and start over.
2358          */
2359         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2360          && (cdm->pos.generations[CAM_BUS_GENERATION] != 0)
2361          && (cdm->pos.generations[CAM_BUS_GENERATION] != bus_generation)) {
2362                 cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
2363                 return(0);
2364         }
2365
2366         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2367          && (cdm->pos.cookie.bus != NULL))
2368                 ret = xptbustraverse((struct cam_eb *)cdm->pos.cookie.bus,
2369                                      xptedtbusfunc, cdm);
2370         else
2371                 ret = xptbustraverse(NULL, xptedtbusfunc, cdm);
2372
2373         /*
2374          * If we get back 0, that means that we had to stop before fully
2375          * traversing the EDT.  It also means that one of the subroutines
2376          * has set the status field to the proper value.  If we get back 1,
2377          * we've fully traversed the EDT and copied out any matching entries.
2378          */
2379         if (ret == 1)
2380                 cdm->status = CAM_DEV_MATCH_LAST;
2381
2382         return(ret);
2383 }
2384
2385 static int
2386 xptplistpdrvfunc(struct periph_driver **pdrv, void *arg)
2387 {
2388         struct ccb_dev_match *cdm;
2389
2390         cdm = (struct ccb_dev_match *)arg;
2391
2392         if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
2393          && (cdm->pos.cookie.pdrv == pdrv)
2394          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2395          && (cdm->pos.generations[CAM_PERIPH_GENERATION] != 0)
2396          && (cdm->pos.generations[CAM_PERIPH_GENERATION] !=
2397              (*pdrv)->generation)) {
2398                 cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
2399                 return(0);
2400         }
2401
2402         if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
2403          && (cdm->pos.cookie.pdrv == pdrv)
2404          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2405          && (cdm->pos.cookie.periph != NULL))
2406                 return(xptpdperiphtraverse(pdrv,
2407                                 (struct cam_periph *)cdm->pos.cookie.periph,
2408                                 xptplistperiphfunc, arg));
2409         else
2410                 return(xptpdperiphtraverse(pdrv, NULL,xptplistperiphfunc, arg));
2411 }
2412
2413 static int
2414 xptplistperiphfunc(struct cam_periph *periph, void *arg)
2415 {
2416         struct ccb_dev_match *cdm;
2417         dev_match_ret retval;
2418
2419         cdm = (struct ccb_dev_match *)arg;
2420
2421         retval = xptperiphmatch(cdm->patterns, cdm->num_patterns, periph);
2422
2423         if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
2424                 cdm->status = CAM_DEV_MATCH_ERROR;
2425                 return(0);
2426         }
2427
2428         /*
2429          * If the copy flag is set, copy this peripheral out.
2430          */
2431         if (retval & DM_RET_COPY) {
2432                 int spaceleft, j;
2433
2434                 spaceleft = cdm->match_buf_len - (cdm->num_matches *
2435                         sizeof(struct dev_match_result));
2436
2437                 /*
2438                  * If we don't have enough space to put in another
2439                  * match result, save our position and tell the
2440                  * user there are more devices to check.
2441                  */
2442                 if (spaceleft < sizeof(struct dev_match_result)) {
2443                         struct periph_driver **pdrv;
2444
2445                         pdrv = NULL;
2446                         bzero(&cdm->pos, sizeof(cdm->pos));
2447                         cdm->pos.position_type = 
2448                                 CAM_DEV_POS_PDRV | CAM_DEV_POS_PDPTR |
2449                                 CAM_DEV_POS_PERIPH;
2450
2451                         /*
2452                          * This may look a bit non-sensical, but it is
2453                          * actually quite logical.  There are very few
2454                          * peripheral drivers, and bloating every peripheral
2455                          * structure with a pointer back to its parent
2456                          * peripheral driver linker set entry would cost
2457                          * more in the long run than doing this quick lookup.
2458                          */
2459                         for (pdrv = periph_drivers; *pdrv != NULL; pdrv++) {
2460                                 if (strcmp((*pdrv)->driver_name,
2461                                     periph->periph_name) == 0)
2462                                         break;
2463                         }
2464
2465                         if (*pdrv == NULL) {
2466                                 cdm->status = CAM_DEV_MATCH_ERROR;
2467                                 return(0);
2468                         }
2469
2470                         cdm->pos.cookie.pdrv = pdrv;
2471                         /*
2472                          * The periph generation slot does double duty, as
2473                          * does the periph pointer slot.  They are used for
2474                          * both edt and pdrv lookups and positioning.
2475                          */
2476                         cdm->pos.cookie.periph = periph;
2477                         cdm->pos.generations[CAM_PERIPH_GENERATION] =
2478                                 (*pdrv)->generation;
2479                         cdm->status = CAM_DEV_MATCH_MORE;
2480                         return(0);
2481                 }
2482
2483                 j = cdm->num_matches;
2484                 cdm->num_matches++;
2485                 cdm->matches[j].type = DEV_MATCH_PERIPH;
2486                 cdm->matches[j].result.periph_result.path_id =
2487                         periph->path->bus->path_id;
2488
2489                 /*
2490                  * The transport layer peripheral doesn't have a target or
2491                  * lun.
2492                  */
2493                 if (periph->path->target)
2494                         cdm->matches[j].result.periph_result.target_id =
2495                                 periph->path->target->target_id;
2496                 else
2497                         cdm->matches[j].result.periph_result.target_id = -1;
2498
2499                 if (periph->path->device)
2500                         cdm->matches[j].result.periph_result.target_lun =
2501                                 periph->path->device->lun_id;
2502                 else
2503                         cdm->matches[j].result.periph_result.target_lun = -1;
2504
2505                 cdm->matches[j].result.periph_result.unit_number =
2506                         periph->unit_number;
2507                 strncpy(cdm->matches[j].result.periph_result.periph_name,
2508                         periph->periph_name, DEV_IDLEN);
2509         }
2510
2511         return(1);
2512 }
2513
2514 static int
2515 xptperiphlistmatch(struct ccb_dev_match *cdm)
2516 {
2517         int ret;
2518
2519         cdm->num_matches = 0;
2520
2521         /*
2522          * At this point in the edt traversal function, we check the bus
2523          * list generation to make sure that no busses have been added or
2524          * removed since the user last sent a XPT_DEV_MATCH ccb through.
2525          * For the peripheral driver list traversal function, however, we
2526          * don't have to worry about new peripheral driver types coming or
2527          * going; they're in a linker set, and therefore can't change
2528          * without a recompile.
2529          */
2530
2531         if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
2532          && (cdm->pos.cookie.pdrv != NULL))
2533                 ret = xptpdrvtraverse(
2534                                 (struct periph_driver **)cdm->pos.cookie.pdrv,
2535                                 xptplistpdrvfunc, cdm);
2536         else
2537                 ret = xptpdrvtraverse(NULL, xptplistpdrvfunc, cdm);
2538
2539         /*
2540          * If we get back 0, that means that we had to stop before fully
2541          * traversing the peripheral driver tree.  It also means that one of
2542          * the subroutines has set the status field to the proper value.  If
2543          * we get back 1, we've fully traversed the EDT and copied out any
2544          * matching entries.
2545          */
2546         if (ret == 1)
2547                 cdm->status = CAM_DEV_MATCH_LAST;
2548
2549         return(ret);
2550 }
2551
2552 static int
2553 xptbustraverse(struct cam_eb *start_bus, xpt_busfunc_t *tr_func, void *arg)
2554 {
2555         struct cam_eb *bus, *next_bus;
2556         int retval;
2557
2558         retval = 1;
2559
2560         for (bus = (start_bus ? start_bus : TAILQ_FIRST(&xpt_busses));
2561              bus != NULL;
2562              bus = next_bus) {
2563                 next_bus = TAILQ_NEXT(bus, links);
2564
2565                 retval = tr_func(bus, arg);
2566                 if (retval == 0)
2567                         return(retval);
2568         }
2569
2570         return(retval);
2571 }
2572
2573 static int
2574 xpttargettraverse(struct cam_eb *bus, struct cam_et *start_target,
2575                   xpt_targetfunc_t *tr_func, void *arg)
2576 {
2577         struct cam_et *target, *next_target;
2578         int retval;
2579
2580         retval = 1;
2581         for (target = (start_target ? start_target :
2582                        TAILQ_FIRST(&bus->et_entries));
2583              target != NULL; target = next_target) {
2584
2585                 next_target = TAILQ_NEXT(target, links);
2586
2587                 retval = tr_func(target, arg);
2588
2589                 if (retval == 0)
2590                         return(retval);
2591         }
2592
2593         return(retval);
2594 }
2595
2596 static int
2597 xptdevicetraverse(struct cam_et *target, struct cam_ed *start_device,
2598                   xpt_devicefunc_t *tr_func, void *arg)
2599 {
2600         struct cam_ed *device, *next_device;
2601         int retval;
2602
2603         retval = 1;
2604         for (device = (start_device ? start_device :
2605                        TAILQ_FIRST(&target->ed_entries));
2606              device != NULL;
2607              device = next_device) {
2608
2609                 next_device = TAILQ_NEXT(device, links);
2610
2611                 retval = tr_func(device, arg);
2612
2613                 if (retval == 0)
2614                         return(retval);
2615         }
2616
2617         return(retval);
2618 }
2619
2620 static int
2621 xptperiphtraverse(struct cam_ed *device, struct cam_periph *start_periph,
2622                   xpt_periphfunc_t *tr_func, void *arg)
2623 {
2624         struct cam_periph *periph, *next_periph;
2625         int retval;
2626
2627         retval = 1;
2628
2629         for (periph = (start_periph ? start_periph :
2630                        SLIST_FIRST(&device->periphs));
2631              periph != NULL;
2632              periph = next_periph) {
2633
2634                 next_periph = SLIST_NEXT(periph, periph_links);
2635
2636                 retval = tr_func(periph, arg);
2637                 if (retval == 0)
2638                         return(retval);
2639         }
2640
2641         return(retval);
2642 }
2643
2644 static int
2645 xptpdrvtraverse(struct periph_driver **start_pdrv,
2646                 xpt_pdrvfunc_t *tr_func, void *arg)
2647 {
2648         struct periph_driver **pdrv;
2649         int retval;
2650
2651         retval = 1;
2652
2653         /*
2654          * We don't traverse the peripheral driver list like we do the
2655          * other lists, because it is a linker set, and therefore cannot be
2656          * changed during runtime.  If the peripheral driver list is ever
2657          * re-done to be something other than a linker set (i.e. it can
2658          * change while the system is running), the list traversal should
2659          * be modified to work like the other traversal functions.
2660          */
2661         for (pdrv = (start_pdrv ? start_pdrv : periph_drivers);
2662              *pdrv != NULL; pdrv++) {
2663                 retval = tr_func(pdrv, arg);
2664
2665                 if (retval == 0)
2666                         return(retval);
2667         }
2668
2669         return(retval);
2670 }
2671
2672 static int
2673 xptpdperiphtraverse(struct periph_driver **pdrv,
2674                     struct cam_periph *start_periph,
2675                     xpt_periphfunc_t *tr_func, void *arg)
2676 {
2677         struct cam_periph *periph, *next_periph;
2678         int retval;
2679
2680         retval = 1;
2681
2682         for (periph = (start_periph ? start_periph :
2683              TAILQ_FIRST(&(*pdrv)->units)); periph != NULL;
2684              periph = next_periph) {
2685
2686                 next_periph = TAILQ_NEXT(periph, unit_links);
2687
2688                 retval = tr_func(periph, arg);
2689                 if (retval == 0)
2690                         return(retval);
2691         }
2692         return(retval);
2693 }
2694
2695 static int
2696 xptdefbusfunc(struct cam_eb *bus, void *arg)
2697 {
2698         struct xpt_traverse_config *tr_config;
2699
2700         tr_config = (struct xpt_traverse_config *)arg;
2701
2702         if (tr_config->depth == XPT_DEPTH_BUS) {
2703                 xpt_busfunc_t *tr_func;
2704
2705                 tr_func = (xpt_busfunc_t *)tr_config->tr_func;
2706
2707                 return(tr_func(bus, tr_config->tr_arg));
2708         } else
2709                 return(xpttargettraverse(bus, NULL, xptdeftargetfunc, arg));
2710 }
2711
2712 static int
2713 xptdeftargetfunc(struct cam_et *target, void *arg)
2714 {
2715         struct xpt_traverse_config *tr_config;
2716
2717         tr_config = (struct xpt_traverse_config *)arg;
2718
2719         if (tr_config->depth == XPT_DEPTH_TARGET) {
2720                 xpt_targetfunc_t *tr_func;
2721
2722                 tr_func = (xpt_targetfunc_t *)tr_config->tr_func;
2723
2724                 return(tr_func(target, tr_config->tr_arg));
2725         } else
2726                 return(xptdevicetraverse(target, NULL, xptdefdevicefunc, arg));
2727 }
2728
2729 static int
2730 xptdefdevicefunc(struct cam_ed *device, void *arg)
2731 {
2732         struct xpt_traverse_config *tr_config;
2733
2734         tr_config = (struct xpt_traverse_config *)arg;
2735
2736         if (tr_config->depth == XPT_DEPTH_DEVICE) {
2737                 xpt_devicefunc_t *tr_func;
2738
2739                 tr_func = (xpt_devicefunc_t *)tr_config->tr_func;
2740
2741                 return(tr_func(device, tr_config->tr_arg));
2742         } else
2743                 return(xptperiphtraverse(device, NULL, xptdefperiphfunc, arg));
2744 }
2745
2746 static int
2747 xptdefperiphfunc(struct cam_periph *periph, void *arg)
2748 {
2749         struct xpt_traverse_config *tr_config;
2750         xpt_periphfunc_t *tr_func;
2751
2752         tr_config = (struct xpt_traverse_config *)arg;
2753
2754         tr_func = (xpt_periphfunc_t *)tr_config->tr_func;
2755
2756         /*
2757          * Unlike the other default functions, we don't check for depth
2758          * here.  The peripheral driver level is the last level in the EDT,
2759          * so if we're here, we should execute the function in question.
2760          */
2761         return(tr_func(periph, tr_config->tr_arg));
2762 }
2763
2764 /*
2765  * Execute the given function for every bus in the EDT.
2766  */
2767 static int
2768 xpt_for_all_busses(xpt_busfunc_t *tr_func, void *arg)
2769 {
2770         struct xpt_traverse_config tr_config;
2771
2772         tr_config.depth = XPT_DEPTH_BUS;
2773         tr_config.tr_func = tr_func;
2774         tr_config.tr_arg = arg;
2775
2776         return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2777 }
2778
2779 #ifdef notusedyet
2780 /*
2781  * Execute the given function for every target in the EDT.
2782  */
2783 static int
2784 xpt_for_all_targets(xpt_targetfunc_t *tr_func, void *arg)
2785 {
2786         struct xpt_traverse_config tr_config;
2787
2788         tr_config.depth = XPT_DEPTH_TARGET;
2789         tr_config.tr_func = tr_func;
2790         tr_config.tr_arg = arg;
2791
2792         return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2793 }
2794 #endif /* notusedyet */
2795
2796 /*
2797  * Execute the given function for every device in the EDT.
2798  */
2799 static int
2800 xpt_for_all_devices(xpt_devicefunc_t *tr_func, void *arg)
2801 {
2802         struct xpt_traverse_config tr_config;
2803
2804         tr_config.depth = XPT_DEPTH_DEVICE;
2805         tr_config.tr_func = tr_func;
2806         tr_config.tr_arg = arg;
2807
2808         return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2809 }
2810
2811 #ifdef notusedyet
2812 /*
2813  * Execute the given function for every peripheral in the EDT.
2814  */
2815 static int
2816 xpt_for_all_periphs(xpt_periphfunc_t *tr_func, void *arg)
2817 {
2818         struct xpt_traverse_config tr_config;
2819
2820         tr_config.depth = XPT_DEPTH_PERIPH;
2821         tr_config.tr_func = tr_func;
2822         tr_config.tr_arg = arg;
2823
2824         return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2825 }
2826 #endif /* notusedyet */
2827
2828 static int
2829 xptsetasyncfunc(struct cam_ed *device, void *arg)
2830 {
2831         struct cam_path path;
2832         struct ccb_getdev cgd;
2833         struct async_node *cur_entry;
2834
2835         cur_entry = (struct async_node *)arg;
2836
2837         /*
2838          * Don't report unconfigured devices (Wildcard devs,
2839          * devices only for target mode, device instances
2840          * that have been invalidated but are waiting for
2841          * their last reference count to be released).
2842          */
2843         if ((device->flags & CAM_DEV_UNCONFIGURED) != 0)
2844                 return (1);
2845
2846         xpt_compile_path(&path,
2847                          NULL,
2848                          device->target->bus->path_id,
2849                          device->target->target_id,
2850                          device->lun_id);
2851         xpt_setup_ccb(&cgd.ccb_h, &path, /*priority*/1);
2852         cgd.ccb_h.func_code = XPT_GDEV_TYPE;
2853         xpt_action((union ccb *)&cgd);
2854         cur_entry->callback(cur_entry->callback_arg,
2855                             AC_FOUND_DEVICE,
2856                             &path, &cgd);
2857         xpt_release_path(&path);
2858
2859         return(1);
2860 }
2861
2862 static int
2863 xptsetasyncbusfunc(struct cam_eb *bus, void *arg)
2864 {
2865         struct cam_path path;
2866         struct ccb_pathinq cpi;
2867         struct async_node *cur_entry;
2868
2869         cur_entry = (struct async_node *)arg;
2870
2871         xpt_compile_path(&path, /*periph*/NULL,
2872                          bus->sim->path_id,
2873                          CAM_TARGET_WILDCARD,
2874                          CAM_LUN_WILDCARD);
2875         xpt_setup_ccb(&cpi.ccb_h, &path, /*priority*/1);
2876         cpi.ccb_h.func_code = XPT_PATH_INQ;
2877         xpt_action((union ccb *)&cpi);
2878         cur_entry->callback(cur_entry->callback_arg,
2879                             AC_PATH_REGISTERED,
2880                             &path, &cpi);
2881         xpt_release_path(&path);
2882
2883         return(1);
2884 }
2885
2886 void
2887 xpt_action(union ccb *start_ccb)
2888 {
2889         CAM_DEBUG(start_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("xpt_action\n"));
2890
2891         start_ccb->ccb_h.status = CAM_REQ_INPROG;
2892
2893         crit_enter();
2894
2895         switch (start_ccb->ccb_h.func_code) {
2896         case XPT_SCSI_IO:
2897         {
2898 #ifdef CAM_NEW_TRAN_CODE
2899                 struct cam_ed *device;
2900 #endif /* CAM_NEW_TRAN_CODE */
2901 #ifdef CAMDEBUG
2902                 char cdb_str[(SCSI_MAX_CDBLEN * 3) + 1];
2903                 struct cam_path *path;
2904
2905                 path = start_ccb->ccb_h.path;
2906 #endif
2907
2908                 /*
2909                  * For the sake of compatibility with SCSI-1
2910                  * devices that may not understand the identify
2911                  * message, we include lun information in the
2912                  * second byte of all commands.  SCSI-1 specifies
2913                  * that luns are a 3 bit value and reserves only 3
2914                  * bits for lun information in the CDB.  Later
2915                  * revisions of the SCSI spec allow for more than 8
2916                  * luns, but have deprecated lun information in the
2917                  * CDB.  So, if the lun won't fit, we must omit.
2918                  *
2919                  * Also be aware that during initial probing for devices,
2920                  * the inquiry information is unknown but initialized to 0.
2921                  * This means that this code will be exercised while probing
2922                  * devices with an ANSI revision greater than 2.
2923                  */
2924 #ifdef CAM_NEW_TRAN_CODE
2925                 device = start_ccb->ccb_h.path->device;
2926                 if (device->protocol_version <= SCSI_REV_2
2927 #else /* CAM_NEW_TRAN_CODE */
2928                 if (SID_ANSI_REV(&start_ccb->ccb_h.path->device->inq_data) <= 2
2929 #endif /* CAM_NEW_TRAN_CODE */
2930                  && start_ccb->ccb_h.target_lun < 8
2931                  && (start_ccb->ccb_h.flags & CAM_CDB_POINTER) == 0) {
2932
2933                         start_ccb->csio.cdb_io.cdb_bytes[1] |=
2934                             start_ccb->ccb_h.target_lun << 5;
2935                 }
2936                 start_ccb->csio.scsi_status = SCSI_STATUS_OK;
2937                 CAM_DEBUG(path, CAM_DEBUG_CDB,("%s. CDB: %s\n",
2938                           scsi_op_desc(start_ccb->csio.cdb_io.cdb_bytes[0],
2939                                        &path->device->inq_data),
2940                           scsi_cdb_string(start_ccb->csio.cdb_io.cdb_bytes,
2941                                           cdb_str, sizeof(cdb_str))));
2942                 /* FALLTHROUGH */
2943         }
2944         case XPT_TARGET_IO:
2945         case XPT_CONT_TARGET_IO:
2946                 start_ccb->csio.sense_resid = 0;
2947                 start_ccb->csio.resid = 0;
2948                 /* FALLTHROUGH */
2949         case XPT_RESET_DEV:
2950         case XPT_ENG_EXEC:
2951         {
2952                 struct cam_path *path;
2953                 int runq;
2954
2955                 path = start_ccb->ccb_h.path;
2956
2957                 cam_ccbq_insert_ccb(&path->device->ccbq, start_ccb);
2958                 if (path->device->qfrozen_cnt == 0)
2959                         runq = xpt_schedule_dev_sendq(path->bus, path->device);
2960                 else
2961                         runq = 0;
2962                 if (runq != 0)
2963                         xpt_run_dev_sendq(path->bus);
2964                 break;
2965         }
2966         case XPT_SET_TRAN_SETTINGS:
2967         {
2968                 xpt_set_transfer_settings(&start_ccb->cts,
2969                                           start_ccb->ccb_h.path->device,
2970                                           /*async_update*/FALSE);
2971                 break;
2972         }
2973         case XPT_CALC_GEOMETRY:
2974         {
2975                 struct cam_sim *sim;
2976
2977                 /* Filter out garbage */
2978                 if (start_ccb->ccg.block_size == 0
2979                  || start_ccb->ccg.volume_size == 0) {
2980                         start_ccb->ccg.cylinders = 0;
2981                         start_ccb->ccg.heads = 0;
2982                         start_ccb->ccg.secs_per_track = 0;
2983                         start_ccb->ccb_h.status = CAM_REQ_CMP;
2984                         break;
2985                 }
2986                 sim = start_ccb->ccb_h.path->bus->sim;
2987                 (*(sim->sim_action))(sim, start_ccb);
2988                 break;
2989         }
2990         case XPT_ABORT:
2991         {
2992                 union ccb* abort_ccb;
2993
2994                 abort_ccb = start_ccb->cab.abort_ccb;
2995                 if (XPT_FC_IS_DEV_QUEUED(abort_ccb)) {
2996
2997                         if (abort_ccb->ccb_h.pinfo.index >= 0) {
2998                                 struct cam_ccbq *ccbq;
2999
3000                                 ccbq = &abort_ccb->ccb_h.path->device->ccbq;
3001                                 cam_ccbq_remove_ccb(ccbq, abort_ccb);
3002                                 abort_ccb->ccb_h.status =
3003                                     CAM_REQ_ABORTED|CAM_DEV_QFRZN;
3004                                 xpt_freeze_devq(abort_ccb->ccb_h.path, 1);
3005                                 xpt_done(abort_ccb);
3006                                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3007                                 break;
3008                         }
3009                         if (abort_ccb->ccb_h.pinfo.index == CAM_UNQUEUED_INDEX
3010                          && (abort_ccb->ccb_h.status & CAM_SIM_QUEUED) == 0) {
3011                                 /*
3012                                  * We've caught this ccb en route to
3013                                  * the SIM.  Flag it for abort and the
3014                                  * SIM will do so just before starting
3015                                  * real work on the CCB.
3016                                  */
3017                                 abort_ccb->ccb_h.status =
3018                                     CAM_REQ_ABORTED|CAM_DEV_QFRZN;
3019                                 xpt_freeze_devq(abort_ccb->ccb_h.path, 1);
3020                                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3021                                 break;
3022                         }
3023                 } 
3024                 if (XPT_FC_IS_QUEUED(abort_ccb)
3025                  && (abort_ccb->ccb_h.pinfo.index == CAM_DONEQ_INDEX)) {
3026                         /*
3027                          * It's already completed but waiting
3028                          * for our SWI to get to it.
3029                          */
3030                         start_ccb->ccb_h.status = CAM_UA_ABORT;
3031                         break;
3032                 }
3033                 /*
3034                  * If we weren't able to take care of the abort request
3035                  * in the XPT, pass the request down to the SIM for processing.
3036                  */
3037                 /* FALLTHROUGH */
3038         }
3039         case XPT_ACCEPT_TARGET_IO:
3040         case XPT_EN_LUN:
3041         case XPT_IMMED_NOTIFY:
3042         case XPT_NOTIFY_ACK:
3043         case XPT_GET_TRAN_SETTINGS:
3044         case XPT_RESET_BUS:
3045         {
3046                 struct cam_sim *sim;
3047
3048                 sim = start_ccb->ccb_h.path->bus->sim;
3049                 (*(sim->sim_action))(sim, start_ccb);
3050                 break;
3051         }
3052         case XPT_PATH_INQ:
3053         {
3054                 struct cam_sim *sim;
3055
3056                 sim = start_ccb->ccb_h.path->bus->sim;
3057                 (*(sim->sim_action))(sim, start_ccb);
3058                 break;
3059         }
3060         case XPT_PATH_STATS:
3061                 start_ccb->cpis.last_reset =
3062                         start_ccb->ccb_h.path->bus->last_reset;
3063                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3064                 break;
3065         case XPT_GDEV_TYPE:
3066         {
3067                 struct cam_ed *dev;
3068
3069                 dev = start_ccb->ccb_h.path->device;
3070                 if ((dev->flags & CAM_DEV_UNCONFIGURED) != 0) {
3071                         start_ccb->ccb_h.status = CAM_DEV_NOT_THERE;
3072                 } else {
3073                         struct ccb_getdev *cgd;
3074                         struct cam_eb *bus;
3075                         struct cam_et *tar;
3076
3077                         cgd = &start_ccb->cgd;
3078                         bus = cgd->ccb_h.path->bus;
3079                         tar = cgd->ccb_h.path->target;
3080                         cgd->inq_data = dev->inq_data;
3081                         cgd->ccb_h.status = CAM_REQ_CMP;
3082                         cgd->serial_num_len = dev->serial_num_len;
3083                         if ((dev->serial_num_len > 0)
3084                          && (dev->serial_num != NULL))
3085                                 bcopy(dev->serial_num, cgd->serial_num,
3086                                       dev->serial_num_len);
3087                 }
3088                 break; 
3089         }
3090         case XPT_GDEV_STATS:
3091         {
3092                 struct cam_ed *dev;
3093
3094                 dev = start_ccb->ccb_h.path->device;
3095                 if ((dev->flags & CAM_DEV_UNCONFIGURED) != 0) {
3096                         start_ccb->ccb_h.status = CAM_DEV_NOT_THERE;
3097                 } else {
3098                         struct ccb_getdevstats *cgds;
3099                         struct cam_eb *bus;
3100                         struct cam_et *tar;
3101
3102                         cgds = &start_ccb->cgds;
3103                         bus = cgds->ccb_h.path->bus;
3104                         tar = cgds->ccb_h.path->target;
3105                         cgds->dev_openings = dev->ccbq.dev_openings;
3106                         cgds->dev_active = dev->ccbq.dev_active;
3107                         cgds->devq_openings = dev->ccbq.devq_openings;
3108                         cgds->devq_queued = dev->ccbq.queue.entries;
3109                         cgds->held = dev->ccbq.held;
3110                         cgds->last_reset = tar->last_reset;
3111                         cgds->maxtags = dev->quirk->maxtags;
3112                         cgds->mintags = dev->quirk->mintags;
3113                         if (timevalcmp(&tar->last_reset, &bus->last_reset, <))
3114                                 cgds->last_reset = bus->last_reset;
3115                         cgds->ccb_h.status = CAM_REQ_CMP;
3116                 }
3117                 break;
3118         }
3119         case XPT_GDEVLIST:
3120         {
3121                 struct cam_periph       *nperiph;
3122                 struct periph_list      *periph_head;
3123                 struct ccb_getdevlist   *cgdl;
3124                 u_int                   i;
3125                 struct cam_ed           *device;
3126                 int                     found;
3127
3128
3129                 found = 0;
3130
3131                 /*
3132                  * Don't want anyone mucking with our data.
3133                  */
3134                 device = start_ccb->ccb_h.path->device;
3135                 periph_head = &device->periphs;
3136                 cgdl = &start_ccb->cgdl;
3137
3138                 /*
3139                  * Check and see if the list has changed since the user
3140                  * last requested a list member.  If so, tell them that the
3141                  * list has changed, and therefore they need to start over 
3142                  * from the beginning.
3143                  */
3144                 if ((cgdl->index != 0) && 
3145                     (cgdl->generation != device->generation)) {
3146                         cgdl->status = CAM_GDEVLIST_LIST_CHANGED;
3147                         break;
3148                 }
3149
3150                 /*
3151                  * Traverse the list of peripherals and attempt to find 
3152                  * the requested peripheral.
3153                  */
3154                 for (nperiph = SLIST_FIRST(periph_head), i = 0;
3155                      (nperiph != NULL) && (i <= cgdl->index);
3156                      nperiph = SLIST_NEXT(nperiph, periph_links), i++) {
3157                         if (i == cgdl->index) {
3158                                 strncpy(cgdl->periph_name,
3159                                         nperiph->periph_name,
3160                                         DEV_IDLEN);
3161                                 cgdl->unit_number = nperiph->unit_number;
3162                                 found = 1;
3163                         }
3164                 }
3165                 if (found == 0) {
3166                         cgdl->status = CAM_GDEVLIST_ERROR;
3167                         break;
3168                 }
3169
3170                 if (nperiph == NULL)
3171                         cgdl->status = CAM_GDEVLIST_LAST_DEVICE;
3172                 else
3173                         cgdl->status = CAM_GDEVLIST_MORE_DEVS;
3174
3175                 cgdl->index++;
3176                 cgdl->generation = device->generation;
3177
3178                 cgdl->ccb_h.status = CAM_REQ_CMP;
3179                 break;
3180         }
3181         case XPT_DEV_MATCH:
3182         {
3183                 dev_pos_type position_type;
3184                 struct ccb_dev_match *cdm;
3185                 int ret;
3186
3187                 cdm = &start_ccb->cdm;
3188
3189                 /*
3190                  * Prevent EDT changes while we traverse it.
3191                  */
3192                 /*
3193                  * There are two ways of getting at information in the EDT.
3194                  * The first way is via the primary EDT tree.  It starts
3195                  * with a list of busses, then a list of targets on a bus,
3196                  * then devices/luns on a target, and then peripherals on a
3197                  * device/lun.  The "other" way is by the peripheral driver
3198                  * lists.  The peripheral driver lists are organized by
3199                  * peripheral driver.  (obviously)  So it makes sense to
3200                  * use the peripheral driver list if the user is looking
3201                  * for something like "da1", or all "da" devices.  If the
3202                  * user is looking for something on a particular bus/target
3203                  * or lun, it's generally better to go through the EDT tree.
3204                  */
3205
3206                 if (cdm->pos.position_type != CAM_DEV_POS_NONE)
3207                         position_type = cdm->pos.position_type;
3208                 else {
3209                         u_int i;
3210
3211                         position_type = CAM_DEV_POS_NONE;
3212
3213                         for (i = 0; i < cdm->num_patterns; i++) {
3214                                 if ((cdm->patterns[i].type == DEV_MATCH_BUS)
3215                                  ||(cdm->patterns[i].type == DEV_MATCH_DEVICE)){
3216                                         position_type = CAM_DEV_POS_EDT;
3217                                         break;
3218                                 }
3219                         }
3220
3221                         if (cdm->num_patterns == 0)
3222                                 position_type = CAM_DEV_POS_EDT;
3223                         else if (position_type == CAM_DEV_POS_NONE)
3224                                 position_type = CAM_DEV_POS_PDRV;
3225                 }
3226
3227                 switch(position_type & CAM_DEV_POS_TYPEMASK) {
3228                 case CAM_DEV_POS_EDT:
3229                         ret = xptedtmatch(cdm);
3230                         break;
3231                 case CAM_DEV_POS_PDRV:
3232                         ret = xptperiphlistmatch(cdm);
3233                         break;
3234                 default:
3235                         cdm->status = CAM_DEV_MATCH_ERROR;
3236                         break;
3237                 }
3238
3239                 if (cdm->status == CAM_DEV_MATCH_ERROR)
3240                         start_ccb->ccb_h.status = CAM_REQ_CMP_ERR;
3241                 else
3242                         start_ccb->ccb_h.status = CAM_REQ_CMP;
3243
3244                 break;
3245         }
3246         case XPT_SASYNC_CB:
3247         {
3248                 struct ccb_setasync *csa;
3249                 struct async_node *cur_entry;
3250                 struct async_list *async_head;
3251                 u_int32_t added;
3252
3253                 csa = &start_ccb->csa;
3254                 added = csa->event_enable;
3255                 async_head = &csa->ccb_h.path->device->asyncs;
3256
3257                 /*
3258                  * If there is already an entry for us, simply
3259                  * update it.
3260                  */
3261                 cur_entry = SLIST_FIRST(async_head);
3262                 while (cur_entry != NULL) {
3263                         if ((cur_entry->callback_arg == csa->callback_arg)
3264                          && (cur_entry->callback == csa->callback))
3265                                 break;
3266                         cur_entry = SLIST_NEXT(cur_entry, links);
3267                 }
3268
3269                 if (cur_entry != NULL) {
3270                         /*
3271                          * If the request has no flags set,
3272                          * remove the entry.
3273                          */
3274                         added &= ~cur_entry->event_enable;
3275                         if (csa->event_enable == 0) {
3276                                 SLIST_REMOVE(async_head, cur_entry,
3277                                              async_node, links);
3278                                 csa->ccb_h.path->device->refcount--;
3279                                 kfree(cur_entry, M_DEVBUF);
3280                         } else {
3281                                 cur_entry->event_enable = csa->event_enable;
3282                         }
3283                 } else {
3284                         cur_entry = kmalloc(sizeof(*cur_entry), 
3285                                             M_DEVBUF, M_INTWAIT);
3286                         cur_entry->event_enable = csa->event_enable;
3287                         cur_entry->callback_arg = csa->callback_arg;
3288                         cur_entry->callback = csa->callback;
3289                         SLIST_INSERT_HEAD(async_head, cur_entry, links);
3290                         csa->ccb_h.path->device->refcount++;
3291                 }
3292
3293                 if ((added & AC_FOUND_DEVICE) != 0) {
3294                         /*
3295                          * Get this peripheral up to date with all
3296                          * the currently existing devices.
3297                          */
3298                         xpt_for_all_devices(xptsetasyncfunc, cur_entry);
3299                 }
3300                 if ((added & AC_PATH_REGISTERED) != 0) {
3301                         /*
3302                          * Get this peripheral up to date with all
3303                          * the currently existing busses.
3304                          */
3305                         xpt_for_all_busses(xptsetasyncbusfunc, cur_entry);
3306                 }
3307                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3308                 break;
3309         }
3310         case XPT_REL_SIMQ:
3311         {
3312                 struct ccb_relsim *crs;
3313                 struct cam_ed *dev;
3314
3315                 crs = &start_ccb->crs;
3316                 dev = crs->ccb_h.path->device;
3317                 if (dev == NULL) {
3318
3319                         crs->ccb_h.status = CAM_DEV_NOT_THERE;
3320                         break;
3321                 }
3322
3323                 if ((crs->release_flags & RELSIM_ADJUST_OPENINGS) != 0) {
3324
3325                         if ((dev->inq_data.flags & SID_CmdQue) != 0) {
3326
3327                                 /* Don't ever go below one opening */
3328                                 if (crs->openings > 0) {
3329                                         xpt_dev_ccbq_resize(crs->ccb_h.path,
3330                                                             crs->openings);
3331
3332                                         if (bootverbose) {
3333                                                 xpt_print_path(crs->ccb_h.path);
3334                                                 kprintf("tagged openings "
3335                                                        "now %d\n",
3336                                                        crs->openings);
3337                                         }
3338                                 }
3339                         }
3340                 }
3341
3342                 if ((crs->release_flags & RELSIM_RELEASE_AFTER_TIMEOUT) != 0) {
3343
3344                         if ((dev->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
3345
3346                                 /*
3347                                  * Just extend the old timeout and decrement
3348                                  * the freeze count so that a single timeout
3349                                  * is sufficient for releasing the queue.
3350                                  */
3351                                 start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
3352                                 callout_stop(&dev->c_handle);
3353                         } else {
3354
3355                                 start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
3356                         }
3357
3358                         callout_reset(&dev->c_handle,
3359                                       (crs->release_timeout * hz) / 1000, 
3360                                       xpt_release_devq_timeout, dev);
3361
3362                         dev->flags |= CAM_DEV_REL_TIMEOUT_PENDING;
3363
3364                 }
3365
3366                 if ((crs->release_flags & RELSIM_RELEASE_AFTER_CMDCMPLT) != 0) {
3367
3368                         if ((dev->flags & CAM_DEV_REL_ON_COMPLETE) != 0) {
3369                                 /*
3370                                  * Decrement the freeze count so that a single
3371                                  * completion is still sufficient to unfreeze
3372                                  * the queue.
3373                                  */
3374                                 start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
3375                         } else {
3376                                 
3377                                 dev->flags |= CAM_DEV_REL_ON_COMPLETE;
3378                                 start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
3379                         }
3380                 }
3381
3382                 if ((crs->release_flags & RELSIM_RELEASE_AFTER_QEMPTY) != 0) {
3383
3384                         if ((dev->flags & CAM_DEV_REL_ON_QUEUE_EMPTY) != 0
3385                          || (dev->ccbq.dev_active == 0)) {
3386
3387                                 start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
3388                         } else {
3389                                 
3390                                 dev->flags |= CAM_DEV_REL_ON_QUEUE_EMPTY;
3391                                 start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
3392                         }
3393                 }
3394                 
3395                 if ((start_ccb->ccb_h.flags & CAM_DEV_QFREEZE) == 0) {
3396
3397                         xpt_release_devq(crs->ccb_h.path, /*count*/1,
3398                                          /*run_queue*/TRUE);
3399                 }
3400                 start_ccb->crs.qfrozen_cnt = dev->qfrozen_cnt;
3401                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3402                 break;
3403         }
3404         case XPT_SCAN_BUS:
3405                 xpt_scan_bus(start_ccb->ccb_h.path->periph, start_ccb);
3406                 break;
3407         case XPT_SCAN_LUN:
3408                 xpt_scan_lun(start_ccb->ccb_h.path->periph,
3409                              start_ccb->ccb_h.path, start_ccb->crcn.flags,
3410                              start_ccb);
3411                 break;
3412         case XPT_DEBUG: {
3413 #ifdef CAMDEBUG
3414 #ifdef CAM_DEBUG_DELAY
3415                 cam_debug_delay = CAM_DEBUG_DELAY;
3416 #endif
3417                 cam_dflags = start_ccb->cdbg.flags;
3418                 if (cam_dpath != NULL) {
3419                         xpt_free_path(cam_dpath);
3420                         cam_dpath = NULL;
3421                 }
3422
3423                 if (cam_dflags != CAM_DEBUG_NONE) {
3424                         if (xpt_create_path(&cam_dpath, xpt_periph,
3425                                             start_ccb->ccb_h.path_id,
3426                                             start_ccb->ccb_h.target_id,
3427                                             start_ccb->ccb_h.target_lun) !=
3428                                             CAM_REQ_CMP) {
3429                                 start_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
3430                                 cam_dflags = CAM_DEBUG_NONE;
3431                         } else {
3432                                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3433                                 xpt_print_path(cam_dpath);
3434                                 kprintf("debugging flags now %x\n", cam_dflags);
3435                         }
3436                 } else {
3437                         cam_dpath = NULL;
3438                         start_ccb->ccb_h.status = CAM_REQ_CMP;
3439                 }
3440 #else /* !CAMDEBUG */
3441                 start_ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
3442 #endif /* CAMDEBUG */
3443                 break;
3444         }
3445         case XPT_NOOP:
3446                 if ((start_ccb->ccb_h.flags & CAM_DEV_QFREEZE) != 0)
3447                         xpt_freeze_devq(start_ccb->ccb_h.path, 1);
3448                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3449                 break;
3450         default:
3451         case XPT_SDEV_TYPE:
3452         case XPT_TERM_IO:
3453         case XPT_ENG_INQ:
3454                 /* XXX Implement */
3455                 start_ccb->ccb_h.status = CAM_PROVIDE_FAIL;
3456                 break;
3457         }
3458         crit_exit();
3459 }
3460
3461 void
3462 xpt_polled_action(union ccb *start_ccb)
3463 {
3464         u_int32_t timeout;
3465         struct    cam_sim *sim; 
3466         struct    cam_devq *devq;
3467         struct    cam_ed *dev;
3468
3469         timeout = start_ccb->ccb_h.timeout;
3470         sim = start_ccb->ccb_h.path->bus->sim;
3471         devq = sim->devq;
3472         dev = start_ccb->ccb_h.path->device;
3473
3474         crit_enter();
3475
3476         /*
3477          * Steal an opening so that no other queued requests
3478          * can get it before us while we simulate interrupts.
3479          */
3480         dev->ccbq.devq_openings--;
3481         dev->ccbq.dev_openings--;       
3482         
3483         while(((devq && devq->send_openings <= 0) || dev->ccbq.dev_openings < 0)
3484            && (--timeout > 0)) {
3485                 DELAY(1000);
3486                 (*(sim->sim_poll))(sim);
3487                 swi_camnet(NULL, NULL);
3488                 swi_cambio(NULL, NULL);         
3489         }
3490         
3491         dev->ccbq.devq_openings++;
3492         dev->ccbq.dev_openings++;
3493         
3494         if (timeout != 0) {
3495                 xpt_action(start_ccb);
3496                 while(--timeout > 0) {
3497                         (*(sim->sim_poll))(sim);
3498                         swi_camnet(NULL, NULL);
3499                         swi_cambio(NULL, NULL);
3500                         if ((start_ccb->ccb_h.status  & CAM_STATUS_MASK)
3501                             != CAM_REQ_INPROG)
3502                                 break;
3503                         DELAY(1000);
3504                 }
3505                 if (timeout == 0) {
3506                         /*
3507                          * XXX Is it worth adding a sim_timeout entry
3508                          * point so we can attempt recovery?  If
3509                          * this is only used for dumps, I don't think
3510                          * it is.
3511                          */
3512                         start_ccb->ccb_h.status = CAM_CMD_TIMEOUT;
3513                 }
3514         } else {
3515                 start_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
3516         }
3517         crit_exit();
3518 }
3519         
3520 /*
3521  * Schedule a peripheral driver to receive a ccb when it's
3522  * target device has space for more transactions.
3523  */
3524 void
3525 xpt_schedule(struct cam_periph *perph, u_int32_t new_priority)
3526 {
3527         struct cam_ed *device;
3528         int runq;
3529
3530         CAM_DEBUG(perph->path, CAM_DEBUG_TRACE, ("xpt_schedule\n"));
3531         device = perph->path->device;
3532         crit_enter();
3533         if (periph_is_queued(perph)) {
3534                 /* Simply reorder based on new priority */
3535                 CAM_DEBUG(perph->path, CAM_DEBUG_SUBTRACE,
3536                           ("   change priority to %d\n", new_priority));
3537                 if (new_priority < perph->pinfo.priority) {
3538                         camq_change_priority(&device->drvq,
3539                                              perph->pinfo.index,
3540                                              new_priority);
3541                 }
3542                 runq = 0;
3543         } else {
3544                 /* New entry on the queue */
3545                 CAM_DEBUG(perph->path, CAM_DEBUG_SUBTRACE,
3546                           ("   added periph to queue\n"));
3547                 perph->pinfo.priority = new_priority;
3548                 perph->pinfo.generation = ++device->drvq.generation;
3549                 camq_insert(&device->drvq, &perph->pinfo);
3550                 runq = xpt_schedule_dev_allocq(perph->path->bus, device);
3551         }
3552         crit_exit();
3553         if (runq != 0) {
3554                 CAM_DEBUG(perph->path, CAM_DEBUG_SUBTRACE,
3555                           ("   calling xpt_run_devq\n"));
3556                 xpt_run_dev_allocq(perph->path->bus);
3557         }
3558 }
3559
3560
3561 /*
3562  * Schedule a device to run on a given queue.
3563  * If the device was inserted as a new entry on the queue,
3564  * return 1 meaning the device queue should be run. If we
3565  * were already queued, implying someone else has already
3566  * started the queue, return 0 so the caller doesn't attempt
3567  * to run the queue.  Must be run in a critical section.
3568  */
3569 static int
3570 xpt_schedule_dev(struct camq *queue, cam_pinfo *pinfo,
3571                  u_int32_t new_priority)
3572 {
3573         int retval;
3574         u_int32_t old_priority;
3575
3576         CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_schedule_dev\n"));
3577
3578         old_priority = pinfo->priority;
3579
3580         /*
3581          * Are we already queued?
3582          */
3583         if (pinfo->index != CAM_UNQUEUED_INDEX) {
3584                 /* Simply reorder based on new priority */
3585                 if (new_priority < old_priority) {
3586                         camq_change_priority(queue, pinfo->index,
3587                                              new_priority);
3588                         CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3589                                         ("changed priority to %d\n",
3590                                          new_priority));
3591                 }
3592                 retval = 0;
3593         } else {
3594                 /* New entry on the queue */
3595                 if (new_priority < old_priority)
3596                         pinfo->priority = new_priority;
3597
3598                 CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3599                                 ("Inserting onto queue\n"));
3600                 pinfo->generation = ++queue->generation;
3601                 camq_insert(queue, pinfo);
3602                 retval = 1;
3603         }
3604         return (retval);
3605 }
3606
3607 static void
3608 xpt_run_dev_allocq(struct cam_eb *bus)
3609 {
3610         struct  cam_devq *devq;
3611
3612         if ((devq = bus->sim->devq) == NULL) {
3613                 CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_dev_allocq: NULL devq\n"));
3614                 return;
3615         }
3616         CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_dev_allocq\n"));
3617
3618         CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3619                         ("   qfrozen_cnt == 0x%x, entries == %d, "
3620                          "openings == %d, active == %d\n",
3621                          devq->alloc_queue.qfrozen_cnt,
3622                          devq->alloc_queue.entries,
3623                          devq->alloc_openings,
3624                          devq->alloc_active));
3625
3626         crit_enter();
3627         devq->alloc_queue.qfrozen_cnt++;
3628         while ((devq->alloc_queue.entries > 0)
3629             && (devq->alloc_openings > 0)
3630             && (devq->alloc_queue.qfrozen_cnt <= 1)) {
3631                 struct  cam_ed_qinfo *qinfo;
3632                 struct  cam_ed *device;
3633                 union   ccb *work_ccb;
3634                 struct  cam_periph *drv;
3635                 struct  camq *drvq;
3636                 
3637                 qinfo = (struct cam_ed_qinfo *)camq_remove(&devq->alloc_queue,
3638                                                            CAMQ_HEAD);
3639                 device = qinfo->device;
3640
3641                 CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3642                                 ("running device %p\n", device));
3643
3644                 drvq = &device->drvq;
3645
3646 #ifdef CAMDEBUG
3647                 if (drvq->entries <= 0) {
3648                         panic("xpt_run_dev_allocq: "
3649                               "Device on queue without any work to do");
3650                 }
3651 #endif
3652                 if ((work_ccb = xpt_get_ccb(device)) != NULL) {
3653                         devq->alloc_openings--;
3654                         devq->alloc_active++;
3655                         drv = (struct cam_periph*)camq_remove(drvq, CAMQ_HEAD);
3656                         crit_exit();
3657                         xpt_setup_ccb(&work_ccb->ccb_h, drv->path,
3658                                       drv->pinfo.priority);
3659                         CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3660                                         ("calling periph start\n"));
3661                         drv->periph_start(drv, work_ccb);
3662                 } else {
3663                         /*
3664                          * Malloc failure in alloc_ccb
3665                          */
3666                         /*
3667                          * XXX add us to a list to be run from free_ccb
3668                          * if we don't have any ccbs active on this
3669                          * device queue otherwise we may never get run
3670                          * again.
3671                          */
3672                         break;
3673                 }
3674         
3675                 /* Raise IPL for possible insertion and test at top of loop */
3676                 crit_enter();
3677
3678                 if (drvq->entries > 0) {
3679                         /* We have more work.  Attempt to reschedule */
3680                         xpt_schedule_dev_allocq(bus, device);
3681                 }
3682         }
3683         devq->alloc_queue.qfrozen_cnt--;
3684         crit_exit();
3685 }
3686
3687 static void
3688 xpt_run_dev_sendq(struct cam_eb *bus)
3689 {
3690         struct  cam_devq *devq;
3691
3692         if ((devq = bus->sim->devq) == NULL) {
3693                 CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_dev_sendq: NULL devq\n"));
3694                 return;
3695         }
3696         CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_dev_sendq\n"));
3697
3698         crit_enter();
3699         devq->send_queue.qfrozen_cnt++;
3700         while ((devq->send_queue.entries > 0)
3701             && (devq->send_openings > 0)) {
3702                 struct  cam_ed_qinfo *qinfo;
3703                 struct  cam_ed *device;
3704                 union ccb *work_ccb;
3705                 struct  cam_sim *sim;
3706
3707                 if (devq->send_queue.qfrozen_cnt > 1) {
3708                         break;
3709                 }
3710
3711                 qinfo = (struct cam_ed_qinfo *)camq_remove(&devq->send_queue,
3712                                                            CAMQ_HEAD);
3713                 device = qinfo->device;
3714
3715                 /*
3716                  * If the device has been "frozen", don't attempt
3717                  * to run it.
3718                  */
3719                 if (device->qfrozen_cnt > 0) {
3720                         continue;
3721                 }
3722
3723                 CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3724                                 ("running device %p\n", device));
3725
3726                 work_ccb = cam_ccbq_peek_ccb(&device->ccbq, CAMQ_HEAD);
3727                 if (work_ccb == NULL) {
3728                         kprintf("device on run queue with no ccbs???\n");
3729                         continue;
3730                 }
3731
3732                 if ((work_ccb->ccb_h.flags & CAM_HIGH_POWER) != 0) {
3733
3734                         if (num_highpower <= 0) {
3735                                 /*
3736                                  * We got a high power command, but we
3737                                  * don't have any available slots.  Freeze
3738                                  * the device queue until we have a slot
3739                                  * available.
3740                                  */
3741                                 device->qfrozen_cnt++;
3742                                 STAILQ_INSERT_TAIL(&highpowerq, 
3743                                                    &work_ccb->ccb_h, 
3744                                                    xpt_links.stqe);
3745
3746                                 continue;
3747                         } else {
3748                                 /*
3749                                  * Consume a high power slot while
3750                                  * this ccb runs.
3751                                  */
3752                                 num_highpower--;
3753                         }
3754                 }
3755                 devq->active_dev = device;
3756                 cam_ccbq_remove_ccb(&device->ccbq, work_ccb);
3757
3758                 cam_ccbq_send_ccb(&device->ccbq, work_ccb);
3759
3760                 devq->send_openings--;
3761                 devq->send_active++;            
3762                 
3763                 if (device->ccbq.queue.entries > 0)
3764                         xpt_schedule_dev_sendq(bus, device);
3765
3766                 if (work_ccb && (work_ccb->ccb_h.flags & CAM_DEV_QFREEZE) != 0){
3767                         /*
3768                          * The client wants to freeze the queue
3769                          * after this CCB is sent.
3770                          */
3771                         device->qfrozen_cnt++;
3772                 }
3773
3774                 /* In Target mode, the peripheral driver knows best... */
3775                 if (work_ccb->ccb_h.func_code == XPT_SCSI_IO) {
3776                         if ((device->inq_flags & SID_CmdQue) != 0
3777                          && work_ccb->csio.tag_action != CAM_TAG_ACTION_NONE)
3778                                 work_ccb->ccb_h.flags |= CAM_TAG_ACTION_VALID;
3779                         else
3780                                 /*
3781                                  * Clear this in case of a retried CCB that
3782                                  * failed due to a rejected tag.
3783                                  */
3784                                 work_ccb->ccb_h.flags &= ~CAM_TAG_ACTION_VALID;
3785                 }
3786
3787                 /*
3788                  * Device queues can be shared among multiple sim instances
3789                  * that reside on different busses.  Use the SIM in the queue
3790                  * CCB's path, rather than the one in the bus that was passed
3791                  * into this function.
3792                  */
3793                 sim = work_ccb->ccb_h.path->bus->sim;
3794                 (*(sim->sim_action))(sim, work_ccb);
3795
3796                 devq->active_dev = NULL;
3797                 /* Raise IPL for possible insertion and test at top of loop */
3798         }
3799         devq->send_queue.qfrozen_cnt--;
3800         crit_exit();
3801 }
3802
3803 /*
3804  * This function merges stuff from the slave ccb into the master ccb, while
3805  * keeping important fields in the master ccb constant.
3806  */
3807 void
3808 xpt_merge_ccb(union ccb *master_ccb, union ccb *slave_ccb)
3809 {
3810         /*
3811          * Pull fields that are valid for peripheral drivers to set
3812          * into the master CCB along with the CCB "payload".
3813          */
3814         master_ccb->ccb_h.retry_count = slave_ccb->ccb_h.retry_count;
3815         master_ccb->ccb_h.func_code = slave_ccb->ccb_h.func_code;
3816         master_ccb->ccb_h.timeout = slave_ccb->ccb_h.timeout;
3817         master_ccb->ccb_h.flags = slave_ccb->ccb_h.flags;
3818         bcopy(&(&slave_ccb->ccb_h)[1], &(&master_ccb->ccb_h)[1],
3819               sizeof(union ccb) - sizeof(struct ccb_hdr));
3820 }
3821
3822 void
3823 xpt_setup_ccb(struct ccb_hdr *ccb_h, struct cam_path *path, u_int32_t priority)
3824 {
3825         CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_setup_ccb\n"));
3826         callout_init(&ccb_h->timeout_ch);
3827         ccb_h->pinfo.priority = priority;
3828         ccb_h->path = path;
3829         ccb_h->path_id = path->bus->path_id;
3830         if (path->target)
3831                 ccb_h->target_id = path->target->target_id;
3832         else
3833                 ccb_h->target_id = CAM_TARGET_WILDCARD;
3834         if (path->device) {
3835                 ccb_h->target_lun = path->device->lun_id;
3836                 ccb_h->pinfo.generation = ++path->device->ccbq.queue.generation;
3837         } else {
3838                 ccb_h->target_lun = CAM_TARGET_WILDCARD;
3839         }
3840         ccb_h->pinfo.index = CAM_UNQUEUED_INDEX;
3841         ccb_h->flags = 0;
3842 }
3843
3844 /* Path manipulation functions */
3845 cam_status
3846 xpt_create_path(struct cam_path **new_path_ptr, struct cam_periph *perph,
3847                 path_id_t path_id, target_id_t target_id, lun_id_t lun_id)
3848 {
3849         struct     cam_path *path;
3850         cam_status status;
3851
3852         path = kmalloc(sizeof(*path), M_DEVBUF, M_INTWAIT);
3853         status = xpt_compile_path(path, perph, path_id, target_id, lun_id);
3854         if (status != CAM_REQ_CMP) {
3855                 kfree(path, M_DEVBUF);
3856                 path = NULL;
3857         }
3858         *new_path_ptr = path;
3859         return (status);
3860 }
3861
3862 static cam_status
3863 xpt_compile_path(struct cam_path *new_path, struct cam_periph *perph,
3864                  path_id_t path_id, target_id_t target_id, lun_id_t lun_id)
3865 {
3866         struct       cam_eb *bus;
3867         struct       cam_et *target;
3868         struct       cam_ed *device;
3869         cam_status   status;
3870
3871         status = CAM_REQ_CMP;   /* Completed without error */
3872         target = NULL;          /* Wildcarded */
3873         device = NULL;          /* Wildcarded */
3874
3875         /*
3876          * We will potentially modify the EDT, so block interrupts
3877          * that may attempt to create cam paths.
3878          */
3879         crit_enter();
3880         bus = xpt_find_bus(path_id);
3881         if (bus == NULL) {
3882                 status = CAM_PATH_INVALID;
3883         } else {
3884                 target = xpt_find_target(bus, target_id);
3885                 if (target == NULL) {
3886                         /* Create one */
3887                         struct cam_et *new_target;
3888
3889                         new_target = xpt_alloc_target(bus, target_id);
3890                         if (new_target == NULL) {
3891                                 status = CAM_RESRC_UNAVAIL;
3892                         } else {
3893                                 target = new_target;
3894                         }
3895                 }
3896                 if (target != NULL) {
3897                         device = xpt_find_device(target, lun_id);
3898                         if (device == NULL) {
3899                                 /* Create one */
3900                                 struct cam_ed *new_device;
3901
3902                                 new_device = xpt_alloc_device(bus,
3903                                                               target,
3904                                                               lun_id);
3905                                 if (new_device == NULL) {
3906                                         status = CAM_RESRC_UNAVAIL;
3907                                 } else {
3908                                         device = new_device;
3909                                 }
3910                         }
3911                 }
3912         }
3913         crit_exit();
3914
3915         /*
3916          * Only touch the user's data if we are successful.
3917          */
3918         if (status == CAM_REQ_CMP) {
3919                 new_path->periph = perph;
3920                 new_path->bus = bus;
3921                 new_path->target = target;
3922                 new_path->device = device;
3923                 CAM_DEBUG(new_path, CAM_DEBUG_TRACE, ("xpt_compile_path\n"));
3924         } else {
3925                 if (device != NULL)
3926                         xpt_release_device(bus, target, device);
3927                 if (target != NULL)
3928                         xpt_release_target(bus, target);
3929                 if (bus != NULL)
3930                         xpt_release_bus(bus);
3931         }
3932         return (status);
3933 }
3934
3935 static void
3936 xpt_release_path(struct cam_path *path)
3937 {
3938         CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_release_path\n"));
3939         if (path->device != NULL) {
3940                 xpt_release_device(path->bus, path->target, path->device);
3941                 path->device = NULL;
3942         }
3943         if (path->target != NULL) {
3944                 xpt_release_target(path->bus, path->target);
3945                 path->target = NULL;
3946         }
3947         if (path->bus != NULL) {
3948                 xpt_release_bus(path->bus);
3949                 path->bus = NULL;
3950         }
3951 }
3952
3953 void
3954 xpt_free_path(struct cam_path *path)
3955 {
3956         CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_free_path\n"));
3957         xpt_release_path(path);
3958         kfree(path, M_DEVBUF);
3959 }
3960
3961
3962 /*
3963  * Return -1 for failure, 0 for exact match, 1 for match with wildcards
3964  * in path1, 2 for match with wildcards in path2.
3965  */
3966 int
3967 xpt_path_comp(struct cam_path *path1, struct cam_path *path2)
3968 {
3969         int retval = 0;
3970
3971         if (path1->bus != path2->bus) {
3972                 if (path1->bus->path_id == CAM_BUS_WILDCARD)
3973                         retval = 1;
3974                 else if (path2->bus->path_id == CAM_BUS_WILDCARD)
3975                         retval = 2;
3976                 else
3977                         return (-1);
3978         }
3979         if (path1->target != path2->target) {
3980                 if (path1->target->target_id == CAM_TARGET_WILDCARD) {
3981                         if (retval == 0)
3982                                 retval = 1;
3983                 } else if (path2->target->target_id == CAM_TARGET_WILDCARD)
3984                         retval = 2;
3985                 else
3986                         return (-1);
3987         }
3988         if (path1->device != path2->device) {
3989                 if (path1->device->lun_id == CAM_LUN_WILDCARD) {
3990                         if (retval == 0)
3991                                 retval = 1;
3992                 } else if (path2->device->lun_id == CAM_LUN_WILDCARD)
3993                         retval = 2;
3994                 else
3995                         return (-1);
3996         }
3997         return (retval);
3998 }
3999
4000 void
4001 xpt_print_path(struct cam_path *path)
4002 {
4003         if (path == NULL)
4004                 kprintf("(nopath): ");
4005         else {
4006                 if (path->periph != NULL)
4007                         kprintf("(%s%d:", path->periph->periph_name,
4008                                path->periph->unit_number);
4009                 else
4010                         kprintf("(noperiph:");
4011
4012                 if (path->bus != NULL)
4013                         kprintf("%s%d:%d:", path->bus->sim->sim_name,
4014                                path->bus->sim->unit_number,
4015                                path->bus->sim->bus_id);
4016                 else
4017                         kprintf("nobus:");
4018
4019                 if (path->target != NULL)
4020                         kprintf("%d:", path->target->target_id);
4021                 else
4022                         kprintf("X:");
4023
4024                 if (path->device != NULL)
4025                         kprintf("%d): ", path->device->lun_id);
4026                 else
4027                         kprintf("X): ");
4028         }
4029 }
4030
4031 int
4032 xpt_path_string(struct cam_path *path, char *str, size_t str_len)
4033 {
4034         struct sbuf sb;
4035
4036         sbuf_new(&sb, str, str_len, 0);
4037
4038         if (path == NULL)
4039                 sbuf_printf(&sb, "(nopath): ");
4040         else {
4041                 if (path->periph != NULL)
4042                         sbuf_printf(&sb, "(%s%d:", path->periph->periph_name,
4043                                     path->periph->unit_number);
4044                 else
4045                         sbuf_printf(&sb, "(noperiph:");
4046
4047                 if (path->bus != NULL)
4048                         sbuf_printf(&sb, "%s%d:%d:", path->bus->sim->sim_name,
4049                                     path->bus->sim->unit_number,
4050                                     path->bus->sim->bus_id);
4051                 else
4052                         sbuf_printf(&sb, "nobus:");
4053
4054                 if (path->target != NULL)
4055                         sbuf_printf(&sb, "%d:", path->target->target_id);
4056                 else
4057                         sbuf_printf(&sb, "X:");
4058
4059                 if (path->device != NULL)
4060                         sbuf_printf(&sb, "%d): ", path->device->lun_id);
4061                 else
4062                         sbuf_printf(&sb, "X): ");
4063         }
4064         sbuf_finish(&sb);
4065
4066         return(sbuf_len(&sb));
4067 }
4068
4069 path_id_t
4070 xpt_path_path_id(struct cam_path *path)
4071 {
4072         return(path->bus->path_id);
4073 }
4074
4075 target_id_t
4076 xpt_path_target_id(struct cam_path *path)
4077 {
4078         if (path->target != NULL)
4079                 return (path->target->target_id);
4080         else
4081                 return (CAM_TARGET_WILDCARD);
4082 }
4083
4084 lun_id_t
4085 xpt_path_lun_id(struct cam_path *path)
4086 {
4087         if (path->device != NULL)
4088                 return (path->device->lun_id);
4089         else
4090                 return (CAM_LUN_WILDCARD);
4091 }
4092
4093 struct cam_sim *
4094 xpt_path_sim(struct cam_path *path)
4095 {
4096         return (path->bus->sim);
4097 }
4098
4099 struct cam_periph*
4100 xpt_path_periph(struct cam_path *path)
4101 {
4102         return (path->periph);
4103 }
4104
4105 /*
4106  * Release a CAM control block for the caller.  Remit the cost of the structure
4107  * to the device referenced by the path.  If the this device had no 'credits'
4108  * and peripheral drivers have registered async callbacks for this notification
4109  * call them now.
4110  */
4111 void
4112 xpt_release_ccb(union ccb *free_ccb)
4113 {
4114         struct   cam_path *path;
4115         struct   cam_ed *device;
4116         struct   cam_eb *bus;
4117
4118         CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_release_ccb\n"));
4119         path = free_ccb->ccb_h.path;
4120         device = path->device;
4121         bus = path->bus;
4122         crit_enter();
4123         cam_ccbq_release_opening(&device->ccbq);
4124         if (xpt_ccb_count > xpt_max_ccbs) {
4125                 xpt_free_ccb(free_ccb);
4126                 xpt_ccb_count--;
4127         } else {
4128                 SLIST_INSERT_HEAD(&ccb_freeq, &free_ccb->ccb_h, xpt_links.sle);
4129         }
4130         if (bus->sim->devq) {
4131                 bus->sim->devq->alloc_openings++;
4132                 bus->sim->devq->alloc_active--;
4133         }
4134         /* XXX Turn this into an inline function - xpt_run_device?? */
4135         if ((device_is_alloc_queued(device) == 0)
4136          && (device->drvq.entries > 0)) {
4137                 xpt_schedule_dev_allocq(bus, device);
4138         }
4139         crit_exit();
4140         if (bus->sim->devq && dev_allocq_is_runnable(bus->sim->devq))
4141                 xpt_run_dev_allocq(bus);
4142 }
4143
4144 /* Functions accessed by SIM drivers */
4145
4146 /*
4147  * A sim structure, listing the SIM entry points and instance
4148  * identification info is passed to xpt_bus_register to hook the SIM
4149  * into the CAM framework.  xpt_bus_register creates a cam_eb entry
4150  * for this new bus and places it in the array of busses and assigns
4151  * it a path_id.  The path_id may be influenced by "hard wiring"
4152  * information specified by the user.  Once interrupt services are
4153  * availible, the bus will be probed.
4154  */
4155 int32_t
4156 xpt_bus_register(struct cam_sim *sim, u_int32_t bus)
4157 {
4158         struct cam_eb *new_bus;
4159         struct cam_eb *old_bus;
4160         struct ccb_pathinq cpi;
4161
4162         sim->bus_id = bus;
4163         new_bus = kmalloc(sizeof(*new_bus), M_DEVBUF, M_INTWAIT);
4164
4165         if (strcmp(sim->sim_name, "xpt") != 0) {
4166                 sim->path_id =
4167                     xptpathid(sim->sim_name, sim->unit_number, sim->bus_id);
4168         }
4169
4170         TAILQ_INIT(&new_bus->et_entries);
4171         new_bus->path_id = sim->path_id;
4172         new_bus->sim = sim;
4173         ++sim->refcount;
4174         timevalclear(&new_bus->last_reset);
4175         new_bus->flags = 0;
4176         new_bus->refcount = 1;  /* Held until a bus_deregister event */
4177         new_bus->generation = 0;
4178         crit_enter();
4179         old_bus = TAILQ_FIRST(&xpt_busses);
4180         while (old_bus != NULL
4181             && old_bus->path_id < new_bus->path_id)
4182                 old_bus = TAILQ_NEXT(old_bus, links);
4183         if (old_bus != NULL)
4184                 TAILQ_INSERT_BEFORE(old_bus, new_bus, links);
4185         else
4186                 TAILQ_INSERT_TAIL(&xpt_busses, new_bus, links);
4187         bus_generation++;
4188         crit_exit();
4189
4190         /* Notify interested parties */
4191         if (sim->path_id != CAM_XPT_PATH_ID) {
4192                 struct cam_path path;
4193
4194                 xpt_compile_path(&path, /*periph*/NULL, sim->path_id,
4195                                  CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
4196                 xpt_setup_ccb(&cpi.ccb_h, &path, /*priority*/1);
4197                 cpi.ccb_h.func_code = XPT_PATH_INQ;
4198                 xpt_action((union ccb *)&cpi);
4199                 xpt_async(AC_PATH_REGISTERED, &path, &cpi);
4200                 xpt_release_path(&path);
4201         }
4202         return (CAM_SUCCESS);
4203 }
4204
4205 /*
4206  * Deregister a bus.  We must clean out all transactions pending on the bus.
4207  * This routine is typically called prior to cam_sim_free() (e.g. see
4208  * dev/usbmisc/umass/umass.c)
4209  */
4210 int32_t
4211 xpt_bus_deregister(path_id_t pathid)
4212 {
4213         struct cam_path bus_path;
4214         cam_status status;
4215
4216         status = xpt_compile_path(&bus_path, NULL, pathid,
4217                                   CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
4218         if (status != CAM_REQ_CMP)
4219                 return (status);
4220
4221         /*
4222          * This should clear out all pending requests and timeouts, but
4223          * the ccb's may be queued to a software interrupt.
4224          *
4225          * XXX AC_LOST_DEVICE does not precisely abort the pending requests,
4226          * and it really ought to.
4227          */
4228         xpt_async(AC_LOST_DEVICE, &bus_path, NULL);
4229         xpt_async(AC_PATH_DEREGISTERED, &bus_path, NULL);
4230
4231         /* make sure all responses have been processed */
4232         camisr(&cam_netq);
4233         camisr(&cam_bioq);
4234         
4235         /* Release the reference count held while registered. */
4236         xpt_release_bus(bus_path.bus);
4237         xpt_release_path(&bus_path);
4238
4239         return (CAM_REQ_CMP);
4240 }
4241
4242 static path_id_t
4243 xptnextfreepathid(void)
4244 {
4245         struct cam_eb *bus;
4246         path_id_t pathid;
4247         char *strval;
4248
4249         pathid = 0;
4250         bus = TAILQ_FIRST(&xpt_busses);
4251 retry:
4252         /* Find an unoccupied pathid */
4253         while (bus != NULL
4254             && bus->path_id <= pathid) {
4255                 if (bus->path_id == pathid)
4256                         pathid++;
4257                 bus = TAILQ_NEXT(bus, links);
4258         }
4259
4260         /*
4261          * Ensure that this pathid is not reserved for
4262          * a bus that may be registered in the future.
4263          */
4264         if (resource_string_value("scbus", pathid, "at", &strval) == 0) {
4265                 ++pathid;
4266                 /* Start the search over */
4267                 goto retry;
4268         }
4269         return (pathid);
4270 }
4271
4272 static path_id_t
4273 xptpathid(const char *sim_name, int sim_unit, int sim_bus)
4274 {
4275         path_id_t pathid;
4276         int i, dunit, val;
4277         char buf[32];
4278
4279         pathid = CAM_XPT_PATH_ID;
4280         ksnprintf(buf, sizeof(buf), "%s%d", sim_name, sim_unit);
4281         i = -1;
4282         while ((i = resource_query_string(i, "at", buf)) != -1) {
4283                 if (strcmp(resource_query_name(i), "scbus")) {
4284                         /* Avoid a bit of foot shooting. */
4285                         continue;
4286                 }
4287                 dunit = resource_query_unit(i);
4288                 if (dunit < 0)          /* unwired?! */
4289                         continue;
4290                 if (resource_int_value("scbus", dunit, "bus", &val) == 0) {
4291                         if (sim_bus == val) {
4292                                 pathid = dunit;
4293                                 break;
4294                         }
4295                 } else if (sim_bus == 0) {
4296                         /* Unspecified matches bus 0 */
4297                         pathid = dunit;
4298                         break;
4299                 } else {
4300                         kprintf("Ambiguous scbus configuration for %s%d "
4301                                "bus %d, cannot wire down.  The kernel "
4302                                "config entry for scbus%d should "
4303                                "specify a controller bus.\n"
4304                                "Scbus will be assigned dynamically.\n",
4305                                sim_name, sim_unit, sim_bus, dunit);
4306                         break;
4307                 }
4308         }
4309
4310         if (pathid == CAM_XPT_PATH_ID)
4311                 pathid = xptnextfreepathid();
4312         return (pathid);
4313 }
4314
4315 void
4316 xpt_async(u_int32_t async_code, struct cam_path *path, void *async_arg)
4317 {
4318         struct cam_eb *bus;
4319         struct cam_et *target, *next_target;
4320         struct cam_ed *device, *next_device;
4321
4322         CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_async\n"));
4323
4324         /*
4325          * Most async events come from a CAM interrupt context.  In
4326          * a few cases, the error recovery code at the peripheral layer,
4327          * which may run from our SWI or a process context, may signal
4328          * deferred events with a call to xpt_async. Ensure async
4329          * notifications are serialized by blocking cam interrupts.
4330          */
4331         crit_enter();
4332
4333         bus = path->bus;
4334
4335         if (async_code == AC_BUS_RESET) { 
4336                 /* Update our notion of when the last reset occurred */
4337                 microuptime(&bus->last_reset);
4338         }
4339
4340         for (target = TAILQ_FIRST(&bus->et_entries);
4341              target != NULL;
4342              target = next_target) {
4343
4344                 next_target = TAILQ_NEXT(target, links);
4345
4346                 if (path->target != target
4347                  && path->target->target_id != CAM_TARGET_WILDCARD
4348                  && target->target_id != CAM_TARGET_WILDCARD)
4349                         continue;
4350
4351                 if (async_code == AC_SENT_BDR) {
4352                         /* Update our notion of when the last reset occurred */
4353                         microuptime(&path->target->last_reset);
4354                 }
4355
4356                 for (device = TAILQ_FIRST(&target->ed_entries);
4357                      device != NULL;
4358                      device = next_device) {
4359
4360                         next_device = TAILQ_NEXT(device, links);
4361
4362                         if (path->device != device 
4363                          && path->device->lun_id != CAM_LUN_WILDCARD
4364                          && device->lun_id != CAM_LUN_WILDCARD)
4365                                 continue;
4366
4367                         xpt_dev_async(async_code, bus, target,
4368                                       device, async_arg);
4369
4370                         xpt_async_bcast(&device->asyncs, async_code,
4371                                         path, async_arg);
4372                 }
4373         }
4374         
4375         /*
4376          * If this wasn't a fully wildcarded async, tell all
4377          * clients that want all async events.
4378          */
4379         if (bus != xpt_periph->path->bus)
4380                 xpt_async_bcast(&xpt_periph->path->device->asyncs, async_code,
4381                                 path, async_arg);
4382         crit_exit();
4383 }
4384
4385 static void
4386 xpt_async_bcast(struct async_list *async_head,
4387                 u_int32_t async_code,
4388                 struct cam_path *path, void *async_arg)
4389 {
4390         struct async_node *cur_entry;
4391
4392         cur_entry = SLIST_FIRST(async_head);
4393         while (cur_entry != NULL) {
4394                 struct async_node *next_entry;
4395                 /*
4396                  * Grab the next list entry before we call the current
4397                  * entry's callback.  This is because the callback function
4398                  * can delete its async callback entry.
4399                  */
4400                 next_entry = SLIST_NEXT(cur_entry, links);
4401                 if ((cur_entry->event_enable & async_code) != 0)
4402                         cur_entry->callback(cur_entry->callback_arg,
4403                                             async_code, path,
4404                                             async_arg);
4405                 cur_entry = next_entry;
4406         }
4407 }
4408
4409 /*
4410  * Handle any per-device event notifications that require action by the XPT.
4411  */
4412 static void
4413 xpt_dev_async(u_int32_t async_code, struct cam_eb *bus, struct cam_et *target,
4414               struct cam_ed *device, void *async_arg)
4415 {
4416         cam_status status;
4417         struct cam_path newpath;
4418
4419         /*
4420          * We only need to handle events for real devices.
4421          */
4422         if (target->target_id == CAM_TARGET_WILDCARD
4423          || device->lun_id == CAM_LUN_WILDCARD)
4424                 return;
4425
4426         /*
4427          * We need our own path with wildcards expanded to
4428          * handle certain types of events.
4429          */
4430         if ((async_code == AC_SENT_BDR)
4431          || (async_code == AC_BUS_RESET)
4432          || (async_code == AC_INQ_CHANGED))
4433                 status = xpt_compile_path(&newpath, NULL,
4434                                           bus->path_id,
4435                                           target->target_id,
4436                                           device->lun_id);
4437         else
4438                 status = CAM_REQ_CMP_ERR;
4439
4440         if (status == CAM_REQ_CMP) {
4441
4442                 /*
4443                  * Allow transfer negotiation to occur in a
4444                  * tag free environment.
4445                  */
4446                 if (async_code == AC_SENT_BDR
4447                  || async_code == AC_BUS_RESET)
4448                         xpt_toggle_tags(&newpath);
4449
4450                 if (async_code == AC_INQ_CHANGED) {
4451                         /*
4452                          * We've sent a start unit command, or
4453                          * something similar to a device that
4454                          * may have caused its inquiry data to
4455                          * change. So we re-scan the device to
4456                          * refresh the inquiry data for it.
4457                          */
4458                         xpt_scan_lun(newpath.periph, &newpath,
4459                                      CAM_EXPECT_INQ_CHANGE, NULL);
4460                 }
4461                 xpt_release_path(&newpath);
4462         } else if (async_code == AC_LOST_DEVICE) {
4463                 /*
4464                  * When we lose a device the device may be about to detach
4465                  * the sim, we have to clear out all pending timeouts and
4466                  * requests before that happens.  XXX it would be nice if
4467                  * we could abort the requests pertaining to the device.
4468                  */
4469                 xpt_release_devq_timeout(device);
4470                 if ((device->flags & CAM_DEV_UNCONFIGURED) == 0) {
4471                         device->flags |= CAM_DEV_UNCONFIGURED;
4472                         xpt_release_device(bus, target, device);
4473                 }
4474         } else if (async_code == AC_TRANSFER_NEG) {
4475                 struct ccb_trans_settings *settings;
4476
4477                 settings = (struct ccb_trans_settings *)async_arg;
4478                 xpt_set_transfer_settings(settings, device,
4479                                           /*async_update*/TRUE);
4480         }
4481 }
4482
4483 u_int32_t
4484 xpt_freeze_devq(struct cam_path *path, u_int count)
4485 {
4486         struct ccb_hdr *ccbh;
4487
4488         crit_enter();
4489         path->device->qfrozen_cnt += count;
4490
4491         /*
4492          * Mark the last CCB in the queue as needing
4493          * to be requeued if the driver hasn't
4494          * changed it's state yet.  This fixes a race
4495          * where a ccb is just about to be queued to
4496          * a controller driver when it's interrupt routine
4497          * freezes the queue.  To completly close the
4498          * hole, controller drives must check to see
4499          * if a ccb's status is still CAM_REQ_INPROG
4500          * under critical section protection just before they queue
4501          * the CCB.  See ahc_action/ahc_freeze_devq for
4502          * an example.
4503          */
4504         ccbh = TAILQ_LAST(&path->device->ccbq.active_ccbs, ccb_hdr_tailq);
4505         if (ccbh && ccbh->status == CAM_REQ_INPROG)
4506                 ccbh->status = CAM_REQUEUE_REQ;
4507         crit_exit();
4508         return (path->device->qfrozen_cnt);
4509 }
4510
4511 u_int32_t
4512 xpt_freeze_simq(struct cam_sim *sim, u_int count)
4513 {
4514         if (sim->devq == NULL)
4515                 return(count);
4516         sim->devq->send_queue.qfrozen_cnt += count;
4517         if (sim->devq->active_dev != NULL) {
4518                 struct ccb_hdr *ccbh;
4519                 
4520                 ccbh = TAILQ_LAST(&sim->devq->active_dev->ccbq.active_ccbs,
4521                                   ccb_hdr_tailq);
4522                 if (ccbh && ccbh->status == CAM_REQ_INPROG)
4523                         ccbh->status = CAM_REQUEUE_REQ;
4524         }
4525         return (sim->devq->send_queue.qfrozen_cnt);
4526 }
4527
4528 /*
4529  * WARNING: most devices, especially USB/UMASS, may detach their sim early.
4530  * We ref-count the sim (and the bus only NULLs it out when the bus has been
4531  * freed, which is not the case here), but the device queue is also freed XXX
4532  * and we have to check that here.
4533  *
4534  * XXX fixme: could we simply not null-out the device queue via 
4535  * cam_sim_free()?
4536  */
4537 static void
4538 xpt_release_devq_timeout(void *arg)
4539 {
4540         struct cam_ed *device;
4541
4542         device = (struct cam_ed *)arg;
4543
4544         xpt_release_devq_device(device, /*count*/1, /*run_queue*/TRUE);
4545 }
4546
4547 void
4548 xpt_release_devq(struct cam_path *path, u_int count, int run_queue)
4549 {
4550         xpt_release_devq_device(path->device, count, run_queue);
4551 }
4552
4553 static void
4554 xpt_release_devq_device(struct cam_ed *dev, u_int count, int run_queue)
4555 {
4556         int     rundevq;
4557
4558         rundevq = 0;
4559         crit_enter();
4560
4561         if (dev->qfrozen_cnt > 0) {
4562
4563                 count = (count > dev->qfrozen_cnt) ? dev->qfrozen_cnt : count;
4564                 dev->qfrozen_cnt -= count;
4565                 if (dev->qfrozen_cnt == 0) {
4566
4567                         /*
4568                          * No longer need to wait for a successful
4569                          * command completion.
4570                          */
4571                         dev->flags &= ~CAM_DEV_REL_ON_COMPLETE;
4572
4573                         /*
4574                          * Remove any timeouts that might be scheduled
4575                          * to release this queue.
4576                          */
4577                         if ((dev->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
4578                                 callout_stop(&dev->c_handle);
4579                                 dev->flags &= ~CAM_DEV_REL_TIMEOUT_PENDING;
4580                         }
4581
4582                         /*
4583                          * Now that we are unfrozen schedule the
4584                          * device so any pending transactions are
4585                          * run.
4586                          */
4587                         if ((dev->ccbq.queue.entries > 0)
4588                          && (xpt_schedule_dev_sendq(dev->target->bus, dev))
4589                          && (run_queue != 0)) {
4590                                 rundevq = 1;
4591                         }
4592                 }
4593         }
4594         if (rundevq != 0)
4595                 xpt_run_dev_sendq(dev->target->bus);
4596         crit_exit();
4597 }
4598
4599 void
4600 xpt_release_simq(struct cam_sim *sim, int run_queue)
4601 {
4602         struct  camq *sendq;
4603
4604         if (sim->devq == NULL)
4605                 return;
4606
4607         sendq = &(sim->devq->send_queue);
4608         crit_enter();
4609
4610         if (sendq->qfrozen_cnt > 0) {
4611                 sendq->qfrozen_cnt--;
4612                 if (sendq->qfrozen_cnt == 0) {
4613                         struct cam_eb *bus;
4614
4615                         /*
4616                          * If there is a timeout scheduled to release this
4617                          * sim queue, remove it.  The queue frozen count is
4618                          * already at 0.
4619                          */
4620                         if ((sim->flags & CAM_SIM_REL_TIMEOUT_PENDING) != 0){
4621                                 callout_stop(&sim->c_handle);
4622                                 sim->flags &= ~CAM_SIM_REL_TIMEOUT_PENDING;
4623                         }
4624                         bus = xpt_find_bus(sim->path_id);
4625                         crit_exit();
4626
4627                         if (run_queue) {
4628                                 /*
4629                                  * Now that we are unfrozen run the send queue.
4630                                  */
4631                                 xpt_run_dev_sendq(bus);
4632                         }
4633                         xpt_release_bus(bus);
4634                 } else {
4635                         crit_exit();
4636                 }
4637         } else {
4638                 crit_exit();
4639         }
4640 }
4641
4642 void
4643 xpt_done(union ccb *done_ccb)
4644 {
4645         crit_enter();
4646
4647         CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("xpt_done\n"));
4648         if ((done_ccb->ccb_h.func_code & XPT_FC_QUEUED) != 0) {
4649                 /*
4650                  * Queue up the request for handling by our SWI handler
4651                  * any of the "non-immediate" type of ccbs.
4652                  */
4653                 switch (done_ccb->ccb_h.path->periph->type) {
4654                 case CAM_PERIPH_BIO:
4655                         TAILQ_INSERT_TAIL(&cam_bioq, &done_ccb->ccb_h,
4656                                           sim_links.tqe);
4657                         done_ccb->ccb_h.pinfo.index = CAM_DONEQ_INDEX;
4658                         setsoftcambio();
4659                         break;
4660                 case CAM_PERIPH_NET:
4661                         TAILQ_INSERT_TAIL(&cam_netq, &done_ccb->ccb_h,
4662                                           sim_links.tqe);
4663                         done_ccb->ccb_h.pinfo.index = CAM_DONEQ_INDEX;
4664                         setsoftcamnet();
4665                         break;
4666                 }
4667         }
4668         crit_exit();
4669 }
4670
4671 union ccb *
4672 xpt_alloc_ccb(void)
4673 {
4674         union ccb *new_ccb;
4675
4676         new_ccb = kmalloc(sizeof(*new_ccb), M_DEVBUF, M_INTWAIT);
4677         return (new_ccb);
4678 }
4679
4680 void
4681 xpt_free_ccb(union ccb *free_ccb)
4682 {
4683         kfree(free_ccb, M_DEVBUF);
4684 }
4685
4686
4687
4688 /* Private XPT functions */
4689
4690 /*
4691  * Get a CAM control block for the caller. Charge the structure to the device
4692  * referenced by the path.  If the this device has no 'credits' then the
4693  * device already has the maximum number of outstanding operations under way
4694  * and we return NULL. If we don't have sufficient resources to allocate more
4695  * ccbs, we also return NULL.
4696  */
4697 static union ccb *
4698 xpt_get_ccb(struct cam_ed *device)
4699 {
4700         union ccb *new_ccb;
4701
4702         crit_enter();
4703         if ((new_ccb = (union ccb *)SLIST_FIRST(&ccb_freeq)) == NULL) {
4704                 new_ccb = kmalloc(sizeof(*new_ccb), M_DEVBUF, M_INTWAIT);
4705                 SLIST_INSERT_HEAD(&ccb_freeq, &new_ccb->ccb_h,
4706                                   xpt_links.sle);
4707                 xpt_ccb_count++;
4708         }
4709         cam_ccbq_take_opening(&device->ccbq);
4710         SLIST_REMOVE_HEAD(&ccb_freeq, xpt_links.sle);
4711         crit_exit();
4712         return (new_ccb);
4713 }
4714
4715 static void
4716 xpt_release_bus(struct cam_eb *bus)
4717 {
4718
4719         crit_enter();
4720         if (bus->refcount == 1) {
4721                 KKASSERT(TAILQ_FIRST(&bus->et_entries) == NULL);
4722                 TAILQ_REMOVE(&xpt_busses, bus, links);
4723                 if (bus->sim) {
4724                         cam_sim_release(bus->sim, 0);
4725                         bus->sim = NULL;
4726                 }
4727                 bus_generation++;
4728                 KKASSERT(bus->refcount == 1);
4729                 kfree(bus, M_DEVBUF);
4730         } else {
4731                 --bus->refcount;
4732         }
4733         crit_exit();
4734 }
4735
4736 static struct cam_et *
4737 xpt_alloc_target(struct cam_eb *bus, target_id_t target_id)
4738 {
4739         struct cam_et *target;
4740         struct cam_et *cur_target;
4741
4742         target = kmalloc(sizeof(*target), M_DEVBUF, M_INTWAIT);
4743
4744         TAILQ_INIT(&target->ed_entries);
4745         target->bus = bus;
4746         target->target_id = target_id;
4747         target->refcount = 1;
4748         target->generation = 0;
4749         timevalclear(&target->last_reset);
4750         /*
4751          * Hold a reference to our parent bus so it
4752          * will not go away before we do.
4753          */
4754         bus->refcount++;
4755
4756         /* Insertion sort into our bus's target list */
4757         cur_target = TAILQ_FIRST(&bus->et_entries);
4758         while (cur_target != NULL && cur_target->target_id < target_id)
4759                 cur_target = TAILQ_NEXT(cur_target, links);
4760
4761         if (cur_target != NULL) {
4762                 TAILQ_INSERT_BEFORE(cur_target, target, links);
4763         } else {
4764                 TAILQ_INSERT_TAIL(&bus->et_entries, target, links);
4765         }
4766         bus->generation++;
4767         return (target);
4768 }
4769
4770 static void
4771 xpt_release_target(struct cam_eb *bus, struct cam_et *target)
4772 {
4773         crit_enter();
4774         if (target->refcount == 1) {
4775                 KKASSERT(TAILQ_FIRST(&target->ed_entries) == NULL);
4776                 TAILQ_REMOVE(&bus->et_entries, target, links);
4777                 bus->generation++;
4778                 xpt_release_bus(bus);
4779                 KKASSERT(target->refcount == 1);
4780                 kfree(target, M_DEVBUF);
4781         } else {
4782                 --target->refcount;
4783         }
4784         crit_exit();
4785 }
4786
4787 static struct cam_ed *
4788 xpt_alloc_device(struct cam_eb *bus, struct cam_et *target, lun_id_t lun_id)
4789 {
4790 #ifdef CAM_NEW_TRAN_CODE
4791         struct     cam_path path;
4792 #endif /* CAM_NEW_TRAN_CODE */
4793         struct     cam_ed *device;
4794         struct     cam_devq *devq;
4795         cam_status status;
4796
4797         /* Make space for us in the device queue on our bus */
4798         if (bus->sim->devq == NULL)
4799                 return(NULL);
4800         devq = bus->sim->devq;
4801         status = cam_devq_resize(devq, devq->alloc_queue.array_size + 1);
4802
4803         if (status != CAM_REQ_CMP) {
4804                 device = NULL;
4805         } else {
4806                 device = kmalloc(sizeof(*device), M_DEVBUF, M_INTWAIT);
4807         }
4808
4809         if (device != NULL) {
4810                 struct cam_ed *cur_device;
4811
4812                 cam_init_pinfo(&device->alloc_ccb_entry.pinfo);
4813                 device->alloc_ccb_entry.device = device;
4814                 cam_init_pinfo(&device->send_ccb_entry.pinfo);
4815                 device->send_ccb_entry.device = device;
4816                 device->target = target;
4817                 device->lun_id = lun_id;
4818                 /* Initialize our queues */
4819                 if (camq_init(&device->drvq, 0) != 0) {
4820                         kfree(device, M_DEVBUF);
4821                         return (NULL);
4822                 }
4823                 if (cam_ccbq_init(&device->ccbq,
4824                                   bus->sim->max_dev_openings) != 0) {
4825                         camq_fini(&device->drvq);
4826                         kfree(device, M_DEVBUF);
4827                         return (NULL);
4828                 }
4829                 SLIST_INIT(&device->asyncs);
4830                 SLIST_INIT(&device->periphs);
4831                 device->generation = 0;
4832                 device->owner = NULL;
4833                 /*
4834                  * Take the default quirk entry until we have inquiry
4835                  * data and can determine a better quirk to use.
4836                  */
4837                 device->quirk = &xpt_quirk_table[xpt_quirk_table_size - 1];
4838                 bzero(&device->inq_data, sizeof(device->inq_data));
4839                 device->inq_flags = 0;
4840                 device->queue_flags = 0;
4841                 device->serial_num = NULL;
4842                 device->serial_num_len = 0;
4843                 device->qfrozen_cnt = 0;
4844                 device->flags = CAM_DEV_UNCONFIGURED;
4845                 device->tag_delay_count = 0;
4846                 device->refcount = 1;
4847                 callout_init(&device->c_handle);
4848
4849                 /*
4850                  * Hold a reference to our parent target so it
4851                  * will not go away before we do.
4852                  */
4853                 target->refcount++;
4854
4855                 /*
4856                  * XXX should be limited by number of CCBs this bus can
4857                  * do.
4858                  */
4859                 xpt_max_ccbs += device->ccbq.devq_openings;
4860                 /* Insertion sort into our target's device list */
4861                 cur_device = TAILQ_FIRST(&target->ed_entries);
4862                 while (cur_device != NULL && cur_device->lun_id < lun_id)
4863                         cur_device = TAILQ_NEXT(cur_device, links);
4864                 if (cur_device != NULL) {
4865                         TAILQ_INSERT_BEFORE(cur_device, device, links);
4866                 } else {
4867                         TAILQ_INSERT_TAIL(&target->ed_entries, device, links);
4868                 }
4869                 target->generation++;
4870 #ifdef CAM_NEW_TRAN_CODE
4871                 if (lun_id != CAM_LUN_WILDCARD) {
4872                         xpt_compile_path(&path,
4873                                          NULL,
4874                                          bus->path_id,
4875                                          target->target_id,
4876                                          lun_id);
4877                         xpt_devise_transport(&path);
4878                         xpt_release_path(&path);
4879                 }
4880 #endif /* CAM_NEW_TRAN_CODE */
4881         }
4882         return (device);
4883 }
4884
4885 static void
4886 xpt_reference_device(struct cam_ed *device)
4887 {
4888         ++device->refcount;
4889 }
4890
4891 static void
4892 xpt_release_device(struct cam_eb *bus, struct cam_et *target,
4893                    struct cam_ed *device)
4894 {
4895         struct cam_devq *devq;
4896
4897         crit_enter();
4898         if (device->refcount == 1) {
4899                 KKASSERT(device->flags & CAM_DEV_UNCONFIGURED);
4900
4901                 if (device->alloc_ccb_entry.pinfo.index != CAM_UNQUEUED_INDEX
4902                  || device->send_ccb_entry.pinfo.index != CAM_UNQUEUED_INDEX)
4903                         panic("Removing device while still queued for ccbs");
4904
4905                 if ((device->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
4906                         device->flags &= ~CAM_DEV_REL_TIMEOUT_PENDING;
4907                         callout_stop(&device->c_handle);
4908                 }
4909
4910                 TAILQ_REMOVE(&target->ed_entries, device,links);
4911                 target->generation++;
4912                 xpt_max_ccbs -= device->ccbq.devq_openings;
4913                 /* Release our slot in the devq */
4914                 devq = bus->sim->devq;
4915                 cam_devq_resize(devq, devq->alloc_queue.array_size - 1);
4916                 xpt_release_target(bus, target);
4917                 KKASSERT(device->refcount == 1);
4918                 kfree(device, M_DEVBUF);
4919         } else {
4920                 --device->refcount;
4921         }
4922         crit_exit();
4923 }
4924
4925 static u_int32_t
4926 xpt_dev_ccbq_resize(struct cam_path *path, int newopenings)
4927 {
4928         int     diff;
4929         int     result;
4930         struct  cam_ed *dev;
4931
4932         dev = path->device;
4933
4934         crit_enter();
4935
4936         diff = newopenings - (dev->ccbq.dev_active + dev->ccbq.dev_openings);
4937         result = cam_ccbq_resize(&dev->ccbq, newopenings);
4938         if (result == CAM_REQ_CMP && (diff < 0)) {
4939                 dev->flags |= CAM_DEV_RESIZE_QUEUE_NEEDED;
4940         }
4941         /* Adjust the global limit */
4942         xpt_max_ccbs += diff;
4943         crit_exit();
4944         return (result);
4945 }
4946
4947 static struct cam_eb *
4948 xpt_find_bus(path_id_t path_id)
4949 {
4950         struct cam_eb *bus;
4951
4952         TAILQ_FOREACH(bus, &xpt_busses, links) {
4953                 if (bus->path_id == path_id) {
4954                         bus->refcount++;
4955                         break;
4956                 }
4957         }
4958         return (bus);
4959 }
4960
4961 static struct cam_et *
4962 xpt_find_target(struct cam_eb *bus, target_id_t target_id)
4963 {
4964         struct cam_et *target;
4965
4966         TAILQ_FOREACH(target, &bus->et_entries, links) {
4967                 if (target->target_id == target_id) {
4968                         target->refcount++;
4969                         break;
4970                 }
4971         }
4972         return (target);
4973 }
4974
4975 static struct cam_ed *
4976 xpt_find_device(struct cam_et *target, lun_id_t lun_id)
4977 {
4978         struct cam_ed *device;
4979
4980         TAILQ_FOREACH(device, &target->ed_entries, links) {
4981                 if (device->lun_id == lun_id) {
4982                         device->refcount++;
4983                         break;
4984                 }
4985         }
4986         return (device);
4987 }
4988
4989 typedef struct {
4990         union   ccb *request_ccb;
4991         struct  ccb_pathinq *cpi;
4992         int     pending_count;
4993 } xpt_scan_bus_info;
4994
4995 /*
4996  * To start a scan, request_ccb is an XPT_SCAN_BUS ccb.
4997  * As the scan progresses, xpt_scan_bus is used as the
4998  * callback on completion function.
4999  */
5000 static void
5001 xpt_scan_bus(struct cam_periph *periph, union ccb *request_ccb)
5002 {
5003         CAM_DEBUG(request_ccb->ccb_h.path, CAM_DEBUG_TRACE,
5004                   ("xpt_scan_bus\n"));
5005         switch (request_ccb->ccb_h.func_code) {
5006         case XPT_SCAN_BUS:
5007         {
5008                 xpt_scan_bus_info *scan_info;
5009                 union   ccb *work_ccb;
5010                 struct  cam_path *path;
5011                 u_int   i;
5012                 u_int   max_target;
5013                 u_int   initiator_id;
5014
5015                 /* Find out the characteristics of the bus */
5016                 work_ccb = xpt_alloc_ccb();
5017                 xpt_setup_ccb(&work_ccb->ccb_h, request_ccb->ccb_h.path,
5018                               request_ccb->ccb_h.pinfo.priority);
5019                 work_ccb->ccb_h.func_code = XPT_PATH_INQ;
5020                 xpt_action(work_ccb);
5021                 if (work_ccb->ccb_h.status != CAM_REQ_CMP) {
5022                         request_ccb->ccb_h.status = work_ccb->ccb_h.status;
5023                         xpt_free_ccb(work_ccb);
5024                         xpt_done(request_ccb);
5025                         return;
5026                 }
5027
5028                 if ((work_ccb->cpi.hba_misc & PIM_NOINITIATOR) != 0) {
5029                         /*
5030                          * Can't scan the bus on an adapter that
5031                          * cannot perform the initiator role.
5032                          */
5033                         request_ccb->ccb_h.status = CAM_REQ_CMP;
5034                         xpt_free_ccb(work_ccb);
5035                         xpt_done(request_ccb);
5036                         return;
5037                 }
5038
5039                 /* Save some state for use while we probe for devices */
5040                 scan_info = (xpt_scan_bus_info *)
5041                     kmalloc(sizeof(xpt_scan_bus_info), M_TEMP, M_INTWAIT);
5042                 scan_info->request_ccb = request_ccb;
5043                 scan_info->cpi = &work_ccb->cpi;
5044
5045                 /* Cache on our stack so we can work asynchronously */
5046                 max_target = scan_info->cpi->max_target;
5047                 initiator_id = scan_info->cpi->initiator_id;
5048
5049                 /*
5050                  * Don't count the initiator if the
5051                  * initiator is addressable.
5052                  */
5053                 scan_info->pending_count = max_target + 1;
5054                 if (initiator_id <= max_target)
5055                         scan_info->pending_count--;
5056
5057                 for (i = 0; i <= max_target; i++) {
5058                         cam_status status;
5059                         if (i == initiator_id)
5060                                 continue;
5061
5062                         status = xpt_create_path(&path, xpt_periph,
5063                                                  request_ccb->ccb_h.path_id,
5064                                                  i, 0);
5065                         if (status != CAM_REQ_CMP) {
5066                                 kprintf("xpt_scan_bus: xpt_create_path failed"
5067                                        " with status %#x, bus scan halted\n",
5068                                        status);
5069                                 break;
5070                         }
5071                         work_ccb = xpt_alloc_ccb();
5072                         xpt_setup_ccb(&work_ccb->ccb_h, path,
5073                                       request_ccb->ccb_h.pinfo.priority);
5074                         work_ccb->ccb_h.func_code = XPT_SCAN_LUN;
5075                         work_ccb->ccb_h.cbfcnp = xpt_scan_bus;
5076                         work_ccb->ccb_h.ppriv_ptr0 = scan_info;
5077                         work_ccb->crcn.flags = request_ccb->crcn.flags;
5078                         xpt_action(work_ccb);
5079                 }
5080                 break;
5081         }
5082         case XPT_SCAN_LUN:
5083         {
5084                 xpt_scan_bus_info *scan_info;
5085                 path_id_t path_id;
5086                 target_id_t target_id;
5087                 lun_id_t lun_id;
5088
5089                 /* Reuse the same CCB to query if a device was really found */
5090                 scan_info = (xpt_scan_bus_info *)request_ccb->ccb_h.ppriv_ptr0;
5091                 xpt_setup_ccb(&request_ccb->ccb_h, request_ccb->ccb_h.path,
5092                               request_ccb->ccb_h.pinfo.priority);
5093                 request_ccb->ccb_h.func_code = XPT_GDEV_TYPE;
5094
5095                 path_id = request_ccb->ccb_h.path_id;
5096                 target_id = request_ccb->ccb_h.target_id;
5097                 lun_id = request_ccb->ccb_h.target_lun;
5098                 xpt_action(request_ccb);
5099
5100                 if (request_ccb->ccb_h.status != CAM_REQ_CMP) {
5101                         struct cam_ed *device;
5102                         struct cam_et *target;
5103                         int phl;
5104
5105                         /*
5106                          * If we already probed lun 0 successfully, or
5107                          * we have additional configured luns on this
5108                          * target that might have "gone away", go onto
5109                          * the next lun.
5110                          */
5111                         target = request_ccb->ccb_h.path->target;
5112                         /*
5113                          * We may touch devices that we don't
5114                          * hold references too, so ensure they
5115                          * don't disappear out from under us.
5116                          * The target above is referenced by the
5117                          * path in the request ccb.
5118                          */
5119                         phl = 0;
5120                         crit_enter();
5121                         device = TAILQ_FIRST(&target->ed_entries);
5122                         if (device != NULL) {
5123                                 phl = device->quirk->quirks & CAM_QUIRK_HILUNS;
5124                                 if (device->lun_id == 0)
5125                                         device = TAILQ_NEXT(device, links);
5126                         }
5127                         crit_exit();
5128                         if ((lun_id != 0) || (device != NULL)) {
5129                                 if (lun_id < (CAM_SCSI2_MAXLUN-1) || phl)
5130                                         lun_id++;
5131                         }
5132                 } else {
5133                         struct cam_ed *device;
5134                         
5135                         device = request_ccb->ccb_h.path->device;
5136
5137                         if ((device->quirk->quirks & CAM_QUIRK_NOLUNS) == 0) {
5138                                 /* Try the next lun */
5139                                 if (lun_id < (CAM_SCSI2_MAXLUN-1) ||
5140                                     (device->quirk->quirks & CAM_QUIRK_HILUNS))
5141                                         lun_id++;
5142                         }
5143                 }
5144
5145                 xpt_free_path(request_ccb->ccb_h.path);
5146
5147                 /* Check Bounds */
5148                 if ((lun_id == request_ccb->ccb_h.target_lun)
5149                  || lun_id > scan_info->cpi->max_lun) {
5150                         /* We're done */
5151
5152                         xpt_free_ccb(request_ccb);
5153                         scan_info->pending_count--;
5154                         if (scan_info->pending_count == 0) {
5155                                 xpt_free_ccb((union ccb *)scan_info->cpi);
5156                                 request_ccb = scan_info->request_ccb;
5157                                 kfree(scan_info, M_TEMP);
5158                                 request_ccb->ccb_h.status = CAM_REQ_CMP;
5159                                 xpt_done(request_ccb);
5160                         }
5161                 } else {
5162                         /* Try the next device */
5163                         struct cam_path *path;
5164                         cam_status status;
5165
5166                         path = request_ccb->ccb_h.path;
5167                         status = xpt_create_path(&path, xpt_periph,
5168                                                  path_id, target_id, lun_id);
5169                         if (status != CAM_REQ_CMP) {
5170                                 kprintf("xpt_scan_bus: xpt_create_path failed "
5171                                        "with status %#x, halting LUN scan\n",
5172                                        status);
5173                                 xpt_free_ccb(request_ccb);
5174                                 scan_info->pending_count--;
5175                                 if (scan_info->pending_count == 0) {
5176                                         xpt_free_ccb(
5177                                                 (union ccb *)scan_info->cpi);
5178                                         request_ccb = scan_info->request_ccb;
5179                                         kfree(scan_info, M_TEMP);
5180                                         request_ccb->ccb_h.status = CAM_REQ_CMP;
5181                                         xpt_done(request_ccb);
5182                                         break;
5183                                 }
5184                         }
5185                         xpt_setup_ccb(&request_ccb->ccb_h, path,
5186                                       request_ccb->ccb_h.pinfo.priority);
5187                         request_ccb->ccb_h.func_code = XPT_SCAN_LUN;
5188                         request_ccb->ccb_h.cbfcnp = xpt_scan_bus;
5189                         request_ccb->ccb_h.ppriv_ptr0 = scan_info;
5190                         request_ccb->crcn.flags =
5191                                 scan_info->request_ccb->crcn.flags;
5192                         xpt_action(request_ccb);
5193                 }
5194                 break;
5195         }
5196         default:
5197                 break;
5198         }
5199 }
5200
5201 typedef enum {
5202         PROBE_TUR,
5203         PROBE_INQUIRY,
5204         PROBE_FULL_INQUIRY,
5205         PROBE_MODE_SENSE,
5206         PROBE_SERIAL_NUM,
5207         PROBE_TUR_FOR_NEGOTIATION
5208 } probe_action;
5209
5210 typedef enum {
5211         PROBE_INQUIRY_CKSUM     = 0x01,
5212         PROBE_SERIAL_CKSUM      = 0x02,
5213         PROBE_NO_ANNOUNCE       = 0x04
5214 } probe_flags;
5215
5216 typedef struct {
5217         TAILQ_HEAD(, ccb_hdr) request_ccbs;
5218         probe_action    action;
5219         union ccb       saved_ccb;
5220         probe_flags     flags;
5221         MD5_CTX         context;
5222         u_int8_t        digest[16];
5223 } probe_softc;
5224
5225 static void
5226 xpt_scan_lun(struct cam_periph *periph, struct cam_path *path,
5227              cam_flags flags, union ccb *request_ccb)
5228 {
5229         struct ccb_pathinq cpi;
5230         cam_status status;
5231         struct cam_path *new_path;
5232         struct cam_periph *old_periph;
5233         
5234         CAM_DEBUG(request_ccb->ccb_h.path, CAM_DEBUG_TRACE,
5235                   ("xpt_scan_lun\n"));
5236         
5237         xpt_setup_ccb(&cpi.ccb_h, path, /*priority*/1);
5238         cpi.ccb_h.func_code = XPT_PATH_INQ;
5239         xpt_action((union ccb *)&cpi);
5240
5241         if (cpi.ccb_h.status != CAM_REQ_CMP) {
5242                 if (request_ccb != NULL) {
5243                         request_ccb->ccb_h.status = cpi.ccb_h.status;
5244                         xpt_done(request_ccb);
5245                 }
5246                 return;
5247         }
5248
5249         if ((cpi.hba_misc & PIM_NOINITIATOR) != 0) {
5250                 /*
5251                  * Can't scan the bus on an adapter that
5252                  * cannot perform the initiator role.
5253                  */
5254                 if (request_ccb != NULL) {
5255                         request_ccb->ccb_h.status = CAM_REQ_CMP;
5256                         xpt_done(request_ccb);
5257                 }
5258                 return;
5259         }
5260
5261         if (request_ccb == NULL) {
5262                 request_ccb = kmalloc(sizeof(union ccb), M_TEMP, M_INTWAIT);
5263                 new_path = kmalloc(sizeof(*new_path), M_TEMP, M_INTWAIT);
5264                 status = xpt_compile_path(new_path, xpt_periph,
5265                                           path->bus->path_id,
5266                                           path->target->target_id,
5267                                           path->device->lun_id);
5268
5269                 if (status != CAM_REQ_CMP) {
5270                         xpt_print_path(path);
5271                         kprintf("xpt_scan_lun: can't compile path, can't "
5272                                "continue\n");
5273                         kfree(request_ccb, M_TEMP);
5274                         kfree(new_path, M_TEMP);
5275                         return;
5276                 }
5277                 xpt_setup_ccb(&request_ccb->ccb_h, new_path, /*priority*/ 1);
5278                 request_ccb->ccb_h.cbfcnp = xptscandone;
5279                 request_ccb->ccb_h.func_code = XPT_SCAN_LUN;
5280                 request_ccb->crcn.flags = flags;
5281         }
5282
5283         crit_enter();
5284         if ((old_periph = cam_periph_find(path, "probe")) != NULL) {
5285                 probe_softc *softc;
5286
5287                 softc = (probe_softc *)old_periph->softc;
5288                 TAILQ_INSERT_TAIL(&softc->request_ccbs, &request_ccb->ccb_h,
5289                                   periph_links.tqe);
5290         } else {
5291                 status = cam_periph_alloc(proberegister, NULL, probecleanup,
5292                                           probestart, "probe",
5293                                           CAM_PERIPH_BIO,
5294                                           request_ccb->ccb_h.path, NULL, 0,
5295                                           request_ccb);
5296
5297                 if (status != CAM_REQ_CMP) {
5298                         xpt_print_path(path);
5299                         kprintf("xpt_scan_lun: cam_alloc_periph returned an "
5300                                "error, can't continue probe\n");
5301                         request_ccb->ccb_h.status = status;
5302                         xpt_done(request_ccb);
5303                 }
5304         }
5305         crit_exit();
5306 }
5307
5308 static void
5309 xptscandone(struct cam_periph *periph, union ccb *done_ccb)
5310 {
5311         xpt_release_path(done_ccb->ccb_h.path);
5312         kfree(done_ccb->ccb_h.path, M_TEMP);
5313         kfree(done_ccb, M_TEMP);
5314 }
5315
5316 static cam_status
5317 proberegister(struct cam_periph *periph, void *arg)
5318 {
5319         union ccb *request_ccb; /* CCB representing the probe request */
5320         probe_softc *softc;
5321
5322         request_ccb = (union ccb *)arg;
5323         if (periph == NULL) {
5324                 kprintf("proberegister: periph was NULL!!\n");
5325                 return(CAM_REQ_CMP_ERR);
5326         }
5327
5328         if (request_ccb == NULL) {
5329                 kprintf("proberegister: no probe CCB, "
5330                        "can't register device\n");
5331                 return(CAM_REQ_CMP_ERR);
5332         }
5333
5334         softc = kmalloc(sizeof(*softc), M_TEMP, M_INTWAIT | M_ZERO);
5335         TAILQ_INIT(&softc->request_ccbs);
5336         TAILQ_INSERT_TAIL(&softc->request_ccbs, &request_ccb->ccb_h,
5337                           periph_links.tqe);
5338         softc->flags = 0;
5339         periph->softc = softc;
5340         cam_periph_acquire(periph);
5341         /*
5342          * Ensure we've waited at least a bus settle
5343          * delay before attempting to probe the device.
5344          * For HBAs that don't do bus resets, this won't make a difference.
5345          */
5346         cam_periph_freeze_after_event(periph, &periph->path->bus->last_reset,
5347                                       SCSI_DELAY);
5348         probeschedule(periph);
5349         return(CAM_REQ_CMP);
5350 }
5351
5352 static void
5353 probeschedule(struct cam_periph *periph)
5354 {
5355         struct ccb_pathinq cpi;
5356         union ccb *ccb;
5357         probe_softc *softc;
5358
5359         softc = (probe_softc *)periph->softc;
5360         ccb = (union ccb *)TAILQ_FIRST(&softc->request_ccbs);
5361
5362         xpt_setup_ccb(&cpi.ccb_h, periph->path, /*priority*/1);
5363         cpi.ccb_h.func_code = XPT_PATH_INQ;
5364         xpt_action((union ccb *)&cpi);
5365
5366         /*
5367          * If a device has gone away and another device, or the same one,
5368          * is back in the same place, it should have a unit attention
5369          * condition pending.  It will not report the unit attention in
5370          * response to an inquiry, which may leave invalid transfer
5371          * negotiations in effect.  The TUR will reveal the unit attention
5372          * condition.  Only send the TUR for lun 0, since some devices 
5373          * will get confused by commands other than inquiry to non-existent
5374          * luns.  If you think a device has gone away start your scan from
5375          * lun 0.  This will insure that any bogus transfer settings are
5376          * invalidated.
5377          *
5378          * If we haven't seen the device before and the controller supports
5379          * some kind of transfer negotiation, negotiate with the first
5380          * sent command if no bus reset was performed at startup.  This
5381          * ensures that the device is not confused by transfer negotiation
5382          * settings left over by loader or BIOS action.
5383          */
5384         if (((ccb->ccb_h.path->device->flags & CAM_DEV_UNCONFIGURED) == 0)
5385          && (ccb->ccb_h.target_lun == 0)) {
5386                 softc->action = PROBE_TUR;
5387         } else if ((cpi.hba_inquiry & (PI_WIDE_32|PI_WIDE_16|PI_SDTR_ABLE)) != 0
5388               && (cpi.hba_misc & PIM_NOBUSRESET) != 0) {
5389                 proberequestdefaultnegotiation(periph);
5390                 softc->action = PROBE_INQUIRY;
5391         } else {
5392                 softc->action = PROBE_INQUIRY;
5393         }
5394
5395         if (ccb->crcn.flags & CAM_EXPECT_INQ_CHANGE)
5396                 softc->flags |= PROBE_NO_ANNOUNCE;
5397         else
5398                 softc->flags &= ~PROBE_NO_ANNOUNCE;
5399
5400         xpt_schedule(periph, ccb->ccb_h.pinfo.priority);
5401 }
5402
5403 static void
5404 probestart(struct cam_periph *periph, union ccb *start_ccb)
5405 {
5406         /* Probe the device that our peripheral driver points to */
5407         struct ccb_scsiio *csio;
5408         probe_softc *softc;
5409
5410         CAM_DEBUG(start_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("probestart\n"));
5411
5412         softc = (probe_softc *)periph->softc;
5413         csio = &start_ccb->csio;
5414
5415         switch (softc->action) {
5416         case PROBE_TUR:
5417         case PROBE_TUR_FOR_NEGOTIATION:
5418         {
5419                 scsi_test_unit_ready(csio,
5420                                      /*retries*/4,
5421                                      probedone,
5422                                      MSG_SIMPLE_Q_TAG,
5423                                      SSD_FULL_SIZE,
5424                                      /*timeout*/60000);
5425                 break;
5426         }
5427         case PROBE_INQUIRY:
5428         case PROBE_FULL_INQUIRY:
5429         {
5430                 u_int inquiry_len;
5431                 struct scsi_inquiry_data *inq_buf;
5432
5433                 inq_buf = &periph->path->device->inq_data;
5434                 /*
5435                  * If the device is currently configured, we calculate an
5436                  * MD5 checksum of the inquiry data, and if the serial number
5437                  * length is greater than 0, add the serial number data
5438                  * into the checksum as well.  Once the inquiry and the
5439                  * serial number check finish, we attempt to figure out
5440                  * whether we still have the same device.
5441                  */
5442                 if ((periph->path->device->flags & CAM_DEV_UNCONFIGURED) == 0) {
5443                         
5444                         MD5Init(&softc->context);
5445                         MD5Update(&softc->context, (unsigned char *)inq_buf,
5446                                   sizeof(struct scsi_inquiry_data));
5447                         softc->flags |= PROBE_INQUIRY_CKSUM;
5448                         if (periph->path->device->serial_num_len > 0) {
5449                                 MD5Update(&softc->context,
5450                                           periph->path->device->serial_num,
5451                                           periph->path->device->serial_num_len);
5452                                 softc->flags |= PROBE_SERIAL_CKSUM;
5453                         }
5454                         MD5Final(softc->digest, &softc->context);
5455                 } 
5456
5457                 if (softc->action == PROBE_INQUIRY)
5458                         inquiry_len = SHORT_INQUIRY_LENGTH;
5459                 else
5460                         inquiry_len = inq_buf->additional_length + 5;
5461         
5462                 scsi_inquiry(csio,
5463                              /*retries*/4,
5464                              probedone,
5465                              MSG_SIMPLE_Q_TAG,
5466                              (u_int8_t *)inq_buf,
5467                              inquiry_len,
5468                              /*evpd*/FALSE,
5469                              /*page_code*/0,
5470                              SSD_MIN_SIZE,
5471                              /*timeout*/60 * 1000);
5472                 break;
5473         }
5474         case PROBE_MODE_SENSE:
5475         {
5476                 void  *mode_buf;
5477                 int    mode_buf_len;
5478
5479                 mode_buf_len = sizeof(struct scsi_mode_header_6)
5480                              + sizeof(struct scsi_mode_blk_desc)
5481                              + sizeof(struct scsi_control_page);
5482                 mode_buf = kmalloc(mode_buf_len, M_TEMP, M_INTWAIT);
5483                 scsi_mode_sense(csio,
5484                                 /*retries*/4,
5485                                 probedone,
5486                                 MSG_SIMPLE_Q_TAG,
5487                                 /*dbd*/FALSE,
5488                                 SMS_PAGE_CTRL_CURRENT,
5489                                 SMS_CONTROL_MODE_PAGE,
5490                                 mode_buf,
5491                                 mode_buf_len,
5492                                 SSD_FULL_SIZE,
5493                                 /*timeout*/60000);
5494                 break;
5495         }
5496         case PROBE_SERIAL_NUM:
5497         {
5498                 struct scsi_vpd_unit_serial_number *serial_buf;
5499                 struct cam_ed* device;
5500
5501                 serial_buf = NULL;
5502                 device = periph->path->device;
5503                 device->serial_num = NULL;
5504                 device->serial_num_len = 0;
5505
5506                 if ((device->quirk->quirks & CAM_QUIRK_NOSERIAL) == 0) {
5507                         serial_buf = kmalloc(sizeof(*serial_buf), M_TEMP,
5508                                             M_INTWAIT | M_ZERO);
5509                         scsi_inquiry(csio,
5510                                      /*retries*/4,
5511                                      probedone,
5512                                      MSG_SIMPLE_Q_TAG,
5513                                      (u_int8_t *)serial_buf,
5514                                      sizeof(*serial_buf),
5515                                      /*evpd*/TRUE,
5516                                      SVPD_UNIT_SERIAL_NUMBER,
5517                                      SSD_MIN_SIZE,
5518                                      /*timeout*/60 * 1000);
5519                         break;
5520                 }
5521                 /*
5522                  * We'll have to do without, let our probedone
5523                  * routine finish up for us.
5524                  */
5525                 start_ccb->csio.data_ptr = NULL;
5526                 probedone(periph, start_ccb);
5527                 return;
5528         }
5529         }
5530         xpt_action(start_ccb);
5531 }
5532
5533 static void
5534 proberequestdefaultnegotiation(struct cam_periph *periph)
5535 {
5536         struct ccb_trans_settings cts;
5537
5538         xpt_setup_ccb(&cts.ccb_h, periph->path, /*priority*/1);
5539         cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
5540 #ifdef CAM_NEW_TRAN_CODE
5541         cts.type = CTS_TYPE_USER_SETTINGS;
5542 #else /* CAM_NEW_TRAN_CODE */
5543         cts.flags = CCB_TRANS_USER_SETTINGS;
5544 #endif /* CAM_NEW_TRAN_CODE */
5545         xpt_action((union ccb *)&cts);
5546         cts.ccb_h.func_code = XPT_SET_TRAN_SETTINGS;
5547 #ifdef CAM_NEW_TRAN_CODE
5548         cts.type = CTS_TYPE_CURRENT_SETTINGS;
5549 #else /* CAM_NEW_TRAN_CODE */
5550         cts.flags &= ~CCB_TRANS_USER_SETTINGS;
5551         cts.flags |= CCB_TRANS_CURRENT_SETTINGS;
5552 #endif /* CAM_NEW_TRAN_CODE */
5553         xpt_action((union ccb *)&cts);
5554 }
5555
5556 static void
5557 probedone(struct cam_periph *periph, union ccb *done_ccb)
5558 {
5559         probe_softc *softc;
5560         struct cam_path *path;
5561         u_int32_t  priority;
5562
5563         CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("probedone\n"));
5564
5565         softc = (probe_softc *)periph->softc;
5566         path = done_ccb->ccb_h.path;
5567         priority = done_ccb->ccb_h.pinfo.priority;
5568
5569         switch (softc->action) {
5570         case PROBE_TUR:
5571         {
5572                 if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
5573
5574                         if (cam_periph_error(done_ccb, 0,
5575                                              SF_NO_PRINT, NULL) == ERESTART)
5576                                 return;
5577                         else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
5578                                 /* Don't wedge the queue */
5579                                 xpt_release_devq(done_ccb->ccb_h.path,
5580                                                  /*count*/1,
5581                                                  /*run_queue*/TRUE);
5582                 }
5583                 softc->action = PROBE_INQUIRY;
5584                 xpt_release_ccb(done_ccb);
5585                 xpt_schedule(periph, priority);
5586                 return;
5587         }
5588         case PROBE_INQUIRY:
5589         case PROBE_FULL_INQUIRY:
5590         {
5591                 if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
5592                         struct scsi_inquiry_data *inq_buf;
5593                         u_int8_t periph_qual;
5594
5595                         path->device->flags |= CAM_DEV_INQUIRY_DATA_VALID;
5596                         inq_buf = &path->device->inq_data;
5597
5598                         periph_qual = SID_QUAL(inq_buf);
5599                         
5600                         switch(periph_qual) {
5601                         case SID_QUAL_LU_CONNECTED:
5602                         {
5603                                 u_int8_t alen;
5604
5605                                 /*
5606                                  * We conservatively request only
5607                                  * SHORT_INQUIRY_LEN bytes of inquiry
5608                                  * information during our first try
5609                                  * at sending an INQUIRY. If the device
5610                                  * has more information to give,
5611                                  * perform a second request specifying
5612                                  * the amount of information the device
5613                                  * is willing to give.
5614                                  */
5615                                 alen = inq_buf->additional_length;
5616                                 if (softc->action == PROBE_INQUIRY
5617                                  && alen > (SHORT_INQUIRY_LENGTH - 5)) {
5618                                         softc->action = PROBE_FULL_INQUIRY;
5619                                         xpt_release_ccb(done_ccb);
5620                                         xpt_schedule(periph, priority);
5621                                         return;
5622                                 }
5623
5624                                 xpt_find_quirk(path->device);
5625
5626 #ifdef CAM_NEW_TRAN_CODE
5627                                 xpt_devise_transport(path);
5628 #endif /* CAM_NEW_TRAN_CODE */
5629                                 if ((inq_buf->flags & SID_CmdQue) != 0)
5630                                         softc->action = PROBE_MODE_SENSE;
5631                                 else
5632                                         softc->action = PROBE_SERIAL_NUM;
5633
5634                                 path->device->flags &= ~CAM_DEV_UNCONFIGURED;
5635                                 xpt_reference_device(path->device);
5636
5637                                 xpt_release_ccb(done_ccb);
5638                                 xpt_schedule(periph, priority);
5639                                 return;
5640                         }
5641                         default:
5642                                 break;
5643                         }
5644                 } else if (cam_periph_error(done_ccb, 0,
5645                                             done_ccb->ccb_h.target_lun > 0
5646                                             ? SF_RETRY_UA|SF_QUIET_IR
5647                                             : SF_RETRY_UA,
5648                                             &softc->saved_ccb) == ERESTART) {
5649                         return;
5650                 } else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
5651                         /* Don't wedge the queue */
5652                         xpt_release_devq(done_ccb->ccb_h.path, /*count*/1,
5653                                          /*run_queue*/TRUE);
5654                 }
5655                 /*
5656                  * If we get to this point, we got an error status back
5657                  * from the inquiry and the error status doesn't require
5658                  * automatically retrying the command.  Therefore, the
5659                  * inquiry failed.  If we had inquiry information before
5660                  * for this device, but this latest inquiry command failed,
5661                  * the device has probably gone away.  If this device isn't
5662                  * already marked unconfigured, notify the peripheral
5663                  * drivers that this device is no more.
5664                  */
5665                 if ((path->device->flags & CAM_DEV_UNCONFIGURED) == 0) {
5666                         /* Send the async notification. */
5667                         xpt_async(AC_LOST_DEVICE, path, NULL);
5668                 }
5669
5670                 xpt_release_ccb(done_ccb);
5671                 break;
5672         }
5673         case PROBE_MODE_SENSE:
5674         {
5675                 struct ccb_scsiio *csio;
5676                 struct scsi_mode_header_6 *mode_hdr;
5677
5678                 csio = &done_ccb->csio;
5679                 mode_hdr = (struct scsi_mode_header_6 *)csio->data_ptr;
5680                 if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
5681                         struct scsi_control_page *page;
5682                         u_int8_t *offset;
5683
5684                         offset = ((u_int8_t *)&mode_hdr[1])
5685                             + mode_hdr->blk_desc_len;
5686                         page = (struct scsi_control_page *)offset;
5687                         path->device->queue_flags = page->queue_flags;
5688                 } else if (cam_periph_error(done_ccb, 0,
5689                                             SF_RETRY_UA|SF_NO_PRINT,
5690                                             &softc->saved_ccb) == ERESTART) {
5691                         return;
5692                 } else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
5693                         /* Don't wedge the queue */
5694                         xpt_release_devq(done_ccb->ccb_h.path,
5695                                          /*count*/1, /*run_queue*/TRUE);
5696                 }
5697                 xpt_release_ccb(done_ccb);
5698                 kfree(mode_hdr, M_TEMP);
5699                 softc->action = PROBE_SERIAL_NUM;
5700                 xpt_schedule(periph, priority);
5701                 return;
5702         }
5703         case PROBE_SERIAL_NUM:
5704         {
5705                 struct ccb_scsiio *csio;
5706                 struct scsi_vpd_unit_serial_number *serial_buf;
5707                 u_int32_t  priority;
5708                 int changed;
5709                 int have_serialnum;
5710
5711                 changed = 1;
5712                 have_serialnum = 0;
5713                 csio = &done_ccb->csio;
5714                 priority = done_ccb->ccb_h.pinfo.priority;
5715                 serial_buf =
5716                     (struct scsi_vpd_unit_serial_number *)csio->data_ptr;
5717
5718                 /* Clean up from previous instance of this device */
5719                 if (path->device->serial_num != NULL) {
5720                         kfree(path->device->serial_num, M_DEVBUF);
5721                         path->device->serial_num = NULL;
5722                         path->device->serial_num_len = 0;
5723                 }
5724
5725                 if (serial_buf == NULL) {
5726                         /*
5727                          * Don't process the command as it was never sent
5728                          */
5729                 } else if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP
5730                         && (serial_buf->length > 0)) {
5731
5732                         have_serialnum = 1;
5733                         path->device->serial_num =
5734                                 kmalloc((serial_buf->length + 1),
5735                                        M_DEVBUF, M_INTWAIT);
5736                         bcopy(serial_buf->serial_num,
5737                               path->device->serial_num,
5738                               serial_buf->length);
5739                         path->device->serial_num_len = serial_buf->length;
5740                         path->device->serial_num[serial_buf->length] = '\0';
5741                 } else if (cam_periph_error(done_ccb, 0,
5742                                             SF_RETRY_UA|SF_NO_PRINT,
5743                                             &softc->saved_ccb) == ERESTART) {
5744                         return;
5745                 } else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
5746                         /* Don't wedge the queue */
5747                         xpt_release_devq(done_ccb->ccb_h.path, /*count*/1,
5748                                          /*run_queue*/TRUE);
5749                 }
5750                 
5751                 /*
5752                  * Let's see if we have seen this device before.
5753                  */
5754                 if ((softc->flags & PROBE_INQUIRY_CKSUM) != 0) {
5755                         MD5_CTX context;
5756                         u_int8_t digest[16];
5757
5758                         MD5Init(&context);
5759                         
5760                         MD5Update(&context,
5761                                   (unsigned char *)&path->device->inq_data,
5762                                   sizeof(struct scsi_inquiry_data));
5763
5764                         if (have_serialnum)
5765                                 MD5Update(&context, serial_buf->serial_num,
5766                                           serial_buf->length);
5767
5768                         MD5Final(digest, &context);
5769                         if (bcmp(softc->digest, digest, 16) == 0)
5770                                 changed = 0;
5771
5772                         /*
5773                          * XXX Do we need to do a TUR in order to ensure
5774                          *     that the device really hasn't changed???
5775                          */
5776                         if ((changed != 0)
5777                          && ((softc->flags & PROBE_NO_ANNOUNCE) == 0))
5778                                 xpt_async(AC_LOST_DEVICE, path, NULL);
5779                 }
5780                 if (serial_buf != NULL)
5781                         kfree(serial_buf, M_TEMP);
5782
5783                 if (changed != 0) {
5784                         /*
5785                          * Now that we have all the necessary
5786                          * information to safely perform transfer
5787                          * negotiations... Controllers don't perform
5788                          * any negotiation or tagged queuing until
5789                          * after the first XPT_SET_TRAN_SETTINGS ccb is
5790                          * received.  So, on a new device, just retreive
5791                          * the user settings, and set them as the current
5792                          * settings to set the device up.
5793                          */
5794                         proberequestdefaultnegotiation(periph);
5795                         xpt_release_ccb(done_ccb);
5796
5797                         /*
5798                          * Perform a TUR to allow the controller to
5799                          * perform any necessary transfer negotiation.
5800                          */
5801                         softc->action = PROBE_TUR_FOR_NEGOTIATION;
5802                         xpt_schedule(periph, priority);
5803                         return;
5804                 }
5805                 xpt_release_ccb(done_ccb);
5806                 break;
5807         }
5808         case PROBE_TUR_FOR_NEGOTIATION:
5809                 if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
5810                         /* Don't wedge the queue */
5811                         xpt_release_devq(done_ccb->ccb_h.path, /*count*/1,
5812                                          /*run_queue*/TRUE);
5813                 }
5814
5815                 path->device->flags &= ~CAM_DEV_UNCONFIGURED;
5816                 xpt_reference_device(path->device);
5817
5818                 if ((softc->flags & PROBE_NO_ANNOUNCE) == 0) {
5819                         /* Inform the XPT that a new device has been found */
5820                         done_ccb->ccb_h.func_code = XPT_GDEV_TYPE;
5821                         xpt_action(done_ccb);
5822
5823                         xpt_async(AC_FOUND_DEVICE, xpt_periph->path, done_ccb);
5824                 }
5825                 xpt_release_ccb(done_ccb);
5826                 break;
5827         }
5828         done_ccb = (union ccb *)TAILQ_FIRST(&softc->request_ccbs);
5829         TAILQ_REMOVE(&softc->request_ccbs, &done_ccb->ccb_h, periph_links.tqe);
5830         done_ccb->ccb_h.status = CAM_REQ_CMP;
5831         xpt_done(done_ccb);
5832         if (TAILQ_FIRST(&softc->request_ccbs) == NULL) {
5833                 cam_periph_invalidate(periph);
5834                 cam_periph_release(periph);
5835         } else {
5836                 probeschedule(periph);
5837         }
5838 }
5839
5840 static void
5841 probecleanup(struct cam_periph *periph)
5842 {
5843         kfree(periph->softc, M_TEMP);
5844 }
5845
5846 static void
5847 xpt_find_quirk(struct cam_ed *device)
5848 {
5849         caddr_t match;
5850
5851         match = cam_quirkmatch((caddr_t)&device->inq_data,
5852                                (caddr_t)xpt_quirk_table,
5853                                sizeof(xpt_quirk_table)/sizeof(*xpt_quirk_table),
5854                                sizeof(*xpt_quirk_table), scsi_inquiry_match);
5855
5856         if (match == NULL)
5857                 panic("xpt_find_quirk: device didn't match wildcard entry!!");
5858
5859         device->quirk = (struct xpt_quirk_entry *)match;
5860 }
5861
5862 #ifdef CAM_NEW_TRAN_CODE
5863
5864 static void
5865 xpt_devise_transport(struct cam_path *path)
5866 {
5867         struct ccb_pathinq cpi;
5868         struct ccb_trans_settings cts;
5869         struct scsi_inquiry_data *inq_buf;
5870
5871         /* Get transport information from the SIM */
5872         xpt_setup_ccb(&cpi.ccb_h, path, /*priority*/1);
5873         cpi.ccb_h.func_code = XPT_PATH_INQ;
5874         xpt_action((union ccb *)&cpi);
5875
5876         inq_buf = NULL;
5877         if ((path->device->flags & CAM_DEV_INQUIRY_DATA_VALID) != 0)
5878                 inq_buf = &path->device->inq_data;
5879         path->device->protocol = PROTO_SCSI;
5880         path->device->protocol_version =
5881             inq_buf != NULL ? SID_ANSI_REV(inq_buf) : cpi.protocol_version;
5882         path->device->transport = cpi.transport;
5883         path->device->transport_version = cpi.transport_version;
5884
5885         /*
5886          * Any device not using SPI3 features should
5887          * be considered SPI2 or lower.
5888          */
5889         if (inq_buf != NULL) {
5890                 if (path->device->transport == XPORT_SPI
5891                  && (inq_buf->spi3data & SID_SPI_MASK) == 0
5892                  && path->device->transport_version > 2)
5893                         path->device->transport_version = 2;
5894         } else {
5895                 struct cam_ed* otherdev;
5896
5897                 for (otherdev = TAILQ_FIRST(&path->target->ed_entries);
5898                      otherdev != NULL;
5899                      otherdev = TAILQ_NEXT(otherdev, links)) {
5900                         if (otherdev != path->device)
5901                                 break;
5902                 }
5903
5904                 if (otherdev != NULL) {
5905                         /*
5906                          * Initially assume the same versioning as
5907                          * prior luns for this target.
5908                          */
5909                         path->device->protocol_version =
5910                             otherdev->protocol_version;
5911                         path->device->transport_version =
5912                             otherdev->transport_version;
5913                 } else {
5914                         /* Until we know better, opt for safty */
5915                         path->device->protocol_version = 2;
5916                         if (path->device->transport == XPORT_SPI)
5917                                 path->device->transport_version = 2;
5918                         else
5919                                 path->device->transport_version = 0;
5920                 }
5921         }
5922
5923         /*
5924          * XXX
5925          * For a device compliant with SPC-2 we should be able
5926          * to determine the transport version supported by
5927          * scrutinizing the version descriptors in the
5928          * inquiry buffer.
5929          */
5930
5931         /* Tell the controller what we think */
5932         xpt_setup_ccb(&cts.ccb_h, path, /*priority*/1);
5933         cts.ccb_h.func_code = XPT_SET_TRAN_SETTINGS;
5934         cts.type = CTS_TYPE_CURRENT_SETTINGS;
5935         cts.transport = path->device->transport;
5936         cts.transport_version = path->device->transport_version;
5937         cts.protocol = path->device->protocol;
5938         cts.protocol_version = path->device->protocol_version;
5939         cts.proto_specific.valid = 0;
5940         cts.xport_specific.valid = 0;
5941         xpt_action((union ccb *)&cts);
5942 }
5943
5944 static void
5945 xpt_set_transfer_settings(struct ccb_trans_settings *cts, struct cam_ed *device,
5946                           int async_update)
5947 {
5948         struct  ccb_pathinq cpi;
5949         struct  ccb_trans_settings cur_cts;
5950         struct  ccb_trans_settings_scsi *scsi;
5951         struct  ccb_trans_settings_scsi *cur_scsi;
5952         struct  cam_sim *sim;
5953         struct  scsi_inquiry_data *inq_data;
5954
5955         if (device == NULL) {
5956                 cts->ccb_h.status = CAM_PATH_INVALID;
5957                 xpt_done((union ccb *)cts);
5958                 return;
5959         }
5960
5961         if (cts->protocol == PROTO_UNKNOWN
5962          || cts->protocol == PROTO_UNSPECIFIED) {
5963                 cts->protocol = device->protocol;
5964                 cts->protocol_version = device->protocol_version;
5965         }
5966
5967         if (cts->protocol_version == PROTO_VERSION_UNKNOWN
5968          || cts->protocol_version == PROTO_VERSION_UNSPECIFIED)
5969                 cts->protocol_version = device->protocol_version;
5970
5971         if (cts->protocol != device->protocol) {
5972                 xpt_print_path(cts->ccb_h.path);
5973                 printf("Uninitialized Protocol %x:%x?\n",
5974                        cts->protocol, device->protocol);
5975                 cts->protocol = device->protocol;
5976         }
5977
5978         if (cts->protocol_version > device->protocol_version) {
5979                 if (bootverbose) {
5980                         xpt_print_path(cts->ccb_h.path);
5981                         printf("Down reving Protocol Version from %d to %d?\n",
5982                                cts->protocol_version, device->protocol_version);
5983                 }
5984                 cts->protocol_version = device->protocol_version;
5985         }
5986
5987         if (cts->transport == XPORT_UNKNOWN
5988          || cts->transport == XPORT_UNSPECIFIED) {
5989                 cts->transport = device->transport;
5990                 cts->transport_version = device->transport_version;
5991         }
5992
5993         if (cts->transport_version == XPORT_VERSION_UNKNOWN
5994          || cts->transport_version == XPORT_VERSION_UNSPECIFIED)
5995                 cts->transport_version = device->transport_version;
5996
5997         if (cts->transport != device->transport) {
5998                 xpt_print_path(cts->ccb_h.path);
5999                 printf("Uninitialized Transport %x:%x?\n",
6000                        cts->transport, device->transport);
6001                 cts->transport = device->transport;
6002         }
6003
6004         if (cts->transport_version > device->transport_version) {
6005                 if (bootverbose) {
6006                         xpt_print_path(cts->ccb_h.path);
6007                         printf("Down reving Transport Version from %d to %d?\n",
6008                                cts->transport_version,
6009                                device->transport_version);
6010                 }
6011                 cts->transport_version = device->transport_version;
6012         }
6013
6014         sim = cts->ccb_h.path->bus->sim;
6015
6016         /*
6017          * Nothing more of interest to do unless
6018          * this is a device connected via the
6019          * SCSI protocol.
6020          */
6021         if (cts->protocol != PROTO_SCSI) {
6022                 if (async_update == FALSE)
6023                         (*(sim->sim_action))(sim, (union ccb *)cts);
6024                 return;
6025         }
6026
6027         inq_data = &device->inq_data;
6028         scsi = &cts->proto_specific.scsi;
6029         xpt_setup_ccb(&cpi.ccb_h, cts->ccb_h.path, /*priority*/1);
6030         cpi.ccb_h.func_code = XPT_PATH_INQ;
6031         xpt_action((union ccb *)&cpi);
6032
6033         /* SCSI specific sanity checking */
6034         if ((cpi.hba_inquiry & PI_TAG_ABLE) == 0
6035          || (inq_data->flags & SID_CmdQue) == 0
6036          || (device->queue_flags & SCP_QUEUE_DQUE) != 0
6037          || (device->quirk->mintags == 0)) {
6038                 /*
6039                  * Can't tag on hardware that doesn't support tags,
6040                  * doesn't have it enabled, or has broken tag support.
6041                  */
6042                 scsi->flags &= ~CTS_SCSI_FLAGS_TAG_ENB;
6043         }
6044
6045         if (async_update == FALSE) {
6046                 /*
6047                  * Perform sanity checking against what the
6048                  * controller and device can do.
6049                  */
6050                 xpt_setup_ccb(&cur_cts.ccb_h, cts->ccb_h.path, /*priority*/1);
6051                 cur_cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
6052                 cur_cts.type = cts->type;
6053                 xpt_action((union ccb *)&cur_cts);
6054
6055                 cur_scsi = &cur_cts.proto_specific.scsi;
6056                 if ((scsi->valid & CTS_SCSI_VALID_TQ) == 0) {
6057                         scsi->flags &= ~CTS_SCSI_FLAGS_TAG_ENB;
6058                         scsi->flags |= cur_scsi->flags & CTS_SCSI_FLAGS_TAG_ENB;
6059                 }
6060                 if ((cur_scsi->valid & CTS_SCSI_VALID_TQ) == 0)
6061                         scsi->flags &= ~CTS_SCSI_FLAGS_TAG_ENB;
6062         }
6063
6064         /* SPI specific sanity checking */
6065         if (cts->transport == XPORT_SPI
6066          && async_update == FALSE) {
6067                 u_int spi3caps;
6068                 struct ccb_trans_settings_spi *spi;
6069                 struct ccb_trans_settings_spi *cur_spi;
6070
6071                 spi = &cts->xport_specific.spi;
6072
6073                 cur_spi = &cur_cts.xport_specific.spi;
6074
6075                 /* Fill in any gaps in what the user gave us */
6076                 if ((spi->valid & CTS_SPI_VALID_SYNC_RATE) == 0)
6077                         spi->sync_period = cur_spi->sync_period;
6078                 if ((cur_spi->valid & CTS_SPI_VALID_SYNC_RATE) == 0)
6079                         spi->sync_period = 0;
6080                 if ((spi->valid & CTS_SPI_VALID_SYNC_OFFSET) == 0)
6081                         spi->sync_offset = cur_spi->sync_offset;
6082                 if ((cur_spi->valid & CTS_SPI_VALID_SYNC_OFFSET) == 0)
6083                         spi->sync_offset = 0;
6084                 if ((spi->valid & CTS_SPI_VALID_PPR_OPTIONS) == 0)
6085                         spi->ppr_options = cur_spi->ppr_options;
6086                 if ((cur_spi->valid & CTS_SPI_VALID_PPR_OPTIONS) == 0)
6087                         spi->ppr_options = 0;
6088                 if ((spi->valid & CTS_SPI_VALID_BUS_WIDTH) == 0)
6089                         spi->bus_width = cur_spi->bus_width;
6090                 if ((cur_spi->valid & CTS_SPI_VALID_BUS_WIDTH) == 0)
6091                         spi->bus_width = 0;
6092                 if ((spi->valid & CTS_SPI_VALID_DISC) == 0) {
6093                         spi->flags &= ~CTS_SPI_FLAGS_DISC_ENB;
6094                         spi->flags |= cur_spi->flags & CTS_SPI_FLAGS_DISC_ENB;
6095                 }
6096                 if ((cur_spi->valid & CTS_SPI_VALID_DISC) == 0)
6097                         spi->flags &= ~CTS_SPI_FLAGS_DISC_ENB;
6098                 if (((device->flags & CAM_DEV_INQUIRY_DATA_VALID) != 0
6099                   && (inq_data->flags & SID_Sync) == 0
6100                   && cts->type == CTS_TYPE_CURRENT_SETTINGS)
6101                  || ((cpi.hba_inquiry & PI_SDTR_ABLE) == 0)
6102                  || (cts->sync_offset == 0)
6103                  || (cts->sync_period == 0)) {
6104                         /* Force async */
6105                         spi->sync_period = 0;
6106                         spi->sync_offset = 0;
6107                 }
6108
6109                 switch (spi->bus_width) {
6110                 case MSG_EXT_WDTR_BUS_32_BIT:
6111                         if (((device->flags & CAM_DEV_INQUIRY_DATA_VALID) == 0
6112                           || (inq_data->flags & SID_WBus32) != 0
6113                           || cts->type == CTS_TYPE_USER_SETTINGS)
6114                          && (cpi.hba_inquiry & PI_WIDE_32) != 0)
6115                                 break;
6116                         /* Fall Through to 16-bit */
6117                 case MSG_EXT_WDTR_BUS_16_BIT:
6118                         if (((device->flags & CAM_DEV_INQUIRY_DATA_VALID) == 0
6119                           || (inq_data->flags & SID_WBus16) != 0
6120                           || cts->type == CTS_TYPE_USER_SETTINGS)
6121                          && (cpi.hba_inquiry & PI_WIDE_16) != 0) {
6122                                 spi->bus_width = MSG_EXT_WDTR_BUS_16_BIT;
6123                                 break;
6124                         }
6125                         /* Fall Through to 8-bit */
6126                 default: /* New bus width?? */
6127                 case MSG_EXT_WDTR_BUS_8_BIT:
6128                         /* All targets can do this */
6129                         spi->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
6130                         break;
6131                 }
6132
6133                 spi3caps = cpi.xport_specific.spi.ppr_options;
6134                 if ((device->flags & CAM_DEV_INQUIRY_DATA_VALID) != 0
6135                  && cts->type == CTS_TYPE_CURRENT_SETTINGS)
6136                         spi3caps &= inq_data->spi3data;
6137
6138                 if ((spi3caps & SID_SPI_CLOCK_DT) == 0)
6139                         spi->ppr_options &= ~MSG_EXT_PPR_DT_REQ;
6140
6141                 if ((spi3caps & SID_SPI_IUS) == 0)
6142                         spi->ppr_options &= ~MSG_EXT_PPR_IU_REQ;
6143
6144                 if ((spi3caps & SID_SPI_QAS) == 0)
6145                         spi->ppr_options &= ~MSG_EXT_PPR_QAS_REQ;
6146
6147                 /* No SPI Transfer settings are allowed unless we are wide */
6148                 if (spi->bus_width == 0)
6149                         spi->ppr_options = 0;
6150
6151                 if ((spi->flags & CTS_SPI_FLAGS_DISC_ENB) == 0) {
6152                         /*
6153                          * Can't tag queue without disconnection.
6154                          */
6155                         scsi->flags &= ~CTS_SCSI_FLAGS_TAG_ENB;
6156                         scsi->valid |= CTS_SCSI_VALID_TQ;
6157                 }
6158
6159                 /*
6160                  * If we are currently performing tagged transactions to
6161                  * this device and want to change its negotiation parameters,
6162                  * go non-tagged for a bit to give the controller a chance to
6163                  * negotiate unhampered by tag messages.
6164                  */
6165                 if (cts->type == CTS_TYPE_CURRENT_SETTINGS
6166                  && (device->inq_flags & SID_CmdQue) != 0
6167                  && (scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) != 0
6168                  && (spi->flags & (CTS_SPI_VALID_SYNC_RATE|
6169                                    CTS_SPI_VALID_SYNC_OFFSET|
6170                                    CTS_SPI_VALID_BUS_WIDTH)) != 0)
6171                         xpt_toggle_tags(cts->ccb_h.path);
6172         }
6173
6174         if (cts->type == CTS_TYPE_CURRENT_SETTINGS
6175          && (scsi->valid & CTS_SCSI_VALID_TQ) != 0) {
6176                 int device_tagenb;
6177
6178                 /*
6179                  * If we are transitioning from tags to no-tags or
6180                  * vice-versa, we need to carefully freeze and restart
6181                  * the queue so that we don't overlap tagged and non-tagged
6182                  * commands.  We also temporarily stop tags if there is
6183                  * a change in transfer negotiation settings to allow
6184                  * "tag-less" negotiation.
6185                  */
6186                 if ((device->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
6187                  || (device->inq_flags & SID_CmdQue) != 0)
6188                         device_tagenb = TRUE;
6189                 else
6190                         device_tagenb = FALSE;
6191
6192                 if (((scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) != 0
6193                   && device_tagenb == FALSE)
6194                  || ((scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) == 0
6195                   && device_tagenb == TRUE)) {
6196
6197                         if ((scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) != 0) {
6198                                 /*
6199                                  * Delay change to use tags until after a
6200                                  * few commands have gone to this device so
6201                                  * the controller has time to perform transfer
6202                                  * negotiations without tagged messages getting
6203                                  * in the way.
6204                                  */
6205                                 device->tag_delay_count = CAM_TAG_DELAY_COUNT;
6206                                 device->flags |= CAM_DEV_TAG_AFTER_COUNT;
6207                         } else {
6208                                 struct ccb_relsim crs;
6209
6210                                 xpt_freeze_devq(cts->ccb_h.path, /*count*/1);
6211                                 device->inq_flags &= ~SID_CmdQue;
6212                                 xpt_dev_ccbq_resize(cts->ccb_h.path,
6213                                                     sim->max_dev_openings);
6214                                 device->flags &= ~CAM_DEV_TAG_AFTER_COUNT;
6215                                 device->tag_delay_count = 0;
6216
6217                                 xpt_setup_ccb(&crs.ccb_h, cts->ccb_h.path,
6218                                               /*priority*/1);
6219                                 crs.ccb_h.func_code = XPT_REL_SIMQ;
6220                                 crs.release_flags = RELSIM_RELEASE_AFTER_QEMPTY;
6221                                 crs.openings
6222                                     = crs.release_timeout
6223                                     = crs.qfrozen_cnt
6224                                     = 0;
6225                                 xpt_action((union ccb *)&crs);
6226                         }
6227                 }
6228         }
6229         if (async_update == FALSE)
6230                 (*(sim->sim_action))(sim, (union ccb *)cts);
6231 }
6232
6233 #else /* CAM_NEW_TRAN_CODE */
6234
6235 static void
6236 xpt_set_transfer_settings(struct ccb_trans_settings *cts, struct cam_ed *device,
6237                           int async_update)
6238 {
6239         struct  cam_sim *sim;
6240         int     qfrozen;
6241
6242         sim = cts->ccb_h.path->bus->sim;
6243         if (async_update == FALSE) {
6244                 struct  scsi_inquiry_data *inq_data;
6245                 struct  ccb_pathinq cpi;
6246                 struct  ccb_trans_settings cur_cts;
6247
6248                 if (device == NULL) {
6249                         cts->ccb_h.status = CAM_PATH_INVALID;
6250                         xpt_done((union ccb *)cts);
6251                         return;
6252                 }
6253
6254                 /*
6255                  * Perform sanity checking against what the
6256                  * controller and device can do.
6257                  */
6258                 xpt_setup_ccb(&cpi.ccb_h, cts->ccb_h.path, /*priority*/1);
6259                 cpi.ccb_h.func_code = XPT_PATH_INQ;
6260                 xpt_action((union ccb *)&cpi);
6261                 xpt_setup_ccb(&cur_cts.ccb_h, cts->ccb_h.path, /*priority*/1);
6262                 cur_cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
6263                 cur_cts.flags = CCB_TRANS_CURRENT_SETTINGS;
6264                 xpt_action((union ccb *)&cur_cts);
6265                 inq_data = &device->inq_data;
6266
6267                 /* Fill in any gaps in what the user gave us */
6268                 if ((cts->valid & CCB_TRANS_SYNC_RATE_VALID) == 0)
6269                         cts->sync_period = cur_cts.sync_period;
6270                 if ((cts->valid & CCB_TRANS_SYNC_OFFSET_VALID) == 0)
6271                         cts->sync_offset = cur_cts.sync_offset;
6272                 if ((cts->valid & CCB_TRANS_BUS_WIDTH_VALID) == 0)
6273                         cts->bus_width = cur_cts.bus_width;
6274                 if ((cts->valid & CCB_TRANS_DISC_VALID) == 0) {
6275                         cts->flags &= ~CCB_TRANS_DISC_ENB;
6276                         cts->flags |= cur_cts.flags & CCB_TRANS_DISC_ENB;
6277                 }
6278                 if ((cts->valid & CCB_TRANS_TQ_VALID) == 0) {
6279                         cts->flags &= ~CCB_TRANS_TAG_ENB;
6280                         cts->flags |= cur_cts.flags & CCB_TRANS_TAG_ENB;
6281                 }
6282
6283                 if (((device->flags & CAM_DEV_INQUIRY_DATA_VALID) != 0
6284                   && (inq_data->flags & SID_Sync) == 0)
6285                  || ((cpi.hba_inquiry & PI_SDTR_ABLE) == 0)
6286                  || (cts->sync_offset == 0)
6287                  || (cts->sync_period == 0)) {
6288                         /* Force async */
6289                         cts->sync_period = 0;
6290                         cts->sync_offset = 0;
6291                 } else if ((device->flags & CAM_DEV_INQUIRY_DATA_VALID) != 0) {
6292
6293                         if ((inq_data->spi3data & SID_SPI_CLOCK_DT) == 0
6294                          && cts->sync_period <= 0x9) {
6295                                 /*
6296                                  * Don't allow DT transmission rates if the
6297                                  * device does not support it.
6298                                  */
6299                                 cts->sync_period = 0xa;
6300                         }
6301                         if ((inq_data->spi3data & SID_SPI_IUS) == 0
6302                          && cts->sync_period <= 0x8) {
6303                                 /*
6304                                  * Don't allow PACE transmission rates
6305                                  * if the device does support packetized
6306                                  * transfers.
6307                                  */
6308                                 cts->sync_period = 0x9;
6309                         }
6310                 }
6311
6312                 switch (cts->bus_width) {
6313                 case MSG_EXT_WDTR_BUS_32_BIT:
6314                         if (((device->flags & CAM_DEV_INQUIRY_DATA_VALID) == 0
6315                           || (inq_data->flags & SID_WBus32) != 0)
6316                          && (cpi.hba_inquiry & PI_WIDE_32) != 0)
6317                                 break;
6318                         /* Fall Through to 16-bit */
6319                 case MSG_EXT_WDTR_BUS_16_BIT:
6320                         if (((device->flags & CAM_DEV_INQUIRY_DATA_VALID) == 0
6321                           || (inq_data->flags & SID_WBus16) != 0)
6322                          && (cpi.hba_inquiry & PI_WIDE_16) != 0) {
6323                                 cts->bus_width = MSG_EXT_WDTR_BUS_16_BIT;
6324                                 break;
6325                         }
6326                         /* Fall Through to 8-bit */
6327                 default: /* New bus width?? */
6328                 case MSG_EXT_WDTR_BUS_8_BIT:
6329                         /* All targets can do this */
6330                         cts->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
6331                         break;
6332                 }
6333
6334                 if ((cts->flags & CCB_TRANS_DISC_ENB) == 0) {
6335                         /*
6336                          * Can't tag queue without disconnection.
6337                          */
6338                         cts->flags &= ~CCB_TRANS_TAG_ENB;
6339                         cts->valid |= CCB_TRANS_TQ_VALID;
6340                 }
6341
6342                 if ((cpi.hba_inquiry & PI_TAG_ABLE) == 0
6343                  || (inq_data->flags & SID_CmdQue) == 0
6344                  || (device->queue_flags & SCP_QUEUE_DQUE) != 0
6345                  || (device->quirk->mintags == 0)) {
6346                         /*
6347                          * Can't tag on hardware that doesn't support,
6348                          * doesn't have it enabled, or has broken tag support.
6349                          */
6350                         cts->flags &= ~CCB_TRANS_TAG_ENB;
6351                 }
6352         }
6353
6354         qfrozen = FALSE;
6355         if ((cts->valid & CCB_TRANS_TQ_VALID) != 0) {
6356                 int device_tagenb;
6357
6358                 /*
6359                  * If we are transitioning from tags to no-tags or
6360                  * vice-versa, we need to carefully freeze and restart
6361                  * the queue so that we don't overlap tagged and non-tagged
6362                  * commands.  We also temporarily stop tags if there is
6363                  * a change in transfer negotiation settings to allow
6364                  * "tag-less" negotiation.
6365                  */
6366                 if ((device->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
6367                  || (device->inq_flags & SID_CmdQue) != 0)
6368                         device_tagenb = TRUE;
6369                 else
6370                         device_tagenb = FALSE;
6371
6372                 if (((cts->flags & CCB_TRANS_TAG_ENB) != 0
6373                   && device_tagenb == FALSE)
6374                  || ((cts->flags & CCB_TRANS_TAG_ENB) == 0
6375                   && device_tagenb == TRUE)) {
6376
6377                         if ((cts->flags & CCB_TRANS_TAG_ENB) != 0) {
6378                                 /*
6379                                  * Delay change to use tags until after a
6380                                  * few commands have gone to this device so
6381                                  * the controller has time to perform transfer
6382                                  * negotiations without tagged messages getting
6383                                  * in the way.
6384                                  */
6385                                 device->tag_delay_count = CAM_TAG_DELAY_COUNT;
6386                                 device->flags |= CAM_DEV_TAG_AFTER_COUNT;
6387                         } else {
6388                                 xpt_freeze_devq(cts->ccb_h.path, /*count*/1);
6389                                 qfrozen = TRUE;
6390                                 device->inq_flags &= ~SID_CmdQue;
6391                                 xpt_dev_ccbq_resize(cts->ccb_h.path,
6392                                                     sim->max_dev_openings);
6393                                 device->flags &= ~CAM_DEV_TAG_AFTER_COUNT;
6394                                 device->tag_delay_count = 0;
6395                         }
6396                 }
6397         }
6398
6399         if (async_update == FALSE) {
6400                 /*
6401                  * If we are currently performing tagged transactions to
6402                  * this device and want to change its negotiation parameters,
6403                  * go non-tagged for a bit to give the controller a chance to
6404                  * negotiate unhampered by tag messages.
6405                  */
6406                 if ((device->inq_flags & SID_CmdQue) != 0
6407                  && (cts->flags & (CCB_TRANS_SYNC_RATE_VALID|
6408                                    CCB_TRANS_SYNC_OFFSET_VALID|
6409                                    CCB_TRANS_BUS_WIDTH_VALID)) != 0)
6410                         xpt_toggle_tags(cts->ccb_h.path);
6411
6412                 (*(sim->sim_action))(sim, (union ccb *)cts);
6413         }
6414
6415         if (qfrozen) {
6416                 struct ccb_relsim crs;
6417
6418                 xpt_setup_ccb(&crs.ccb_h, cts->ccb_h.path,
6419                               /*priority*/1);
6420                 crs.ccb_h.func_code = XPT_REL_SIMQ;
6421                 crs.release_flags = RELSIM_RELEASE_AFTER_QEMPTY;
6422                 crs.openings
6423                     = crs.release_timeout 
6424                     = crs.qfrozen_cnt
6425                     = 0;
6426                 xpt_action((union ccb *)&crs);
6427         }
6428 }
6429
6430
6431 #endif /* CAM_NEW_TRAN_CODE */
6432
6433 static void
6434 xpt_toggle_tags(struct cam_path *path)
6435 {
6436         struct cam_ed *dev;
6437
6438         /*
6439          * Give controllers a chance to renegotiate
6440          * before starting tag operations.  We
6441          * "toggle" tagged queuing off then on
6442          * which causes the tag enable command delay
6443          * counter to come into effect.
6444          */
6445         dev = path->device;
6446         if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
6447          || ((dev->inq_flags & SID_CmdQue) != 0
6448           && (dev->inq_flags & (SID_Sync|SID_WBus16|SID_WBus32)) != 0)) {
6449                 struct ccb_trans_settings cts;
6450
6451                 xpt_setup_ccb(&cts.ccb_h, path, 1);
6452 #ifdef CAM_NEW_TRAN_CODE
6453                 cts.protocol = PROTO_SCSI;
6454                 cts.protocol_version = PROTO_VERSION_UNSPECIFIED;
6455                 cts.transport = XPORT_UNSPECIFIED;
6456                 cts.transport_version = XPORT_VERSION_UNSPECIFIED;
6457                 cts.proto_specific.scsi.flags = 0;
6458                 cts.proto_specific.scsi.valid = CTS_SCSI_VALID_TQ;
6459 #else /* CAM_NEW_TRAN_CODE */
6460                 cts.flags = 0;
6461                 cts.valid = CCB_TRANS_TQ_VALID;
6462 #endif /* CAM_NEW_TRAN_CODE */
6463                 xpt_set_transfer_settings(&cts, path->device,
6464                                           /*async_update*/TRUE);
6465 #ifdef CAM_NEW_TRAN_CODE
6466                 cts.proto_specific.scsi.flags = CTS_SCSI_FLAGS_TAG_ENB;
6467 #else /* CAM_NEW_TRAN_CODE */
6468                 cts.flags = CCB_TRANS_TAG_ENB;
6469 #endif /* CAM_NEW_TRAN_CODE */
6470                 xpt_set_transfer_settings(&cts, path->device,
6471                                           /*async_update*/TRUE);
6472         }
6473 }
6474
6475 static void
6476 xpt_start_tags(struct cam_path *path)
6477 {
6478         struct ccb_relsim crs;
6479         struct cam_ed *device;
6480         struct cam_sim *sim;
6481         int    newopenings;
6482
6483         device = path->device;
6484         sim = path->bus->sim;
6485         device->flags &= ~CAM_DEV_TAG_AFTER_COUNT;
6486         xpt_freeze_devq(path, /*count*/1);
6487         device->inq_flags |= SID_CmdQue;
6488         newopenings = min(device->quirk->maxtags, sim->max_tagged_dev_openings);
6489         xpt_dev_ccbq_resize(path, newopenings);
6490         xpt_setup_ccb(&crs.ccb_h, path, /*priority*/1);
6491         crs.ccb_h.func_code = XPT_REL_SIMQ;
6492         crs.release_flags = RELSIM_RELEASE_AFTER_QEMPTY;
6493         crs.openings
6494             = crs.release_timeout 
6495             = crs.qfrozen_cnt
6496             = 0;
6497         xpt_action((union ccb *)&crs);
6498 }
6499
6500 static int busses_to_config;
6501 static int busses_to_reset;
6502
6503 static int
6504 xptconfigbuscountfunc(struct cam_eb *bus, void *arg)
6505 {
6506         if (bus->path_id != CAM_XPT_PATH_ID) {
6507                 struct cam_path path;
6508                 struct ccb_pathinq cpi;
6509                 int can_negotiate;
6510
6511                 busses_to_config++;
6512                 xpt_compile_path(&path, NULL, bus->path_id,
6513                                  CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
6514                 xpt_setup_ccb(&cpi.ccb_h, &path, /*priority*/1);
6515                 cpi.ccb_h.func_code = XPT_PATH_INQ;
6516                 xpt_action((union ccb *)&cpi);
6517                 can_negotiate = cpi.hba_inquiry;
6518                 can_negotiate &= (PI_WIDE_32|PI_WIDE_16|PI_SDTR_ABLE);
6519                 if ((cpi.hba_misc & PIM_NOBUSRESET) == 0
6520                  && can_negotiate)
6521                         busses_to_reset++;
6522                 xpt_release_path(&path);
6523         }
6524
6525         return(1);
6526 }
6527
6528 static int
6529 xptconfigfunc(struct cam_eb *bus, void *arg)
6530 {
6531         struct  cam_path *path;
6532         union   ccb *work_ccb;
6533
6534         if (bus->path_id != CAM_XPT_PATH_ID) {
6535                 cam_status status;
6536                 int can_negotiate;
6537
6538                 work_ccb = xpt_alloc_ccb();
6539                 if ((status = xpt_create_path(&path, xpt_periph, bus->path_id,
6540                                               CAM_TARGET_WILDCARD,
6541                                               CAM_LUN_WILDCARD)) !=CAM_REQ_CMP){
6542                         kprintf("xptconfigfunc: xpt_create_path failed with "
6543                                "status %#x for bus %d\n", status, bus->path_id);
6544                         kprintf("xptconfigfunc: halting bus configuration\n");
6545                         xpt_free_ccb(work_ccb);
6546                         busses_to_config--;
6547                         xpt_finishconfig(xpt_periph, NULL);
6548                         return(0);
6549                 }
6550                 xpt_setup_ccb(&work_ccb->ccb_h, path, /*priority*/1);
6551                 work_ccb->ccb_h.func_code = XPT_PATH_INQ;
6552                 xpt_action(work_ccb);
6553                 if (work_ccb->ccb_h.status != CAM_REQ_CMP) {
6554                         kprintf("xptconfigfunc: CPI failed on bus %d "
6555                                "with status %d\n", bus->path_id,
6556                                work_ccb->ccb_h.status);
6557                         xpt_finishconfig(xpt_periph, work_ccb);
6558                         return(1);
6559                 }
6560
6561                 can_negotiate = work_ccb->cpi.hba_inquiry;
6562                 can_negotiate &= (PI_WIDE_32|PI_WIDE_16|PI_SDTR_ABLE);
6563                 if ((work_ccb->cpi.hba_misc & PIM_NOBUSRESET) == 0
6564                  && (can_negotiate != 0)) {
6565                         xpt_setup_ccb(&work_ccb->ccb_h, path, /*priority*/1);
6566                         work_ccb->ccb_h.func_code = XPT_RESET_BUS;
6567                         work_ccb->ccb_h.cbfcnp = NULL;
6568                         CAM_DEBUG(path, CAM_DEBUG_SUBTRACE,
6569                                   ("Resetting Bus\n"));
6570                         xpt_action(work_ccb);
6571                         xpt_finishconfig(xpt_periph, work_ccb);
6572                 } else {
6573                         /* Act as though we performed a successful BUS RESET */
6574                         work_ccb->ccb_h.func_code = XPT_RESET_BUS;
6575                         xpt_finishconfig(xpt_periph, work_ccb);
6576                 }
6577         }
6578
6579         return(1);
6580 }
6581
6582 static void
6583 xpt_config(void *arg)
6584 {
6585         /*
6586          * Now that interrupts are enabled, go find our devices
6587          */
6588
6589 #ifdef CAMDEBUG
6590         /* Setup debugging flags and path */
6591 #ifdef CAM_DEBUG_FLAGS
6592         cam_dflags = CAM_DEBUG_FLAGS;
6593 #else /* !CAM_DEBUG_FLAGS */
6594         cam_dflags = CAM_DEBUG_NONE;
6595 #endif /* CAM_DEBUG_FLAGS */
6596 #ifdef CAM_DEBUG_BUS
6597         if (cam_dflags != CAM_DEBUG_NONE) {
6598                 if (xpt_create_path(&cam_dpath, xpt_periph,
6599                                     CAM_DEBUG_BUS, CAM_DEBUG_TARGET,
6600                                     CAM_DEBUG_LUN) != CAM_REQ_CMP) {
6601                         kprintf("xpt_config: xpt_create_path() failed for debug"
6602                                " target %d:%d:%d, debugging disabled\n",
6603                                CAM_DEBUG_BUS, CAM_DEBUG_TARGET, CAM_DEBUG_LUN);
6604                         cam_dflags = CAM_DEBUG_NONE;
6605                 }
6606         } else
6607                 cam_dpath = NULL;
6608 #else /* !CAM_DEBUG_BUS */
6609         cam_dpath = NULL;
6610 #endif /* CAM_DEBUG_BUS */
6611 #endif /* CAMDEBUG */
6612
6613         /*
6614          * Scan all installed busses.
6615          */
6616         xpt_for_all_busses(xptconfigbuscountfunc, NULL);
6617
6618         if (busses_to_config == 0) {
6619                 /* Call manually because we don't have any busses */
6620                 xpt_finishconfig(xpt_periph, NULL);
6621         } else  {
6622                 if (busses_to_reset > 0 && SCSI_DELAY >= 2000) {
6623                         kprintf("Waiting %d seconds for SCSI "
6624                                "devices to settle\n", SCSI_DELAY/1000);
6625                 }
6626                 xpt_for_all_busses(xptconfigfunc, NULL);
6627         }
6628 }
6629
6630 /*
6631  * If the given device only has one peripheral attached to it, and if that
6632  * peripheral is the passthrough driver, announce it.  This insures that the
6633  * user sees some sort of announcement for every peripheral in their system.
6634  */
6635 static int
6636 xptpassannouncefunc(struct cam_ed *device, void *arg)
6637 {
6638         struct cam_periph *periph;
6639         int i;
6640
6641         for (periph = SLIST_FIRST(&device->periphs), i = 0; periph != NULL;
6642              periph = SLIST_NEXT(periph, periph_links), i++);
6643
6644         periph = SLIST_FIRST(&device->periphs);
6645         if ((i == 1)
6646          && (strncmp(periph->periph_name, "pass", 4) == 0))
6647                 xpt_announce_periph(periph, NULL);
6648
6649         return(1);
6650 }
6651
6652 static void
6653 xpt_finishconfig(struct cam_periph *periph, union ccb *done_ccb)
6654 {
6655         struct  periph_driver **p_drv;
6656         int     i;
6657
6658         if (done_ccb != NULL) {
6659                 CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE,
6660                           ("xpt_finishconfig\n"));
6661                 switch(done_ccb->ccb_h.func_code) {
6662                 case XPT_RESET_BUS:
6663                         if (done_ccb->ccb_h.status == CAM_REQ_CMP) {
6664                                 done_ccb->ccb_h.func_code = XPT_SCAN_BUS;
6665                                 done_ccb->ccb_h.cbfcnp = xpt_finishconfig;
6666                                 xpt_action(done_ccb);
6667                                 return;
6668                         }
6669                         /* FALLTHROUGH */
6670                 case XPT_SCAN_BUS:
6671                 default:
6672                         xpt_free_path(done_ccb->ccb_h.path);
6673                         busses_to_config--;
6674                         break;
6675                 }
6676         }
6677
6678         if (busses_to_config == 0) {
6679                 /* Register all the peripheral drivers */
6680                 /* XXX This will have to change when we have loadable modules */
6681                 p_drv = periph_drivers;
6682                 for (i = 0; p_drv[i] != NULL; i++) {
6683                         (*p_drv[i]->init)();
6684                 }
6685
6686                 /*
6687                  * Check for devices with no "standard" peripheral driver
6688                  * attached.  For any devices like that, announce the
6689                  * passthrough driver so the user will see something.
6690                  */
6691                 xpt_for_all_devices(xptpassannouncefunc, NULL);
6692
6693                 /* Release our hook so that the boot can continue. */
6694                 config_intrhook_disestablish(xpt_config_hook);
6695                 kfree(xpt_config_hook, M_TEMP);
6696                 xpt_config_hook = NULL;
6697         }
6698         if (done_ccb != NULL)
6699                 xpt_free_ccb(done_ccb);
6700 }
6701
6702 static void
6703 xptaction(struct cam_sim *sim, union ccb *work_ccb)
6704 {
6705         CAM_DEBUG(work_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("xptaction\n"));
6706
6707         switch (work_ccb->ccb_h.func_code) {
6708         /* Common cases first */
6709         case XPT_PATH_INQ:              /* Path routing inquiry */
6710         {
6711                 struct ccb_pathinq *cpi;
6712
6713                 cpi = &work_ccb->cpi;
6714                 cpi->version_num = 1; /* XXX??? */
6715                 cpi->hba_inquiry = 0;
6716                 cpi->target_sprt = 0;
6717                 cpi->hba_misc = 0;
6718                 cpi->hba_eng_cnt = 0;
6719                 cpi->max_target = 0;
6720                 cpi->max_lun = 0;
6721                 cpi->initiator_id = 0;
6722                 strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
6723                 strncpy(cpi->hba_vid, "", HBA_IDLEN);
6724                 strncpy(cpi->dev_name, sim->sim_name, DEV_IDLEN);
6725                 cpi->unit_number = sim->unit_number;
6726                 cpi->bus_id = sim->bus_id;
6727                 cpi->base_transfer_speed = 0;
6728 #ifdef CAM_NEW_TRAN_CODE
6729                 cpi->protocol = PROTO_UNSPECIFIED;
6730                 cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
6731                 cpi->transport = XPORT_UNSPECIFIED;
6732                 cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
6733 #endif /* CAM_NEW_TRAN_CODE */
6734                 cpi->ccb_h.status = CAM_REQ_CMP;
6735                 xpt_done(work_ccb);
6736                 break;
6737         }
6738         default:
6739                 work_ccb->ccb_h.status = CAM_REQ_INVALID;
6740                 xpt_done(work_ccb);
6741                 break;
6742         }
6743 }
6744
6745 /*
6746  * The xpt as a "controller" has no interrupt sources, so polling
6747  * is a no-op.
6748  */
6749 static void
6750 xptpoll(struct cam_sim *sim)
6751 {
6752 }
6753
6754 /*
6755  * Should only be called by the machine interrupt dispatch routines,
6756  * so put these prototypes here instead of in the header.
6757  */
6758
6759 static void
6760 swi_camnet(void *arg, void *frame)
6761 {
6762         camisr(&cam_netq);
6763 }
6764
6765 static void
6766 swi_cambio(void *arg, void *frame)
6767 {
6768         camisr(&cam_bioq);
6769 }
6770
6771 static void
6772 camisr(cam_isrq_t *queue)
6773 {
6774         struct  ccb_hdr *ccb_h;
6775
6776         crit_enter();
6777         while ((ccb_h = TAILQ_FIRST(queue)) != NULL) {
6778                 int     runq;
6779
6780                 TAILQ_REMOVE(queue, ccb_h, sim_links.tqe);
6781                 ccb_h->pinfo.index = CAM_UNQUEUED_INDEX;
6782                 splz();
6783
6784                 CAM_DEBUG(ccb_h->path, CAM_DEBUG_TRACE,
6785                           ("camisr\n"));
6786
6787                 runq = FALSE;
6788
6789                 if (ccb_h->flags & CAM_HIGH_POWER) {
6790                         struct highpowerlist    *hphead;
6791                         struct cam_ed           *device;
6792                         union ccb               *send_ccb;
6793
6794                         hphead = &highpowerq;
6795
6796                         send_ccb = (union ccb *)STAILQ_FIRST(hphead);
6797
6798                         /*
6799                          * Increment the count since this command is done.
6800                          */
6801                         num_highpower++;
6802
6803                         /* 
6804                          * Any high powered commands queued up?
6805                          */
6806                         if (send_ccb != NULL) {
6807                                 device = send_ccb->ccb_h.path->device;
6808
6809                                 STAILQ_REMOVE_HEAD(hphead, xpt_links.stqe);
6810
6811                                 xpt_release_devq(send_ccb->ccb_h.path,
6812                                                  /*count*/1, /*runqueue*/TRUE);
6813                         }
6814                 }
6815                 if ((ccb_h->func_code & XPT_FC_USER_CCB) == 0) {
6816                         struct cam_ed *dev;
6817
6818                         dev = ccb_h->path->device;
6819
6820                         cam_ccbq_ccb_done(&dev->ccbq, (union ccb *)ccb_h);
6821
6822                         if (ccb_h->path->bus->sim->devq) {
6823                                 ccb_h->path->bus->sim->devq->send_active--;
6824                                 ccb_h->path->bus->sim->devq->send_openings++;
6825                         }
6826                         
6827                         if (((dev->flags & CAM_DEV_REL_ON_COMPLETE) != 0
6828                           && (ccb_h->status&CAM_STATUS_MASK) != CAM_REQUEUE_REQ)
6829                          || ((dev->flags & CAM_DEV_REL_ON_QUEUE_EMPTY) != 0
6830                           && (dev->ccbq.dev_active == 0))) {
6831                                 
6832                                 xpt_release_devq(ccb_h->path, /*count*/1,
6833                                                  /*run_queue*/TRUE);
6834                         }
6835
6836                         if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
6837                          && (--dev->tag_delay_count == 0))
6838                                 xpt_start_tags(ccb_h->path);
6839
6840                         if ((dev->ccbq.queue.entries > 0)
6841                          && (dev->qfrozen_cnt == 0)
6842                          && (device_is_send_queued(dev) == 0)) {
6843                                 runq = xpt_schedule_dev_sendq(ccb_h->path->bus,
6844                                                               dev);
6845                         }
6846                 }
6847
6848                 if (ccb_h->status & CAM_RELEASE_SIMQ) {
6849                         xpt_release_simq(ccb_h->path->bus->sim,
6850                                          /*run_queue*/TRUE);
6851                         ccb_h->status &= ~CAM_RELEASE_SIMQ;
6852                         runq = FALSE;
6853                 } 
6854
6855                 if ((ccb_h->flags & CAM_DEV_QFRZDIS)
6856                  && (ccb_h->status & CAM_DEV_QFRZN)) {
6857                         xpt_release_devq(ccb_h->path, /*count*/1,
6858                                          /*run_queue*/TRUE);
6859                         ccb_h->status &= ~CAM_DEV_QFRZN;
6860                 } else if (runq) {
6861                         xpt_run_dev_sendq(ccb_h->path->bus);
6862                 }
6863
6864                 /* Call the peripheral driver's callback */
6865                 (*ccb_h->cbfcnp)(ccb_h->path->periph, (union ccb *)ccb_h);
6866         }
6867         crit_exit();
6868 }