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