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