f281fb7c8b51f1702af9d0e4393ecba807003a77
[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 #include <sys/thread2.h>
51 #include <sys/spinlock2.h>
52
53 #include <machine/clock.h>
54 #include <machine/stdarg.h>
55
56 #include "cam.h"
57 #include "cam_ccb.h"
58 #include "cam_periph.h"
59 #include "cam_sim.h"
60 #include "cam_xpt.h"
61 #include "cam_xpt_sim.h"
62 #include "cam_xpt_periph.h"
63 #include "cam_debug.h"
64
65 #include "scsi/scsi_all.h"
66 #include "scsi/scsi_message.h"
67 #include "scsi/scsi_pass.h"
68 #include <sys/kthread.h>
69 #include "opt_cam.h"
70
71 /* Datastructures internal to the xpt layer */
72 MALLOC_DEFINE(M_CAMXPT, "CAM XPT", "CAM XPT buffers");
73
74 /* Object for defering XPT actions to a taskqueue */
75 struct xpt_task {
76         struct task     task;
77         void            *data1;
78         uintptr_t       data2;
79 };
80
81 /*
82  * Definition of an async handler callback block.  These are used to add
83  * SIMs and peripherals to the async callback lists.
84  */
85 struct async_node {
86         SLIST_ENTRY(async_node) links;
87         u_int32_t       event_enable;   /* Async Event enables */
88         void            (*callback)(void *arg, u_int32_t code,
89                                     struct cam_path *path, void *args);
90         void            *callback_arg;
91 };
92
93 SLIST_HEAD(async_list, async_node);
94 SLIST_HEAD(periph_list, cam_periph);
95
96 /*
97  * This is the maximum number of high powered commands (e.g. start unit)
98  * that can be outstanding at a particular time.
99  */
100 #ifndef CAM_MAX_HIGHPOWER
101 #define CAM_MAX_HIGHPOWER  4
102 #endif
103
104 /*
105  * Structure for queueing a device in a run queue.
106  * There is one run queue for allocating new ccbs,
107  * and another for sending ccbs to the controller.
108  */
109 struct cam_ed_qinfo {
110         cam_pinfo pinfo;
111         struct    cam_ed *device;
112 };
113
114 /*
115  * The CAM EDT (Existing Device Table) contains the device information for
116  * all devices for all busses in the system.  The table contains a
117  * cam_ed structure for each device on the bus.
118  */
119 struct cam_ed {
120         TAILQ_ENTRY(cam_ed) links;
121         struct  cam_ed_qinfo alloc_ccb_entry;
122         struct  cam_ed_qinfo send_ccb_entry;
123         struct  cam_et   *target;
124         struct  cam_sim  *sim;
125         lun_id_t         lun_id;
126         struct  camq drvq;              /*
127                                          * Queue of type drivers wanting to do
128                                          * work on this device.
129                                          */
130         struct  cam_ccbq ccbq;          /* Queue of pending ccbs */
131         struct  async_list asyncs;      /* Async callback info for this B/T/L */
132         struct  periph_list periphs;    /* All attached devices */
133         u_int   generation;             /* Generation number */
134         struct  cam_periph *owner;      /* Peripheral driver's ownership tag */
135         struct  xpt_quirk_entry *quirk; /* Oddities about this device */
136                                         /* Storage for the inquiry data */
137         cam_proto        protocol;
138         u_int            protocol_version;
139         cam_xport        transport;
140         u_int            transport_version;
141         struct           scsi_inquiry_data inq_data;
142         u_int8_t         inq_flags;     /*
143                                          * Current settings for inquiry flags.
144                                          * This allows us to override settings
145                                          * like disconnection and tagged
146                                          * queuing for a device.
147                                          */
148         u_int8_t         queue_flags;   /* Queue flags from the control page */
149         u_int8_t         serial_num_len;
150         u_int8_t        *serial_num;
151         u_int32_t        qfrozen_cnt;
152         u_int32_t        flags;
153 #define CAM_DEV_UNCONFIGURED            0x01
154 #define CAM_DEV_REL_TIMEOUT_PENDING     0x02
155 #define CAM_DEV_REL_ON_COMPLETE         0x04
156 #define CAM_DEV_REL_ON_QUEUE_EMPTY      0x08
157 #define CAM_DEV_RESIZE_QUEUE_NEEDED     0x10
158 #define CAM_DEV_TAG_AFTER_COUNT         0x20
159 #define CAM_DEV_INQUIRY_DATA_VALID      0x40
160 #define CAM_DEV_IN_DV                   0x80
161 #define CAM_DEV_DV_HIT_BOTTOM           0x100
162         u_int32_t        tag_delay_count;
163 #define CAM_TAG_DELAY_COUNT             5
164         u_int32_t        tag_saved_openings;
165         u_int32_t        refcount;
166         struct callout   callout;
167 };
168
169 /*
170  * Each target is represented by an ET (Existing Target).  These
171  * entries are created when a target is successfully probed with an
172  * identify, and removed when a device fails to respond after a number
173  * of retries, or a bus rescan finds the device missing.
174  */
175 struct cam_et {
176         TAILQ_HEAD(, cam_ed) ed_entries;
177         TAILQ_ENTRY(cam_et) links;
178         struct  cam_eb  *bus;
179         target_id_t     target_id;
180         u_int32_t       refcount;
181         u_int           generation;
182         struct          timeval last_reset;     /* uptime of last reset */
183 };
184
185 /*
186  * Each bus is represented by an EB (Existing Bus).  These entries
187  * are created by calls to xpt_bus_register and deleted by calls to
188  * xpt_bus_deregister.
189  */
190 struct cam_eb {
191         TAILQ_HEAD(, cam_et) et_entries;
192         TAILQ_ENTRY(cam_eb)  links;
193         path_id_t            path_id;
194         struct cam_sim       *sim;
195         struct timeval       last_reset;        /* uptime of last reset */
196         u_int32_t            flags;
197 #define CAM_EB_RUNQ_SCHEDULED   0x01
198         u_int32_t            refcount;
199         u_int                generation;
200 };
201
202 struct cam_path {
203         struct cam_periph *periph;
204         struct cam_eb     *bus;
205         struct cam_et     *target;
206         struct cam_ed     *device;
207 };
208
209 struct xpt_quirk_entry {
210         struct scsi_inquiry_pattern inq_pat;
211         u_int8_t quirks;
212 #define CAM_QUIRK_NOLUNS        0x01
213 #define CAM_QUIRK_NOSERIAL      0x02
214 #define CAM_QUIRK_HILUNS        0x04
215 #define CAM_QUIRK_NOHILUNS      0x08
216         u_int mintags;
217         u_int maxtags;
218 };
219
220 static int cam_srch_hi = 0;
221 TUNABLE_INT("kern.cam.cam_srch_hi", &cam_srch_hi);
222 static int sysctl_cam_search_luns(SYSCTL_HANDLER_ARGS);
223 SYSCTL_PROC(_kern_cam, OID_AUTO, cam_srch_hi, CTLTYPE_INT|CTLFLAG_RW, 0, 0,
224     sysctl_cam_search_luns, "I",
225     "allow search above LUN 7 for SCSI3 and greater devices");
226
227 #define CAM_SCSI2_MAXLUN        8
228 /*
229  * If we're not quirked to search <= the first 8 luns
230  * and we are either quirked to search above lun 8,
231  * or we're > SCSI-2 and we've enabled hilun searching,
232  * or we're > SCSI-2 and the last lun was a success,
233  * we can look for luns above lun 8.
234  */
235 #define CAN_SRCH_HI_SPARSE(dv)                          \
236   (((dv->quirk->quirks & CAM_QUIRK_NOHILUNS) == 0)      \
237   && ((dv->quirk->quirks & CAM_QUIRK_HILUNS)            \
238   || (SID_ANSI_REV(&dv->inq_data) > SCSI_REV_2 && cam_srch_hi)))
239
240 #define CAN_SRCH_HI_DENSE(dv)                           \
241   (((dv->quirk->quirks & CAM_QUIRK_NOHILUNS) == 0)      \
242   && ((dv->quirk->quirks & CAM_QUIRK_HILUNS)            \
243   || (SID_ANSI_REV(&dv->inq_data) > SCSI_REV_2)))
244
245 typedef enum {
246         XPT_FLAG_OPEN           = 0x01
247 } xpt_flags;
248
249 struct xpt_softc {
250         xpt_flags               flags;
251         u_int32_t               xpt_generation;
252
253         /* number of high powered commands that can go through right now */
254         STAILQ_HEAD(highpowerlist, ccb_hdr)     highpowerq;
255         int                     num_highpower;
256
257         /* queue for handling async rescan requests. */
258         TAILQ_HEAD(, ccb_hdr) ccb_scanq;
259
260         /* Registered busses */
261         TAILQ_HEAD(,cam_eb)     xpt_busses;
262         u_int                   bus_generation;
263
264         struct intr_config_hook *xpt_config_hook;
265
266         struct lock             xpt_topo_lock;
267         struct lock             xpt_lock;
268 };
269
270 static const char quantum[] = "QUANTUM";
271 static const char sony[] = "SONY";
272 static const char west_digital[] = "WDIGTL";
273 static const char samsung[] = "SAMSUNG";
274 static const char seagate[] = "SEAGATE";
275 static const char microp[] = "MICROP";
276
277 static struct xpt_quirk_entry xpt_quirk_table[] =
278 {
279         {
280                 /* Reports QUEUE FULL for temporary resource shortages */
281                 { T_DIRECT, SIP_MEDIA_FIXED, quantum, "XP39100*", "*" },
282                 /*quirks*/0, /*mintags*/24, /*maxtags*/32
283         },
284         {
285                 /* Reports QUEUE FULL for temporary resource shortages */
286                 { T_DIRECT, SIP_MEDIA_FIXED, quantum, "XP34550*", "*" },
287                 /*quirks*/0, /*mintags*/24, /*maxtags*/32
288         },
289         {
290                 /* Reports QUEUE FULL for temporary resource shortages */
291                 { T_DIRECT, SIP_MEDIA_FIXED, quantum, "XP32275*", "*" },
292                 /*quirks*/0, /*mintags*/24, /*maxtags*/32
293         },
294         {
295                 /* Broken tagged queuing drive */
296                 { T_DIRECT, SIP_MEDIA_FIXED, microp, "4421-07*", "*" },
297                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
298         },
299         {
300                 /* Broken tagged queuing drive */
301                 { T_DIRECT, SIP_MEDIA_FIXED, "HP", "C372*", "*" },
302                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
303         },
304         {
305                 /* Broken tagged queuing drive */
306                 { T_DIRECT, SIP_MEDIA_FIXED, microp, "3391*", "x43h" },
307                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
308         },
309         {
310                 /*
311                  * Unfortunately, the Quantum Atlas III has the same
312                  * problem as the Atlas II drives above.
313                  * Reported by: "Johan Granlund" <johan@granlund.nu>
314                  *
315                  * For future reference, the drive with the problem was:
316                  * QUANTUM QM39100TD-SW N1B0
317                  *
318                  * It's possible that Quantum will fix the problem in later
319                  * firmware revisions.  If that happens, the quirk entry
320                  * will need to be made specific to the firmware revisions
321                  * with the problem.
322                  *
323                  */
324                 /* Reports QUEUE FULL for temporary resource shortages */
325                 { T_DIRECT, SIP_MEDIA_FIXED, quantum, "QM39100*", "*" },
326                 /*quirks*/0, /*mintags*/24, /*maxtags*/32
327         },
328         {
329                 /*
330                  * 18 Gig Atlas III, same problem as the 9G version.
331                  * Reported by: Andre Albsmeier
332                  *              <andre.albsmeier@mchp.siemens.de>
333                  *
334                  * For future reference, the drive with the problem was:
335                  * QUANTUM QM318000TD-S N491
336                  */
337                 /* Reports QUEUE FULL for temporary resource shortages */
338                 { T_DIRECT, SIP_MEDIA_FIXED, quantum, "QM318000*", "*" },
339                 /*quirks*/0, /*mintags*/24, /*maxtags*/32
340         },
341         {
342                 /*
343                  * Broken tagged queuing drive
344                  * Reported by: Bret Ford <bford@uop.cs.uop.edu>
345                  *         and: Martin Renters <martin@tdc.on.ca>
346                  */
347                 { T_DIRECT, SIP_MEDIA_FIXED, seagate, "ST410800*", "71*" },
348                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
349         },
350                 /*
351                  * The Seagate Medalist Pro drives have very poor write
352                  * performance with anything more than 2 tags.
353                  *
354                  * Reported by:  Paul van der Zwan <paulz@trantor.xs4all.nl>
355                  * Drive:  <SEAGATE ST36530N 1444>
356                  *
357                  * Reported by:  Jeremy Lea <reg@shale.csir.co.za>
358                  * Drive:  <SEAGATE ST34520W 1281>
359                  *
360                  * No one has actually reported that the 9G version
361                  * (ST39140*) of the Medalist Pro has the same problem, but
362                  * we're assuming that it does because the 4G and 6.5G
363                  * versions of the drive are broken.
364                  */
365         {
366                 { T_DIRECT, SIP_MEDIA_FIXED, seagate, "ST34520*", "*"},
367                 /*quirks*/0, /*mintags*/2, /*maxtags*/2
368         },
369         {
370                 { T_DIRECT, SIP_MEDIA_FIXED, seagate, "ST36530*", "*"},
371                 /*quirks*/0, /*mintags*/2, /*maxtags*/2
372         },
373         {
374                 { T_DIRECT, SIP_MEDIA_FIXED, seagate, "ST39140*", "*"},
375                 /*quirks*/0, /*mintags*/2, /*maxtags*/2
376         },
377         {
378                 /*
379                  * Slow when tagged queueing is enabled.  Write performance
380                  * steadily drops off with more and more concurrent
381                  * transactions.  Best sequential write performance with
382                  * tagged queueing turned off and write caching turned on.
383                  *
384                  * PR:  kern/10398
385                  * Submitted by:  Hideaki Okada <hokada@isl.melco.co.jp>
386                  * Drive:  DCAS-34330 w/ "S65A" firmware.
387                  *
388                  * The drive with the problem had the "S65A" firmware
389                  * revision, and has also been reported (by Stephen J.
390                  * Roznowski <sjr@home.net>) for a drive with the "S61A"
391                  * firmware revision.
392                  *
393                  * Although no one has reported problems with the 2 gig
394                  * version of the DCAS drive, the assumption is that it
395                  * has the same problems as the 4 gig version.  Therefore
396                  * this quirk entries disables tagged queueing for all
397                  * DCAS drives.
398                  */
399                 { T_DIRECT, SIP_MEDIA_FIXED, "IBM", "DCAS*", "*" },
400                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
401         },
402         {
403                 /* Broken tagged queuing drive */
404                 { T_DIRECT, SIP_MEDIA_REMOVABLE, "iomega", "jaz*", "*" },
405                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
406         },
407         {
408                 /* Broken tagged queuing drive */
409                 { T_DIRECT, SIP_MEDIA_FIXED, "CONNER", "CFP2107*", "*" },
410                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
411         },
412         {
413                 /* This does not support other than LUN 0 */
414                 { T_DIRECT, SIP_MEDIA_FIXED, "VMware*", "*", "*" },
415                 CAM_QUIRK_NOLUNS, /*mintags*/2, /*maxtags*/255
416         },
417         {
418                 /*
419                  * Broken tagged queuing drive.
420                  * Submitted by:
421                  * NAKAJI Hiroyuki <nakaji@zeisei.dpri.kyoto-u.ac.jp>
422                  * in PR kern/9535
423                  */
424                 { T_DIRECT, SIP_MEDIA_FIXED, samsung, "WN34324U*", "*" },
425                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
426         },
427         {
428                 /*
429                  * Slow when tagged queueing is enabled. (1.5MB/sec versus
430                  * 8MB/sec.)
431                  * Submitted by: Andrew Gallatin <gallatin@cs.duke.edu>
432                  * Best performance with these drives is achieved with
433                  * tagged queueing turned off, and write caching turned on.
434                  */
435                 { T_DIRECT, SIP_MEDIA_FIXED, west_digital, "WDE*", "*" },
436                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
437         },
438         {
439                 /*
440                  * Slow when tagged queueing is enabled. (1.5MB/sec versus
441                  * 8MB/sec.)
442                  * Submitted by: Andrew Gallatin <gallatin@cs.duke.edu>
443                  * Best performance with these drives is achieved with
444                  * tagged queueing turned off, and write caching turned on.
445                  */
446                 { T_DIRECT, SIP_MEDIA_FIXED, west_digital, "ENTERPRISE", "*" },
447                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
448         },
449         {
450                 /*
451                  * Doesn't handle queue full condition correctly,
452                  * so we need to limit maxtags to what the device
453                  * can handle instead of determining this automatically.
454                  */
455                 { T_DIRECT, SIP_MEDIA_FIXED, samsung, "WN321010S*", "*" },
456                 /*quirks*/0, /*mintags*/2, /*maxtags*/32
457         },
458         {
459                 /* Really only one LUN */
460                 { T_ENCLOSURE, SIP_MEDIA_FIXED, "SUN", "SENA", "*" },
461                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
462         },
463         {
464                 /* I can't believe we need a quirk for DPT volumes. */
465                 { T_ANY, SIP_MEDIA_FIXED|SIP_MEDIA_REMOVABLE, "DPT", "*", "*" },
466                 CAM_QUIRK_NOLUNS,
467                 /*mintags*/0, /*maxtags*/255
468         },
469         {
470                 /*
471                  * Many Sony CDROM drives don't like multi-LUN probing.
472                  */
473                 { T_CDROM, SIP_MEDIA_REMOVABLE, sony, "CD-ROM CDU*", "*" },
474                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
475         },
476         {
477                 /*
478                  * This drive doesn't like multiple LUN probing.
479                  * Submitted by:  Parag Patel <parag@cgt.com>
480                  */
481                 { T_WORM, SIP_MEDIA_REMOVABLE, sony, "CD-R   CDU9*", "*" },
482                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
483         },
484         {
485                 { T_WORM, SIP_MEDIA_REMOVABLE, "YAMAHA", "CDR100*", "*" },
486                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
487         },
488         {
489                 /*
490                  * The 8200 doesn't like multi-lun probing, and probably
491                  * don't like serial number requests either.
492                  */
493                 {
494                         T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "EXABYTE",
495                         "EXB-8200*", "*"
496                 },
497                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
498         },
499         {
500                 /*
501                  * Let's try the same as above, but for a drive that says
502                  * it's an IPL-6860 but is actually an EXB 8200.
503                  */
504                 {
505                         T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "EXABYTE",
506                         "IPL-6860*", "*"
507                 },
508                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
509         },
510         {
511                 /*
512                  * These Hitachi drives don't like multi-lun probing.
513                  * The PR submitter has a DK319H, but says that the Linux
514                  * kernel has a similar work-around for the DK312 and DK314,
515                  * so all DK31* drives are quirked here.
516                  * PR:            misc/18793
517                  * Submitted by:  Paul Haddad <paul@pth.com>
518                  */
519                 { T_DIRECT, SIP_MEDIA_FIXED, "HITACHI", "DK31*", "*" },
520                 CAM_QUIRK_NOLUNS, /*mintags*/2, /*maxtags*/255
521         },
522         {
523                 /*
524                  * The Hitachi CJ series with J8A8 firmware apparantly has
525                  * problems with tagged commands.
526                  * PR: 23536
527                  * Reported by: amagai@nue.org
528                  */
529                 { T_DIRECT, SIP_MEDIA_FIXED, "HITACHI", "DK32CJ*", "J8A8" },
530                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
531         },
532         {
533                 /*
534                  * These are the large storage arrays.
535                  * Submitted by:  William Carrel <william.carrel@infospace.com>
536                  */
537                 { T_DIRECT, SIP_MEDIA_FIXED, "HITACHI", "OPEN*", "*" },
538                 CAM_QUIRK_HILUNS, 2, 1024
539         },
540         {
541                 /*
542                  * This old revision of the TDC3600 is also SCSI-1, and
543                  * hangs upon serial number probing.
544                  */
545                 {
546                         T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "TANDBERG",
547                         " TDC 3600", "U07:"
548                 },
549                 CAM_QUIRK_NOSERIAL, /*mintags*/0, /*maxtags*/0
550         },
551         {
552                 /*
553                  * Would repond to all LUNs if asked for.
554                  */
555                 {
556                         T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "CALIPER",
557                         "CP150", "*"
558                 },
559                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
560         },
561         {
562                 /*
563                  * Would repond to all LUNs if asked for.
564                  */
565                 {
566                         T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "KENNEDY",
567                         "96X2*", "*"
568                 },
569                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
570         },
571         {
572                 /* Submitted by: Matthew Dodd <winter@jurai.net> */
573                 { T_PROCESSOR, SIP_MEDIA_FIXED, "Cabletrn", "EA41*", "*" },
574                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
575         },
576         {
577                 /* Submitted by: Matthew Dodd <winter@jurai.net> */
578                 { T_PROCESSOR, SIP_MEDIA_FIXED, "CABLETRN", "EA41*", "*" },
579                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
580         },
581         {
582                 /* TeraSolutions special settings for TRC-22 RAID */
583                 { T_DIRECT, SIP_MEDIA_FIXED, "TERASOLU", "TRC-22", "*" },
584                   /*quirks*/0, /*mintags*/55, /*maxtags*/255
585         },
586         {
587                 /* Veritas Storage Appliance */
588                 { T_DIRECT, SIP_MEDIA_FIXED, "VERITAS", "*", "*" },
589                   CAM_QUIRK_HILUNS, /*mintags*/2, /*maxtags*/1024
590         },
591         {
592                 /*
593                  * Would respond to all LUNs.  Device type and removable
594                  * flag are jumper-selectable.
595                  */
596                 { T_ANY, SIP_MEDIA_REMOVABLE|SIP_MEDIA_FIXED, "MaxOptix",
597                   "Tahiti 1", "*"
598                 },
599                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
600         },
601         {
602                 /* EasyRAID E5A aka. areca ARC-6010 */
603                 { T_DIRECT, SIP_MEDIA_FIXED, "easyRAID", "*", "*" },
604                   CAM_QUIRK_NOHILUNS, /*mintags*/2, /*maxtags*/255
605         },
606         {
607                 { T_ENCLOSURE, SIP_MEDIA_FIXED, "DP", "BACKPLANE", "*" },
608                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
609         },
610         {
611                 /* Default tagged queuing parameters for all devices */
612                 {
613                   T_ANY, SIP_MEDIA_REMOVABLE|SIP_MEDIA_FIXED,
614                   /*vendor*/"*", /*product*/"*", /*revision*/"*"
615                 },
616                 /*quirks*/0, /*mintags*/2, /*maxtags*/255
617         },
618 };
619
620 static const int xpt_quirk_table_size =
621         sizeof(xpt_quirk_table) / sizeof(*xpt_quirk_table);
622
623 typedef enum {
624         DM_RET_COPY             = 0x01,
625         DM_RET_FLAG_MASK        = 0x0f,
626         DM_RET_NONE             = 0x00,
627         DM_RET_STOP             = 0x10,
628         DM_RET_DESCEND          = 0x20,
629         DM_RET_ERROR            = 0x30,
630         DM_RET_ACTION_MASK      = 0xf0
631 } dev_match_ret;
632
633 typedef enum {
634         XPT_DEPTH_BUS,
635         XPT_DEPTH_TARGET,
636         XPT_DEPTH_DEVICE,
637         XPT_DEPTH_PERIPH
638 } xpt_traverse_depth;
639
640 struct xpt_traverse_config {
641         xpt_traverse_depth      depth;
642         void                    *tr_func;
643         void                    *tr_arg;
644 };
645
646 typedef int     xpt_busfunc_t (struct cam_eb *bus, void *arg);
647 typedef int     xpt_targetfunc_t (struct cam_et *target, void *arg);
648 typedef int     xpt_devicefunc_t (struct cam_ed *device, void *arg);
649 typedef int     xpt_periphfunc_t (struct cam_periph *periph, void *arg);
650 typedef int     xpt_pdrvfunc_t (struct periph_driver **pdrv, void *arg);
651
652 /* Transport layer configuration information */
653 static struct xpt_softc xsoftc;
654
655 /* Queues for our software interrupt handler */
656 typedef TAILQ_HEAD(cam_isrq, ccb_hdr) cam_isrq_t;
657 typedef TAILQ_HEAD(cam_simq, cam_sim) cam_simq_t;
658 static cam_simq_t cam_simq;
659 static struct spinlock cam_simq_spin;
660
661 struct cam_periph *xpt_periph;
662
663 static periph_init_t xpt_periph_init;
664
665 static periph_init_t probe_periph_init;
666
667 static struct periph_driver xpt_driver =
668 {
669         xpt_periph_init, "xpt",
670         TAILQ_HEAD_INITIALIZER(xpt_driver.units)
671 };
672
673 static struct periph_driver probe_driver =
674 {
675         probe_periph_init, "probe",
676         TAILQ_HEAD_INITIALIZER(probe_driver.units)
677 };
678
679 PERIPHDRIVER_DECLARE(xpt, xpt_driver);
680 PERIPHDRIVER_DECLARE(probe, probe_driver);
681
682 #define XPT_CDEV_MAJOR 104
683
684 static d_open_t xptopen;
685 static d_close_t xptclose;
686 static d_ioctl_t xptioctl;
687
688 static struct dev_ops xpt_ops = {
689         { "xpt", XPT_CDEV_MAJOR, 0 },
690         .d_open = xptopen,
691         .d_close = xptclose,
692         .d_ioctl = xptioctl
693 };
694
695 static void dead_sim_action(struct cam_sim *sim, union ccb *ccb);
696 static void dead_sim_poll(struct cam_sim *sim);
697
698 /* Dummy SIM that is used when the real one has gone. */
699 static struct cam_sim cam_dead_sim;
700 static struct lock    cam_dead_lock;
701
702 /* Storage for debugging datastructures */
703 #ifdef  CAMDEBUG
704 struct cam_path *cam_dpath;
705 u_int32_t cam_dflags;
706 u_int32_t cam_debug_delay;
707 #endif
708
709 #if defined(CAM_DEBUG_FLAGS) && !defined(CAMDEBUG)
710 #error "You must have options CAMDEBUG to use options CAM_DEBUG_FLAGS"
711 #endif
712
713 /*
714  * In order to enable the CAM_DEBUG_* options, the user must have CAMDEBUG
715  * enabled.  Also, the user must have either none, or all of CAM_DEBUG_BUS,
716  * CAM_DEBUG_TARGET, and CAM_DEBUG_LUN specified.
717  */
718 #if defined(CAM_DEBUG_BUS) || defined(CAM_DEBUG_TARGET) \
719     || defined(CAM_DEBUG_LUN)
720 #ifdef CAMDEBUG
721 #if !defined(CAM_DEBUG_BUS) || !defined(CAM_DEBUG_TARGET) \
722     || !defined(CAM_DEBUG_LUN)
723 #error "You must define all or none of CAM_DEBUG_BUS, CAM_DEBUG_TARGET \
724         and CAM_DEBUG_LUN"
725 #endif /* !CAM_DEBUG_BUS || !CAM_DEBUG_TARGET || !CAM_DEBUG_LUN */
726 #else /* !CAMDEBUG */
727 #error "You must use options CAMDEBUG if you use the CAM_DEBUG_* options"
728 #endif /* CAMDEBUG */
729 #endif /* CAM_DEBUG_BUS || CAM_DEBUG_TARGET || CAM_DEBUG_LUN */
730
731 /* Our boot-time initialization hook */
732 static int cam_module_event_handler(module_t, int /*modeventtype_t*/, void *);
733
734 static moduledata_t cam_moduledata = {
735         "cam",
736         cam_module_event_handler,
737         NULL
738 };
739
740 static int      xpt_init(void *);
741
742 DECLARE_MODULE(cam, cam_moduledata, SI_SUB_CONFIGURE, SI_ORDER_SECOND);
743 MODULE_VERSION(cam, 1);
744
745
746 static cam_status       xpt_compile_path(struct cam_path *new_path,
747                                          struct cam_periph *perph,
748                                          path_id_t path_id,
749                                          target_id_t target_id,
750                                          lun_id_t lun_id);
751
752 static void             xpt_release_path(struct cam_path *path);
753
754 static void             xpt_async_bcast(struct async_list *async_head,
755                                         u_int32_t async_code,
756                                         struct cam_path *path,
757                                         void *async_arg);
758 static void             xpt_dev_async(u_int32_t async_code,
759                                       struct cam_eb *bus,
760                                       struct cam_et *target,
761                                       struct cam_ed *device,
762                                       void *async_arg);
763 static path_id_t xptnextfreepathid(void);
764 static path_id_t xptpathid(const char *sim_name, int sim_unit, int sim_bus);
765 static union ccb *xpt_get_ccb(struct cam_ed *device);
766 static int       xpt_schedule_dev(struct camq *queue, cam_pinfo *dev_pinfo,
767                                   u_int32_t new_priority);
768 static void      xpt_run_dev_allocq(struct cam_eb *bus);
769 static void      xpt_run_dev_sendq(struct cam_eb *bus);
770 static timeout_t xpt_release_devq_timeout;
771 static void      xpt_release_bus(struct cam_eb *bus);
772 static void      xpt_release_devq_device(struct cam_ed *dev, u_int count,
773                                          int run_queue);
774 static struct cam_et*
775                  xpt_alloc_target(struct cam_eb *bus, target_id_t target_id);
776 static void      xpt_release_target(struct cam_eb *bus, struct cam_et *target);
777 static struct cam_ed*
778                  xpt_alloc_device(struct cam_eb *bus, struct cam_et *target,
779                                   lun_id_t lun_id);
780 static void      xpt_release_device(struct cam_eb *bus, struct cam_et *target,
781                                     struct cam_ed *device);
782 static u_int32_t xpt_dev_ccbq_resize(struct cam_path *path, int newopenings);
783 static struct cam_eb*
784                  xpt_find_bus(path_id_t path_id);
785 static struct cam_et*
786                  xpt_find_target(struct cam_eb *bus, target_id_t target_id);
787 static struct cam_ed*
788                  xpt_find_device(struct cam_et *target, lun_id_t lun_id);
789 static void      xpt_scan_bus(struct cam_periph *periph, union ccb *ccb);
790 static void      xpt_scan_lun(struct cam_periph *periph,
791                               struct cam_path *path, cam_flags flags,
792                               union ccb *ccb);
793 static void      xptscandone(struct cam_periph *periph, union ccb *done_ccb);
794 static xpt_busfunc_t    xptconfigbuscountfunc;
795 static xpt_busfunc_t    xptconfigfunc;
796 static void      xpt_config(void *arg);
797 static xpt_devicefunc_t xptpassannouncefunc;
798 static void      xpt_finishconfig(struct cam_periph *periph, union ccb *ccb);
799 static void      xptaction(struct cam_sim *sim, union ccb *work_ccb);
800 static void      xptpoll(struct cam_sim *sim);
801 static inthand2_t swi_cambio;
802 static void      camisr(void *);
803 static void      camisr_runqueue(struct cam_sim *);
804 static dev_match_ret    xptbusmatch(struct dev_match_pattern *patterns,
805                                     u_int num_patterns, struct cam_eb *bus);
806 static dev_match_ret    xptdevicematch(struct dev_match_pattern *patterns,
807                                        u_int num_patterns,
808                                        struct cam_ed *device);
809 static dev_match_ret    xptperiphmatch(struct dev_match_pattern *patterns,
810                                        u_int num_patterns,
811                                        struct cam_periph *periph);
812 static xpt_busfunc_t    xptedtbusfunc;
813 static xpt_targetfunc_t xptedttargetfunc;
814 static xpt_devicefunc_t xptedtdevicefunc;
815 static xpt_periphfunc_t xptedtperiphfunc;
816 static xpt_pdrvfunc_t   xptplistpdrvfunc;
817 static xpt_periphfunc_t xptplistperiphfunc;
818 static int              xptedtmatch(struct ccb_dev_match *cdm);
819 static int              xptperiphlistmatch(struct ccb_dev_match *cdm);
820 static int              xptbustraverse(struct cam_eb *start_bus,
821                                        xpt_busfunc_t *tr_func, void *arg);
822 static int              xpttargettraverse(struct cam_eb *bus,
823                                           struct cam_et *start_target,
824                                           xpt_targetfunc_t *tr_func, void *arg);
825 static int              xptdevicetraverse(struct cam_et *target,
826                                           struct cam_ed *start_device,
827                                           xpt_devicefunc_t *tr_func, void *arg);
828 static int              xptperiphtraverse(struct cam_ed *device,
829                                           struct cam_periph *start_periph,
830                                           xpt_periphfunc_t *tr_func, void *arg);
831 static int              xptpdrvtraverse(struct periph_driver **start_pdrv,
832                                         xpt_pdrvfunc_t *tr_func, void *arg);
833 static int              xptpdperiphtraverse(struct periph_driver **pdrv,
834                                             struct cam_periph *start_periph,
835                                             xpt_periphfunc_t *tr_func,
836                                             void *arg);
837 static xpt_busfunc_t    xptdefbusfunc;
838 static xpt_targetfunc_t xptdeftargetfunc;
839 static xpt_devicefunc_t xptdefdevicefunc;
840 static xpt_periphfunc_t xptdefperiphfunc;
841 static int              xpt_for_all_busses(xpt_busfunc_t *tr_func, void *arg);
842 static int              xpt_for_all_devices(xpt_devicefunc_t *tr_func,
843                                             void *arg);
844 static xpt_devicefunc_t xptsetasyncfunc;
845 static xpt_busfunc_t    xptsetasyncbusfunc;
846 static cam_status       xptregister(struct cam_periph *periph,
847                                     void *arg);
848 static cam_status       proberegister(struct cam_periph *periph,
849                                       void *arg);
850 static void      probeschedule(struct cam_periph *probe_periph);
851 static void      probestart(struct cam_periph *periph, union ccb *start_ccb);
852 static void      proberequestdefaultnegotiation(struct cam_periph *periph);
853 static int       proberequestbackoff(struct cam_periph *periph,
854                                      struct cam_ed *device);
855 static void      probedone(struct cam_periph *periph, union ccb *done_ccb);
856 static void      probecleanup(struct cam_periph *periph);
857 static void      xpt_find_quirk(struct cam_ed *device);
858 static void      xpt_devise_transport(struct cam_path *path);
859 static void      xpt_set_transfer_settings(struct ccb_trans_settings *cts,
860                                            struct cam_ed *device,
861                                            int async_update);
862 static void      xpt_toggle_tags(struct cam_path *path);
863 static void      xpt_start_tags(struct cam_path *path);
864 static __inline int xpt_schedule_dev_allocq(struct cam_eb *bus,
865                                             struct cam_ed *dev);
866 static __inline int xpt_schedule_dev_sendq(struct cam_eb *bus,
867                                            struct cam_ed *dev);
868 static __inline int periph_is_queued(struct cam_periph *periph);
869 static __inline int device_is_alloc_queued(struct cam_ed *device);
870 static __inline int device_is_send_queued(struct cam_ed *device);
871 static __inline int dev_allocq_is_runnable(struct cam_devq *devq);
872
873 static __inline int
874 xpt_schedule_dev_allocq(struct cam_eb *bus, struct cam_ed *dev)
875 {
876         int retval;
877
878         if (bus->sim->devq && dev->ccbq.devq_openings > 0) {
879                 if ((dev->flags & CAM_DEV_RESIZE_QUEUE_NEEDED) != 0) {
880                         cam_ccbq_resize(&dev->ccbq,
881                                         dev->ccbq.dev_openings
882                                         + dev->ccbq.dev_active);
883                         dev->flags &= ~CAM_DEV_RESIZE_QUEUE_NEEDED;
884                 }
885                 /*
886                  * The priority of a device waiting for CCB resources
887                  * is that of the the highest priority peripheral driver
888                  * enqueued.
889                  */
890                 retval = xpt_schedule_dev(&bus->sim->devq->alloc_queue,
891                                           &dev->alloc_ccb_entry.pinfo,
892                                           CAMQ_GET_HEAD(&dev->drvq)->priority);
893         } else {
894                 retval = 0;
895         }
896
897         return (retval);
898 }
899
900 static __inline int
901 xpt_schedule_dev_sendq(struct cam_eb *bus, struct cam_ed *dev)
902 {
903         int     retval;
904
905         if (bus->sim->devq && dev->ccbq.dev_openings > 0) {
906                 /*
907                  * The priority of a device waiting for controller
908                  * resources is that of the the highest priority CCB
909                  * enqueued.
910                  */
911                 retval =
912                     xpt_schedule_dev(&bus->sim->devq->send_queue,
913                                      &dev->send_ccb_entry.pinfo,
914                                      CAMQ_GET_HEAD(&dev->ccbq.queue)->priority);
915         } else {
916                 retval = 0;
917         }
918         return (retval);
919 }
920
921 static __inline int
922 periph_is_queued(struct cam_periph *periph)
923 {
924         return (periph->pinfo.index != CAM_UNQUEUED_INDEX);
925 }
926
927 static __inline int
928 device_is_alloc_queued(struct cam_ed *device)
929 {
930         return (device->alloc_ccb_entry.pinfo.index != CAM_UNQUEUED_INDEX);
931 }
932
933 static __inline int
934 device_is_send_queued(struct cam_ed *device)
935 {
936         return (device->send_ccb_entry.pinfo.index != CAM_UNQUEUED_INDEX);
937 }
938
939 static __inline int
940 dev_allocq_is_runnable(struct cam_devq *devq)
941 {
942         /*
943          * Have work to do.
944          * Have space to do more work.
945          * Allowed to do work.
946          */
947         return ((devq->alloc_queue.qfrozen_cnt == 0)
948              && (devq->alloc_queue.entries > 0)
949              && (devq->alloc_openings > 0));
950 }
951
952 static void
953 xpt_periph_init(void)
954 {
955         dev_ops_add(&xpt_ops, 0, 0);
956         make_dev(&xpt_ops, 0, UID_ROOT, GID_OPERATOR, 0600, "xpt0");
957 }
958
959 static void
960 probe_periph_init(void)
961 {
962 }
963
964
965 static void
966 xptdone(struct cam_periph *periph, union ccb *done_ccb)
967 {
968         /* Caller will release the CCB */
969         wakeup(&done_ccb->ccb_h.cbfcnp);
970 }
971
972 static int
973 xptopen(struct dev_open_args *ap)
974 {
975         cdev_t dev = ap->a_head.a_dev;
976
977         /*
978          * Only allow read-write access.
979          */
980         if (((ap->a_oflags & FWRITE) == 0) || ((ap->a_oflags & FREAD) == 0))
981                 return(EPERM);
982
983         /*
984          * We don't allow nonblocking access.
985          */
986         if ((ap->a_oflags & O_NONBLOCK) != 0) {
987                 kprintf("%s: can't do nonblocking access\n", devtoname(dev));
988                 return(ENODEV);
989         }
990
991         /* Mark ourselves open */
992         lockmgr(&xsoftc.xpt_lock, LK_EXCLUSIVE);
993         xsoftc.flags |= XPT_FLAG_OPEN;
994         lockmgr(&xsoftc.xpt_lock, LK_RELEASE);
995
996         return(0);
997 }
998
999 static int
1000 xptclose(struct dev_close_args *ap)
1001 {
1002
1003         /* Mark ourselves closed */
1004         lockmgr(&xsoftc.xpt_lock, LK_EXCLUSIVE);
1005         xsoftc.flags &= ~XPT_FLAG_OPEN;
1006         lockmgr(&xsoftc.xpt_lock, LK_RELEASE);
1007
1008         return(0);
1009 }
1010
1011 /*
1012  * Don't automatically grab the xpt softc lock here even though this is going
1013  * through the xpt device.  The xpt device is really just a back door for
1014  * accessing other devices and SIMs, so the right thing to do is to grab
1015  * the appropriate SIM lock once the bus/SIM is located.
1016  */
1017 static int
1018 xptioctl(struct dev_ioctl_args *ap)
1019 {
1020         int error;
1021
1022         error = 0;
1023
1024         switch(ap->a_cmd) {
1025         /*
1026          * For the transport layer CAMIOCOMMAND ioctl, we really only want
1027          * to accept CCB types that don't quite make sense to send through a
1028          * passthrough driver.
1029          */
1030         case CAMIOCOMMAND: {
1031                 union ccb *ccb;
1032                 union ccb *inccb;
1033                 struct cam_eb *bus;
1034
1035                 inccb = (union ccb *)ap->a_data;
1036
1037                 bus = xpt_find_bus(inccb->ccb_h.path_id);
1038                 if (bus == NULL) {
1039                         error = EINVAL;
1040                         break;
1041                 }
1042
1043                 switch(inccb->ccb_h.func_code) {
1044                 case XPT_SCAN_BUS:
1045                 case XPT_RESET_BUS:
1046                         if ((inccb->ccb_h.target_id != CAM_TARGET_WILDCARD)
1047                          || (inccb->ccb_h.target_lun != CAM_LUN_WILDCARD)) {
1048                                 error = EINVAL;
1049                                 break;
1050                         }
1051                         /* FALLTHROUGH */
1052                 case XPT_PATH_INQ:
1053                 case XPT_ENG_INQ:
1054                 case XPT_SCAN_LUN:
1055
1056                         ccb = xpt_alloc_ccb();
1057
1058                         CAM_SIM_LOCK(bus->sim);
1059
1060                         /*
1061                          * Create a path using the bus, target, and lun the
1062                          * user passed in.
1063                          */
1064                         if (xpt_create_path(&ccb->ccb_h.path, xpt_periph,
1065                                             inccb->ccb_h.path_id,
1066                                             inccb->ccb_h.target_id,
1067                                             inccb->ccb_h.target_lun) !=
1068                                             CAM_REQ_CMP){
1069                                 error = EINVAL;
1070                                 CAM_SIM_UNLOCK(bus->sim);
1071                                 xpt_free_ccb(ccb);
1072                                 break;
1073                         }
1074                         /* Ensure all of our fields are correct */
1075                         xpt_setup_ccb(&ccb->ccb_h, ccb->ccb_h.path,
1076                                       inccb->ccb_h.pinfo.priority);
1077                         xpt_merge_ccb(ccb, inccb);
1078                         ccb->ccb_h.cbfcnp = xptdone;
1079                         cam_periph_runccb(ccb, NULL, 0, 0, NULL);
1080                         bcopy(ccb, inccb, sizeof(union ccb));
1081                         xpt_free_path(ccb->ccb_h.path);
1082                         xpt_free_ccb(ccb);
1083                         CAM_SIM_UNLOCK(bus->sim);
1084                         break;
1085
1086                 case XPT_DEBUG: {
1087                         union ccb ccb;
1088
1089                         /*
1090                          * This is an immediate CCB, so it's okay to
1091                          * allocate it on the stack.
1092                          */
1093
1094                         CAM_SIM_LOCK(bus->sim);
1095
1096                         /*
1097                          * Create a path using the bus, target, and lun the
1098                          * user passed in.
1099                          */
1100                         if (xpt_create_path(&ccb.ccb_h.path, xpt_periph,
1101                                             inccb->ccb_h.path_id,
1102                                             inccb->ccb_h.target_id,
1103                                             inccb->ccb_h.target_lun) !=
1104                                             CAM_REQ_CMP){
1105                                 error = EINVAL;
1106                                 CAM_SIM_UNLOCK(bus->sim);
1107                                 break;
1108                         }
1109                         /* Ensure all of our fields are correct */
1110                         xpt_setup_ccb(&ccb.ccb_h, ccb.ccb_h.path,
1111                                       inccb->ccb_h.pinfo.priority);
1112                         xpt_merge_ccb(&ccb, inccb);
1113                         ccb.ccb_h.cbfcnp = xptdone;
1114                         xpt_action(&ccb);
1115                         CAM_SIM_UNLOCK(bus->sim);
1116                         bcopy(&ccb, inccb, sizeof(union ccb));
1117                         xpt_free_path(ccb.ccb_h.path);
1118                         break;
1119
1120                 }
1121                 case XPT_DEV_MATCH: {
1122                         struct cam_periph_map_info mapinfo;
1123                         struct cam_path *old_path;
1124
1125                         /*
1126                          * We can't deal with physical addresses for this
1127                          * type of transaction.
1128                          */
1129                         if (inccb->ccb_h.flags & CAM_DATA_PHYS) {
1130                                 error = EINVAL;
1131                                 break;
1132                         }
1133
1134                         /*
1135                          * Save this in case the caller had it set to
1136                          * something in particular.
1137                          */
1138                         old_path = inccb->ccb_h.path;
1139
1140                         /*
1141                          * We really don't need a path for the matching
1142                          * code.  The path is needed because of the
1143                          * debugging statements in xpt_action().  They
1144                          * assume that the CCB has a valid path.
1145                          */
1146                         inccb->ccb_h.path = xpt_periph->path;
1147
1148                         bzero(&mapinfo, sizeof(mapinfo));
1149
1150                         /*
1151                          * Map the pattern and match buffers into kernel
1152                          * virtual address space.
1153                          */
1154                         error = cam_periph_mapmem(inccb, &mapinfo);
1155
1156                         if (error) {
1157                                 inccb->ccb_h.path = old_path;
1158                                 break;
1159                         }
1160
1161                         /*
1162                          * This is an immediate CCB, we can send it on directly.
1163                          */
1164                         xpt_action(inccb);
1165
1166                         /*
1167                          * Map the buffers back into user space.
1168                          */
1169                         cam_periph_unmapmem(inccb, &mapinfo);
1170
1171                         inccb->ccb_h.path = old_path;
1172
1173                         error = 0;
1174                         break;
1175                 }
1176                 default:
1177                         error = ENOTSUP;
1178                         break;
1179                 }
1180                 xpt_release_bus(bus);
1181                 break;
1182         }
1183         /*
1184          * This is the getpassthru ioctl. It takes a XPT_GDEVLIST ccb as input,
1185          * with the periphal driver name and unit name filled in.  The other
1186          * fields don't really matter as input.  The passthrough driver name
1187          * ("pass"), and unit number are passed back in the ccb.  The current
1188          * device generation number, and the index into the device peripheral
1189          * driver list, and the status are also passed back.  Note that
1190          * since we do everything in one pass, unlike the XPT_GDEVLIST ccb,
1191          * we never return a status of CAM_GDEVLIST_LIST_CHANGED.  It is
1192          * (or rather should be) impossible for the device peripheral driver
1193          * list to change since we look at the whole thing in one pass, and
1194          * we do it with lock protection.
1195          *
1196          */
1197         case CAMGETPASSTHRU: {
1198                 union ccb *ccb;
1199                 struct cam_periph *periph;
1200                 struct periph_driver **p_drv;
1201                 char   *name;
1202                 u_int unit;
1203                 u_int cur_generation;
1204                 int base_periph_found;
1205                 int splbreaknum;
1206
1207                 ccb = (union ccb *)ap->a_data;
1208                 unit = ccb->cgdl.unit_number;
1209                 name = ccb->cgdl.periph_name;
1210                 /*
1211                  * Every 100 devices, we want to drop our lock protection to
1212                  * give the software interrupt handler a chance to run.
1213                  * Most systems won't run into this check, but this should
1214                  * avoid starvation in the software interrupt handler in
1215                  * large systems.
1216                  */
1217                 splbreaknum = 100;
1218
1219                 ccb = (union ccb *)ap->a_data;
1220
1221                 base_periph_found = 0;
1222
1223                 /*
1224                  * Sanity check -- make sure we don't get a null peripheral
1225                  * driver name.
1226                  */
1227                 if (*ccb->cgdl.periph_name == '\0') {
1228                         error = EINVAL;
1229                         break;
1230                 }
1231
1232                 /* Keep the list from changing while we traverse it */
1233                 lockmgr(&xsoftc.xpt_topo_lock, LK_EXCLUSIVE);
1234 ptstartover:
1235                 cur_generation = xsoftc.xpt_generation;
1236
1237                 /* first find our driver in the list of drivers */
1238                 for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
1239                         if (strcmp((*p_drv)->driver_name, name) == 0)
1240                                 break;
1241                 }
1242
1243                 if (*p_drv == NULL) {
1244                         lockmgr(&xsoftc.xpt_topo_lock, LK_RELEASE);
1245                         ccb->ccb_h.status = CAM_REQ_CMP_ERR;
1246                         ccb->cgdl.status = CAM_GDEVLIST_ERROR;
1247                         *ccb->cgdl.periph_name = '\0';
1248                         ccb->cgdl.unit_number = 0;
1249                         error = ENOENT;
1250                         break;
1251                 }
1252
1253                 /*
1254                  * Run through every peripheral instance of this driver
1255                  * and check to see whether it matches the unit passed
1256                  * in by the user.  If it does, get out of the loops and
1257                  * find the passthrough driver associated with that
1258                  * peripheral driver.
1259                  */
1260                 TAILQ_FOREACH(periph, &(*p_drv)->units, unit_links) {
1261
1262                         if (periph->unit_number == unit) {
1263                                 break;
1264                         } else if (--splbreaknum == 0) {
1265                                 lockmgr(&xsoftc.xpt_topo_lock, LK_RELEASE);
1266                                 lockmgr(&xsoftc.xpt_topo_lock, LK_EXCLUSIVE);
1267                                 splbreaknum = 100;
1268                                 if (cur_generation != xsoftc.xpt_generation)
1269                                        goto ptstartover;
1270                         }
1271                 }
1272                 /*
1273                  * If we found the peripheral driver that the user passed
1274                  * in, go through all of the peripheral drivers for that
1275                  * particular device and look for a passthrough driver.
1276                  */
1277                 if (periph != NULL) {
1278                         struct cam_ed *device;
1279                         int i;
1280
1281                         base_periph_found = 1;
1282                         device = periph->path->device;
1283                         for (i = 0, periph = SLIST_FIRST(&device->periphs);
1284                              periph != NULL;
1285                              periph = SLIST_NEXT(periph, periph_links), i++) {
1286                                 /*
1287                                  * Check to see whether we have a
1288                                  * passthrough device or not.
1289                                  */
1290                                 if (strcmp(periph->periph_name, "pass") == 0) {
1291                                         /*
1292                                          * Fill in the getdevlist fields.
1293                                          */
1294                                         strcpy(ccb->cgdl.periph_name,
1295                                                periph->periph_name);
1296                                         ccb->cgdl.unit_number =
1297                                                 periph->unit_number;
1298                                         if (SLIST_NEXT(periph, periph_links))
1299                                                 ccb->cgdl.status =
1300                                                         CAM_GDEVLIST_MORE_DEVS;
1301                                         else
1302                                                 ccb->cgdl.status =
1303                                                        CAM_GDEVLIST_LAST_DEVICE;
1304                                         ccb->cgdl.generation =
1305                                                 device->generation;
1306                                         ccb->cgdl.index = i;
1307                                         /*
1308                                          * Fill in some CCB header fields
1309                                          * that the user may want.
1310                                          */
1311                                         ccb->ccb_h.path_id =
1312                                                 periph->path->bus->path_id;
1313                                         ccb->ccb_h.target_id =
1314                                                 periph->path->target->target_id;
1315                                         ccb->ccb_h.target_lun =
1316                                                 periph->path->device->lun_id;
1317                                         ccb->ccb_h.status = CAM_REQ_CMP;
1318                                         break;
1319                                 }
1320                         }
1321                 }
1322
1323                 /*
1324                  * If the periph is null here, one of two things has
1325                  * happened.  The first possibility is that we couldn't
1326                  * find the unit number of the particular peripheral driver
1327                  * that the user is asking about.  e.g. the user asks for
1328                  * the passthrough driver for "da11".  We find the list of
1329                  * "da" peripherals all right, but there is no unit 11.
1330                  * The other possibility is that we went through the list
1331                  * of peripheral drivers attached to the device structure,
1332                  * but didn't find one with the name "pass".  Either way,
1333                  * we return ENOENT, since we couldn't find something.
1334                  */
1335                 if (periph == NULL) {
1336                         ccb->ccb_h.status = CAM_REQ_CMP_ERR;
1337                         ccb->cgdl.status = CAM_GDEVLIST_ERROR;
1338                         *ccb->cgdl.periph_name = '\0';
1339                         ccb->cgdl.unit_number = 0;
1340                         error = ENOENT;
1341                         /*
1342                          * It is unfortunate that this is even necessary,
1343                          * but there are many, many clueless users out there.
1344                          * If this is true, the user is looking for the
1345                          * passthrough driver, but doesn't have one in his
1346                          * kernel.
1347                          */
1348                         if (base_periph_found == 1) {
1349                                 kprintf("xptioctl: pass driver is not in the "
1350                                        "kernel\n");
1351                                 kprintf("xptioctl: put \"device pass\" in "
1352                                        "your kernel config file\n");
1353                         }
1354                 }
1355                 lockmgr(&xsoftc.xpt_topo_lock, LK_RELEASE);
1356                 break;
1357                 }
1358         default:
1359                 error = ENOTTY;
1360                 break;
1361         }
1362
1363         return(error);
1364 }
1365
1366 static int
1367 cam_module_event_handler(module_t mod, int what, void *arg)
1368 {
1369         int error;
1370
1371         switch (what) {
1372         case MOD_LOAD:
1373                 if ((error = xpt_init(NULL)) != 0)
1374                         return (error);
1375                 break;
1376         case MOD_UNLOAD:
1377                 return EBUSY;
1378         default:
1379                 return EOPNOTSUPP;
1380         }
1381
1382         return 0;
1383 }
1384
1385 /* thread to handle bus rescans */
1386 static void
1387 xpt_scanner_thread(void *dummy)
1388 {
1389         cam_isrq_t      queue;
1390         union ccb       *ccb;
1391         struct cam_sim  *sim;
1392
1393         for (;;) {
1394                 /*
1395                  * Wait for a rescan request to come in.  When it does, splice
1396                  * it onto a queue from local storage so that the xpt lock
1397                  * doesn't need to be held while the requests are being
1398                  * processed.
1399                  */
1400                 crit_enter();
1401                 tsleep_interlock(&xsoftc.ccb_scanq);
1402                 xpt_unlock_buses();
1403                 tsleep(&xsoftc.ccb_scanq, 0, "ccb_scanq", 0);
1404                 xpt_lock_buses();
1405                 crit_exit();
1406                 TAILQ_INIT(&queue);
1407                 TAILQ_CONCAT(&queue, &xsoftc.ccb_scanq, sim_links.tqe);
1408                 xpt_unlock_buses();
1409
1410                 while ((ccb = (union ccb *)TAILQ_FIRST(&queue)) != NULL) {
1411                         TAILQ_REMOVE(&queue, &ccb->ccb_h, sim_links.tqe);
1412
1413                         sim = ccb->ccb_h.path->bus->sim;
1414                         CAM_SIM_LOCK(sim);
1415
1416                         ccb->ccb_h.func_code = XPT_SCAN_BUS;
1417                         ccb->ccb_h.cbfcnp = xptdone;
1418                         xpt_setup_ccb(&ccb->ccb_h, ccb->ccb_h.path, 5);
1419                         cam_periph_runccb(ccb, NULL, 0, 0, NULL);
1420                         xpt_free_path(ccb->ccb_h.path);
1421                         xpt_free_ccb(ccb);
1422                         CAM_SIM_UNLOCK(sim);
1423                 }
1424         }
1425 }
1426
1427 void
1428 xpt_rescan(union ccb *ccb)
1429 {
1430         struct ccb_hdr *hdr;
1431
1432         /*
1433          * Don't make duplicate entries for the same paths.
1434          */
1435         xpt_lock_buses();
1436         TAILQ_FOREACH(hdr, &xsoftc.ccb_scanq, sim_links.tqe) {
1437                 if (xpt_path_comp(hdr->path, ccb->ccb_h.path) == 0) {
1438                         xpt_unlock_buses();
1439                         xpt_print(ccb->ccb_h.path, "rescan already queued\n");
1440                         xpt_free_path(ccb->ccb_h.path);
1441                         xpt_free_ccb(ccb);
1442                         return;
1443                 }
1444         }
1445         TAILQ_INSERT_TAIL(&xsoftc.ccb_scanq, &ccb->ccb_h, sim_links.tqe);
1446         wakeup(&xsoftc.ccb_scanq);
1447         xpt_unlock_buses();
1448 }
1449
1450
1451 /* Functions accessed by the peripheral drivers */
1452 static int
1453 xpt_init(void *dummy)
1454 {
1455         struct cam_sim *xpt_sim;
1456         struct cam_path *path;
1457         struct cam_devq *devq;
1458         cam_status status;
1459
1460         TAILQ_INIT(&xsoftc.xpt_busses);
1461         TAILQ_INIT(&cam_simq);
1462         TAILQ_INIT(&xsoftc.ccb_scanq);
1463         STAILQ_INIT(&xsoftc.highpowerq);
1464         xsoftc.num_highpower = CAM_MAX_HIGHPOWER;
1465
1466         spin_init(&cam_simq_spin);
1467         lockinit(&xsoftc.xpt_lock, "XPT lock", 0, LK_CANRECURSE);
1468         lockinit(&xsoftc.xpt_topo_lock, "XPT topology lock", 0, LK_CANRECURSE);
1469
1470         SLIST_INIT(&cam_dead_sim.ccb_freeq);
1471         TAILQ_INIT(&cam_dead_sim.sim_doneq);
1472         spin_init(&cam_dead_sim.sim_spin);
1473         cam_dead_sim.sim_action = dead_sim_action;
1474         cam_dead_sim.sim_poll = dead_sim_poll;
1475         cam_dead_sim.sim_name = "dead_sim";
1476         cam_dead_sim.lock = &cam_dead_lock;
1477         lockinit(&cam_dead_lock, "XPT dead_sim lock", 0, LK_CANRECURSE);
1478         cam_dead_sim.flags |= CAM_SIM_DEREGISTERED;
1479
1480         /*
1481          * The xpt layer is, itself, the equivelent of a SIM.
1482          * Allow 16 ccbs in the ccb pool for it.  This should
1483          * give decent parallelism when we probe busses and
1484          * perform other XPT functions.
1485          */
1486         devq = cam_simq_alloc(16);
1487         xpt_sim = cam_sim_alloc(xptaction,
1488                                 xptpoll,
1489                                 "xpt",
1490                                 /*softc*/NULL,
1491                                 /*unit*/0,
1492                                 /*lock*/&xsoftc.xpt_lock,
1493                                 /*max_dev_transactions*/0,
1494                                 /*max_tagged_dev_transactions*/0,
1495                                 devq);
1496         cam_simq_release(devq);
1497         if (xpt_sim == NULL)
1498                 return (ENOMEM);
1499
1500         xpt_sim->max_ccbs = 16;
1501
1502         lockmgr(&xsoftc.xpt_lock, LK_EXCLUSIVE);
1503         if ((status = xpt_bus_register(xpt_sim, /*bus #*/0)) != CAM_SUCCESS) {
1504                 kprintf("xpt_init: xpt_bus_register failed with status %#x,"
1505                        " failing attach\n", status);
1506                 return (EINVAL);
1507         }
1508
1509         /*
1510          * Looking at the XPT from the SIM layer, the XPT is
1511          * the equivelent of a peripheral driver.  Allocate
1512          * a peripheral driver entry for us.
1513          */
1514         if ((status = xpt_create_path(&path, NULL, CAM_XPT_PATH_ID,
1515                                       CAM_TARGET_WILDCARD,
1516                                       CAM_LUN_WILDCARD)) != CAM_REQ_CMP) {
1517                 kprintf("xpt_init: xpt_create_path failed with status %#x,"
1518                        " failing attach\n", status);
1519                 return (EINVAL);
1520         }
1521
1522         cam_periph_alloc(xptregister, NULL, NULL, NULL, "xpt", CAM_PERIPH_BIO,
1523                          path, NULL, 0, xpt_sim);
1524         xpt_free_path(path);
1525
1526         lockmgr(&xsoftc.xpt_lock, LK_RELEASE);
1527
1528         /*
1529          * Register a callback for when interrupts are enabled.
1530          */
1531         xsoftc.xpt_config_hook = kmalloc(sizeof(struct intr_config_hook),
1532                                   M_CAMXPT, M_INTWAIT | M_ZERO);
1533         xsoftc.xpt_config_hook->ich_func = xpt_config;
1534         xsoftc.xpt_config_hook->ich_desc = "xpt";
1535         xsoftc.xpt_config_hook->ich_order = 1000;
1536         if (config_intrhook_establish(xsoftc.xpt_config_hook) != 0) {
1537                 kfree (xsoftc.xpt_config_hook, M_CAMXPT);
1538                 kprintf("xpt_init: config_intrhook_establish failed "
1539                        "- failing attach\n");
1540         }
1541
1542         /* fire up rescan thread */
1543         if (kthread_create(xpt_scanner_thread, NULL, NULL, "xpt_thrd")) {
1544                 kprintf("xpt_init: failed to create rescan thread\n");
1545         }
1546         /* Install our software interrupt handlers */
1547         register_swi(SWI_CAMBIO, swi_cambio, NULL, "swi_cambio", NULL);
1548
1549         return (0);
1550 }
1551
1552 static cam_status
1553 xptregister(struct cam_periph *periph, void *arg)
1554 {
1555         struct cam_sim *xpt_sim;
1556
1557         if (periph == NULL) {
1558                 kprintf("xptregister: periph was NULL!!\n");
1559                 return(CAM_REQ_CMP_ERR);
1560         }
1561
1562         xpt_sim = (struct cam_sim *)arg;
1563         xpt_sim->softc = periph;
1564         xpt_periph = periph;
1565         periph->softc = NULL;
1566
1567         return(CAM_REQ_CMP);
1568 }
1569
1570 int32_t
1571 xpt_add_periph(struct cam_periph *periph)
1572 {
1573         struct cam_ed *device;
1574         int32_t  status;
1575         struct periph_list *periph_head;
1576
1577         sim_lock_assert_owned(periph->sim->lock);
1578
1579         device = periph->path->device;
1580
1581         periph_head = &device->periphs;
1582
1583         status = CAM_REQ_CMP;
1584
1585         if (device != NULL) {
1586                 /*
1587                  * Make room for this peripheral
1588                  * so it will fit in the queue
1589                  * when it's scheduled to run
1590                  */
1591                 status = camq_resize(&device->drvq,
1592                                      device->drvq.array_size + 1);
1593
1594                 device->generation++;
1595
1596                 SLIST_INSERT_HEAD(periph_head, periph, periph_links);
1597         }
1598
1599         lockmgr(&xsoftc.xpt_topo_lock, LK_EXCLUSIVE);
1600         xsoftc.xpt_generation++;
1601         lockmgr(&xsoftc.xpt_topo_lock, LK_RELEASE);
1602
1603         return (status);
1604 }
1605
1606 void
1607 xpt_remove_periph(struct cam_periph *periph)
1608 {
1609         struct cam_ed *device;
1610
1611         sim_lock_assert_owned(periph->sim->lock);
1612
1613         device = periph->path->device;
1614
1615         if (device != NULL) {
1616                 struct periph_list *periph_head;
1617
1618                 periph_head = &device->periphs;
1619
1620                 /* Release the slot for this peripheral */
1621                 camq_resize(&device->drvq, device->drvq.array_size - 1);
1622
1623                 device->generation++;
1624
1625                 SLIST_REMOVE(periph_head, periph, cam_periph, periph_links);
1626         }
1627
1628         lockmgr(&xsoftc.xpt_topo_lock, LK_EXCLUSIVE);
1629         xsoftc.xpt_generation++;
1630         lockmgr(&xsoftc.xpt_topo_lock, LK_RELEASE);
1631 }
1632
1633 void
1634 xpt_announce_periph(struct cam_periph *periph, char *announce_string)
1635 {
1636         struct  ccb_pathinq cpi;
1637         struct  ccb_trans_settings cts;
1638         struct  cam_path *path;
1639         u_int   speed;
1640         u_int   freq;
1641         u_int   mb;
1642
1643         sim_lock_assert_owned(periph->sim->lock);
1644
1645         path = periph->path;
1646         /*
1647          * To ensure that this is printed in one piece,
1648          * mask out CAM interrupts.
1649          */
1650         kprintf("%s%d at %s%d bus %d target %d lun %d\n",
1651                periph->periph_name, periph->unit_number,
1652                path->bus->sim->sim_name,
1653                path->bus->sim->unit_number,
1654                path->bus->sim->bus_id,
1655                path->target->target_id,
1656                path->device->lun_id);
1657         kprintf("%s%d: ", periph->periph_name, periph->unit_number);
1658         scsi_print_inquiry(&path->device->inq_data);
1659         if (bootverbose && path->device->serial_num_len > 0) {
1660                 /* Don't wrap the screen  - print only the first 60 chars */
1661                 kprintf("%s%d: Serial Number %.60s\n", periph->periph_name,
1662                        periph->unit_number, path->device->serial_num);
1663         }
1664         xpt_setup_ccb(&cts.ccb_h, path, /*priority*/1);
1665         cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
1666         cts.type = CTS_TYPE_CURRENT_SETTINGS;
1667         xpt_action((union ccb*)&cts);
1668         if ((cts.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1669                 return;
1670         }
1671
1672         /* Ask the SIM for its base transfer speed */
1673         xpt_setup_ccb(&cpi.ccb_h, path, /*priority*/1);
1674         cpi.ccb_h.func_code = XPT_PATH_INQ;
1675         xpt_action((union ccb *)&cpi);
1676
1677         speed = cpi.base_transfer_speed;
1678         freq = 0;
1679         if (cts.ccb_h.status == CAM_REQ_CMP && cts.transport == XPORT_SPI) {
1680                 struct  ccb_trans_settings_spi *spi;
1681
1682                 spi = &cts.xport_specific.spi;
1683                 if ((spi->valid & CTS_SPI_VALID_SYNC_OFFSET) != 0
1684                   && spi->sync_offset != 0) {
1685                         freq = scsi_calc_syncsrate(spi->sync_period);
1686                         speed = freq;
1687                 }
1688
1689                 if ((spi->valid & CTS_SPI_VALID_BUS_WIDTH) != 0)
1690                         speed *= (0x01 << spi->bus_width);
1691         }
1692         if (cts.ccb_h.status == CAM_REQ_CMP && cts.transport == XPORT_FC) {
1693                 struct  ccb_trans_settings_fc *fc = &cts.xport_specific.fc;
1694                 if (fc->valid & CTS_FC_VALID_SPEED) {
1695                         speed = fc->bitrate;
1696                 }
1697         }
1698
1699         if (cts.ccb_h.status == CAM_REQ_CMP && cts.transport == XPORT_SAS) {
1700                 struct  ccb_trans_settings_sas *sas = &cts.xport_specific.sas;
1701                 if (sas->valid & CTS_SAS_VALID_SPEED) {
1702                         speed = sas->bitrate;
1703                 }
1704         }
1705
1706         mb = speed / 1000;
1707         if (mb > 0)
1708                 kprintf("%s%d: %d.%03dMB/s transfers",
1709                        periph->periph_name, periph->unit_number,
1710                        mb, speed % 1000);
1711         else
1712                 kprintf("%s%d: %dKB/s transfers", periph->periph_name,
1713                        periph->unit_number, speed);
1714         /* Report additional information about SPI connections */
1715         if (cts.ccb_h.status == CAM_REQ_CMP && cts.transport == XPORT_SPI) {
1716                 struct  ccb_trans_settings_spi *spi;
1717
1718                 spi = &cts.xport_specific.spi;
1719                 if (freq != 0) {
1720                         kprintf(" (%d.%03dMHz%s, offset %d", freq / 1000,
1721                                freq % 1000,
1722                                (spi->ppr_options & MSG_EXT_PPR_DT_REQ) != 0
1723                              ? " DT" : "",
1724                                spi->sync_offset);
1725                 }
1726                 if ((spi->valid & CTS_SPI_VALID_BUS_WIDTH) != 0
1727                  && spi->bus_width > 0) {
1728                         if (freq != 0) {
1729                                 kprintf(", ");
1730                         } else {
1731                                 kprintf(" (");
1732                         }
1733                         kprintf("%dbit)", 8 * (0x01 << spi->bus_width));
1734                 } else if (freq != 0) {
1735                         kprintf(")");
1736                 }
1737         }
1738         if (cts.ccb_h.status == CAM_REQ_CMP && cts.transport == XPORT_FC) {
1739                 struct  ccb_trans_settings_fc *fc;
1740
1741                 fc = &cts.xport_specific.fc;
1742                 if (fc->valid & CTS_FC_VALID_WWNN)
1743                         kprintf(" WWNN 0x%llx", (long long) fc->wwnn);
1744                 if (fc->valid & CTS_FC_VALID_WWPN)
1745                         kprintf(" WWPN 0x%llx", (long long) fc->wwpn);
1746                 if (fc->valid & CTS_FC_VALID_PORT)
1747                         kprintf(" PortID 0x%x", fc->port);
1748         }
1749
1750         if (path->device->inq_flags & SID_CmdQue
1751          || path->device->flags & CAM_DEV_TAG_AFTER_COUNT) {
1752                 kprintf("\n%s%d: Command Queueing Enabled",
1753                        periph->periph_name, periph->unit_number);
1754         }
1755         kprintf("\n");
1756
1757         /*
1758          * We only want to print the caller's announce string if they've
1759          * passed one in..
1760          */
1761         if (announce_string != NULL)
1762                 kprintf("%s%d: %s\n", periph->periph_name,
1763                        periph->unit_number, announce_string);
1764 }
1765
1766 static dev_match_ret
1767 xptbusmatch(struct dev_match_pattern *patterns, u_int num_patterns,
1768             struct cam_eb *bus)
1769 {
1770         dev_match_ret retval;
1771         int i;
1772
1773         retval = DM_RET_NONE;
1774
1775         /*
1776          * If we aren't given something to match against, that's an error.
1777          */
1778         if (bus == NULL)
1779                 return(DM_RET_ERROR);
1780
1781         /*
1782          * If there are no match entries, then this bus matches no
1783          * matter what.
1784          */
1785         if ((patterns == NULL) || (num_patterns == 0))
1786                 return(DM_RET_DESCEND | DM_RET_COPY);
1787
1788         for (i = 0; i < num_patterns; i++) {
1789                 struct bus_match_pattern *cur_pattern;
1790
1791                 /*
1792                  * If the pattern in question isn't for a bus node, we
1793                  * aren't interested.  However, we do indicate to the
1794                  * calling routine that we should continue descending the
1795                  * tree, since the user wants to match against lower-level
1796                  * EDT elements.
1797                  */
1798                 if (patterns[i].type != DEV_MATCH_BUS) {
1799                         if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1800                                 retval |= DM_RET_DESCEND;
1801                         continue;
1802                 }
1803
1804                 cur_pattern = &patterns[i].pattern.bus_pattern;
1805
1806                 /*
1807                  * If they want to match any bus node, we give them any
1808                  * device node.
1809                  */
1810                 if (cur_pattern->flags == BUS_MATCH_ANY) {
1811                         /* set the copy flag */
1812                         retval |= DM_RET_COPY;
1813
1814                         /*
1815                          * If we've already decided on an action, go ahead
1816                          * and return.
1817                          */
1818                         if ((retval & DM_RET_ACTION_MASK) != DM_RET_NONE)
1819                                 return(retval);
1820                 }
1821
1822                 /*
1823                  * Not sure why someone would do this...
1824                  */
1825                 if (cur_pattern->flags == BUS_MATCH_NONE)
1826                         continue;
1827
1828                 if (((cur_pattern->flags & BUS_MATCH_PATH) != 0)
1829                  && (cur_pattern->path_id != bus->path_id))
1830                         continue;
1831
1832                 if (((cur_pattern->flags & BUS_MATCH_BUS_ID) != 0)
1833                  && (cur_pattern->bus_id != bus->sim->bus_id))
1834                         continue;
1835
1836                 if (((cur_pattern->flags & BUS_MATCH_UNIT) != 0)
1837                  && (cur_pattern->unit_number != bus->sim->unit_number))
1838                         continue;
1839
1840                 if (((cur_pattern->flags & BUS_MATCH_NAME) != 0)
1841                  && (strncmp(cur_pattern->dev_name, bus->sim->sim_name,
1842                              DEV_IDLEN) != 0))
1843                         continue;
1844
1845                 /*
1846                  * If we get to this point, the user definitely wants
1847                  * information on this bus.  So tell the caller to copy the
1848                  * data out.
1849                  */
1850                 retval |= DM_RET_COPY;
1851
1852                 /*
1853                  * If the return action has been set to descend, then we
1854                  * know that we've already seen a non-bus matching
1855                  * expression, therefore we need to further descend the tree.
1856                  * This won't change by continuing around the loop, so we
1857                  * go ahead and return.  If we haven't seen a non-bus
1858                  * matching expression, we keep going around the loop until
1859                  * we exhaust the matching expressions.  We'll set the stop
1860                  * flag once we fall out of the loop.
1861                  */
1862                 if ((retval & DM_RET_ACTION_MASK) == DM_RET_DESCEND)
1863                         return(retval);
1864         }
1865
1866         /*
1867          * If the return action hasn't been set to descend yet, that means
1868          * we haven't seen anything other than bus matching patterns.  So
1869          * tell the caller to stop descending the tree -- the user doesn't
1870          * want to match against lower level tree elements.
1871          */
1872         if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1873                 retval |= DM_RET_STOP;
1874
1875         return(retval);
1876 }
1877
1878 static dev_match_ret
1879 xptdevicematch(struct dev_match_pattern *patterns, u_int num_patterns,
1880                struct cam_ed *device)
1881 {
1882         dev_match_ret retval;
1883         int i;
1884
1885         retval = DM_RET_NONE;
1886
1887         /*
1888          * If we aren't given something to match against, that's an error.
1889          */
1890         if (device == NULL)
1891                 return(DM_RET_ERROR);
1892
1893         /*
1894          * If there are no match entries, then this device matches no
1895          * matter what.
1896          */
1897         if ((patterns == NULL) || (num_patterns == 0))
1898                 return(DM_RET_DESCEND | DM_RET_COPY);
1899
1900         for (i = 0; i < num_patterns; i++) {
1901                 struct device_match_pattern *cur_pattern;
1902
1903                 /*
1904                  * If the pattern in question isn't for a device node, we
1905                  * aren't interested.
1906                  */
1907                 if (patterns[i].type != DEV_MATCH_DEVICE) {
1908                         if ((patterns[i].type == DEV_MATCH_PERIPH)
1909                          && ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE))
1910                                 retval |= DM_RET_DESCEND;
1911                         continue;
1912                 }
1913
1914                 cur_pattern = &patterns[i].pattern.device_pattern;
1915
1916                 /*
1917                  * If they want to match any device node, we give them any
1918                  * device node.
1919                  */
1920                 if (cur_pattern->flags == DEV_MATCH_ANY) {
1921                         /* set the copy flag */
1922                         retval |= DM_RET_COPY;
1923
1924
1925                         /*
1926                          * If we've already decided on an action, go ahead
1927                          * and return.
1928                          */
1929                         if ((retval & DM_RET_ACTION_MASK) != DM_RET_NONE)
1930                                 return(retval);
1931                 }
1932
1933                 /*
1934                  * Not sure why someone would do this...
1935                  */
1936                 if (cur_pattern->flags == DEV_MATCH_NONE)
1937                         continue;
1938
1939                 if (((cur_pattern->flags & DEV_MATCH_PATH) != 0)
1940                  && (cur_pattern->path_id != device->target->bus->path_id))
1941                         continue;
1942
1943                 if (((cur_pattern->flags & DEV_MATCH_TARGET) != 0)
1944                  && (cur_pattern->target_id != device->target->target_id))
1945                         continue;
1946
1947                 if (((cur_pattern->flags & DEV_MATCH_LUN) != 0)
1948                  && (cur_pattern->target_lun != device->lun_id))
1949                         continue;
1950
1951                 if (((cur_pattern->flags & DEV_MATCH_INQUIRY) != 0)
1952                  && (cam_quirkmatch((caddr_t)&device->inq_data,
1953                                     (caddr_t)&cur_pattern->inq_pat,
1954                                     1, sizeof(cur_pattern->inq_pat),
1955                                     scsi_static_inquiry_match) == NULL))
1956                         continue;
1957
1958                 /*
1959                  * If we get to this point, the user definitely wants
1960                  * information on this device.  So tell the caller to copy
1961                  * the data out.
1962                  */
1963                 retval |= DM_RET_COPY;
1964
1965                 /*
1966                  * If the return action has been set to descend, then we
1967                  * know that we've already seen a peripheral matching
1968                  * expression, therefore we need to further descend the tree.
1969                  * This won't change by continuing around the loop, so we
1970                  * go ahead and return.  If we haven't seen a peripheral
1971                  * matching expression, we keep going around the loop until
1972                  * we exhaust the matching expressions.  We'll set the stop
1973                  * flag once we fall out of the loop.
1974                  */
1975                 if ((retval & DM_RET_ACTION_MASK) == DM_RET_DESCEND)
1976                         return(retval);
1977         }
1978
1979         /*
1980          * If the return action hasn't been set to descend yet, that means
1981          * we haven't seen any peripheral matching patterns.  So tell the
1982          * caller to stop descending the tree -- the user doesn't want to
1983          * match against lower level tree elements.
1984          */
1985         if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1986                 retval |= DM_RET_STOP;
1987
1988         return(retval);
1989 }
1990
1991 /*
1992  * Match a single peripheral against any number of match patterns.
1993  */
1994 static dev_match_ret
1995 xptperiphmatch(struct dev_match_pattern *patterns, u_int num_patterns,
1996                struct cam_periph *periph)
1997 {
1998         dev_match_ret retval;
1999         int i;
2000
2001         /*
2002          * If we aren't given something to match against, that's an error.
2003          */
2004         if (periph == NULL)
2005                 return(DM_RET_ERROR);
2006
2007         /*
2008          * If there are no match entries, then this peripheral matches no
2009          * matter what.
2010          */
2011         if ((patterns == NULL) || (num_patterns == 0))
2012                 return(DM_RET_STOP | DM_RET_COPY);
2013
2014         /*
2015          * There aren't any nodes below a peripheral node, so there's no
2016          * reason to descend the tree any further.
2017          */
2018         retval = DM_RET_STOP;
2019
2020         for (i = 0; i < num_patterns; i++) {
2021                 struct periph_match_pattern *cur_pattern;
2022
2023                 /*
2024                  * If the pattern in question isn't for a peripheral, we
2025                  * aren't interested.
2026                  */
2027                 if (patterns[i].type != DEV_MATCH_PERIPH)
2028                         continue;
2029
2030                 cur_pattern = &patterns[i].pattern.periph_pattern;
2031
2032                 /*
2033                  * If they want to match on anything, then we will do so.
2034                  */
2035                 if (cur_pattern->flags == PERIPH_MATCH_ANY) {
2036                         /* set the copy flag */
2037                         retval |= DM_RET_COPY;
2038
2039                         /*
2040                          * We've already set the return action to stop,
2041                          * since there are no nodes below peripherals in
2042                          * the tree.
2043                          */
2044                         return(retval);
2045                 }
2046
2047                 /*
2048                  * Not sure why someone would do this...
2049                  */
2050                 if (cur_pattern->flags == PERIPH_MATCH_NONE)
2051                         continue;
2052
2053                 if (((cur_pattern->flags & PERIPH_MATCH_PATH) != 0)
2054                  && (cur_pattern->path_id != periph->path->bus->path_id))
2055                         continue;
2056
2057                 /*
2058                  * For the target and lun id's, we have to make sure the
2059                  * target and lun pointers aren't NULL.  The xpt peripheral
2060                  * has a wildcard target and device.
2061                  */
2062                 if (((cur_pattern->flags & PERIPH_MATCH_TARGET) != 0)
2063                  && ((periph->path->target == NULL)
2064                  ||(cur_pattern->target_id != periph->path->target->target_id)))
2065                         continue;
2066
2067                 if (((cur_pattern->flags & PERIPH_MATCH_LUN) != 0)
2068                  && ((periph->path->device == NULL)
2069                  || (cur_pattern->target_lun != periph->path->device->lun_id)))
2070                         continue;
2071
2072                 if (((cur_pattern->flags & PERIPH_MATCH_UNIT) != 0)
2073                  && (cur_pattern->unit_number != periph->unit_number))
2074                         continue;
2075
2076                 if (((cur_pattern->flags & PERIPH_MATCH_NAME) != 0)
2077                  && (strncmp(cur_pattern->periph_name, periph->periph_name,
2078                              DEV_IDLEN) != 0))
2079                         continue;
2080
2081                 /*
2082                  * If we get to this point, the user definitely wants
2083                  * information on this peripheral.  So tell the caller to
2084                  * copy the data out.
2085                  */
2086                 retval |= DM_RET_COPY;
2087
2088                 /*
2089                  * The return action has already been set to stop, since
2090                  * peripherals don't have any nodes below them in the EDT.
2091                  */
2092                 return(retval);
2093         }
2094
2095         /*
2096          * If we get to this point, the peripheral that was passed in
2097          * doesn't match any of the patterns.
2098          */
2099         return(retval);
2100 }
2101
2102 static int
2103 xptedtbusfunc(struct cam_eb *bus, void *arg)
2104 {
2105         struct ccb_dev_match *cdm;
2106         dev_match_ret retval;
2107
2108         cdm = (struct ccb_dev_match *)arg;
2109
2110         /*
2111          * If our position is for something deeper in the tree, that means
2112          * that we've already seen this node.  So, we keep going down.
2113          */
2114         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2115          && (cdm->pos.cookie.bus == bus)
2116          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2117          && (cdm->pos.cookie.target != NULL))
2118                 retval = DM_RET_DESCEND;
2119         else
2120                 retval = xptbusmatch(cdm->patterns, cdm->num_patterns, bus);
2121
2122         /*
2123          * If we got an error, bail out of the search.
2124          */
2125         if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
2126                 cdm->status = CAM_DEV_MATCH_ERROR;
2127                 return(0);
2128         }
2129
2130         /*
2131          * If the copy flag is set, copy this bus out.
2132          */
2133         if (retval & DM_RET_COPY) {
2134                 int spaceleft, j;
2135
2136                 spaceleft = cdm->match_buf_len - (cdm->num_matches *
2137                         sizeof(struct dev_match_result));
2138
2139                 /*
2140                  * If we don't have enough space to put in another
2141                  * match result, save our position and tell the
2142                  * user there are more devices to check.
2143                  */
2144                 if (spaceleft < sizeof(struct dev_match_result)) {
2145                         bzero(&cdm->pos, sizeof(cdm->pos));
2146                         cdm->pos.position_type =
2147                                 CAM_DEV_POS_EDT | CAM_DEV_POS_BUS;
2148
2149                         cdm->pos.cookie.bus = bus;
2150                         cdm->pos.generations[CAM_BUS_GENERATION]=
2151                                 xsoftc.bus_generation;
2152                         cdm->status = CAM_DEV_MATCH_MORE;
2153                         return(0);
2154                 }
2155                 j = cdm->num_matches;
2156                 cdm->num_matches++;
2157                 cdm->matches[j].type = DEV_MATCH_BUS;
2158                 cdm->matches[j].result.bus_result.path_id = bus->path_id;
2159                 cdm->matches[j].result.bus_result.bus_id = bus->sim->bus_id;
2160                 cdm->matches[j].result.bus_result.unit_number =
2161                         bus->sim->unit_number;
2162                 strncpy(cdm->matches[j].result.bus_result.dev_name,
2163                         bus->sim->sim_name, DEV_IDLEN);
2164         }
2165
2166         /*
2167          * If the user is only interested in busses, there's no
2168          * reason to descend to the next level in the tree.
2169          */
2170         if ((retval & DM_RET_ACTION_MASK) == DM_RET_STOP)
2171                 return(1);
2172
2173         /*
2174          * If there is a target generation recorded, check it to
2175          * make sure the target list hasn't changed.
2176          */
2177         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2178          && (bus == cdm->pos.cookie.bus)
2179          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2180          && (cdm->pos.generations[CAM_TARGET_GENERATION] != 0)
2181          && (cdm->pos.generations[CAM_TARGET_GENERATION] !=
2182              bus->generation)) {
2183                 cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
2184                 return(0);
2185         }
2186
2187         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2188          && (cdm->pos.cookie.bus == bus)
2189          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2190          && (cdm->pos.cookie.target != NULL))
2191                 return(xpttargettraverse(bus,
2192                                         (struct cam_et *)cdm->pos.cookie.target,
2193                                          xptedttargetfunc, arg));
2194         else
2195                 return(xpttargettraverse(bus, NULL, xptedttargetfunc, arg));
2196 }
2197
2198 static int
2199 xptedttargetfunc(struct cam_et *target, void *arg)
2200 {
2201         struct ccb_dev_match *cdm;
2202
2203         cdm = (struct ccb_dev_match *)arg;
2204
2205         /*
2206          * If there is a device list generation recorded, check it to
2207          * make sure the device list hasn't changed.
2208          */
2209         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2210          && (cdm->pos.cookie.bus == target->bus)
2211          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2212          && (cdm->pos.cookie.target == target)
2213          && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
2214          && (cdm->pos.generations[CAM_DEV_GENERATION] != 0)
2215          && (cdm->pos.generations[CAM_DEV_GENERATION] !=
2216              target->generation)) {
2217                 cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
2218                 return(0);
2219         }
2220
2221         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2222          && (cdm->pos.cookie.bus == target->bus)
2223          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2224          && (cdm->pos.cookie.target == target)
2225          && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
2226          && (cdm->pos.cookie.device != NULL))
2227                 return(xptdevicetraverse(target,
2228                                         (struct cam_ed *)cdm->pos.cookie.device,
2229                                          xptedtdevicefunc, arg));
2230         else
2231                 return(xptdevicetraverse(target, NULL, xptedtdevicefunc, arg));
2232 }
2233
2234 static int
2235 xptedtdevicefunc(struct cam_ed *device, void *arg)
2236 {
2237
2238         struct ccb_dev_match *cdm;
2239         dev_match_ret retval;
2240
2241         cdm = (struct ccb_dev_match *)arg;
2242
2243         /*
2244          * If our position is for something deeper in the tree, that means
2245          * that we've already seen this node.  So, we keep going down.
2246          */
2247         if ((cdm->pos.position_type & CAM_DEV_POS_DEVICE)
2248          && (cdm->pos.cookie.device == device)
2249          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2250          && (cdm->pos.cookie.periph != NULL))
2251                 retval = DM_RET_DESCEND;
2252         else
2253                 retval = xptdevicematch(cdm->patterns, cdm->num_patterns,
2254                                         device);
2255
2256         if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
2257                 cdm->status = CAM_DEV_MATCH_ERROR;
2258                 return(0);
2259         }
2260
2261         /*
2262          * If the copy flag is set, copy this device out.
2263          */
2264         if (retval & DM_RET_COPY) {
2265                 int spaceleft, j;
2266
2267                 spaceleft = cdm->match_buf_len - (cdm->num_matches *
2268                         sizeof(struct dev_match_result));
2269
2270                 /*
2271                  * If we don't have enough space to put in another
2272                  * match result, save our position and tell the
2273                  * user there are more devices to check.
2274                  */
2275                 if (spaceleft < sizeof(struct dev_match_result)) {
2276                         bzero(&cdm->pos, sizeof(cdm->pos));
2277                         cdm->pos.position_type =
2278                                 CAM_DEV_POS_EDT | CAM_DEV_POS_BUS |
2279                                 CAM_DEV_POS_TARGET | CAM_DEV_POS_DEVICE;
2280
2281                         cdm->pos.cookie.bus = device->target->bus;
2282                         cdm->pos.generations[CAM_BUS_GENERATION]=
2283                                 xsoftc.bus_generation;
2284                         cdm->pos.cookie.target = device->target;
2285                         cdm->pos.generations[CAM_TARGET_GENERATION] =
2286                                 device->target->bus->generation;
2287                         cdm->pos.cookie.device = device;
2288                         cdm->pos.generations[CAM_DEV_GENERATION] =
2289                                 device->target->generation;
2290                         cdm->status = CAM_DEV_MATCH_MORE;
2291                         return(0);
2292                 }
2293                 j = cdm->num_matches;
2294                 cdm->num_matches++;
2295                 cdm->matches[j].type = DEV_MATCH_DEVICE;
2296                 cdm->matches[j].result.device_result.path_id =
2297                         device->target->bus->path_id;
2298                 cdm->matches[j].result.device_result.target_id =
2299                         device->target->target_id;
2300                 cdm->matches[j].result.device_result.target_lun =
2301                         device->lun_id;
2302                 bcopy(&device->inq_data,
2303                       &cdm->matches[j].result.device_result.inq_data,
2304                       sizeof(struct scsi_inquiry_data));
2305
2306                 /* Let the user know whether this device is unconfigured */
2307                 if (device->flags & CAM_DEV_UNCONFIGURED)
2308                         cdm->matches[j].result.device_result.flags =
2309                                 DEV_RESULT_UNCONFIGURED;
2310                 else
2311                         cdm->matches[j].result.device_result.flags =
2312                                 DEV_RESULT_NOFLAG;
2313         }
2314
2315         /*
2316          * If the user isn't interested in peripherals, don't descend
2317          * the tree any further.
2318          */
2319         if ((retval & DM_RET_ACTION_MASK) == DM_RET_STOP)
2320                 return(1);
2321
2322         /*
2323          * If there is a peripheral list generation recorded, make sure
2324          * it hasn't changed.
2325          */
2326         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2327          && (device->target->bus == cdm->pos.cookie.bus)
2328          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2329          && (device->target == cdm->pos.cookie.target)
2330          && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
2331          && (device == cdm->pos.cookie.device)
2332          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2333          && (cdm->pos.generations[CAM_PERIPH_GENERATION] != 0)
2334          && (cdm->pos.generations[CAM_PERIPH_GENERATION] !=
2335              device->generation)){
2336                 cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
2337                 return(0);
2338         }
2339
2340         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2341          && (cdm->pos.cookie.bus == device->target->bus)
2342          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2343          && (cdm->pos.cookie.target == device->target)
2344          && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
2345          && (cdm->pos.cookie.device == device)
2346          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2347          && (cdm->pos.cookie.periph != NULL))
2348                 return(xptperiphtraverse(device,
2349                                 (struct cam_periph *)cdm->pos.cookie.periph,
2350                                 xptedtperiphfunc, arg));
2351         else
2352                 return(xptperiphtraverse(device, NULL, xptedtperiphfunc, arg));
2353 }
2354
2355 static int
2356 xptedtperiphfunc(struct cam_periph *periph, void *arg)
2357 {
2358         struct ccb_dev_match *cdm;
2359         dev_match_ret retval;
2360
2361         cdm = (struct ccb_dev_match *)arg;
2362
2363         retval = xptperiphmatch(cdm->patterns, cdm->num_patterns, periph);
2364
2365         if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
2366                 cdm->status = CAM_DEV_MATCH_ERROR;
2367                 return(0);
2368         }
2369
2370         /*
2371          * If the copy flag is set, copy this peripheral out.
2372          */
2373         if (retval & DM_RET_COPY) {
2374                 int spaceleft, j;
2375
2376                 spaceleft = cdm->match_buf_len - (cdm->num_matches *
2377                         sizeof(struct dev_match_result));
2378
2379                 /*
2380                  * If we don't have enough space to put in another
2381                  * match result, save our position and tell the
2382                  * user there are more devices to check.
2383                  */
2384                 if (spaceleft < sizeof(struct dev_match_result)) {
2385                         bzero(&cdm->pos, sizeof(cdm->pos));
2386                         cdm->pos.position_type =
2387                                 CAM_DEV_POS_EDT | CAM_DEV_POS_BUS |
2388                                 CAM_DEV_POS_TARGET | CAM_DEV_POS_DEVICE |
2389                                 CAM_DEV_POS_PERIPH;
2390
2391                         cdm->pos.cookie.bus = periph->path->bus;
2392                         cdm->pos.generations[CAM_BUS_GENERATION]=
2393                                 xsoftc.bus_generation;
2394                         cdm->pos.cookie.target = periph->path->target;
2395                         cdm->pos.generations[CAM_TARGET_GENERATION] =
2396                                 periph->path->bus->generation;
2397                         cdm->pos.cookie.device = periph->path->device;
2398                         cdm->pos.generations[CAM_DEV_GENERATION] =
2399                                 periph->path->target->generation;
2400                         cdm->pos.cookie.periph = periph;
2401                         cdm->pos.generations[CAM_PERIPH_GENERATION] =
2402                                 periph->path->device->generation;
2403                         cdm->status = CAM_DEV_MATCH_MORE;
2404                         return(0);
2405                 }
2406
2407                 j = cdm->num_matches;
2408                 cdm->num_matches++;
2409                 cdm->matches[j].type = DEV_MATCH_PERIPH;
2410                 cdm->matches[j].result.periph_result.path_id =
2411                         periph->path->bus->path_id;
2412                 cdm->matches[j].result.periph_result.target_id =
2413                         periph->path->target->target_id;
2414                 cdm->matches[j].result.periph_result.target_lun =
2415                         periph->path->device->lun_id;
2416                 cdm->matches[j].result.periph_result.unit_number =
2417                         periph->unit_number;
2418                 strncpy(cdm->matches[j].result.periph_result.periph_name,
2419                         periph->periph_name, DEV_IDLEN);
2420         }
2421
2422         return(1);
2423 }
2424
2425 static int
2426 xptedtmatch(struct ccb_dev_match *cdm)
2427 {
2428         int ret;
2429
2430         cdm->num_matches = 0;
2431
2432         /*
2433          * Check the bus list generation.  If it has changed, the user
2434          * needs to reset everything and start over.
2435          */
2436         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2437          && (cdm->pos.generations[CAM_BUS_GENERATION] != 0)
2438          && (cdm->pos.generations[CAM_BUS_GENERATION] != xsoftc.bus_generation)) {
2439                 cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
2440                 return(0);
2441         }
2442
2443         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2444          && (cdm->pos.cookie.bus != NULL))
2445                 ret = xptbustraverse((struct cam_eb *)cdm->pos.cookie.bus,
2446                                      xptedtbusfunc, cdm);
2447         else
2448                 ret = xptbustraverse(NULL, xptedtbusfunc, cdm);
2449
2450         /*
2451          * If we get back 0, that means that we had to stop before fully
2452          * traversing the EDT.  It also means that one of the subroutines
2453          * has set the status field to the proper value.  If we get back 1,
2454          * we've fully traversed the EDT and copied out any matching entries.
2455          */
2456         if (ret == 1)
2457                 cdm->status = CAM_DEV_MATCH_LAST;
2458
2459         return(ret);
2460 }
2461
2462 static int
2463 xptplistpdrvfunc(struct periph_driver **pdrv, void *arg)
2464 {
2465         struct ccb_dev_match *cdm;
2466
2467         cdm = (struct ccb_dev_match *)arg;
2468
2469         if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
2470          && (cdm->pos.cookie.pdrv == pdrv)
2471          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2472          && (cdm->pos.generations[CAM_PERIPH_GENERATION] != 0)
2473          && (cdm->pos.generations[CAM_PERIPH_GENERATION] !=
2474              (*pdrv)->generation)) {
2475                 cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
2476                 return(0);
2477         }
2478
2479         if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
2480          && (cdm->pos.cookie.pdrv == pdrv)
2481          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2482          && (cdm->pos.cookie.periph != NULL))
2483                 return(xptpdperiphtraverse(pdrv,
2484                                 (struct cam_periph *)cdm->pos.cookie.periph,
2485                                 xptplistperiphfunc, arg));
2486         else
2487                 return(xptpdperiphtraverse(pdrv, NULL,xptplistperiphfunc, arg));
2488 }
2489
2490 static int
2491 xptplistperiphfunc(struct cam_periph *periph, void *arg)
2492 {
2493         struct ccb_dev_match *cdm;
2494         dev_match_ret retval;
2495
2496         cdm = (struct ccb_dev_match *)arg;
2497
2498         retval = xptperiphmatch(cdm->patterns, cdm->num_patterns, periph);
2499
2500         if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
2501                 cdm->status = CAM_DEV_MATCH_ERROR;
2502                 return(0);
2503         }
2504
2505         /*
2506          * If the copy flag is set, copy this peripheral out.
2507          */
2508         if (retval & DM_RET_COPY) {
2509                 int spaceleft, j;
2510
2511                 spaceleft = cdm->match_buf_len - (cdm->num_matches *
2512                         sizeof(struct dev_match_result));
2513
2514                 /*
2515                  * If we don't have enough space to put in another
2516                  * match result, save our position and tell the
2517                  * user there are more devices to check.
2518                  */
2519                 if (spaceleft < sizeof(struct dev_match_result)) {
2520                         struct periph_driver **pdrv;
2521
2522                         pdrv = NULL;
2523                         bzero(&cdm->pos, sizeof(cdm->pos));
2524                         cdm->pos.position_type =
2525                                 CAM_DEV_POS_PDRV | CAM_DEV_POS_PDPTR |
2526                                 CAM_DEV_POS_PERIPH;
2527
2528                         /*
2529                          * This may look a bit non-sensical, but it is
2530                          * actually quite logical.  There are very few
2531                          * peripheral drivers, and bloating every peripheral
2532                          * structure with a pointer back to its parent
2533                          * peripheral driver linker set entry would cost
2534                          * more in the long run than doing this quick lookup.
2535                          */
2536                         for (pdrv = periph_drivers; *pdrv != NULL; pdrv++) {
2537                                 if (strcmp((*pdrv)->driver_name,
2538                                     periph->periph_name) == 0)
2539                                         break;
2540                         }
2541
2542                         if (*pdrv == NULL) {
2543                                 cdm->status = CAM_DEV_MATCH_ERROR;
2544                                 return(0);
2545                         }
2546
2547                         cdm->pos.cookie.pdrv = pdrv;
2548                         /*
2549                          * The periph generation slot does double duty, as
2550                          * does the periph pointer slot.  They are used for
2551                          * both edt and pdrv lookups and positioning.
2552                          */
2553                         cdm->pos.cookie.periph = periph;
2554                         cdm->pos.generations[CAM_PERIPH_GENERATION] =
2555                                 (*pdrv)->generation;
2556                         cdm->status = CAM_DEV_MATCH_MORE;
2557                         return(0);
2558                 }
2559
2560                 j = cdm->num_matches;
2561                 cdm->num_matches++;
2562                 cdm->matches[j].type = DEV_MATCH_PERIPH;
2563                 cdm->matches[j].result.periph_result.path_id =
2564                         periph->path->bus->path_id;
2565
2566                 /*
2567                  * The transport layer peripheral doesn't have a target or
2568                  * lun.
2569                  */
2570                 if (periph->path->target)
2571                         cdm->matches[j].result.periph_result.target_id =
2572                                 periph->path->target->target_id;
2573                 else
2574                         cdm->matches[j].result.periph_result.target_id = -1;
2575
2576                 if (periph->path->device)
2577                         cdm->matches[j].result.periph_result.target_lun =
2578                                 periph->path->device->lun_id;
2579                 else
2580                         cdm->matches[j].result.periph_result.target_lun = -1;
2581
2582                 cdm->matches[j].result.periph_result.unit_number =
2583                         periph->unit_number;
2584                 strncpy(cdm->matches[j].result.periph_result.periph_name,
2585                         periph->periph_name, DEV_IDLEN);
2586         }
2587
2588         return(1);
2589 }
2590
2591 static int
2592 xptperiphlistmatch(struct ccb_dev_match *cdm)
2593 {
2594         int ret;
2595
2596         cdm->num_matches = 0;
2597
2598         /*
2599          * At this point in the edt traversal function, we check the bus
2600          * list generation to make sure that no busses have been added or
2601          * removed since the user last sent a XPT_DEV_MATCH ccb through.
2602          * For the peripheral driver list traversal function, however, we
2603          * don't have to worry about new peripheral driver types coming or
2604          * going; they're in a linker set, and therefore can't change
2605          * without a recompile.
2606          */
2607
2608         if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
2609          && (cdm->pos.cookie.pdrv != NULL))
2610                 ret = xptpdrvtraverse(
2611                                 (struct periph_driver **)cdm->pos.cookie.pdrv,
2612                                 xptplistpdrvfunc, cdm);
2613         else
2614                 ret = xptpdrvtraverse(NULL, xptplistpdrvfunc, cdm);
2615
2616         /*
2617          * If we get back 0, that means that we had to stop before fully
2618          * traversing the peripheral driver tree.  It also means that one of
2619          * the subroutines has set the status field to the proper value.  If
2620          * we get back 1, we've fully traversed the EDT and copied out any
2621          * matching entries.
2622          */
2623         if (ret == 1)
2624                 cdm->status = CAM_DEV_MATCH_LAST;
2625
2626         return(ret);
2627 }
2628
2629 static int
2630 xptbustraverse(struct cam_eb *start_bus, xpt_busfunc_t *tr_func, void *arg)
2631 {
2632         struct cam_eb *bus, *next_bus;
2633         int retval;
2634
2635         retval = 1;
2636
2637         lockmgr(&xsoftc.xpt_topo_lock, LK_EXCLUSIVE);
2638         for (bus = (start_bus ? start_bus : TAILQ_FIRST(&xsoftc.xpt_busses));
2639              bus != NULL;
2640              bus = next_bus) {
2641                 next_bus = TAILQ_NEXT(bus, links);
2642
2643                 lockmgr(&xsoftc.xpt_topo_lock, LK_RELEASE);
2644                 CAM_SIM_LOCK(bus->sim);
2645                 retval = tr_func(bus, arg);
2646                 CAM_SIM_UNLOCK(bus->sim);
2647                 if (retval == 0)
2648                         return(retval);
2649                 lockmgr(&xsoftc.xpt_topo_lock, LK_EXCLUSIVE);
2650         }
2651         lockmgr(&xsoftc.xpt_topo_lock, LK_RELEASE);
2652
2653         return(retval);
2654 }
2655
2656 static int
2657 xpttargettraverse(struct cam_eb *bus, struct cam_et *start_target,
2658                   xpt_targetfunc_t *tr_func, void *arg)
2659 {
2660         struct cam_et *target, *next_target;
2661         int retval;
2662
2663         retval = 1;
2664         for (target = (start_target ? start_target :
2665                        TAILQ_FIRST(&bus->et_entries));
2666              target != NULL; target = next_target) {
2667
2668                 next_target = TAILQ_NEXT(target, links);
2669
2670                 retval = tr_func(target, arg);
2671
2672                 if (retval == 0)
2673                         return(retval);
2674         }
2675
2676         return(retval);
2677 }
2678
2679 static int
2680 xptdevicetraverse(struct cam_et *target, struct cam_ed *start_device,
2681                   xpt_devicefunc_t *tr_func, void *arg)
2682 {
2683         struct cam_ed *device, *next_device;
2684         int retval;
2685
2686         retval = 1;
2687         for (device = (start_device ? start_device :
2688                        TAILQ_FIRST(&target->ed_entries));
2689              device != NULL;
2690              device = next_device) {
2691
2692                 next_device = TAILQ_NEXT(device, links);
2693
2694                 retval = tr_func(device, arg);
2695
2696                 if (retval == 0)
2697                         return(retval);
2698         }
2699
2700         return(retval);
2701 }
2702
2703 static int
2704 xptperiphtraverse(struct cam_ed *device, struct cam_periph *start_periph,
2705                   xpt_periphfunc_t *tr_func, void *arg)
2706 {
2707         struct cam_periph *periph, *next_periph;
2708         int retval;
2709
2710         retval = 1;
2711
2712         for (periph = (start_periph ? start_periph :
2713                        SLIST_FIRST(&device->periphs));
2714              periph != NULL;
2715              periph = next_periph) {
2716
2717                 next_periph = SLIST_NEXT(periph, periph_links);
2718
2719                 retval = tr_func(periph, arg);
2720                 if (retval == 0)
2721                         return(retval);
2722         }
2723
2724         return(retval);
2725 }
2726
2727 static int
2728 xptpdrvtraverse(struct periph_driver **start_pdrv,
2729                 xpt_pdrvfunc_t *tr_func, void *arg)
2730 {
2731         struct periph_driver **pdrv;
2732         int retval;
2733
2734         retval = 1;
2735
2736         /*
2737          * We don't traverse the peripheral driver list like we do the
2738          * other lists, because it is a linker set, and therefore cannot be
2739          * changed during runtime.  If the peripheral driver list is ever
2740          * re-done to be something other than a linker set (i.e. it can
2741          * change while the system is running), the list traversal should
2742          * be modified to work like the other traversal functions.
2743          */
2744         for (pdrv = (start_pdrv ? start_pdrv : periph_drivers);
2745              *pdrv != NULL; pdrv++) {
2746                 retval = tr_func(pdrv, arg);
2747
2748                 if (retval == 0)
2749                         return(retval);
2750         }
2751
2752         return(retval);
2753 }
2754
2755 static int
2756 xptpdperiphtraverse(struct periph_driver **pdrv,
2757                     struct cam_periph *start_periph,
2758                     xpt_periphfunc_t *tr_func, void *arg)
2759 {
2760         struct cam_periph *periph, *next_periph;
2761         int retval;
2762
2763         retval = 1;
2764
2765         for (periph = (start_periph ? start_periph :
2766              TAILQ_FIRST(&(*pdrv)->units)); periph != NULL;
2767              periph = next_periph) {
2768
2769                 next_periph = TAILQ_NEXT(periph, unit_links);
2770
2771                 retval = tr_func(periph, arg);
2772                 if (retval == 0)
2773                         return(retval);
2774         }
2775         return(retval);
2776 }
2777
2778 static int
2779 xptdefbusfunc(struct cam_eb *bus, void *arg)
2780 {
2781         struct xpt_traverse_config *tr_config;
2782
2783         tr_config = (struct xpt_traverse_config *)arg;
2784
2785         if (tr_config->depth == XPT_DEPTH_BUS) {
2786                 xpt_busfunc_t *tr_func;
2787
2788                 tr_func = (xpt_busfunc_t *)tr_config->tr_func;
2789
2790                 return(tr_func(bus, tr_config->tr_arg));
2791         } else
2792                 return(xpttargettraverse(bus, NULL, xptdeftargetfunc, arg));
2793 }
2794
2795 static int
2796 xptdeftargetfunc(struct cam_et *target, void *arg)
2797 {
2798         struct xpt_traverse_config *tr_config;
2799
2800         tr_config = (struct xpt_traverse_config *)arg;
2801
2802         if (tr_config->depth == XPT_DEPTH_TARGET) {
2803                 xpt_targetfunc_t *tr_func;
2804
2805                 tr_func = (xpt_targetfunc_t *)tr_config->tr_func;
2806
2807                 return(tr_func(target, tr_config->tr_arg));
2808         } else
2809                 return(xptdevicetraverse(target, NULL, xptdefdevicefunc, arg));
2810 }
2811
2812 static int
2813 xptdefdevicefunc(struct cam_ed *device, void *arg)
2814 {
2815         struct xpt_traverse_config *tr_config;
2816
2817         tr_config = (struct xpt_traverse_config *)arg;
2818
2819         if (tr_config->depth == XPT_DEPTH_DEVICE) {
2820                 xpt_devicefunc_t *tr_func;
2821
2822                 tr_func = (xpt_devicefunc_t *)tr_config->tr_func;
2823
2824                 return(tr_func(device, tr_config->tr_arg));
2825         } else
2826                 return(xptperiphtraverse(device, NULL, xptdefperiphfunc, arg));
2827 }
2828
2829 static int
2830 xptdefperiphfunc(struct cam_periph *periph, void *arg)
2831 {
2832         struct xpt_traverse_config *tr_config;
2833         xpt_periphfunc_t *tr_func;
2834
2835         tr_config = (struct xpt_traverse_config *)arg;
2836
2837         tr_func = (xpt_periphfunc_t *)tr_config->tr_func;
2838
2839         /*
2840          * Unlike the other default functions, we don't check for depth
2841          * here.  The peripheral driver level is the last level in the EDT,
2842          * so if we're here, we should execute the function in question.
2843          */
2844         return(tr_func(periph, tr_config->tr_arg));
2845 }
2846
2847 /*
2848  * Execute the given function for every bus in the EDT.
2849  */
2850 static int
2851 xpt_for_all_busses(xpt_busfunc_t *tr_func, void *arg)
2852 {
2853         struct xpt_traverse_config tr_config;
2854
2855         tr_config.depth = XPT_DEPTH_BUS;
2856         tr_config.tr_func = tr_func;
2857         tr_config.tr_arg = arg;
2858
2859         return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2860 }
2861
2862 /*
2863  * Execute the given function for every device in the EDT.
2864  */
2865 static int
2866 xpt_for_all_devices(xpt_devicefunc_t *tr_func, void *arg)
2867 {
2868         struct xpt_traverse_config tr_config;
2869
2870         tr_config.depth = XPT_DEPTH_DEVICE;
2871         tr_config.tr_func = tr_func;
2872         tr_config.tr_arg = arg;
2873
2874         return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2875 }
2876
2877 static int
2878 xptsetasyncfunc(struct cam_ed *device, void *arg)
2879 {
2880         struct cam_path path;
2881         struct ccb_getdev cgd;
2882         struct async_node *cur_entry;
2883
2884         cur_entry = (struct async_node *)arg;
2885
2886         /*
2887          * Don't report unconfigured devices (Wildcard devs,
2888          * devices only for target mode, device instances
2889          * that have been invalidated but are waiting for
2890          * their last reference count to be released).
2891          */
2892         if ((device->flags & CAM_DEV_UNCONFIGURED) != 0)
2893                 return (1);
2894
2895         xpt_compile_path(&path,
2896                          NULL,
2897                          device->target->bus->path_id,
2898                          device->target->target_id,
2899                          device->lun_id);
2900         xpt_setup_ccb(&cgd.ccb_h, &path, /*priority*/1);
2901         cgd.ccb_h.func_code = XPT_GDEV_TYPE;
2902         xpt_action((union ccb *)&cgd);
2903         cur_entry->callback(cur_entry->callback_arg,
2904                             AC_FOUND_DEVICE,
2905                             &path, &cgd);
2906         xpt_release_path(&path);
2907
2908         return(1);
2909 }
2910
2911 static int
2912 xptsetasyncbusfunc(struct cam_eb *bus, void *arg)
2913 {
2914         struct cam_path path;
2915         struct ccb_pathinq cpi;
2916         struct async_node *cur_entry;
2917
2918         cur_entry = (struct async_node *)arg;
2919
2920         xpt_compile_path(&path, /*periph*/NULL,
2921                          bus->sim->path_id,
2922                          CAM_TARGET_WILDCARD,
2923                          CAM_LUN_WILDCARD);
2924         xpt_setup_ccb(&cpi.ccb_h, &path, /*priority*/1);
2925         cpi.ccb_h.func_code = XPT_PATH_INQ;
2926         xpt_action((union ccb *)&cpi);
2927         cur_entry->callback(cur_entry->callback_arg,
2928                             AC_PATH_REGISTERED,
2929                             &path, &cpi);
2930         xpt_release_path(&path);
2931
2932         return(1);
2933 }
2934
2935 static void
2936 xpt_action_sasync_cb(void *context, int pending)
2937 {
2938         struct async_node *cur_entry;
2939         struct xpt_task *task;
2940         uint32_t added;
2941
2942         task = (struct xpt_task *)context;
2943         cur_entry = (struct async_node *)task->data1;
2944         added = task->data2;
2945
2946         if ((added & AC_FOUND_DEVICE) != 0) {
2947                 /*
2948                  * Get this peripheral up to date with all
2949                  * the currently existing devices.
2950                  */
2951                 xpt_for_all_devices(xptsetasyncfunc, cur_entry);
2952         }
2953         if ((added & AC_PATH_REGISTERED) != 0) {
2954                 /*
2955                  * Get this peripheral up to date with all
2956                  * the currently existing busses.
2957                  */
2958                 xpt_for_all_busses(xptsetasyncbusfunc, cur_entry);
2959         }
2960
2961         kfree(task, M_CAMXPT);
2962 }
2963
2964 void
2965 xpt_action(union ccb *start_ccb)
2966 {
2967         CAM_DEBUG(start_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("xpt_action\n"));
2968
2969         start_ccb->ccb_h.status = CAM_REQ_INPROG;
2970
2971         switch (start_ccb->ccb_h.func_code) {
2972         case XPT_SCSI_IO:
2973         {
2974                 struct cam_ed *device;
2975 #ifdef CAMDEBUG
2976                 char cdb_str[(SCSI_MAX_CDBLEN * 3) + 1];
2977                 struct cam_path *path;
2978
2979                 path = start_ccb->ccb_h.path;
2980 #endif
2981
2982                 /*
2983                  * For the sake of compatibility with SCSI-1
2984                  * devices that may not understand the identify
2985                  * message, we include lun information in the
2986                  * second byte of all commands.  SCSI-1 specifies
2987                  * that luns are a 3 bit value and reserves only 3
2988                  * bits for lun information in the CDB.  Later
2989                  * revisions of the SCSI spec allow for more than 8
2990                  * luns, but have deprecated lun information in the
2991                  * CDB.  So, if the lun won't fit, we must omit.
2992                  *
2993                  * Also be aware that during initial probing for devices,
2994                  * the inquiry information is unknown but initialized to 0.
2995                  * This means that this code will be exercised while probing
2996                  * devices with an ANSI revision greater than 2.
2997                  */
2998                 device = start_ccb->ccb_h.path->device;
2999                 if (device->protocol_version <= SCSI_REV_2
3000                  && start_ccb->ccb_h.target_lun < 8
3001                  && (start_ccb->ccb_h.flags & CAM_CDB_POINTER) == 0) {
3002
3003                         start_ccb->csio.cdb_io.cdb_bytes[1] |=
3004                             start_ccb->ccb_h.target_lun << 5;
3005                 }
3006                 start_ccb->csio.scsi_status = SCSI_STATUS_OK;
3007                 CAM_DEBUG(path, CAM_DEBUG_CDB,("%s. CDB: %s\n",
3008                           scsi_op_desc(start_ccb->csio.cdb_io.cdb_bytes[0],
3009                                        &path->device->inq_data),
3010                           scsi_cdb_string(start_ccb->csio.cdb_io.cdb_bytes,
3011                                           cdb_str, sizeof(cdb_str))));
3012                 /* FALLTHROUGH */
3013         }
3014         case XPT_TARGET_IO:
3015         case XPT_CONT_TARGET_IO:
3016                 start_ccb->csio.sense_resid = 0;
3017                 start_ccb->csio.resid = 0;
3018                 /* FALLTHROUGH */
3019         case XPT_RESET_DEV:
3020         case XPT_ENG_EXEC:
3021         {
3022                 struct cam_path *path;
3023                 struct cam_sim *sim;
3024                 int runq;
3025
3026                 path = start_ccb->ccb_h.path;
3027
3028                 sim = path->bus->sim;
3029                 if (sim == &cam_dead_sim) {
3030                         /* The SIM has gone; just execute the CCB directly. */
3031                         cam_ccbq_send_ccb(&path->device->ccbq, start_ccb);
3032                         (*(sim->sim_action))(sim, start_ccb);
3033                         break;
3034                 }
3035
3036                 cam_ccbq_insert_ccb(&path->device->ccbq, start_ccb);
3037                 if (path->device->qfrozen_cnt == 0)
3038                         runq = xpt_schedule_dev_sendq(path->bus, path->device);
3039                 else
3040                         runq = 0;
3041                 if (runq != 0)
3042                         xpt_run_dev_sendq(path->bus);
3043                 break;
3044         }
3045         case XPT_SET_TRAN_SETTINGS:
3046         {
3047                 xpt_set_transfer_settings(&start_ccb->cts,
3048                                           start_ccb->ccb_h.path->device,
3049                                           /*async_update*/FALSE);
3050                 break;
3051         }
3052         case XPT_CALC_GEOMETRY:
3053         {
3054                 struct cam_sim *sim;
3055
3056                 /* Filter out garbage */
3057                 if (start_ccb->ccg.block_size == 0
3058                  || start_ccb->ccg.volume_size == 0) {
3059                         start_ccb->ccg.cylinders = 0;
3060                         start_ccb->ccg.heads = 0;
3061                         start_ccb->ccg.secs_per_track = 0;
3062                         start_ccb->ccb_h.status = CAM_REQ_CMP;
3063                         break;
3064                 }
3065                 sim = start_ccb->ccb_h.path->bus->sim;
3066                 (*(sim->sim_action))(sim, start_ccb);
3067                 break;
3068         }
3069         case XPT_ABORT:
3070         {
3071                 union ccb* abort_ccb;
3072
3073                 abort_ccb = start_ccb->cab.abort_ccb;
3074                 if (XPT_FC_IS_DEV_QUEUED(abort_ccb)) {
3075
3076                         if (abort_ccb->ccb_h.pinfo.index >= 0) {
3077                                 struct cam_ccbq *ccbq;
3078
3079                                 ccbq = &abort_ccb->ccb_h.path->device->ccbq;
3080                                 cam_ccbq_remove_ccb(ccbq, abort_ccb);
3081                                 abort_ccb->ccb_h.status =
3082                                     CAM_REQ_ABORTED|CAM_DEV_QFRZN;
3083                                 xpt_freeze_devq(abort_ccb->ccb_h.path, 1);
3084                                 xpt_done(abort_ccb);
3085                                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3086                                 break;
3087                         }
3088                         if (abort_ccb->ccb_h.pinfo.index == CAM_UNQUEUED_INDEX
3089                          && (abort_ccb->ccb_h.status & CAM_SIM_QUEUED) == 0) {
3090                                 /*
3091                                  * We've caught this ccb en route to
3092                                  * the SIM.  Flag it for abort and the
3093                                  * SIM will do so just before starting
3094                                  * real work on the CCB.
3095                                  */
3096                                 abort_ccb->ccb_h.status =
3097                                     CAM_REQ_ABORTED|CAM_DEV_QFRZN;
3098                                 xpt_freeze_devq(abort_ccb->ccb_h.path, 1);
3099                                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3100                                 break;
3101                         }
3102                 }
3103                 if (XPT_FC_IS_QUEUED(abort_ccb)
3104                  && (abort_ccb->ccb_h.pinfo.index == CAM_DONEQ_INDEX)) {
3105                         /*
3106                          * It's already completed but waiting
3107                          * for our SWI to get to it.
3108                          */
3109                         start_ccb->ccb_h.status = CAM_UA_ABORT;
3110                         break;
3111                 }
3112                 /*
3113                  * If we weren't able to take care of the abort request
3114                  * in the XPT, pass the request down to the SIM for processing.
3115                  */
3116                 /* FALLTHROUGH */
3117         }
3118         case XPT_ACCEPT_TARGET_IO:
3119         case XPT_EN_LUN:
3120         case XPT_IMMED_NOTIFY:
3121         case XPT_NOTIFY_ACK:
3122         case XPT_GET_TRAN_SETTINGS:
3123         case XPT_RESET_BUS:
3124         {
3125                 struct cam_sim *sim;
3126
3127                 sim = start_ccb->ccb_h.path->bus->sim;
3128                 (*(sim->sim_action))(sim, start_ccb);
3129                 break;
3130         }
3131         case XPT_PATH_INQ:
3132         {
3133                 struct cam_sim *sim;
3134
3135                 sim = start_ccb->ccb_h.path->bus->sim;
3136                 (*(sim->sim_action))(sim, start_ccb);
3137                 break;
3138         }
3139         case XPT_PATH_STATS:
3140                 start_ccb->cpis.last_reset =
3141                         start_ccb->ccb_h.path->bus->last_reset;
3142                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3143                 break;
3144         case XPT_GDEV_TYPE:
3145         {
3146                 struct cam_ed *dev;
3147
3148                 dev = start_ccb->ccb_h.path->device;
3149                 if ((dev->flags & CAM_DEV_UNCONFIGURED) != 0) {
3150                         start_ccb->ccb_h.status = CAM_DEV_NOT_THERE;
3151                 } else {
3152                         struct ccb_getdev *cgd;
3153                         struct cam_eb *bus;
3154                         struct cam_et *tar;
3155
3156                         cgd = &start_ccb->cgd;
3157                         bus = cgd->ccb_h.path->bus;
3158                         tar = cgd->ccb_h.path->target;
3159                         cgd->inq_data = dev->inq_data;
3160                         cgd->ccb_h.status = CAM_REQ_CMP;
3161                         cgd->serial_num_len = dev->serial_num_len;
3162                         if ((dev->serial_num_len > 0)
3163                          && (dev->serial_num != NULL))
3164                                 bcopy(dev->serial_num, cgd->serial_num,
3165                                       dev->serial_num_len);
3166                 }
3167                 break;
3168         }
3169         case XPT_GDEV_STATS:
3170         {
3171                 struct cam_ed *dev;
3172
3173                 dev = start_ccb->ccb_h.path->device;
3174                 if ((dev->flags & CAM_DEV_UNCONFIGURED) != 0) {
3175                         start_ccb->ccb_h.status = CAM_DEV_NOT_THERE;
3176                 } else {
3177                         struct ccb_getdevstats *cgds;
3178                         struct cam_eb *bus;
3179                         struct cam_et *tar;
3180
3181                         cgds = &start_ccb->cgds;
3182                         bus = cgds->ccb_h.path->bus;
3183                         tar = cgds->ccb_h.path->target;
3184                         cgds->dev_openings = dev->ccbq.dev_openings;
3185                         cgds->dev_active = dev->ccbq.dev_active;
3186                         cgds->devq_openings = dev->ccbq.devq_openings;
3187                         cgds->devq_queued = dev->ccbq.queue.entries;
3188                         cgds->held = dev->ccbq.held;
3189                         cgds->last_reset = tar->last_reset;
3190                         cgds->maxtags = dev->quirk->maxtags;
3191                         cgds->mintags = dev->quirk->mintags;
3192                         if (timevalcmp(&tar->last_reset, &bus->last_reset, <))
3193                                 cgds->last_reset = bus->last_reset;
3194                         cgds->ccb_h.status = CAM_REQ_CMP;
3195                 }
3196                 break;
3197         }
3198         case XPT_GDEVLIST:
3199         {
3200                 struct cam_periph       *nperiph;
3201                 struct periph_list      *periph_head;
3202                 struct ccb_getdevlist   *cgdl;
3203                 u_int                   i;
3204                 struct cam_ed           *device;
3205                 int                     found;
3206
3207
3208                 found = 0;
3209
3210                 /*
3211                  * Don't want anyone mucking with our data.
3212                  */
3213                 device = start_ccb->ccb_h.path->device;
3214                 periph_head = &device->periphs;
3215                 cgdl = &start_ccb->cgdl;
3216
3217                 /*
3218                  * Check and see if the list has changed since the user
3219                  * last requested a list member.  If so, tell them that the
3220                  * list has changed, and therefore they need to start over
3221                  * from the beginning.
3222                  */
3223                 if ((cgdl->index != 0) &&
3224                     (cgdl->generation != device->generation)) {
3225                         cgdl->status = CAM_GDEVLIST_LIST_CHANGED;
3226                         break;
3227                 }
3228
3229                 /*
3230                  * Traverse the list of peripherals and attempt to find
3231                  * the requested peripheral.
3232                  */
3233                 for (nperiph = SLIST_FIRST(periph_head), i = 0;
3234                      (nperiph != NULL) && (i <= cgdl->index);
3235                      nperiph = SLIST_NEXT(nperiph, periph_links), i++) {
3236                         if (i == cgdl->index) {
3237                                 strncpy(cgdl->periph_name,
3238                                         nperiph->periph_name,
3239                                         DEV_IDLEN);
3240                                 cgdl->unit_number = nperiph->unit_number;
3241                                 found = 1;
3242                         }
3243                 }
3244                 if (found == 0) {
3245                         cgdl->status = CAM_GDEVLIST_ERROR;
3246                         break;
3247                 }
3248
3249                 if (nperiph == NULL)
3250                         cgdl->status = CAM_GDEVLIST_LAST_DEVICE;
3251                 else
3252                         cgdl->status = CAM_GDEVLIST_MORE_DEVS;
3253
3254                 cgdl->index++;
3255                 cgdl->generation = device->generation;
3256
3257                 cgdl->ccb_h.status = CAM_REQ_CMP;
3258                 break;
3259         }
3260         case XPT_DEV_MATCH:
3261         {
3262                 dev_pos_type position_type;
3263                 struct ccb_dev_match *cdm;
3264                 int ret;
3265
3266                 cdm = &start_ccb->cdm;
3267
3268                 /*
3269                  * There are two ways of getting at information in the EDT.
3270                  * The first way is via the primary EDT tree.  It starts
3271                  * with a list of busses, then a list of targets on a bus,
3272                  * then devices/luns on a target, and then peripherals on a
3273                  * device/lun.  The "other" way is by the peripheral driver
3274                  * lists.  The peripheral driver lists are organized by
3275                  * peripheral driver.  (obviously)  So it makes sense to
3276                  * use the peripheral driver list if the user is looking
3277                  * for something like "da1", or all "da" devices.  If the
3278                  * user is looking for something on a particular bus/target
3279                  * or lun, it's generally better to go through the EDT tree.
3280                  */
3281
3282                 if (cdm->pos.position_type != CAM_DEV_POS_NONE)
3283                         position_type = cdm->pos.position_type;
3284                 else {
3285                         u_int i;
3286
3287                         position_type = CAM_DEV_POS_NONE;
3288
3289                         for (i = 0; i < cdm->num_patterns; i++) {
3290                                 if ((cdm->patterns[i].type == DEV_MATCH_BUS)
3291                                  ||(cdm->patterns[i].type == DEV_MATCH_DEVICE)){
3292                                         position_type = CAM_DEV_POS_EDT;
3293                                         break;
3294                                 }
3295                         }
3296
3297                         if (cdm->num_patterns == 0)
3298                                 position_type = CAM_DEV_POS_EDT;
3299                         else if (position_type == CAM_DEV_POS_NONE)
3300                                 position_type = CAM_DEV_POS_PDRV;
3301                 }
3302
3303                 switch(position_type & CAM_DEV_POS_TYPEMASK) {
3304                 case CAM_DEV_POS_EDT:
3305                         ret = xptedtmatch(cdm);
3306                         break;
3307                 case CAM_DEV_POS_PDRV:
3308                         ret = xptperiphlistmatch(cdm);
3309                         break;
3310                 default:
3311                         cdm->status = CAM_DEV_MATCH_ERROR;
3312                         break;
3313                 }
3314
3315                 if (cdm->status == CAM_DEV_MATCH_ERROR)
3316                         start_ccb->ccb_h.status = CAM_REQ_CMP_ERR;
3317                 else
3318                         start_ccb->ccb_h.status = CAM_REQ_CMP;
3319
3320                 break;
3321         }
3322         case XPT_SASYNC_CB:
3323         {
3324                 struct ccb_setasync *csa;
3325                 struct async_node *cur_entry;
3326                 struct async_list *async_head;
3327                 u_int32_t added;
3328
3329                 csa = &start_ccb->csa;
3330                 added = csa->event_enable;
3331                 async_head = &csa->ccb_h.path->device->asyncs;
3332
3333                 /*
3334                  * If there is already an entry for us, simply
3335                  * update it.
3336                  */
3337                 cur_entry = SLIST_FIRST(async_head);
3338                 while (cur_entry != NULL) {
3339                         if ((cur_entry->callback_arg == csa->callback_arg)
3340                          && (cur_entry->callback == csa->callback))
3341                                 break;
3342                         cur_entry = SLIST_NEXT(cur_entry, links);
3343                 }
3344
3345                 if (cur_entry != NULL) {
3346                         /*
3347                          * If the request has no flags set,
3348                          * remove the entry.
3349                          */
3350                         added &= ~cur_entry->event_enable;
3351                         if (csa->event_enable == 0) {
3352                                 SLIST_REMOVE(async_head, cur_entry,
3353                                              async_node, links);
3354                                 csa->ccb_h.path->device->refcount--;
3355                                 kfree(cur_entry, M_CAMXPT);
3356                         } else {
3357                                 cur_entry->event_enable = csa->event_enable;
3358                         }
3359                 } else {
3360                         cur_entry = kmalloc(sizeof(*cur_entry), M_CAMXPT,
3361                                            M_INTWAIT);
3362                         cur_entry->event_enable = csa->event_enable;
3363                         cur_entry->callback_arg = csa->callback_arg;
3364                         cur_entry->callback = csa->callback;
3365                         SLIST_INSERT_HEAD(async_head, cur_entry, links);
3366                         csa->ccb_h.path->device->refcount++;
3367                 }
3368
3369                 /*
3370                  * Need to decouple this operation via a taskqueue so that
3371                  * the locking doesn't become a mess.
3372                  */
3373                 if ((added & (AC_FOUND_DEVICE | AC_PATH_REGISTERED)) != 0) {
3374                         struct xpt_task *task;
3375
3376                         task = kmalloc(sizeof(struct xpt_task), M_CAMXPT,
3377                                       M_INTWAIT);
3378
3379                         TASK_INIT(&task->task, 0, xpt_action_sasync_cb, task);
3380                         task->data1 = cur_entry;
3381                         task->data2 = added;
3382                         taskqueue_enqueue(taskqueue_thread[mycpuid],
3383                                           &task->task);
3384                 }
3385
3386                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3387                 break;
3388         }
3389         case XPT_REL_SIMQ:
3390         {
3391                 struct ccb_relsim *crs;
3392                 struct cam_ed *dev;
3393
3394                 crs = &start_ccb->crs;
3395                 dev = crs->ccb_h.path->device;
3396                 if (dev == NULL) {
3397
3398                         crs->ccb_h.status = CAM_DEV_NOT_THERE;
3399                         break;
3400                 }
3401
3402                 if ((crs->release_flags & RELSIM_ADJUST_OPENINGS) != 0) {
3403
3404                         if (INQ_DATA_TQ_ENABLED(&dev->inq_data)) {
3405                                 /* Don't ever go below one opening */
3406                                 if (crs->openings > 0) {
3407                                         xpt_dev_ccbq_resize(crs->ccb_h.path,
3408                                                             crs->openings);
3409
3410                                         if (bootverbose) {
3411                                                 xpt_print(crs->ccb_h.path,
3412                                                     "tagged openings now %d\n",
3413                                                     crs->openings);
3414                                         }
3415                                 }
3416                         }
3417                 }
3418
3419                 if ((crs->release_flags & RELSIM_RELEASE_AFTER_TIMEOUT) != 0) {
3420
3421                         if ((dev->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
3422
3423                                 /*
3424                                  * Just extend the old timeout and decrement
3425                                  * the freeze count so that a single timeout
3426                                  * is sufficient for releasing the queue.
3427                                  */
3428                                 start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
3429                                 callout_stop(&dev->callout);
3430                         } else {
3431
3432                                 start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
3433                         }
3434
3435                         callout_reset(&dev->callout,
3436                                       (crs->release_timeout * hz) / 1000, 
3437                                       xpt_release_devq_timeout, dev);
3438
3439                         dev->flags |= CAM_DEV_REL_TIMEOUT_PENDING;
3440
3441                 }
3442
3443                 if ((crs->release_flags & RELSIM_RELEASE_AFTER_CMDCMPLT) != 0) {
3444
3445                         if ((dev->flags & CAM_DEV_REL_ON_COMPLETE) != 0) {
3446                                 /*
3447                                  * Decrement the freeze count so that a single
3448                                  * completion is still sufficient to unfreeze
3449                                  * the queue.
3450                                  */
3451                                 start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
3452                         } else {
3453
3454                                 dev->flags |= CAM_DEV_REL_ON_COMPLETE;
3455                                 start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
3456                         }
3457                 }
3458
3459                 if ((crs->release_flags & RELSIM_RELEASE_AFTER_QEMPTY) != 0) {
3460
3461                         if ((dev->flags & CAM_DEV_REL_ON_QUEUE_EMPTY) != 0
3462                          || (dev->ccbq.dev_active == 0)) {
3463
3464                                 start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
3465                         } else {
3466
3467                                 dev->flags |= CAM_DEV_REL_ON_QUEUE_EMPTY;
3468                                 start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
3469                         }
3470                 }
3471                 
3472                 if ((start_ccb->ccb_h.flags & CAM_DEV_QFREEZE) == 0) {
3473
3474                         xpt_release_devq(crs->ccb_h.path, /*count*/1,
3475                                          /*run_queue*/TRUE);
3476                 }
3477                 start_ccb->crs.qfrozen_cnt = dev->qfrozen_cnt;
3478                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3479                 break;
3480         }
3481         case XPT_SCAN_BUS:
3482                 xpt_scan_bus(start_ccb->ccb_h.path->periph, start_ccb);
3483                 break;
3484         case XPT_SCAN_LUN:
3485                 xpt_scan_lun(start_ccb->ccb_h.path->periph,
3486                              start_ccb->ccb_h.path, start_ccb->crcn.flags,
3487                              start_ccb);
3488                 break;
3489         case XPT_DEBUG: {
3490 #ifdef CAMDEBUG
3491 #ifdef CAM_DEBUG_DELAY
3492                 cam_debug_delay = CAM_DEBUG_DELAY;
3493 #endif
3494                 cam_dflags = start_ccb->cdbg.flags;
3495                 if (cam_dpath != NULL) {
3496                         xpt_free_path(cam_dpath);
3497                         cam_dpath = NULL;
3498                 }
3499
3500                 if (cam_dflags != CAM_DEBUG_NONE) {
3501                         if (xpt_create_path(&cam_dpath, xpt_periph,
3502                                             start_ccb->ccb_h.path_id,
3503                                             start_ccb->ccb_h.target_id,
3504                                             start_ccb->ccb_h.target_lun) !=
3505                                             CAM_REQ_CMP) {
3506                                 start_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
3507                                 cam_dflags = CAM_DEBUG_NONE;
3508                         } else {
3509                                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3510                                 xpt_print(cam_dpath, "debugging flags now %x\n",
3511                                     cam_dflags);
3512                         }
3513                 } else {
3514                         cam_dpath = NULL;
3515                         start_ccb->ccb_h.status = CAM_REQ_CMP;
3516                 }
3517 #else /* !CAMDEBUG */
3518                 start_ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
3519 #endif /* CAMDEBUG */
3520                 break;
3521         }
3522         case XPT_NOOP:
3523                 if ((start_ccb->ccb_h.flags & CAM_DEV_QFREEZE) != 0)
3524                         xpt_freeze_devq(start_ccb->ccb_h.path, 1);
3525                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3526                 break;
3527         default:
3528         case XPT_SDEV_TYPE:
3529         case XPT_TERM_IO:
3530         case XPT_ENG_INQ:
3531                 /* XXX Implement */
3532                 start_ccb->ccb_h.status = CAM_PROVIDE_FAIL;
3533                 break;
3534         }
3535 }
3536
3537 void
3538 xpt_polled_action(union ccb *start_ccb)
3539 {
3540         u_int32_t timeout;
3541         struct    cam_sim *sim;
3542         struct    cam_devq *devq;
3543         struct    cam_ed *dev;
3544
3545         timeout = start_ccb->ccb_h.timeout;
3546         sim = start_ccb->ccb_h.path->bus->sim;
3547         devq = sim->devq;
3548         dev = start_ccb->ccb_h.path->device;
3549
3550         sim_lock_assert_owned(sim->lock);
3551
3552         /*
3553          * Steal an opening so that no other queued requests
3554          * can get it before us while we simulate interrupts.
3555          */
3556         dev->ccbq.devq_openings--;
3557         dev->ccbq.dev_openings--;
3558
3559         while(((devq && devq->send_openings <= 0) || dev->ccbq.dev_openings < 0)
3560            && (--timeout > 0)) {
3561                 DELAY(1000);
3562                 (*(sim->sim_poll))(sim);
3563                 camisr_runqueue(sim);
3564         }
3565
3566         dev->ccbq.devq_openings++;
3567         dev->ccbq.dev_openings++;
3568
3569         if (timeout != 0) {
3570                 xpt_action(start_ccb);
3571                 while(--timeout > 0) {
3572                         (*(sim->sim_poll))(sim);
3573                         camisr_runqueue(sim);
3574                         if ((start_ccb->ccb_h.status  & CAM_STATUS_MASK)
3575                             != CAM_REQ_INPROG)
3576                                 break;
3577                         DELAY(1000);
3578                 }
3579                 if (timeout == 0) {
3580                         /*
3581                          * XXX Is it worth adding a sim_timeout entry
3582                          * point so we can attempt recovery?  If
3583                          * this is only used for dumps, I don't think
3584                          * it is.
3585                          */
3586                         start_ccb->ccb_h.status = CAM_CMD_TIMEOUT;
3587                 }
3588         } else {
3589                 start_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
3590         }
3591 }
3592
3593 /*
3594  * Schedule a peripheral driver to receive a ccb when it's
3595  * target device has space for more transactions.
3596  */
3597 void
3598 xpt_schedule(struct cam_periph *perph, u_int32_t new_priority)
3599 {
3600         struct cam_ed *device;
3601         union ccb *work_ccb;
3602         int runq;
3603
3604         sim_lock_assert_owned(perph->sim->lock);
3605
3606         CAM_DEBUG(perph->path, CAM_DEBUG_TRACE, ("xpt_schedule\n"));
3607         device = perph->path->device;
3608         if (periph_is_queued(perph)) {
3609                 /* Simply reorder based on new priority */
3610                 CAM_DEBUG(perph->path, CAM_DEBUG_SUBTRACE,
3611                           ("   change priority to %d\n", new_priority));
3612                 if (new_priority < perph->pinfo.priority) {
3613                         camq_change_priority(&device->drvq,
3614                                              perph->pinfo.index,
3615                                              new_priority);
3616                 }
3617                 runq = 0;
3618         } else if (perph->path->bus->sim == &cam_dead_sim) {
3619                 /* The SIM is gone so just call periph_start directly. */
3620                 work_ccb = xpt_get_ccb(perph->path->device);
3621                 if (work_ccb == NULL)
3622                         return; /* XXX */
3623                 xpt_setup_ccb(&work_ccb->ccb_h, perph->path, new_priority);
3624                 perph->pinfo.priority = new_priority;
3625                 perph->periph_start(perph, work_ccb);
3626                 return;
3627         } else {
3628                 /* New entry on the queue */
3629                 CAM_DEBUG(perph->path, CAM_DEBUG_SUBTRACE,
3630                           ("   added periph to queue\n"));
3631                 perph->pinfo.priority = new_priority;
3632                 perph->pinfo.generation = ++device->drvq.generation;
3633                 camq_insert(&device->drvq, &perph->pinfo);
3634                 runq = xpt_schedule_dev_allocq(perph->path->bus, device);
3635         }
3636         if (runq != 0) {
3637                 CAM_DEBUG(perph->path, CAM_DEBUG_SUBTRACE,
3638                           ("   calling xpt_run_devq\n"));
3639                 xpt_run_dev_allocq(perph->path->bus);
3640         }
3641 }
3642
3643
3644 /*
3645  * Schedule a device to run on a given queue.
3646  * If the device was inserted as a new entry on the queue,
3647  * return 1 meaning the device queue should be run. If we
3648  * were already queued, implying someone else has already
3649  * started the queue, return 0 so the caller doesn't attempt
3650  * to run the queue.
3651  */
3652 static int
3653 xpt_schedule_dev(struct camq *queue, cam_pinfo *pinfo,
3654                  u_int32_t new_priority)
3655 {
3656         int retval;
3657         u_int32_t old_priority;
3658
3659         CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_schedule_dev\n"));
3660
3661         old_priority = pinfo->priority;
3662
3663         /*
3664          * Are we already queued?
3665          */
3666         if (pinfo->index != CAM_UNQUEUED_INDEX) {
3667                 /* Simply reorder based on new priority */
3668                 if (new_priority < old_priority) {
3669                         camq_change_priority(queue, pinfo->index,
3670                                              new_priority);
3671                         CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3672                                         ("changed priority to %d\n",
3673                                          new_priority));
3674                 }
3675                 retval = 0;
3676         } else {
3677                 /* New entry on the queue */
3678                 if (new_priority < old_priority)
3679                         pinfo->priority = new_priority;
3680
3681                 CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3682                                 ("Inserting onto queue\n"));
3683                 pinfo->generation = ++queue->generation;
3684                 camq_insert(queue, pinfo);
3685                 retval = 1;
3686         }
3687         return (retval);
3688 }
3689
3690 static void
3691 xpt_run_dev_allocq(struct cam_eb *bus)
3692 {
3693         struct  cam_devq *devq;
3694
3695         if ((devq = bus->sim->devq) == NULL) {
3696                 CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_dev_allocq: NULL devq\n"));
3697                 return;
3698         }
3699         CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_dev_allocq\n"));
3700
3701         CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3702                         ("   qfrozen_cnt == 0x%x, entries == %d, "
3703                          "openings == %d, active == %d\n",
3704                          devq->alloc_queue.qfrozen_cnt,
3705                          devq->alloc_queue.entries,
3706                          devq->alloc_openings,
3707                          devq->alloc_active));
3708
3709         devq->alloc_queue.qfrozen_cnt++;
3710         while ((devq->alloc_queue.entries > 0)
3711             && (devq->alloc_openings > 0)
3712             && (devq->alloc_queue.qfrozen_cnt <= 1)) {
3713                 struct  cam_ed_qinfo *qinfo;
3714                 struct  cam_ed *device;
3715                 union   ccb *work_ccb;
3716                 struct  cam_periph *drv;
3717                 struct  camq *drvq;
3718
3719                 qinfo = (struct cam_ed_qinfo *)camq_remove(&devq->alloc_queue,
3720                                                            CAMQ_HEAD);
3721                 device = qinfo->device;
3722
3723                 CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3724                                 ("running device %p\n", device));
3725
3726                 drvq = &device->drvq;
3727
3728 #ifdef CAMDEBUG
3729                 if (drvq->entries <= 0) {
3730                         panic("xpt_run_dev_allocq: "
3731                               "Device on queue without any work to do");
3732                 }
3733 #endif
3734                 if ((work_ccb = xpt_get_ccb(device)) != NULL) {
3735                         devq->alloc_openings--;
3736                         devq->alloc_active++;
3737                         drv = (struct cam_periph*)camq_remove(drvq, CAMQ_HEAD);
3738                         xpt_setup_ccb(&work_ccb->ccb_h, drv->path,
3739                                       drv->pinfo.priority);
3740                         CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3741                                         ("calling periph start\n"));
3742                         drv->periph_start(drv, work_ccb);
3743                 } else {
3744                         /*
3745                          * Malloc failure in alloc_ccb
3746                          */
3747                         /*
3748                          * XXX add us to a list to be run from free_ccb
3749                          * if we don't have any ccbs active on this
3750                          * device queue otherwise we may never get run
3751                          * again.
3752                          */
3753                         break;
3754                 }
3755
3756                 if (drvq->entries > 0) {
3757                         /* We have more work.  Attempt to reschedule */
3758                         xpt_schedule_dev_allocq(bus, device);
3759                 }
3760         }
3761         devq->alloc_queue.qfrozen_cnt--;
3762 }
3763
3764 static void
3765 xpt_run_dev_sendq(struct cam_eb *bus)
3766 {
3767         struct  cam_devq *devq;
3768
3769         if ((devq = bus->sim->devq) == NULL) {
3770                 CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_dev_sendq: NULL devq\n"));
3771                 return;
3772         }
3773         CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_dev_sendq\n"));
3774
3775         devq->send_queue.qfrozen_cnt++;
3776         while ((devq->send_queue.entries > 0)
3777             && (devq->send_openings > 0)) {
3778                 struct  cam_ed_qinfo *qinfo;
3779                 struct  cam_ed *device;
3780                 union ccb *work_ccb;
3781                 struct  cam_sim *sim;
3782
3783                 if (devq->send_queue.qfrozen_cnt > 1) {
3784                         break;
3785                 }
3786
3787                 qinfo = (struct cam_ed_qinfo *)camq_remove(&devq->send_queue,
3788                                                            CAMQ_HEAD);
3789                 device = qinfo->device;
3790
3791                 /*
3792                  * If the device has been "frozen", don't attempt
3793                  * to run it.
3794                  */
3795                 if (device->qfrozen_cnt > 0) {
3796                         continue;
3797                 }
3798
3799                 CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3800                                 ("running device %p\n", device));
3801
3802                 work_ccb = cam_ccbq_peek_ccb(&device->ccbq, CAMQ_HEAD);
3803                 if (work_ccb == NULL) {
3804                         kprintf("device on run queue with no ccbs???\n");
3805                         continue;
3806         &n