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