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