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