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