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