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