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