]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/cam/cam_xpt.c
MFC r241456:
[FreeBSD/stable/9.git] / sys / cam / cam_xpt.c
1 /*-
2  * Implementation of the Common Access Method Transport (XPT) layer.
3  *
4  * Copyright (c) 1997, 1998, 1999 Justin T. Gibbs.
5  * Copyright (c) 1997, 1998, 1999 Kenneth D. Merry.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions, and the following disclaimer,
13  *    without modification, immediately at the beginning of the file.
14  * 2. The name of the author may not be used to endorse or promote products
15  *    derived from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
21  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32
33 #include <sys/param.h>
34 #include <sys/bus.h>
35 #include <sys/systm.h>
36 #include <sys/types.h>
37 #include <sys/malloc.h>
38 #include <sys/kernel.h>
39 #include <sys/time.h>
40 #include <sys/conf.h>
41 #include <sys/fcntl.h>
42 #include <sys/interrupt.h>
43 #include <sys/sbuf.h>
44 #include <sys/taskqueue.h>
45
46 #include <sys/lock.h>
47 #include <sys/mutex.h>
48 #include <sys/sysctl.h>
49 #include <sys/kthread.h>
50
51 #include <cam/cam.h>
52 #include <cam/cam_ccb.h>
53 #include <cam/cam_periph.h>
54 #include <cam/cam_queue.h>
55 #include <cam/cam_sim.h>
56 #include <cam/cam_xpt.h>
57 #include <cam/cam_xpt_sim.h>
58 #include <cam/cam_xpt_periph.h>
59 #include <cam/cam_xpt_internal.h>
60 #include <cam/cam_debug.h>
61
62 #include <cam/scsi/scsi_all.h>
63 #include <cam/scsi/scsi_message.h>
64 #include <cam/scsi/scsi_pass.h>
65
66 #include <machine/md_var.h>     /* geometry translation */
67 #include <machine/stdarg.h>     /* for xpt_print below */
68
69 #include "opt_cam.h"
70
71 /*
72  * This is the maximum number of high powered commands (e.g. start unit)
73  * that can be outstanding at a particular time.
74  */
75 #ifndef CAM_MAX_HIGHPOWER
76 #define CAM_MAX_HIGHPOWER  4
77 #endif
78
79 /* Datastructures internal to the xpt layer */
80 MALLOC_DEFINE(M_CAMXPT, "CAM XPT", "CAM XPT buffers");
81 MALLOC_DEFINE(M_CAMDEV, "CAM DEV", "CAM devices");
82 MALLOC_DEFINE(M_CAMCCB, "CAM CCB", "CAM CCBs");
83 MALLOC_DEFINE(M_CAMPATH, "CAM path", "CAM paths");
84
85 /* Object for defering XPT actions to a taskqueue */
86 struct xpt_task {
87         struct task     task;
88         void            *data1;
89         uintptr_t       data2;
90 };
91
92 typedef enum {
93         XPT_FLAG_OPEN           = 0x01
94 } xpt_flags;
95
96 struct xpt_softc {
97         xpt_flags               flags;
98         u_int32_t               xpt_generation;
99
100         /* number of high powered commands that can go through right now */
101         STAILQ_HEAD(highpowerlist, ccb_hdr)     highpowerq;
102         int                     num_highpower;
103
104         /* queue for handling async rescan requests. */
105         TAILQ_HEAD(, ccb_hdr) ccb_scanq;
106         int buses_to_config;
107         int buses_config_done;
108
109         /* Registered busses */
110         TAILQ_HEAD(,cam_eb)     xpt_busses;
111         u_int                   bus_generation;
112
113         struct intr_config_hook *xpt_config_hook;
114
115         int                     boot_delay;
116         struct callout          boot_callout;
117
118         struct mtx              xpt_topo_lock;
119         struct mtx              xpt_lock;
120 };
121
122 typedef enum {
123         DM_RET_COPY             = 0x01,
124         DM_RET_FLAG_MASK        = 0x0f,
125         DM_RET_NONE             = 0x00,
126         DM_RET_STOP             = 0x10,
127         DM_RET_DESCEND          = 0x20,
128         DM_RET_ERROR            = 0x30,
129         DM_RET_ACTION_MASK      = 0xf0
130 } dev_match_ret;
131
132 typedef enum {
133         XPT_DEPTH_BUS,
134         XPT_DEPTH_TARGET,
135         XPT_DEPTH_DEVICE,
136         XPT_DEPTH_PERIPH
137 } xpt_traverse_depth;
138
139 struct xpt_traverse_config {
140         xpt_traverse_depth      depth;
141         void                    *tr_func;
142         void                    *tr_arg;
143 };
144
145 typedef int     xpt_busfunc_t (struct cam_eb *bus, void *arg);
146 typedef int     xpt_targetfunc_t (struct cam_et *target, void *arg);
147 typedef int     xpt_devicefunc_t (struct cam_ed *device, void *arg);
148 typedef int     xpt_periphfunc_t (struct cam_periph *periph, void *arg);
149 typedef int     xpt_pdrvfunc_t (struct periph_driver **pdrv, void *arg);
150
151 /* Transport layer configuration information */
152 static struct xpt_softc xsoftc;
153
154 TUNABLE_INT("kern.cam.boot_delay", &xsoftc.boot_delay);
155 SYSCTL_INT(_kern_cam, OID_AUTO, boot_delay, CTLFLAG_RDTUN,
156            &xsoftc.boot_delay, 0, "Bus registration wait time");
157
158 /* Queues for our software interrupt handler */
159 typedef TAILQ_HEAD(cam_isrq, ccb_hdr) cam_isrq_t;
160 typedef TAILQ_HEAD(cam_simq, cam_sim) cam_simq_t;
161 static cam_simq_t cam_simq;
162 static struct mtx cam_simq_lock;
163
164 /* Pointers to software interrupt handlers */
165 static void *cambio_ih;
166
167 struct cam_periph *xpt_periph;
168
169 static periph_init_t xpt_periph_init;
170
171 static struct periph_driver xpt_driver =
172 {
173         xpt_periph_init, "xpt",
174         TAILQ_HEAD_INITIALIZER(xpt_driver.units), /* generation */ 0,
175         CAM_PERIPH_DRV_EARLY
176 };
177
178 PERIPHDRIVER_DECLARE(xpt, xpt_driver);
179
180 static d_open_t xptopen;
181 static d_close_t xptclose;
182 static d_ioctl_t xptioctl;
183
184 static struct cdevsw xpt_cdevsw = {
185         .d_version =    D_VERSION,
186         .d_flags =      0,
187         .d_open =       xptopen,
188         .d_close =      xptclose,
189         .d_ioctl =      xptioctl,
190         .d_name =       "xpt",
191 };
192
193 /* Storage for debugging datastructures */
194 struct cam_path *cam_dpath;
195 u_int32_t cam_dflags = CAM_DEBUG_FLAGS;
196 TUNABLE_INT("kern.cam.dflags", &cam_dflags);
197 SYSCTL_UINT(_kern_cam, OID_AUTO, dflags, CTLFLAG_RW,
198         &cam_dflags, 0, "Enabled debug flags");
199 u_int32_t cam_debug_delay = CAM_DEBUG_DELAY;
200 TUNABLE_INT("kern.cam.debug_delay", &cam_debug_delay);
201 SYSCTL_UINT(_kern_cam, OID_AUTO, debug_delay, CTLFLAG_RW,
202         &cam_debug_delay, 0, "Delay in us after each debug message");
203
204 /* Our boot-time initialization hook */
205 static int cam_module_event_handler(module_t, int /*modeventtype_t*/, void *);
206
207 static moduledata_t cam_moduledata = {
208         "cam",
209         cam_module_event_handler,
210         NULL
211 };
212
213 static int      xpt_init(void *);
214
215 DECLARE_MODULE(cam, cam_moduledata, SI_SUB_CONFIGURE, SI_ORDER_SECOND);
216 MODULE_VERSION(cam, 1);
217
218
219 static void             xpt_async_bcast(struct async_list *async_head,
220                                         u_int32_t async_code,
221                                         struct cam_path *path,
222                                         void *async_arg);
223 static path_id_t xptnextfreepathid(void);
224 static path_id_t xptpathid(const char *sim_name, int sim_unit, int sim_bus);
225 static union ccb *xpt_get_ccb(struct cam_ed *device);
226 static void      xpt_run_dev_allocq(struct cam_eb *bus);
227 static void      xpt_run_dev_sendq(struct cam_eb *bus);
228 static timeout_t xpt_release_devq_timeout;
229 static void      xpt_release_simq_timeout(void *arg) __unused;
230 static void      xpt_release_bus(struct cam_eb *bus);
231 static void      xpt_release_devq_device(struct cam_ed *dev, cam_rl rl,
232                     u_int count, int run_queue);
233 static struct cam_et*
234                  xpt_alloc_target(struct cam_eb *bus, target_id_t target_id);
235 static void      xpt_release_target(struct cam_et *target);
236 static struct cam_eb*
237                  xpt_find_bus(path_id_t path_id);
238 static struct cam_et*
239                  xpt_find_target(struct cam_eb *bus, target_id_t target_id);
240 static struct cam_ed*
241                  xpt_find_device(struct cam_et *target, lun_id_t lun_id);
242 static void      xpt_config(void *arg);
243 static xpt_devicefunc_t xptpassannouncefunc;
244 static void      xptaction(struct cam_sim *sim, union ccb *work_ccb);
245 static void      xptpoll(struct cam_sim *sim);
246 static void      camisr(void *);
247 static void      camisr_runqueue(void *);
248 static dev_match_ret    xptbusmatch(struct dev_match_pattern *patterns,
249                                     u_int num_patterns, struct cam_eb *bus);
250 static dev_match_ret    xptdevicematch(struct dev_match_pattern *patterns,
251                                        u_int num_patterns,
252                                        struct cam_ed *device);
253 static dev_match_ret    xptperiphmatch(struct dev_match_pattern *patterns,
254                                        u_int num_patterns,
255                                        struct cam_periph *periph);
256 static xpt_busfunc_t    xptedtbusfunc;
257 static xpt_targetfunc_t xptedttargetfunc;
258 static xpt_devicefunc_t xptedtdevicefunc;
259 static xpt_periphfunc_t xptedtperiphfunc;
260 static xpt_pdrvfunc_t   xptplistpdrvfunc;
261 static xpt_periphfunc_t xptplistperiphfunc;
262 static int              xptedtmatch(struct ccb_dev_match *cdm);
263 static int              xptperiphlistmatch(struct ccb_dev_match *cdm);
264 static int              xptbustraverse(struct cam_eb *start_bus,
265                                        xpt_busfunc_t *tr_func, void *arg);
266 static int              xpttargettraverse(struct cam_eb *bus,
267                                           struct cam_et *start_target,
268                                           xpt_targetfunc_t *tr_func, void *arg);
269 static int              xptdevicetraverse(struct cam_et *target,
270                                           struct cam_ed *start_device,
271                                           xpt_devicefunc_t *tr_func, void *arg);
272 static int              xptperiphtraverse(struct cam_ed *device,
273                                           struct cam_periph *start_periph,
274                                           xpt_periphfunc_t *tr_func, void *arg);
275 static int              xptpdrvtraverse(struct periph_driver **start_pdrv,
276                                         xpt_pdrvfunc_t *tr_func, void *arg);
277 static int              xptpdperiphtraverse(struct periph_driver **pdrv,
278                                             struct cam_periph *start_periph,
279                                             xpt_periphfunc_t *tr_func,
280                                             void *arg);
281 static xpt_busfunc_t    xptdefbusfunc;
282 static xpt_targetfunc_t xptdeftargetfunc;
283 static xpt_devicefunc_t xptdefdevicefunc;
284 static xpt_periphfunc_t xptdefperiphfunc;
285 static void             xpt_finishconfig_task(void *context, int pending);
286 static void             xpt_dev_async_default(u_int32_t async_code,
287                                               struct cam_eb *bus,
288                                               struct cam_et *target,
289                                               struct cam_ed *device,
290                                               void *async_arg);
291 static struct cam_ed *  xpt_alloc_device_default(struct cam_eb *bus,
292                                                  struct cam_et *target,
293                                                  lun_id_t lun_id);
294 static xpt_devicefunc_t xptsetasyncfunc;
295 static xpt_busfunc_t    xptsetasyncbusfunc;
296 static cam_status       xptregister(struct cam_periph *periph,
297                                     void *arg);
298 static __inline int periph_is_queued(struct cam_periph *periph);
299 static __inline int device_is_alloc_queued(struct cam_ed *device);
300 static __inline int device_is_send_queued(struct cam_ed *device);
301
302 static __inline int
303 xpt_schedule_dev_allocq(struct cam_eb *bus, struct cam_ed *dev)
304 {
305         int retval;
306
307         if ((dev->drvq.entries > 0) &&
308             (dev->ccbq.devq_openings > 0) &&
309             (cam_ccbq_frozen(&dev->ccbq, CAM_PRIORITY_TO_RL(
310                 CAMQ_GET_PRIO(&dev->drvq))) == 0)) {
311                 /*
312                  * The priority of a device waiting for CCB resources
313                  * is that of the highest priority peripheral driver
314                  * enqueued.
315                  */
316                 retval = xpt_schedule_dev(&bus->sim->devq->alloc_queue,
317                                           &dev->alloc_ccb_entry.pinfo,
318                                           CAMQ_GET_PRIO(&dev->drvq));
319         } else {
320                 retval = 0;
321         }
322
323         return (retval);
324 }
325
326 static __inline int
327 xpt_schedule_dev_sendq(struct cam_eb *bus, struct cam_ed *dev)
328 {
329         int     retval;
330
331         if ((dev->ccbq.queue.entries > 0) &&
332             (dev->ccbq.dev_openings > 0) &&
333             (cam_ccbq_frozen_top(&dev->ccbq) == 0)) {
334                 /*
335                  * The priority of a device waiting for controller
336                  * resources is that of the highest priority CCB
337                  * enqueued.
338                  */
339                 retval =
340                     xpt_schedule_dev(&bus->sim->devq->send_queue,
341                                      &dev->send_ccb_entry.pinfo,
342                                      CAMQ_GET_PRIO(&dev->ccbq.queue));
343         } else {
344                 retval = 0;
345         }
346         return (retval);
347 }
348
349 static __inline int
350 periph_is_queued(struct cam_periph *periph)
351 {
352         return (periph->pinfo.index != CAM_UNQUEUED_INDEX);
353 }
354
355 static __inline int
356 device_is_alloc_queued(struct cam_ed *device)
357 {
358         return (device->alloc_ccb_entry.pinfo.index != CAM_UNQUEUED_INDEX);
359 }
360
361 static __inline int
362 device_is_send_queued(struct cam_ed *device)
363 {
364         return (device->send_ccb_entry.pinfo.index != CAM_UNQUEUED_INDEX);
365 }
366
367 static void
368 xpt_periph_init()
369 {
370         make_dev(&xpt_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600, "xpt0");
371 }
372
373 static void
374 xptdone(struct cam_periph *periph, union ccb *done_ccb)
375 {
376         /* Caller will release the CCB */
377         wakeup(&done_ccb->ccb_h.cbfcnp);
378 }
379
380 static int
381 xptopen(struct cdev *dev, int flags, int fmt, struct thread *td)
382 {
383
384         /*
385          * Only allow read-write access.
386          */
387         if (((flags & FWRITE) == 0) || ((flags & FREAD) == 0))
388                 return(EPERM);
389
390         /*
391          * We don't allow nonblocking access.
392          */
393         if ((flags & O_NONBLOCK) != 0) {
394                 printf("%s: can't do nonblocking access\n", devtoname(dev));
395                 return(ENODEV);
396         }
397
398         /* Mark ourselves open */
399         mtx_lock(&xsoftc.xpt_lock);
400         xsoftc.flags |= XPT_FLAG_OPEN;
401         mtx_unlock(&xsoftc.xpt_lock);
402
403         return(0);
404 }
405
406 static int
407 xptclose(struct cdev *dev, int flag, int fmt, struct thread *td)
408 {
409
410         /* Mark ourselves closed */
411         mtx_lock(&xsoftc.xpt_lock);
412         xsoftc.flags &= ~XPT_FLAG_OPEN;
413         mtx_unlock(&xsoftc.xpt_lock);
414
415         return(0);
416 }
417
418 /*
419  * Don't automatically grab the xpt softc lock here even though this is going
420  * through the xpt device.  The xpt device is really just a back door for
421  * accessing other devices and SIMs, so the right thing to do is to grab
422  * the appropriate SIM lock once the bus/SIM is located.
423  */
424 static int
425 xptioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
426 {
427         int error;
428
429         error = 0;
430
431         switch(cmd) {
432         /*
433          * For the transport layer CAMIOCOMMAND ioctl, we really only want
434          * to accept CCB types that don't quite make sense to send through a
435          * passthrough driver. XPT_PATH_INQ is an exception to this, as stated
436          * in the CAM spec.
437          */
438         case CAMIOCOMMAND: {
439                 union ccb *ccb;
440                 union ccb *inccb;
441                 struct cam_eb *bus;
442
443                 inccb = (union ccb *)addr;
444
445                 bus = xpt_find_bus(inccb->ccb_h.path_id);
446                 if (bus == NULL)
447                         return (EINVAL);
448
449                 switch (inccb->ccb_h.func_code) {
450                 case XPT_SCAN_BUS:
451                 case XPT_RESET_BUS:
452                         if (inccb->ccb_h.target_id != CAM_TARGET_WILDCARD ||
453                             inccb->ccb_h.target_lun != CAM_LUN_WILDCARD) {
454                                 xpt_release_bus(bus);
455                                 return (EINVAL);
456                         }
457                         break;
458                 case XPT_SCAN_TGT:
459                         if (inccb->ccb_h.target_id == CAM_TARGET_WILDCARD ||
460                             inccb->ccb_h.target_lun != CAM_LUN_WILDCARD) {
461                                 xpt_release_bus(bus);
462                                 return (EINVAL);
463                         }
464                         break;
465                 default:
466                         break;
467                 }
468
469                 switch(inccb->ccb_h.func_code) {
470                 case XPT_SCAN_BUS:
471                 case XPT_RESET_BUS:
472                 case XPT_PATH_INQ:
473                 case XPT_ENG_INQ:
474                 case XPT_SCAN_LUN:
475                 case XPT_SCAN_TGT:
476
477                         ccb = xpt_alloc_ccb();
478
479                         CAM_SIM_LOCK(bus->sim);
480
481                         /*
482                          * Create a path using the bus, target, and lun the
483                          * user passed in.
484                          */
485                         if (xpt_create_path(&ccb->ccb_h.path, xpt_periph,
486                                             inccb->ccb_h.path_id,
487                                             inccb->ccb_h.target_id,
488                                             inccb->ccb_h.target_lun) !=
489                                             CAM_REQ_CMP){
490                                 error = EINVAL;
491                                 CAM_SIM_UNLOCK(bus->sim);
492                                 xpt_free_ccb(ccb);
493                                 break;
494                         }
495                         /* Ensure all of our fields are correct */
496                         xpt_setup_ccb(&ccb->ccb_h, ccb->ccb_h.path,
497                                       inccb->ccb_h.pinfo.priority);
498                         xpt_merge_ccb(ccb, inccb);
499                         ccb->ccb_h.cbfcnp = xptdone;
500                         cam_periph_runccb(ccb, NULL, 0, 0, NULL);
501                         bcopy(ccb, inccb, sizeof(union ccb));
502                         xpt_free_path(ccb->ccb_h.path);
503                         xpt_free_ccb(ccb);
504                         CAM_SIM_UNLOCK(bus->sim);
505                         break;
506
507                 case XPT_DEBUG: {
508                         union ccb ccb;
509
510                         /*
511                          * This is an immediate CCB, so it's okay to
512                          * allocate it on the stack.
513                          */
514
515                         CAM_SIM_LOCK(bus->sim);
516
517                         /*
518                          * Create a path using the bus, target, and lun the
519                          * user passed in.
520                          */
521                         if (xpt_create_path(&ccb.ccb_h.path, xpt_periph,
522                                             inccb->ccb_h.path_id,
523                                             inccb->ccb_h.target_id,
524                                             inccb->ccb_h.target_lun) !=
525                                             CAM_REQ_CMP){
526                                 error = EINVAL;
527                                 CAM_SIM_UNLOCK(bus->sim);
528                                 break;
529                         }
530                         /* Ensure all of our fields are correct */
531                         xpt_setup_ccb(&ccb.ccb_h, ccb.ccb_h.path,
532                                       inccb->ccb_h.pinfo.priority);
533                         xpt_merge_ccb(&ccb, inccb);
534                         ccb.ccb_h.cbfcnp = xptdone;
535                         xpt_action(&ccb);
536                         CAM_SIM_UNLOCK(bus->sim);
537                         bcopy(&ccb, inccb, sizeof(union ccb));
538                         xpt_free_path(ccb.ccb_h.path);
539                         break;
540
541                 }
542                 case XPT_DEV_MATCH: {
543                         struct cam_periph_map_info mapinfo;
544                         struct cam_path *old_path;
545
546                         /*
547                          * We can't deal with physical addresses for this
548                          * type of transaction.
549                          */
550                         if (inccb->ccb_h.flags & CAM_DATA_PHYS) {
551                                 error = EINVAL;
552                                 break;
553                         }
554
555                         /*
556                          * Save this in case the caller had it set to
557                          * something in particular.
558                          */
559                         old_path = inccb->ccb_h.path;
560
561                         /*
562                          * We really don't need a path for the matching
563                          * code.  The path is needed because of the
564                          * debugging statements in xpt_action().  They
565                          * assume that the CCB has a valid path.
566                          */
567                         inccb->ccb_h.path = xpt_periph->path;
568
569                         bzero(&mapinfo, sizeof(mapinfo));
570
571                         /*
572                          * Map the pattern and match buffers into kernel
573                          * virtual address space.
574                          */
575                         error = cam_periph_mapmem(inccb, &mapinfo);
576
577                         if (error) {
578                                 inccb->ccb_h.path = old_path;
579                                 break;
580                         }
581
582                         /*
583                          * This is an immediate CCB, we can send it on directly.
584                          */
585                         xpt_action(inccb);
586
587                         /*
588                          * Map the buffers back into user space.
589                          */
590                         cam_periph_unmapmem(inccb, &mapinfo);
591
592                         inccb->ccb_h.path = old_path;
593
594                         error = 0;
595                         break;
596                 }
597                 default:
598                         error = ENOTSUP;
599                         break;
600                 }
601                 xpt_release_bus(bus);
602                 break;
603         }
604         /*
605          * This is the getpassthru ioctl. It takes a XPT_GDEVLIST ccb as input,
606          * with the periphal driver name and unit name filled in.  The other
607          * fields don't really matter as input.  The passthrough driver name
608          * ("pass"), and unit number are passed back in the ccb.  The current
609          * device generation number, and the index into the device peripheral
610          * driver list, and the status are also passed back.  Note that
611          * since we do everything in one pass, unlike the XPT_GDEVLIST ccb,
612          * we never return a status of CAM_GDEVLIST_LIST_CHANGED.  It is
613          * (or rather should be) impossible for the device peripheral driver
614          * list to change since we look at the whole thing in one pass, and
615          * we do it with lock protection.
616          *
617          */
618         case CAMGETPASSTHRU: {
619                 union ccb *ccb;
620                 struct cam_periph *periph;
621                 struct periph_driver **p_drv;
622                 char   *name;
623                 u_int unit;
624                 u_int cur_generation;
625                 int base_periph_found;
626                 int splbreaknum;
627
628                 ccb = (union ccb *)addr;
629                 unit = ccb->cgdl.unit_number;
630                 name = ccb->cgdl.periph_name;
631                 /*
632                  * Every 100 devices, we want to drop our lock protection to
633                  * give the software interrupt handler a chance to run.
634                  * Most systems won't run into this check, but this should
635                  * avoid starvation in the software interrupt handler in
636                  * large systems.
637                  */
638                 splbreaknum = 100;
639
640                 ccb = (union ccb *)addr;
641
642                 base_periph_found = 0;
643
644                 /*
645                  * Sanity check -- make sure we don't get a null peripheral
646                  * driver name.
647                  */
648                 if (*ccb->cgdl.periph_name == '\0') {
649                         error = EINVAL;
650                         break;
651                 }
652
653                 /* Keep the list from changing while we traverse it */
654                 mtx_lock(&xsoftc.xpt_topo_lock);
655 ptstartover:
656                 cur_generation = xsoftc.xpt_generation;
657
658                 /* first find our driver in the list of drivers */
659                 for (p_drv = periph_drivers; *p_drv != NULL; p_drv++)
660                         if (strcmp((*p_drv)->driver_name, name) == 0)
661                                 break;
662
663                 if (*p_drv == NULL) {
664                         mtx_unlock(&xsoftc.xpt_topo_lock);
665                         ccb->ccb_h.status = CAM_REQ_CMP_ERR;
666                         ccb->cgdl.status = CAM_GDEVLIST_ERROR;
667                         *ccb->cgdl.periph_name = '\0';
668                         ccb->cgdl.unit_number = 0;
669                         error = ENOENT;
670                         break;
671                 }
672
673                 /*
674                  * Run through every peripheral instance of this driver
675                  * and check to see whether it matches the unit passed
676                  * in by the user.  If it does, get out of the loops and
677                  * find the passthrough driver associated with that
678                  * peripheral driver.
679                  */
680                 for (periph = TAILQ_FIRST(&(*p_drv)->units); periph != NULL;
681                      periph = TAILQ_NEXT(periph, unit_links)) {
682
683                         if (periph->unit_number == unit) {
684                                 break;
685                         } else if (--splbreaknum == 0) {
686                                 mtx_unlock(&xsoftc.xpt_topo_lock);
687                                 mtx_lock(&xsoftc.xpt_topo_lock);
688                                 splbreaknum = 100;
689                                 if (cur_generation != xsoftc.xpt_generation)
690                                        goto ptstartover;
691                         }
692                 }
693                 /*
694                  * If we found the peripheral driver that the user passed
695                  * in, go through all of the peripheral drivers for that
696                  * particular device and look for a passthrough driver.
697                  */
698                 if (periph != NULL) {
699                         struct cam_ed *device;
700                         int i;
701
702                         base_periph_found = 1;
703                         device = periph->path->device;
704                         for (i = 0, periph = SLIST_FIRST(&device->periphs);
705                              periph != NULL;
706                              periph = SLIST_NEXT(periph, periph_links), i++) {
707                                 /*
708                                  * Check to see whether we have a
709                                  * passthrough device or not.
710                                  */
711                                 if (strcmp(periph->periph_name, "pass") == 0) {
712                                         /*
713                                          * Fill in the getdevlist fields.
714                                          */
715                                         strcpy(ccb->cgdl.periph_name,
716                                                periph->periph_name);
717                                         ccb->cgdl.unit_number =
718                                                 periph->unit_number;
719                                         if (SLIST_NEXT(periph, periph_links))
720                                                 ccb->cgdl.status =
721                                                         CAM_GDEVLIST_MORE_DEVS;
722                                         else
723                                                 ccb->cgdl.status =
724                                                        CAM_GDEVLIST_LAST_DEVICE;
725                                         ccb->cgdl.generation =
726                                                 device->generation;
727                                         ccb->cgdl.index = i;
728                                         /*
729                                          * Fill in some CCB header fields
730                                          * that the user may want.
731                                          */
732                                         ccb->ccb_h.path_id =
733                                                 periph->path->bus->path_id;
734                                         ccb->ccb_h.target_id =
735                                                 periph->path->target->target_id;
736                                         ccb->ccb_h.target_lun =
737                                                 periph->path->device->lun_id;
738                                         ccb->ccb_h.status = CAM_REQ_CMP;
739                                         break;
740                                 }
741                         }
742                 }
743
744                 /*
745                  * If the periph is null here, one of two things has
746                  * happened.  The first possibility is that we couldn't
747                  * find the unit number of the particular peripheral driver
748                  * that the user is asking about.  e.g. the user asks for
749                  * the passthrough driver for "da11".  We find the list of
750                  * "da" peripherals all right, but there is no unit 11.
751                  * The other possibility is that we went through the list
752                  * of peripheral drivers attached to the device structure,
753                  * but didn't find one with the name "pass".  Either way,
754                  * we return ENOENT, since we couldn't find something.
755                  */
756                 if (periph == NULL) {
757                         ccb->ccb_h.status = CAM_REQ_CMP_ERR;
758                         ccb->cgdl.status = CAM_GDEVLIST_ERROR;
759                         *ccb->cgdl.periph_name = '\0';
760                         ccb->cgdl.unit_number = 0;
761                         error = ENOENT;
762                         /*
763                          * It is unfortunate that this is even necessary,
764                          * but there are many, many clueless users out there.
765                          * If this is true, the user is looking for the
766                          * passthrough driver, but doesn't have one in his
767                          * kernel.
768                          */
769                         if (base_periph_found == 1) {
770                                 printf("xptioctl: pass driver is not in the "
771                                        "kernel\n");
772                                 printf("xptioctl: put \"device pass\" in "
773                                        "your kernel config file\n");
774                         }
775                 }
776                 mtx_unlock(&xsoftc.xpt_topo_lock);
777                 break;
778                 }
779         default:
780                 error = ENOTTY;
781                 break;
782         }
783
784         return(error);
785 }
786
787 static int
788 cam_module_event_handler(module_t mod, int what, void *arg)
789 {
790         int error;
791
792         switch (what) {
793         case MOD_LOAD:
794                 if ((error = xpt_init(NULL)) != 0)
795                         return (error);
796                 break;
797         case MOD_UNLOAD:
798                 return EBUSY;
799         default:
800                 return EOPNOTSUPP;
801         }
802
803         return 0;
804 }
805
806 static void
807 xpt_rescan_done(struct cam_periph *periph, union ccb *done_ccb)
808 {
809
810         if (done_ccb->ccb_h.ppriv_ptr1 == NULL) {
811                 xpt_free_path(done_ccb->ccb_h.path);
812                 xpt_free_ccb(done_ccb);
813         } else {
814                 done_ccb->ccb_h.cbfcnp = done_ccb->ccb_h.ppriv_ptr1;
815                 (*done_ccb->ccb_h.cbfcnp)(periph, done_ccb);
816         }
817         xpt_release_boot();
818 }
819
820 /* thread to handle bus rescans */
821 static void
822 xpt_scanner_thread(void *dummy)
823 {
824         union ccb       *ccb;
825         struct cam_sim  *sim;
826
827         xpt_lock_buses();
828         for (;;) {
829                 if (TAILQ_EMPTY(&xsoftc.ccb_scanq))
830                         msleep(&xsoftc.ccb_scanq, &xsoftc.xpt_topo_lock, PRIBIO,
831                                "ccb_scanq", 0);
832                 if ((ccb = (union ccb *)TAILQ_FIRST(&xsoftc.ccb_scanq)) != NULL) {
833                         TAILQ_REMOVE(&xsoftc.ccb_scanq, &ccb->ccb_h, sim_links.tqe);
834                         xpt_unlock_buses();
835
836                         sim = ccb->ccb_h.path->bus->sim;
837                         CAM_SIM_LOCK(sim);
838                         xpt_action(ccb);
839                         CAM_SIM_UNLOCK(sim);
840
841                         xpt_lock_buses();
842                 }
843         }
844 }
845
846 void
847 xpt_rescan(union ccb *ccb)
848 {
849         struct ccb_hdr *hdr;
850
851         /* Prepare request */
852         if (ccb->ccb_h.path->target->target_id == CAM_TARGET_WILDCARD &&
853             ccb->ccb_h.path->device->lun_id == CAM_LUN_WILDCARD)
854                 ccb->ccb_h.func_code = XPT_SCAN_BUS;
855         else if (ccb->ccb_h.path->target->target_id != CAM_TARGET_WILDCARD &&
856             ccb->ccb_h.path->device->lun_id == CAM_LUN_WILDCARD)
857                 ccb->ccb_h.func_code = XPT_SCAN_TGT;
858         else if (ccb->ccb_h.path->target->target_id != CAM_TARGET_WILDCARD &&
859             ccb->ccb_h.path->device->lun_id != CAM_LUN_WILDCARD)
860                 ccb->ccb_h.func_code = XPT_SCAN_LUN;
861         else {
862                 xpt_print(ccb->ccb_h.path, "illegal scan path\n");
863                 xpt_free_path(ccb->ccb_h.path);
864                 xpt_free_ccb(ccb);
865                 return;
866         }
867         ccb->ccb_h.ppriv_ptr1 = ccb->ccb_h.cbfcnp;
868         ccb->ccb_h.cbfcnp = xpt_rescan_done;
869         xpt_setup_ccb(&ccb->ccb_h, ccb->ccb_h.path, CAM_PRIORITY_XPT);
870         /* Don't make duplicate entries for the same paths. */
871         xpt_lock_buses();
872         if (ccb->ccb_h.ppriv_ptr1 == NULL) {
873                 TAILQ_FOREACH(hdr, &xsoftc.ccb_scanq, sim_links.tqe) {
874                         if (xpt_path_comp(hdr->path, ccb->ccb_h.path) == 0) {
875                                 wakeup(&xsoftc.ccb_scanq);
876                                 xpt_unlock_buses();
877                                 xpt_print(ccb->ccb_h.path, "rescan already queued\n");
878                                 xpt_free_path(ccb->ccb_h.path);
879                                 xpt_free_ccb(ccb);
880                                 return;
881                         }
882                 }
883         }
884         TAILQ_INSERT_TAIL(&xsoftc.ccb_scanq, &ccb->ccb_h, sim_links.tqe);
885         xsoftc.buses_to_config++;
886         wakeup(&xsoftc.ccb_scanq);
887         xpt_unlock_buses();
888 }
889
890 /* Functions accessed by the peripheral drivers */
891 static int
892 xpt_init(void *dummy)
893 {
894         struct cam_sim *xpt_sim;
895         struct cam_path *path;
896         struct cam_devq *devq;
897         cam_status status;
898
899         TAILQ_INIT(&xsoftc.xpt_busses);
900         TAILQ_INIT(&cam_simq);
901         TAILQ_INIT(&xsoftc.ccb_scanq);
902         STAILQ_INIT(&xsoftc.highpowerq);
903         xsoftc.num_highpower = CAM_MAX_HIGHPOWER;
904
905         mtx_init(&cam_simq_lock, "CAM SIMQ lock", NULL, MTX_DEF);
906         mtx_init(&xsoftc.xpt_lock, "XPT lock", NULL, MTX_DEF);
907         mtx_init(&xsoftc.xpt_topo_lock, "XPT topology lock", NULL, MTX_DEF);
908
909         /*
910          * The xpt layer is, itself, the equivelent of a SIM.
911          * Allow 16 ccbs in the ccb pool for it.  This should
912          * give decent parallelism when we probe busses and
913          * perform other XPT functions.
914          */
915         devq = cam_simq_alloc(16);
916         xpt_sim = cam_sim_alloc(xptaction,
917                                 xptpoll,
918                                 "xpt",
919                                 /*softc*/NULL,
920                                 /*unit*/0,
921                                 /*mtx*/&xsoftc.xpt_lock,
922                                 /*max_dev_transactions*/0,
923                                 /*max_tagged_dev_transactions*/0,
924                                 devq);
925         if (xpt_sim == NULL)
926                 return (ENOMEM);
927
928         mtx_lock(&xsoftc.xpt_lock);
929         if ((status = xpt_bus_register(xpt_sim, NULL, 0)) != CAM_SUCCESS) {
930                 mtx_unlock(&xsoftc.xpt_lock);
931                 printf("xpt_init: xpt_bus_register failed with status %#x,"
932                        " failing attach\n", status);
933                 return (EINVAL);
934         }
935
936         /*
937          * Looking at the XPT from the SIM layer, the XPT is
938          * the equivelent of a peripheral driver.  Allocate
939          * a peripheral driver entry for us.
940          */
941         if ((status = xpt_create_path(&path, NULL, CAM_XPT_PATH_ID,
942                                       CAM_TARGET_WILDCARD,
943                                       CAM_LUN_WILDCARD)) != CAM_REQ_CMP) {
944                 mtx_unlock(&xsoftc.xpt_lock);
945                 printf("xpt_init: xpt_create_path failed with status %#x,"
946                        " failing attach\n", status);
947                 return (EINVAL);
948         }
949
950         cam_periph_alloc(xptregister, NULL, NULL, NULL, "xpt", CAM_PERIPH_BIO,
951                          path, NULL, 0, xpt_sim);
952         xpt_free_path(path);
953         mtx_unlock(&xsoftc.xpt_lock);
954         /* Install our software interrupt handlers */
955         swi_add(NULL, "cambio", camisr, NULL, SWI_CAMBIO, INTR_MPSAFE, &cambio_ih);
956         /*
957          * Register a callback for when interrupts are enabled.
958          */
959         xsoftc.xpt_config_hook =
960             (struct intr_config_hook *)malloc(sizeof(struct intr_config_hook),
961                                               M_CAMXPT, M_NOWAIT | M_ZERO);
962         if (xsoftc.xpt_config_hook == NULL) {
963                 printf("xpt_init: Cannot malloc config hook "
964                        "- failing attach\n");
965                 return (ENOMEM);
966         }
967         xsoftc.xpt_config_hook->ich_func = xpt_config;
968         if (config_intrhook_establish(xsoftc.xpt_config_hook) != 0) {
969                 free (xsoftc.xpt_config_hook, M_CAMXPT);
970                 printf("xpt_init: config_intrhook_establish failed "
971                        "- failing attach\n");
972         }
973
974         return (0);
975 }
976
977 static cam_status
978 xptregister(struct cam_periph *periph, void *arg)
979 {
980         struct cam_sim *xpt_sim;
981
982         if (periph == NULL) {
983                 printf("xptregister: periph was NULL!!\n");
984                 return(CAM_REQ_CMP_ERR);
985         }
986
987         xpt_sim = (struct cam_sim *)arg;
988         xpt_sim->softc = periph;
989         xpt_periph = periph;
990         periph->softc = NULL;
991
992         return(CAM_REQ_CMP);
993 }
994
995 int32_t
996 xpt_add_periph(struct cam_periph *periph)
997 {
998         struct cam_ed *device;
999         int32_t  status;
1000         struct periph_list *periph_head;
1001
1002         mtx_assert(periph->sim->mtx, MA_OWNED);
1003
1004         device = periph->path->device;
1005
1006         periph_head = &device->periphs;
1007
1008         status = CAM_REQ_CMP;
1009
1010         if (device != NULL) {
1011                 /*
1012                  * Make room for this peripheral
1013                  * so it will fit in the queue
1014                  * when it's scheduled to run
1015                  */
1016                 status = camq_resize(&device->drvq,
1017                                      device->drvq.array_size + 1);
1018
1019                 device->generation++;
1020
1021                 SLIST_INSERT_HEAD(periph_head, periph, periph_links);
1022         }
1023
1024         mtx_lock(&xsoftc.xpt_topo_lock);
1025         xsoftc.xpt_generation++;
1026         mtx_unlock(&xsoftc.xpt_topo_lock);
1027
1028         return (status);
1029 }
1030
1031 void
1032 xpt_remove_periph(struct cam_periph *periph, int topology_lock_held)
1033 {
1034         struct cam_ed *device;
1035
1036         mtx_assert(periph->sim->mtx, MA_OWNED);
1037
1038         device = periph->path->device;
1039
1040         if (device != NULL) {
1041                 struct periph_list *periph_head;
1042
1043                 periph_head = &device->periphs;
1044
1045                 /* Release the slot for this peripheral */
1046                 camq_resize(&device->drvq, device->drvq.array_size - 1);
1047
1048                 device->generation++;
1049
1050                 SLIST_REMOVE(periph_head, periph, cam_periph, periph_links);
1051         }
1052
1053         if (topology_lock_held == 0)
1054                 mtx_lock(&xsoftc.xpt_topo_lock);
1055
1056         xsoftc.xpt_generation++;
1057
1058         if (topology_lock_held == 0)
1059                 mtx_unlock(&xsoftc.xpt_topo_lock);
1060 }
1061
1062
1063 void
1064 xpt_announce_periph(struct cam_periph *periph, char *announce_string)
1065 {
1066         struct  cam_path *path = periph->path;
1067
1068         mtx_assert(periph->sim->mtx, MA_OWNED);
1069
1070         printf("%s%d at %s%d bus %d scbus%d target %d lun %d\n",
1071                periph->periph_name, periph->unit_number,
1072                path->bus->sim->sim_name,
1073                path->bus->sim->unit_number,
1074                path->bus->sim->bus_id,
1075                path->bus->path_id,
1076                path->target->target_id,
1077                path->device->lun_id);
1078         printf("%s%d: ", periph->periph_name, periph->unit_number);
1079         if (path->device->protocol == PROTO_SCSI)
1080                 scsi_print_inquiry(&path->device->inq_data);
1081         else if (path->device->protocol == PROTO_ATA ||
1082             path->device->protocol == PROTO_SATAPM)
1083                 ata_print_ident(&path->device->ident_data);
1084         else if (path->device->protocol == PROTO_SEMB)
1085                 semb_print_ident(
1086                     (struct sep_identify_data *)&path->device->ident_data);
1087         else
1088                 printf("Unknown protocol device\n");
1089         if (bootverbose && path->device->serial_num_len > 0) {
1090                 /* Don't wrap the screen  - print only the first 60 chars */
1091                 printf("%s%d: Serial Number %.60s\n", periph->periph_name,
1092                        periph->unit_number, path->device->serial_num);
1093         }
1094         /* Announce transport details. */
1095         (*(path->bus->xport->announce))(periph);
1096         /* Announce command queueing. */
1097         if (path->device->inq_flags & SID_CmdQue
1098          || path->device->flags & CAM_DEV_TAG_AFTER_COUNT) {
1099                 printf("%s%d: Command Queueing enabled\n",
1100                        periph->periph_name, periph->unit_number);
1101         }
1102         /* Announce caller's details if they've passed in. */
1103         if (announce_string != NULL)
1104                 printf("%s%d: %s\n", periph->periph_name,
1105                        periph->unit_number, announce_string);
1106 }
1107
1108 int
1109 xpt_getattr(char *buf, size_t len, const char *attr, struct cam_path *path)
1110 {
1111         int ret = -1;
1112         struct ccb_dev_advinfo cdai;
1113
1114         memset(&cdai, 0, sizeof(cdai));
1115         xpt_setup_ccb(&cdai.ccb_h, path, CAM_PRIORITY_NORMAL);
1116         cdai.ccb_h.func_code = XPT_DEV_ADVINFO;
1117         cdai.bufsiz = len;
1118
1119         if (!strcmp(attr, "GEOM::ident"))
1120                 cdai.buftype = CDAI_TYPE_SERIAL_NUM;
1121         else if (!strcmp(attr, "GEOM::physpath"))
1122                 cdai.buftype = CDAI_TYPE_PHYS_PATH;
1123         else
1124                 goto out;
1125
1126         cdai.buf = malloc(cdai.bufsiz, M_CAMXPT, M_NOWAIT|M_ZERO);
1127         if (cdai.buf == NULL) {
1128                 ret = ENOMEM;
1129                 goto out;
1130         }
1131         xpt_action((union ccb *)&cdai); /* can only be synchronous */
1132         if ((cdai.ccb_h.status & CAM_DEV_QFRZN) != 0)
1133                 cam_release_devq(cdai.ccb_h.path, 0, 0, 0, FALSE);
1134         if (cdai.provsiz == 0)
1135                 goto out;
1136         ret = 0;
1137         if (strlcpy(buf, cdai.buf, len) >= len)
1138                 ret = EFAULT;
1139
1140 out:
1141         if (cdai.buf != NULL)
1142                 free(cdai.buf, M_CAMXPT);
1143         return ret;
1144 }
1145
1146 static dev_match_ret
1147 xptbusmatch(struct dev_match_pattern *patterns, u_int num_patterns,
1148             struct cam_eb *bus)
1149 {
1150         dev_match_ret retval;
1151         int i;
1152
1153         retval = DM_RET_NONE;
1154
1155         /*
1156          * If we aren't given something to match against, that's an error.
1157          */
1158         if (bus == NULL)
1159                 return(DM_RET_ERROR);
1160
1161         /*
1162          * If there are no match entries, then this bus matches no
1163          * matter what.
1164          */
1165         if ((patterns == NULL) || (num_patterns == 0))
1166                 return(DM_RET_DESCEND | DM_RET_COPY);
1167
1168         for (i = 0; i < num_patterns; i++) {
1169                 struct bus_match_pattern *cur_pattern;
1170
1171                 /*
1172                  * If the pattern in question isn't for a bus node, we
1173                  * aren't interested.  However, we do indicate to the
1174                  * calling routine that we should continue descending the
1175                  * tree, since the user wants to match against lower-level
1176                  * EDT elements.
1177                  */
1178                 if (patterns[i].type != DEV_MATCH_BUS) {
1179                         if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1180                                 retval |= DM_RET_DESCEND;
1181                         continue;
1182                 }
1183
1184                 cur_pattern = &patterns[i].pattern.bus_pattern;
1185
1186                 /*
1187                  * If they want to match any bus node, we give them any
1188                  * device node.
1189                  */
1190                 if (cur_pattern->flags == BUS_MATCH_ANY) {
1191                         /* set the copy flag */
1192                         retval |= DM_RET_COPY;
1193
1194                         /*
1195                          * If we've already decided on an action, go ahead
1196                          * and return.
1197                          */
1198                         if ((retval & DM_RET_ACTION_MASK) != DM_RET_NONE)
1199                                 return(retval);
1200                 }
1201
1202                 /*
1203                  * Not sure why someone would do this...
1204                  */
1205                 if (cur_pattern->flags == BUS_MATCH_NONE)
1206                         continue;
1207
1208                 if (((cur_pattern->flags & BUS_MATCH_PATH) != 0)
1209                  && (cur_pattern->path_id != bus->path_id))
1210                         continue;
1211
1212                 if (((cur_pattern->flags & BUS_MATCH_BUS_ID) != 0)
1213                  && (cur_pattern->bus_id != bus->sim->bus_id))
1214                         continue;
1215
1216                 if (((cur_pattern->flags & BUS_MATCH_UNIT) != 0)
1217                  && (cur_pattern->unit_number != bus->sim->unit_number))
1218                         continue;
1219
1220                 if (((cur_pattern->flags & BUS_MATCH_NAME) != 0)
1221                  && (strncmp(cur_pattern->dev_name, bus->sim->sim_name,
1222                              DEV_IDLEN) != 0))
1223                         continue;
1224
1225                 /*
1226                  * If we get to this point, the user definitely wants
1227                  * information on this bus.  So tell the caller to copy the
1228                  * data out.
1229                  */
1230                 retval |= DM_RET_COPY;
1231
1232                 /*
1233                  * If the return action has been set to descend, then we
1234                  * know that we've already seen a non-bus matching
1235                  * expression, therefore we need to further descend the tree.
1236                  * This won't change by continuing around the loop, so we
1237                  * go ahead and return.  If we haven't seen a non-bus
1238                  * matching expression, we keep going around the loop until
1239                  * we exhaust the matching expressions.  We'll set the stop
1240                  * flag once we fall out of the loop.
1241                  */
1242                 if ((retval & DM_RET_ACTION_MASK) == DM_RET_DESCEND)
1243                         return(retval);
1244         }
1245
1246         /*
1247          * If the return action hasn't been set to descend yet, that means
1248          * we haven't seen anything other than bus matching patterns.  So
1249          * tell the caller to stop descending the tree -- the user doesn't
1250          * want to match against lower level tree elements.
1251          */
1252         if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1253                 retval |= DM_RET_STOP;
1254
1255         return(retval);
1256 }
1257
1258 static dev_match_ret
1259 xptdevicematch(struct dev_match_pattern *patterns, u_int num_patterns,
1260                struct cam_ed *device)
1261 {
1262         dev_match_ret retval;
1263         int i;
1264
1265         retval = DM_RET_NONE;
1266
1267         /*
1268          * If we aren't given something to match against, that's an error.
1269          */
1270         if (device == NULL)
1271                 return(DM_RET_ERROR);
1272
1273         /*
1274          * If there are no match entries, then this device matches no
1275          * matter what.
1276          */
1277         if ((patterns == NULL) || (num_patterns == 0))
1278                 return(DM_RET_DESCEND | DM_RET_COPY);
1279
1280         for (i = 0; i < num_patterns; i++) {
1281                 struct device_match_pattern *cur_pattern;
1282                 struct scsi_vpd_device_id *device_id_page;
1283
1284                 /*
1285                  * If the pattern in question isn't for a device node, we
1286                  * aren't interested.
1287                  */
1288                 if (patterns[i].type != DEV_MATCH_DEVICE) {
1289                         if ((patterns[i].type == DEV_MATCH_PERIPH)
1290                          && ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE))
1291                                 retval |= DM_RET_DESCEND;
1292                         continue;
1293                 }
1294
1295                 cur_pattern = &patterns[i].pattern.device_pattern;
1296
1297                 /* Error out if mutually exclusive options are specified. */ 
1298                 if ((cur_pattern->flags & (DEV_MATCH_INQUIRY|DEV_MATCH_DEVID))
1299                  == (DEV_MATCH_INQUIRY|DEV_MATCH_DEVID))
1300                         return(DM_RET_ERROR);
1301
1302                 /*
1303                  * If they want to match any device node, we give them any
1304                  * device node.
1305                  */
1306                 if (cur_pattern->flags == DEV_MATCH_ANY)
1307                         goto copy_dev_node;
1308
1309                 /*
1310                  * Not sure why someone would do this...
1311                  */
1312                 if (cur_pattern->flags == DEV_MATCH_NONE)
1313                         continue;
1314
1315                 if (((cur_pattern->flags & DEV_MATCH_PATH) != 0)
1316                  && (cur_pattern->path_id != device->target->bus->path_id))
1317                         continue;
1318
1319                 if (((cur_pattern->flags & DEV_MATCH_TARGET) != 0)
1320                  && (cur_pattern->target_id != device->target->target_id))
1321                         continue;
1322
1323                 if (((cur_pattern->flags & DEV_MATCH_LUN) != 0)
1324                  && (cur_pattern->target_lun != device->lun_id))
1325                         continue;
1326
1327                 if (((cur_pattern->flags & DEV_MATCH_INQUIRY) != 0)
1328                  && (cam_quirkmatch((caddr_t)&device->inq_data,
1329                                     (caddr_t)&cur_pattern->data.inq_pat,
1330                                     1, sizeof(cur_pattern->data.inq_pat),
1331                                     scsi_static_inquiry_match) == NULL))
1332                         continue;
1333
1334                 device_id_page = (struct scsi_vpd_device_id *)device->device_id;
1335                 if (((cur_pattern->flags & DEV_MATCH_DEVID) != 0)
1336                  && (device->device_id_len < SVPD_DEVICE_ID_HDR_LEN
1337                   || scsi_devid_match((uint8_t *)device_id_page->desc_list,
1338                                       device->device_id_len
1339                                     - SVPD_DEVICE_ID_HDR_LEN,
1340                                       cur_pattern->data.devid_pat.id,
1341                                       cur_pattern->data.devid_pat.id_len) != 0))
1342                         continue;
1343
1344 copy_dev_node:
1345                 /*
1346                  * If we get to this point, the user definitely wants
1347                  * information on this device.  So tell the caller to copy
1348                  * the data out.
1349                  */
1350                 retval |= DM_RET_COPY;
1351
1352                 /*
1353                  * If the return action has been set to descend, then we
1354                  * know that we've already seen a peripheral matching
1355                  * expression, therefore we need to further descend the tree.
1356                  * This won't change by continuing around the loop, so we
1357                  * go ahead and return.  If we haven't seen a peripheral
1358                  * matching expression, we keep going around the loop until
1359                  * we exhaust the matching expressions.  We'll set the stop
1360                  * flag once we fall out of the loop.
1361                  */
1362                 if ((retval & DM_RET_ACTION_MASK) == DM_RET_DESCEND)
1363                         return(retval);
1364         }
1365
1366         /*
1367          * If the return action hasn't been set to descend yet, that means
1368          * we haven't seen any peripheral matching patterns.  So tell the
1369          * caller to stop descending the tree -- the user doesn't want to
1370          * match against lower level tree elements.
1371          */
1372         if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1373                 retval |= DM_RET_STOP;
1374
1375         return(retval);
1376 }
1377
1378 /*
1379  * Match a single peripheral against any number of match patterns.
1380  */
1381 static dev_match_ret
1382 xptperiphmatch(struct dev_match_pattern *patterns, u_int num_patterns,
1383                struct cam_periph *periph)
1384 {
1385         dev_match_ret retval;
1386         int i;
1387
1388         /*
1389          * If we aren't given something to match against, that's an error.
1390          */
1391         if (periph == NULL)
1392                 return(DM_RET_ERROR);
1393
1394         /*
1395          * If there are no match entries, then this peripheral matches no
1396          * matter what.
1397          */
1398         if ((patterns == NULL) || (num_patterns == 0))
1399                 return(DM_RET_STOP | DM_RET_COPY);
1400
1401         /*
1402          * There aren't any nodes below a peripheral node, so there's no
1403          * reason to descend the tree any further.
1404          */
1405         retval = DM_RET_STOP;
1406
1407         for (i = 0; i < num_patterns; i++) {
1408                 struct periph_match_pattern *cur_pattern;
1409
1410                 /*
1411                  * If the pattern in question isn't for a peripheral, we
1412                  * aren't interested.
1413                  */
1414                 if (patterns[i].type != DEV_MATCH_PERIPH)
1415                         continue;
1416
1417                 cur_pattern = &patterns[i].pattern.periph_pattern;
1418
1419                 /*
1420                  * If they want to match on anything, then we will do so.
1421                  */
1422                 if (cur_pattern->flags == PERIPH_MATCH_ANY) {
1423                         /* set the copy flag */
1424                         retval |= DM_RET_COPY;
1425
1426                         /*
1427                          * We've already set the return action to stop,
1428                          * since there are no nodes below peripherals in
1429                          * the tree.
1430                          */
1431                         return(retval);
1432                 }
1433
1434                 /*
1435                  * Not sure why someone would do this...
1436                  */
1437                 if (cur_pattern->flags == PERIPH_MATCH_NONE)
1438                         continue;
1439
1440                 if (((cur_pattern->flags & PERIPH_MATCH_PATH) != 0)
1441                  && (cur_pattern->path_id != periph->path->bus->path_id))
1442                         continue;
1443
1444                 /*
1445                  * For the target and lun id's, we have to make sure the
1446                  * target and lun pointers aren't NULL.  The xpt peripheral
1447                  * has a wildcard target and device.
1448                  */
1449                 if (((cur_pattern->flags & PERIPH_MATCH_TARGET) != 0)
1450                  && ((periph->path->target == NULL)
1451                  ||(cur_pattern->target_id != periph->path->target->target_id)))
1452                         continue;
1453
1454                 if (((cur_pattern->flags & PERIPH_MATCH_LUN) != 0)
1455                  && ((periph->path->device == NULL)
1456                  || (cur_pattern->target_lun != periph->path->device->lun_id)))
1457                         continue;
1458
1459                 if (((cur_pattern->flags & PERIPH_MATCH_UNIT) != 0)
1460                  && (cur_pattern->unit_number != periph->unit_number))
1461                         continue;
1462
1463                 if (((cur_pattern->flags & PERIPH_MATCH_NAME) != 0)
1464                  && (strncmp(cur_pattern->periph_name, periph->periph_name,
1465                              DEV_IDLEN) != 0))
1466                         continue;
1467
1468                 /*
1469                  * If we get to this point, the user definitely wants
1470                  * information on this peripheral.  So tell the caller to
1471                  * copy the data out.
1472                  */
1473                 retval |= DM_RET_COPY;
1474
1475                 /*
1476                  * The return action has already been set to stop, since
1477                  * peripherals don't have any nodes below them in the EDT.
1478                  */
1479                 return(retval);
1480         }
1481
1482         /*
1483          * If we get to this point, the peripheral that was passed in
1484          * doesn't match any of the patterns.
1485          */
1486         return(retval);
1487 }
1488
1489 static int
1490 xptedtbusfunc(struct cam_eb *bus, void *arg)
1491 {
1492         struct ccb_dev_match *cdm;
1493         dev_match_ret retval;
1494
1495         cdm = (struct ccb_dev_match *)arg;
1496
1497         /*
1498          * If our position is for something deeper in the tree, that means
1499          * that we've already seen this node.  So, we keep going down.
1500          */
1501         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1502          && (cdm->pos.cookie.bus == bus)
1503          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1504          && (cdm->pos.cookie.target != NULL))
1505                 retval = DM_RET_DESCEND;
1506         else
1507                 retval = xptbusmatch(cdm->patterns, cdm->num_patterns, bus);
1508
1509         /*
1510          * If we got an error, bail out of the search.
1511          */
1512         if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
1513                 cdm->status = CAM_DEV_MATCH_ERROR;
1514                 return(0);
1515         }
1516
1517         /*
1518          * If the copy flag is set, copy this bus out.
1519          */
1520         if (retval & DM_RET_COPY) {
1521                 int spaceleft, j;
1522
1523                 spaceleft = cdm->match_buf_len - (cdm->num_matches *
1524                         sizeof(struct dev_match_result));
1525
1526                 /*
1527                  * If we don't have enough space to put in another
1528                  * match result, save our position and tell the
1529                  * user there are more devices to check.
1530                  */
1531                 if (spaceleft < sizeof(struct dev_match_result)) {
1532                         bzero(&cdm->pos, sizeof(cdm->pos));
1533                         cdm->pos.position_type =
1534                                 CAM_DEV_POS_EDT | CAM_DEV_POS_BUS;
1535
1536                         cdm->pos.cookie.bus = bus;
1537                         cdm->pos.generations[CAM_BUS_GENERATION]=
1538                                 xsoftc.bus_generation;
1539                         cdm->status = CAM_DEV_MATCH_MORE;
1540                         return(0);
1541                 }
1542                 j = cdm->num_matches;
1543                 cdm->num_matches++;
1544                 cdm->matches[j].type = DEV_MATCH_BUS;
1545                 cdm->matches[j].result.bus_result.path_id = bus->path_id;
1546                 cdm->matches[j].result.bus_result.bus_id = bus->sim->bus_id;
1547                 cdm->matches[j].result.bus_result.unit_number =
1548                         bus->sim->unit_number;
1549                 strncpy(cdm->matches[j].result.bus_result.dev_name,
1550                         bus->sim->sim_name, DEV_IDLEN);
1551         }
1552
1553         /*
1554          * If the user is only interested in busses, there's no
1555          * reason to descend to the next level in the tree.
1556          */
1557         if ((retval & DM_RET_ACTION_MASK) == DM_RET_STOP)
1558                 return(1);
1559
1560         /*
1561          * If there is a target generation recorded, check it to
1562          * make sure the target list hasn't changed.
1563          */
1564         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1565          && (bus == cdm->pos.cookie.bus)
1566          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1567          && (cdm->pos.generations[CAM_TARGET_GENERATION] != 0)
1568          && (cdm->pos.generations[CAM_TARGET_GENERATION] !=
1569              bus->generation)) {
1570                 cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1571                 return(0);
1572         }
1573
1574         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1575          && (cdm->pos.cookie.bus == bus)
1576          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1577          && (cdm->pos.cookie.target != NULL))
1578                 return(xpttargettraverse(bus,
1579                                         (struct cam_et *)cdm->pos.cookie.target,
1580                                          xptedttargetfunc, arg));
1581         else
1582                 return(xpttargettraverse(bus, NULL, xptedttargetfunc, arg));
1583 }
1584
1585 static int
1586 xptedttargetfunc(struct cam_et *target, void *arg)
1587 {
1588         struct ccb_dev_match *cdm;
1589
1590         cdm = (struct ccb_dev_match *)arg;
1591
1592         /*
1593          * If there is a device list generation recorded, check it to
1594          * make sure the device list hasn't changed.
1595          */
1596         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1597          && (cdm->pos.cookie.bus == target->bus)
1598          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1599          && (cdm->pos.cookie.target == target)
1600          && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
1601          && (cdm->pos.generations[CAM_DEV_GENERATION] != 0)
1602          && (cdm->pos.generations[CAM_DEV_GENERATION] !=
1603              target->generation)) {
1604                 cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1605                 return(0);
1606         }
1607
1608         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1609          && (cdm->pos.cookie.bus == target->bus)
1610          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1611          && (cdm->pos.cookie.target == target)
1612          && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
1613          && (cdm->pos.cookie.device != NULL))
1614                 return(xptdevicetraverse(target,
1615                                         (struct cam_ed *)cdm->pos.cookie.device,
1616                                          xptedtdevicefunc, arg));
1617         else
1618                 return(xptdevicetraverse(target, NULL, xptedtdevicefunc, arg));
1619 }
1620
1621 static int
1622 xptedtdevicefunc(struct cam_ed *device, void *arg)
1623 {
1624
1625         struct ccb_dev_match *cdm;
1626         dev_match_ret retval;
1627
1628         cdm = (struct ccb_dev_match *)arg;
1629
1630         /*
1631          * If our position is for something deeper in the tree, that means
1632          * that we've already seen this node.  So, we keep going down.
1633          */
1634         if ((cdm->pos.position_type & CAM_DEV_POS_DEVICE)
1635          && (cdm->pos.cookie.device == device)
1636          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
1637          && (cdm->pos.cookie.periph != NULL))
1638                 retval = DM_RET_DESCEND;
1639         else
1640                 retval = xptdevicematch(cdm->patterns, cdm->num_patterns,
1641                                         device);
1642
1643         if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
1644                 cdm->status = CAM_DEV_MATCH_ERROR;
1645                 return(0);
1646         }
1647
1648         /*
1649          * If the copy flag is set, copy this device out.
1650          */
1651         if (retval & DM_RET_COPY) {
1652                 int spaceleft, j;
1653
1654                 spaceleft = cdm->match_buf_len - (cdm->num_matches *
1655                         sizeof(struct dev_match_result));
1656
1657                 /*
1658                  * If we don't have enough space to put in another
1659                  * match result, save our position and tell the
1660                  * user there are more devices to check.
1661                  */
1662                 if (spaceleft < sizeof(struct dev_match_result)) {
1663                         bzero(&cdm->pos, sizeof(cdm->pos));
1664                         cdm->pos.position_type =
1665                                 CAM_DEV_POS_EDT | CAM_DEV_POS_BUS |
1666                                 CAM_DEV_POS_TARGET | CAM_DEV_POS_DEVICE;
1667
1668                         cdm->pos.cookie.bus = device->target->bus;
1669                         cdm->pos.generations[CAM_BUS_GENERATION]=
1670                                 xsoftc.bus_generation;
1671                         cdm->pos.cookie.target = device->target;
1672                         cdm->pos.generations[CAM_TARGET_GENERATION] =
1673                                 device->target->bus->generation;
1674                         cdm->pos.cookie.device = device;
1675                         cdm->pos.generations[CAM_DEV_GENERATION] =
1676                                 device->target->generation;
1677                         cdm->status = CAM_DEV_MATCH_MORE;
1678                         return(0);
1679                 }
1680                 j = cdm->num_matches;
1681                 cdm->num_matches++;
1682                 cdm->matches[j].type = DEV_MATCH_DEVICE;
1683                 cdm->matches[j].result.device_result.path_id =
1684                         device->target->bus->path_id;
1685                 cdm->matches[j].result.device_result.target_id =
1686                         device->target->target_id;
1687                 cdm->matches[j].result.device_result.target_lun =
1688                         device->lun_id;
1689                 cdm->matches[j].result.device_result.protocol =
1690                         device->protocol;
1691                 bcopy(&device->inq_data,
1692                       &cdm->matches[j].result.device_result.inq_data,
1693                       sizeof(struct scsi_inquiry_data));
1694                 bcopy(&device->ident_data,
1695                       &cdm->matches[j].result.device_result.ident_data,
1696                       sizeof(struct ata_params));
1697
1698                 /* Let the user know whether this device is unconfigured */
1699                 if (device->flags & CAM_DEV_UNCONFIGURED)
1700                         cdm->matches[j].result.device_result.flags =
1701                                 DEV_RESULT_UNCONFIGURED;
1702                 else
1703                         cdm->matches[j].result.device_result.flags =
1704                                 DEV_RESULT_NOFLAG;
1705         }
1706
1707         /*
1708          * If the user isn't interested in peripherals, don't descend
1709          * the tree any further.
1710          */
1711         if ((retval & DM_RET_ACTION_MASK) == DM_RET_STOP)
1712                 return(1);
1713
1714         /*
1715          * If there is a peripheral list generation recorded, make sure
1716          * it hasn't changed.
1717          */
1718         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1719          && (device->target->bus == cdm->pos.cookie.bus)
1720          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1721          && (device->target == cdm->pos.cookie.target)
1722          && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
1723          && (device == cdm->pos.cookie.device)
1724          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
1725          && (cdm->pos.generations[CAM_PERIPH_GENERATION] != 0)
1726          && (cdm->pos.generations[CAM_PERIPH_GENERATION] !=
1727              device->generation)){
1728                 cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1729                 return(0);
1730         }
1731
1732         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1733          && (cdm->pos.cookie.bus == device->target->bus)
1734          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1735          && (cdm->pos.cookie.target == device->target)
1736          && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
1737          && (cdm->pos.cookie.device == device)
1738          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
1739          && (cdm->pos.cookie.periph != NULL))
1740                 return(xptperiphtraverse(device,
1741                                 (struct cam_periph *)cdm->pos.cookie.periph,
1742                                 xptedtperiphfunc, arg));
1743         else
1744                 return(xptperiphtraverse(device, NULL, xptedtperiphfunc, arg));
1745 }
1746
1747 static int
1748 xptedtperiphfunc(struct cam_periph *periph, void *arg)
1749 {
1750         struct ccb_dev_match *cdm;
1751         dev_match_ret retval;
1752
1753         cdm = (struct ccb_dev_match *)arg;
1754
1755         retval = xptperiphmatch(cdm->patterns, cdm->num_patterns, periph);
1756
1757         if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
1758                 cdm->status = CAM_DEV_MATCH_ERROR;
1759                 return(0);
1760         }
1761
1762         /*
1763          * If the copy flag is set, copy this peripheral out.
1764          */
1765         if (retval & DM_RET_COPY) {
1766                 int spaceleft, j;
1767
1768                 spaceleft = cdm->match_buf_len - (cdm->num_matches *
1769                         sizeof(struct dev_match_result));
1770
1771                 /*
1772                  * If we don't have enough space to put in another
1773                  * match result, save our position and tell the
1774                  * user there are more devices to check.
1775                  */
1776                 if (spaceleft < sizeof(struct dev_match_result)) {
1777                         bzero(&cdm->pos, sizeof(cdm->pos));
1778                         cdm->pos.position_type =
1779                                 CAM_DEV_POS_EDT | CAM_DEV_POS_BUS |
1780                                 CAM_DEV_POS_TARGET | CAM_DEV_POS_DEVICE |
1781                                 CAM_DEV_POS_PERIPH;
1782
1783                         cdm->pos.cookie.bus = periph->path->bus;
1784                         cdm->pos.generations[CAM_BUS_GENERATION]=
1785                                 xsoftc.bus_generation;
1786                         cdm->pos.cookie.target = periph->path->target;
1787                         cdm->pos.generations[CAM_TARGET_GENERATION] =
1788                                 periph->path->bus->generation;
1789                         cdm->pos.cookie.device = periph->path->device;
1790                         cdm->pos.generations[CAM_DEV_GENERATION] =
1791                                 periph->path->target->generation;
1792                         cdm->pos.cookie.periph = periph;
1793                         cdm->pos.generations[CAM_PERIPH_GENERATION] =
1794                                 periph->path->device->generation;
1795                         cdm->status = CAM_DEV_MATCH_MORE;
1796                         return(0);
1797                 }
1798
1799                 j = cdm->num_matches;
1800                 cdm->num_matches++;
1801                 cdm->matches[j].type = DEV_MATCH_PERIPH;
1802                 cdm->matches[j].result.periph_result.path_id =
1803                         periph->path->bus->path_id;
1804                 cdm->matches[j].result.periph_result.target_id =
1805                         periph->path->target->target_id;
1806                 cdm->matches[j].result.periph_result.target_lun =
1807                         periph->path->device->lun_id;
1808                 cdm->matches[j].result.periph_result.unit_number =
1809                         periph->unit_number;
1810                 strncpy(cdm->matches[j].result.periph_result.periph_name,
1811                         periph->periph_name, DEV_IDLEN);
1812         }
1813
1814         return(1);
1815 }
1816
1817 static int
1818 xptedtmatch(struct ccb_dev_match *cdm)
1819 {
1820         int ret;
1821
1822         cdm->num_matches = 0;
1823
1824         /*
1825          * Check the bus list generation.  If it has changed, the user
1826          * needs to reset everything and start over.
1827          */
1828         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1829          && (cdm->pos.generations[CAM_BUS_GENERATION] != 0)
1830          && (cdm->pos.generations[CAM_BUS_GENERATION] != xsoftc.bus_generation)) {
1831                 cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1832                 return(0);
1833         }
1834
1835         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1836          && (cdm->pos.cookie.bus != NULL))
1837                 ret = xptbustraverse((struct cam_eb *)cdm->pos.cookie.bus,
1838                                      xptedtbusfunc, cdm);
1839         else
1840                 ret = xptbustraverse(NULL, xptedtbusfunc, cdm);
1841
1842         /*
1843          * If we get back 0, that means that we had to stop before fully
1844          * traversing the EDT.  It also means that one of the subroutines
1845          * has set the status field to the proper value.  If we get back 1,
1846          * we've fully traversed the EDT and copied out any matching entries.
1847          */
1848         if (ret == 1)
1849                 cdm->status = CAM_DEV_MATCH_LAST;
1850
1851         return(ret);
1852 }
1853
1854 static int
1855 xptplistpdrvfunc(struct periph_driver **pdrv, void *arg)
1856 {
1857         struct ccb_dev_match *cdm;
1858
1859         cdm = (struct ccb_dev_match *)arg;
1860
1861         if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
1862          && (cdm->pos.cookie.pdrv == pdrv)
1863          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
1864          && (cdm->pos.generations[CAM_PERIPH_GENERATION] != 0)
1865          && (cdm->pos.generations[CAM_PERIPH_GENERATION] !=
1866              (*pdrv)->generation)) {
1867                 cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1868                 return(0);
1869         }
1870
1871         if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
1872          && (cdm->pos.cookie.pdrv == pdrv)
1873          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
1874          && (cdm->pos.cookie.periph != NULL))
1875                 return(xptpdperiphtraverse(pdrv,
1876                                 (struct cam_periph *)cdm->pos.cookie.periph,
1877                                 xptplistperiphfunc, arg));
1878         else
1879                 return(xptpdperiphtraverse(pdrv, NULL,xptplistperiphfunc, arg));
1880 }
1881
1882 static int
1883 xptplistperiphfunc(struct cam_periph *periph, void *arg)
1884 {
1885         struct ccb_dev_match *cdm;
1886         dev_match_ret retval;
1887
1888         cdm = (struct ccb_dev_match *)arg;
1889
1890         retval = xptperiphmatch(cdm->patterns, cdm->num_patterns, periph);
1891
1892         if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
1893                 cdm->status = CAM_DEV_MATCH_ERROR;
1894                 return(0);
1895         }
1896
1897         /*
1898          * If the copy flag is set, copy this peripheral out.
1899          */
1900         if (retval & DM_RET_COPY) {
1901                 int spaceleft, j;
1902
1903                 spaceleft = cdm->match_buf_len - (cdm->num_matches *
1904                         sizeof(struct dev_match_result));
1905
1906                 /*
1907                  * If we don't have enough space to put in another
1908                  * match result, save our position and tell the
1909                  * user there are more devices to check.
1910                  */
1911                 if (spaceleft < sizeof(struct dev_match_result)) {
1912                         struct periph_driver **pdrv;
1913
1914                         pdrv = NULL;
1915                         bzero(&cdm->pos, sizeof(cdm->pos));
1916                         cdm->pos.position_type =
1917                                 CAM_DEV_POS_PDRV | CAM_DEV_POS_PDPTR |
1918                                 CAM_DEV_POS_PERIPH;
1919
1920                         /*
1921                          * This may look a bit non-sensical, but it is
1922                          * actually quite logical.  There are very few
1923                          * peripheral drivers, and bloating every peripheral
1924                          * structure with a pointer back to its parent
1925                          * peripheral driver linker set entry would cost
1926                          * more in the long run than doing this quick lookup.
1927                          */
1928                         for (pdrv = periph_drivers; *pdrv != NULL; pdrv++) {
1929                                 if (strcmp((*pdrv)->driver_name,
1930                                     periph->periph_name) == 0)
1931                                         break;
1932                         }
1933
1934                         if (*pdrv == NULL) {
1935                                 cdm->status = CAM_DEV_MATCH_ERROR;
1936                                 return(0);
1937                         }
1938
1939                         cdm->pos.cookie.pdrv = pdrv;
1940                         /*
1941                          * The periph generation slot does double duty, as
1942                          * does the periph pointer slot.  They are used for
1943                          * both edt and pdrv lookups and positioning.
1944                          */
1945                         cdm->pos.cookie.periph = periph;
1946                         cdm->pos.generations[CAM_PERIPH_GENERATION] =
1947                                 (*pdrv)->generation;
1948                         cdm->status = CAM_DEV_MATCH_MORE;
1949                         return(0);
1950                 }
1951
1952                 j = cdm->num_matches;
1953                 cdm->num_matches++;
1954                 cdm->matches[j].type = DEV_MATCH_PERIPH;
1955                 cdm->matches[j].result.periph_result.path_id =
1956                         periph->path->bus->path_id;
1957
1958                 /*
1959                  * The transport layer peripheral doesn't have a target or
1960                  * lun.
1961                  */
1962                 if (periph->path->target)
1963                         cdm->matches[j].result.periph_result.target_id =
1964                                 periph->path->target->target_id;
1965                 else
1966                         cdm->matches[j].result.periph_result.target_id = -1;
1967
1968                 if (periph->path->device)
1969                         cdm->matches[j].result.periph_result.target_lun =
1970                                 periph->path->device->lun_id;
1971                 else
1972                         cdm->matches[j].result.periph_result.target_lun = -1;
1973
1974                 cdm->matches[j].result.periph_result.unit_number =
1975                         periph->unit_number;
1976                 strncpy(cdm->matches[j].result.periph_result.periph_name,
1977                         periph->periph_name, DEV_IDLEN);
1978         }
1979
1980         return(1);
1981 }
1982
1983 static int
1984 xptperiphlistmatch(struct ccb_dev_match *cdm)
1985 {
1986         int ret;
1987
1988         cdm->num_matches = 0;
1989
1990         /*
1991          * At this point in the edt traversal function, we check the bus
1992          * list generation to make sure that no busses have been added or
1993          * removed since the user last sent a XPT_DEV_MATCH ccb through.
1994          * For the peripheral driver list traversal function, however, we
1995          * don't have to worry about new peripheral driver types coming or
1996          * going; they're in a linker set, and therefore can't change
1997          * without a recompile.
1998          */
1999
2000         if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
2001          && (cdm->pos.cookie.pdrv != NULL))
2002                 ret = xptpdrvtraverse(
2003                                 (struct periph_driver **)cdm->pos.cookie.pdrv,
2004                                 xptplistpdrvfunc, cdm);
2005         else
2006                 ret = xptpdrvtraverse(NULL, xptplistpdrvfunc, cdm);
2007
2008         /*
2009          * If we get back 0, that means that we had to stop before fully
2010          * traversing the peripheral driver tree.  It also means that one of
2011          * the subroutines has set the status field to the proper value.  If
2012          * we get back 1, we've fully traversed the EDT and copied out any
2013          * matching entries.
2014          */
2015         if (ret == 1)
2016                 cdm->status = CAM_DEV_MATCH_LAST;
2017
2018         return(ret);
2019 }
2020
2021 static int
2022 xptbustraverse(struct cam_eb *start_bus, xpt_busfunc_t *tr_func, void *arg)
2023 {
2024         struct cam_eb *bus, *next_bus;
2025         int retval;
2026
2027         retval = 1;
2028
2029         mtx_lock(&xsoftc.xpt_topo_lock);
2030         for (bus = (start_bus ? start_bus : TAILQ_FIRST(&xsoftc.xpt_busses));
2031              bus != NULL;
2032              bus = next_bus) {
2033
2034                 bus->refcount++;
2035
2036                 /*
2037                  * XXX The locking here is obviously very complex.  We
2038                  * should work to simplify it.
2039                  */
2040                 mtx_unlock(&xsoftc.xpt_topo_lock);
2041                 CAM_SIM_LOCK(bus->sim);
2042                 retval = tr_func(bus, arg);
2043                 CAM_SIM_UNLOCK(bus->sim);
2044
2045                 mtx_lock(&xsoftc.xpt_topo_lock);
2046                 next_bus = TAILQ_NEXT(bus, links);
2047                 mtx_unlock(&xsoftc.xpt_topo_lock);
2048
2049                 xpt_release_bus(bus);
2050
2051                 if (retval == 0)
2052                         return(retval);
2053                 mtx_lock(&xsoftc.xpt_topo_lock);
2054         }
2055         mtx_unlock(&xsoftc.xpt_topo_lock);
2056
2057         return(retval);
2058 }
2059
2060 int
2061 xpt_sim_opened(struct cam_sim *sim)
2062 {
2063         struct cam_eb *bus;
2064         struct cam_et *target;
2065         struct cam_ed *device;
2066         struct cam_periph *periph;
2067
2068         KASSERT(sim->refcount >= 1, ("sim->refcount >= 1"));
2069         mtx_assert(sim->mtx, MA_OWNED);
2070
2071         mtx_lock(&xsoftc.xpt_topo_lock);
2072         TAILQ_FOREACH(bus, &xsoftc.xpt_busses, links) {
2073                 if (bus->sim != sim)
2074                         continue;
2075
2076                 TAILQ_FOREACH(target, &bus->et_entries, links) {
2077                         TAILQ_FOREACH(device, &target->ed_entries, links) {
2078                                 SLIST_FOREACH(periph, &device->periphs,
2079                                     periph_links) {
2080                                         if (periph->refcount > 0) {
2081                                                 mtx_unlock(&xsoftc.xpt_topo_lock);
2082                                                 return (1);
2083                                         }
2084                                 }
2085                         }
2086                 }
2087         }
2088
2089         mtx_unlock(&xsoftc.xpt_topo_lock);
2090         return (0);
2091 }
2092
2093 static int
2094 xpttargettraverse(struct cam_eb *bus, struct cam_et *start_target,
2095                   xpt_targetfunc_t *tr_func, void *arg)
2096 {
2097         struct cam_et *target, *next_target;
2098         int retval;
2099
2100         retval = 1;
2101         for (target = (start_target ? start_target :
2102                        TAILQ_FIRST(&bus->et_entries));
2103              target != NULL; target = next_target) {
2104
2105                 target->refcount++;
2106
2107                 retval = tr_func(target, arg);
2108
2109                 next_target = TAILQ_NEXT(target, links);
2110
2111                 xpt_release_target(target);
2112
2113                 if (retval == 0)
2114                         return(retval);
2115         }
2116
2117         return(retval);
2118 }
2119
2120 static int
2121 xptdevicetraverse(struct cam_et *target, struct cam_ed *start_device,
2122                   xpt_devicefunc_t *tr_func, void *arg)
2123 {
2124         struct cam_ed *device, *next_device;
2125         int retval;
2126
2127         retval = 1;
2128         for (device = (start_device ? start_device :
2129                        TAILQ_FIRST(&target->ed_entries));
2130              device != NULL;
2131              device = next_device) {
2132
2133                 /*
2134                  * Hold a reference so the current device does not go away
2135                  * on us.
2136                  */
2137                 device->refcount++;
2138
2139                 retval = tr_func(device, arg);
2140
2141                 /*
2142                  * Grab our next pointer before we release the current
2143                  * device.
2144                  */
2145                 next_device = TAILQ_NEXT(device, links);
2146
2147                 xpt_release_device(device);
2148
2149                 if (retval == 0)
2150                         return(retval);
2151         }
2152
2153         return(retval);
2154 }
2155
2156 static int
2157 xptperiphtraverse(struct cam_ed *device, struct cam_periph *start_periph,
2158                   xpt_periphfunc_t *tr_func, void *arg)
2159 {
2160         struct cam_periph *periph, *next_periph;
2161         int retval;
2162
2163         retval = 1;
2164
2165         xpt_lock_buses();
2166         for (periph = (start_periph ? start_periph :
2167                        SLIST_FIRST(&device->periphs));
2168              periph != NULL;
2169              periph = next_periph) {
2170
2171
2172                 /*
2173                  * In this case, we want to show peripherals that have been
2174                  * invalidated, but not peripherals that are scheduled to
2175                  * be freed.  So instead of calling cam_periph_acquire(),
2176                  * which will fail if the periph has been invalidated, we
2177                  * just check for the free flag here.  If it is free, we
2178                  * skip to the next periph.
2179                  */
2180                 if (periph->flags & CAM_PERIPH_FREE) {
2181                         next_periph = SLIST_NEXT(periph, periph_links);
2182                         continue;
2183                 }
2184
2185                 /*
2186                  * Acquire a reference to this periph while we call the
2187                  * traversal function, so it can't go away.
2188                  */
2189                 periph->refcount++;
2190
2191                 xpt_unlock_buses();
2192
2193                 retval = tr_func(periph, arg);
2194
2195                 /*
2196                  * We need the lock for list traversal.
2197                  */
2198                 xpt_lock_buses();
2199
2200                 /*
2201                  * Grab the next peripheral before we release this one, so
2202                  * our next pointer is still valid.
2203                  */
2204                 next_periph = SLIST_NEXT(periph, periph_links);
2205
2206                 cam_periph_release_locked_buses(periph);
2207
2208                 if (retval == 0)
2209                         goto bailout_done;
2210         }
2211
2212 bailout_done:
2213
2214         xpt_unlock_buses();
2215
2216         return(retval);
2217 }
2218
2219 static int
2220 xptpdrvtraverse(struct periph_driver **start_pdrv,
2221                 xpt_pdrvfunc_t *tr_func, void *arg)
2222 {
2223         struct periph_driver **pdrv;
2224         int retval;
2225
2226         retval = 1;
2227
2228         /*
2229          * We don't traverse the peripheral driver list like we do the
2230          * other lists, because it is a linker set, and therefore cannot be
2231          * changed during runtime.  If the peripheral driver list is ever
2232          * re-done to be something other than a linker set (i.e. it can
2233          * change while the system is running), the list traversal should
2234          * be modified to work like the other traversal functions.
2235          */
2236         for (pdrv = (start_pdrv ? start_pdrv : periph_drivers);
2237              *pdrv != NULL; pdrv++) {
2238                 retval = tr_func(pdrv, arg);
2239
2240                 if (retval == 0)
2241                         return(retval);
2242         }
2243
2244         return(retval);
2245 }
2246
2247 static int
2248 xptpdperiphtraverse(struct periph_driver **pdrv,
2249                     struct cam_periph *start_periph,
2250                     xpt_periphfunc_t *tr_func, void *arg)
2251 {
2252         struct cam_periph *periph, *next_periph;
2253         int retval;
2254
2255         retval = 1;
2256
2257         xpt_lock_buses();
2258         for (periph = (start_periph ? start_periph :
2259              TAILQ_FIRST(&(*pdrv)->units)); periph != NULL;
2260              periph = next_periph) {
2261
2262
2263                 /*
2264                  * In this case, we want to show peripherals that have been
2265                  * invalidated, but not peripherals that are scheduled to
2266                  * be freed.  So instead of calling cam_periph_acquire(),
2267                  * which will fail if the periph has been invalidated, we
2268                  * just check for the free flag here.  If it is free, we
2269                  * skip to the next periph.
2270                  */
2271                 if (periph->flags & CAM_PERIPH_FREE) {
2272                         next_periph = TAILQ_NEXT(periph, unit_links);
2273                         continue;
2274                 }
2275
2276                 /*
2277                  * Acquire a reference to this periph while we call the
2278                  * traversal function, so it can't go away.
2279                  */
2280                 periph->refcount++;
2281
2282                 /*
2283                  * XXX KDM we have the toplogy lock here, but in
2284                  * xptperiphtraverse(), we drop it before calling the
2285                  * traversal function.  Which is correct?
2286                  */
2287                 retval = tr_func(periph, arg);
2288
2289                 /*
2290                  * Grab the next peripheral before we release this one, so
2291                  * our next pointer is still valid.
2292                  */
2293                 next_periph = TAILQ_NEXT(periph, unit_links);
2294
2295                 cam_periph_release_locked_buses(periph);
2296
2297                 if (retval == 0)
2298                         goto bailout_done;
2299         }
2300 bailout_done:
2301
2302         xpt_unlock_buses();
2303
2304         return(retval);
2305 }
2306
2307 static int
2308 xptdefbusfunc(struct cam_eb *bus, void *arg)
2309 {
2310         struct xpt_traverse_config *tr_config;
2311
2312         tr_config = (struct xpt_traverse_config *)arg;
2313
2314         if (tr_config->depth == XPT_DEPTH_BUS) {
2315                 xpt_busfunc_t *tr_func;
2316
2317                 tr_func = (xpt_busfunc_t *)tr_config->tr_func;
2318
2319                 return(tr_func(bus, tr_config->tr_arg));
2320         } else
2321                 return(xpttargettraverse(bus, NULL, xptdeftargetfunc, arg));
2322 }
2323
2324 static int
2325 xptdeftargetfunc(struct cam_et *target, void *arg)
2326 {
2327         struct xpt_traverse_config *tr_config;
2328
2329         tr_config = (struct xpt_traverse_config *)arg;
2330
2331         if (tr_config->depth == XPT_DEPTH_TARGET) {
2332                 xpt_targetfunc_t *tr_func;
2333
2334                 tr_func = (xpt_targetfunc_t *)tr_config->tr_func;
2335
2336                 return(tr_func(target, tr_config->tr_arg));
2337         } else
2338                 return(xptdevicetraverse(target, NULL, xptdefdevicefunc, arg));
2339 }
2340
2341 static int
2342 xptdefdevicefunc(struct cam_ed *device, void *arg)
2343 {
2344         struct xpt_traverse_config *tr_config;
2345
2346         tr_config = (struct xpt_traverse_config *)arg;
2347
2348         if (tr_config->depth == XPT_DEPTH_DEVICE) {
2349                 xpt_devicefunc_t *tr_func;
2350
2351                 tr_func = (xpt_devicefunc_t *)tr_config->tr_func;
2352
2353                 return(tr_func(device, tr_config->tr_arg));
2354         } else
2355                 return(xptperiphtraverse(device, NULL, xptdefperiphfunc, arg));
2356 }
2357
2358 static int
2359 xptdefperiphfunc(struct cam_periph *periph, void *arg)
2360 {
2361         struct xpt_traverse_config *tr_config;
2362         xpt_periphfunc_t *tr_func;
2363
2364         tr_config = (struct xpt_traverse_config *)arg;
2365
2366         tr_func = (xpt_periphfunc_t *)tr_config->tr_func;
2367
2368         /*
2369          * Unlike the other default functions, we don't check for depth
2370          * here.  The peripheral driver level is the last level in the EDT,
2371          * so if we're here, we should execute the function in question.
2372          */
2373         return(tr_func(periph, tr_config->tr_arg));
2374 }
2375
2376 /*
2377  * Execute the given function for every bus in the EDT.
2378  */
2379 static int
2380 xpt_for_all_busses(xpt_busfunc_t *tr_func, void *arg)
2381 {
2382         struct xpt_traverse_config tr_config;
2383
2384         tr_config.depth = XPT_DEPTH_BUS;
2385         tr_config.tr_func = tr_func;
2386         tr_config.tr_arg = arg;
2387
2388         return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2389 }
2390
2391 /*
2392  * Execute the given function for every device in the EDT.
2393  */
2394 static int
2395 xpt_for_all_devices(xpt_devicefunc_t *tr_func, void *arg)
2396 {
2397         struct xpt_traverse_config tr_config;
2398
2399         tr_config.depth = XPT_DEPTH_DEVICE;
2400         tr_config.tr_func = tr_func;
2401         tr_config.tr_arg = arg;
2402
2403         return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2404 }
2405
2406 static int
2407 xptsetasyncfunc(struct cam_ed *device, void *arg)
2408 {
2409         struct cam_path path;
2410         struct ccb_getdev cgd;
2411         struct ccb_setasync *csa = (struct ccb_setasync *)arg;
2412
2413         /*
2414          * Don't report unconfigured devices (Wildcard devs,
2415          * devices only for target mode, device instances
2416          * that have been invalidated but are waiting for
2417          * their last reference count to be released).
2418          */
2419         if ((device->flags & CAM_DEV_UNCONFIGURED) != 0)
2420                 return (1);
2421
2422         xpt_compile_path(&path,
2423                          NULL,
2424                          device->target->bus->path_id,
2425                          device->target->target_id,
2426                          device->lun_id);
2427         xpt_setup_ccb(&cgd.ccb_h, &path, CAM_PRIORITY_NORMAL);
2428         cgd.ccb_h.func_code = XPT_GDEV_TYPE;
2429         xpt_action((union ccb *)&cgd);
2430         csa->callback(csa->callback_arg,
2431                             AC_FOUND_DEVICE,
2432                             &path, &cgd);
2433         xpt_release_path(&path);
2434
2435         return(1);
2436 }
2437
2438 static int
2439 xptsetasyncbusfunc(struct cam_eb *bus, void *arg)
2440 {
2441         struct cam_path path;
2442         struct ccb_pathinq cpi;
2443         struct ccb_setasync *csa = (struct ccb_setasync *)arg;
2444
2445         xpt_compile_path(&path, /*periph*/NULL,
2446                          bus->sim->path_id,
2447                          CAM_TARGET_WILDCARD,
2448                          CAM_LUN_WILDCARD);
2449         xpt_setup_ccb(&cpi.ccb_h, &path, CAM_PRIORITY_NORMAL);
2450         cpi.ccb_h.func_code = XPT_PATH_INQ;
2451         xpt_action((union ccb *)&cpi);
2452         csa->callback(csa->callback_arg,
2453                             AC_PATH_REGISTERED,
2454                             &path, &cpi);
2455         xpt_release_path(&path);
2456
2457         return(1);
2458 }
2459
2460 void
2461 xpt_action(union ccb *start_ccb)
2462 {
2463
2464         CAM_DEBUG(start_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("xpt_action\n"));
2465
2466         start_ccb->ccb_h.status = CAM_REQ_INPROG;
2467         /* Compatibility for RL-unaware code. */
2468         if (CAM_PRIORITY_TO_RL(start_ccb->ccb_h.pinfo.priority) == 0)
2469             start_ccb->ccb_h.pinfo.priority += CAM_PRIORITY_NORMAL - 1;
2470         (*(start_ccb->ccb_h.path->bus->xport->action))(start_ccb);
2471 }
2472
2473 void
2474 xpt_action_default(union ccb *start_ccb)
2475 {
2476         char cdb_str[(SCSI_MAX_CDBLEN * 3) + 1];
2477         struct cam_path *path;
2478
2479         path = start_ccb->ccb_h.path;
2480         CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_action_default\n"));
2481
2482         switch (start_ccb->ccb_h.func_code) {
2483         case XPT_SCSI_IO:
2484         {
2485                 struct cam_ed *device;
2486
2487                 /*
2488                  * For the sake of compatibility with SCSI-1
2489                  * devices that may not understand the identify
2490                  * message, we include lun information in the
2491                  * second byte of all commands.  SCSI-1 specifies
2492                  * that luns are a 3 bit value and reserves only 3
2493                  * bits for lun information in the CDB.  Later
2494                  * revisions of the SCSI spec allow for more than 8
2495                  * luns, but have deprecated lun information in the
2496                  * CDB.  So, if the lun won't fit, we must omit.
2497                  *
2498                  * Also be aware that during initial probing for devices,
2499                  * the inquiry information is unknown but initialized to 0.
2500                  * This means that this code will be exercised while probing
2501                  * devices with an ANSI revision greater than 2.
2502                  */
2503                 device = path->device;
2504                 if (device->protocol_version <= SCSI_REV_2
2505                  && start_ccb->ccb_h.target_lun < 8
2506                  && (start_ccb->ccb_h.flags & CAM_CDB_POINTER) == 0) {
2507
2508                         start_ccb->csio.cdb_io.cdb_bytes[1] |=
2509                             start_ccb->ccb_h.target_lun << 5;
2510                 }
2511                 start_ccb->csio.scsi_status = SCSI_STATUS_OK;
2512                 CAM_DEBUG(path, CAM_DEBUG_CDB,("%s. CDB: %s\n",
2513                           scsi_op_desc(start_ccb->csio.cdb_io.cdb_bytes[0],
2514                                        &path->device->inq_data),
2515                           scsi_cdb_string(start_ccb->csio.cdb_io.cdb_bytes,
2516                                           cdb_str, sizeof(cdb_str))));
2517         }
2518         /* FALLTHROUGH */
2519         case XPT_TARGET_IO:
2520         case XPT_CONT_TARGET_IO:
2521                 start_ccb->csio.sense_resid = 0;
2522                 start_ccb->csio.resid = 0;
2523                 /* FALLTHROUGH */
2524         case XPT_ATA_IO:
2525                 if (start_ccb->ccb_h.func_code == XPT_ATA_IO) {
2526                         start_ccb->ataio.resid = 0;
2527                         CAM_DEBUG(path, CAM_DEBUG_CDB,("%s. ACB: %s\n",
2528                             ata_op_string(&start_ccb->ataio.cmd),
2529                             ata_cmd_string(&start_ccb->ataio.cmd,
2530                                           cdb_str, sizeof(cdb_str))));
2531                 }
2532                 /* FALLTHROUGH */
2533         case XPT_RESET_DEV:
2534         case XPT_ENG_EXEC:
2535         case XPT_SMP_IO:
2536         {
2537                 int frozen;
2538
2539                 frozen = cam_ccbq_insert_ccb(&path->device->ccbq, start_ccb);
2540                 path->device->sim->devq->alloc_openings += frozen;
2541                 if (frozen > 0)
2542                         xpt_run_dev_allocq(path->bus);
2543                 if (xpt_schedule_dev_sendq(path->bus, path->device))
2544                         xpt_run_dev_sendq(path->bus);
2545                 break;
2546         }
2547         case XPT_CALC_GEOMETRY:
2548         {
2549                 struct cam_sim *sim;
2550
2551                 /* Filter out garbage */
2552                 if (start_ccb->ccg.block_size == 0
2553                  || start_ccb->ccg.volume_size == 0) {
2554                         start_ccb->ccg.cylinders = 0;
2555                         start_ccb->ccg.heads = 0;
2556                         start_ccb->ccg.secs_per_track = 0;
2557                         start_ccb->ccb_h.status = CAM_REQ_CMP;
2558                         break;
2559                 }
2560 #if defined(PC98) || defined(__sparc64__)
2561                 /*
2562                  * In a PC-98 system, geometry translation depens on
2563                  * the "real" device geometry obtained from mode page 4.
2564                  * SCSI geometry translation is performed in the
2565                  * initialization routine of the SCSI BIOS and the result
2566                  * stored in host memory.  If the translation is available
2567                  * in host memory, use it.  If not, rely on the default
2568                  * translation the device driver performs.
2569                  * For sparc64, we may need adjust the geometry of large
2570                  * disks in order to fit the limitations of the 16-bit
2571                  * fields of the VTOC8 disk label.
2572                  */
2573                 if (scsi_da_bios_params(&start_ccb->ccg) != 0) {
2574                         start_ccb->ccb_h.status = CAM_REQ_CMP;
2575                         break;
2576                 }
2577 #endif
2578                 sim = path->bus->sim;
2579                 (*(sim->sim_action))(sim, start_ccb);
2580                 break;
2581         }
2582         case XPT_ABORT:
2583         {
2584                 union ccb* abort_ccb;
2585
2586                 abort_ccb = start_ccb->cab.abort_ccb;
2587                 if (XPT_FC_IS_DEV_QUEUED(abort_ccb)) {
2588
2589                         if (abort_ccb->ccb_h.pinfo.index >= 0) {
2590                                 struct cam_ccbq *ccbq;
2591                                 struct cam_ed *device;
2592
2593                                 device = abort_ccb->ccb_h.path->device;
2594                                 ccbq = &device->ccbq;
2595                                 device->sim->devq->alloc_openings -= 
2596                                     cam_ccbq_remove_ccb(ccbq, abort_ccb);
2597                                 abort_ccb->ccb_h.status =
2598                                     CAM_REQ_ABORTED|CAM_DEV_QFRZN;
2599                                 xpt_freeze_devq(abort_ccb->ccb_h.path, 1);
2600                                 xpt_done(abort_ccb);
2601                                 start_ccb->ccb_h.status = CAM_REQ_CMP;
2602                                 break;
2603                         }
2604                         if (abort_ccb->ccb_h.pinfo.index == CAM_UNQUEUED_INDEX
2605                          && (abort_ccb->ccb_h.status & CAM_SIM_QUEUED) == 0) {
2606                                 /*
2607                                  * We've caught this ccb en route to
2608                                  * the SIM.  Flag it for abort and the
2609                                  * SIM will do so just before starting
2610                                  * real work on the CCB.
2611                                  */
2612                                 abort_ccb->ccb_h.status =
2613                                     CAM_REQ_ABORTED|CAM_DEV_QFRZN;
2614                                 xpt_freeze_devq(abort_ccb->ccb_h.path, 1);
2615                                 start_ccb->ccb_h.status = CAM_REQ_CMP;
2616                                 break;
2617                         }
2618                 }
2619                 if (XPT_FC_IS_QUEUED(abort_ccb)
2620                  && (abort_ccb->ccb_h.pinfo.index == CAM_DONEQ_INDEX)) {
2621                         /*
2622                          * It's already completed but waiting
2623                          * for our SWI to get to it.
2624                          */
2625                         start_ccb->ccb_h.status = CAM_UA_ABORT;
2626                         break;
2627                 }
2628                 /*
2629                  * If we weren't able to take care of the abort request
2630                  * in the XPT, pass the request down to the SIM for processing.
2631                  */
2632         }
2633         /* FALLTHROUGH */
2634         case XPT_ACCEPT_TARGET_IO:
2635         case XPT_EN_LUN:
2636         case XPT_IMMED_NOTIFY:
2637         case XPT_NOTIFY_ACK:
2638         case XPT_RESET_BUS:
2639         case XPT_IMMEDIATE_NOTIFY:
2640         case XPT_NOTIFY_ACKNOWLEDGE:
2641         case XPT_GET_SIM_KNOB:
2642         case XPT_SET_SIM_KNOB:
2643         {
2644                 struct cam_sim *sim;
2645
2646                 sim = path->bus->sim;
2647                 (*(sim->sim_action))(sim, start_ccb);
2648                 break;
2649         }
2650         case XPT_PATH_INQ:
2651         {
2652                 struct cam_sim *sim;
2653
2654                 sim = path->bus->sim;
2655                 (*(sim->sim_action))(sim, start_ccb);
2656                 break;
2657         }
2658         case XPT_PATH_STATS:
2659                 start_ccb->cpis.last_reset = path->bus->last_reset;
2660                 start_ccb->ccb_h.status = CAM_REQ_CMP;
2661                 break;
2662         case XPT_GDEV_TYPE:
2663         {
2664                 struct cam_ed *dev;
2665
2666                 dev = path->device;
2667                 if ((dev->flags & CAM_DEV_UNCONFIGURED) != 0) {
2668                         start_ccb->ccb_h.status = CAM_DEV_NOT_THERE;
2669                 } else {
2670                         struct ccb_getdev *cgd;
2671
2672                         cgd = &start_ccb->cgd;
2673                         cgd->protocol = dev->protocol;
2674                         cgd->inq_data = dev->inq_data;
2675                         cgd->ident_data = dev->ident_data;
2676                         cgd->inq_flags = dev->inq_flags;
2677                         cgd->ccb_h.status = CAM_REQ_CMP;
2678                         cgd->serial_num_len = dev->serial_num_len;
2679                         if ((dev->serial_num_len > 0)
2680                          && (dev->serial_num != NULL))
2681                                 bcopy(dev->serial_num, cgd->serial_num,
2682                                       dev->serial_num_len);
2683                 }
2684                 break;
2685         }
2686         case XPT_GDEV_STATS:
2687         {
2688                 struct cam_ed *dev;
2689
2690                 dev = path->device;
2691                 if ((dev->flags & CAM_DEV_UNCONFIGURED) != 0) {
2692                         start_ccb->ccb_h.status = CAM_DEV_NOT_THERE;
2693                 } else {
2694                         struct ccb_getdevstats *cgds;
2695                         struct cam_eb *bus;
2696                         struct cam_et *tar;
2697
2698                         cgds = &start_ccb->cgds;
2699                         bus = path->bus;
2700                         tar = path->target;
2701                         cgds->dev_openings = dev->ccbq.dev_openings;
2702                         cgds->dev_active = dev->ccbq.dev_active;
2703                         cgds->devq_openings = dev->ccbq.devq_openings;
2704                         cgds->devq_queued = dev->ccbq.queue.entries;
2705                         cgds->held = dev->ccbq.held;
2706                         cgds->last_reset = tar->last_reset;
2707                         cgds->maxtags = dev->maxtags;
2708                         cgds->mintags = dev->mintags;
2709                         if (timevalcmp(&tar->last_reset, &bus->last_reset, <))
2710                                 cgds->last_reset = bus->last_reset;
2711                         cgds->ccb_h.status = CAM_REQ_CMP;
2712                 }
2713                 break;
2714         }
2715         case XPT_GDEVLIST:
2716         {
2717                 struct cam_periph       *nperiph;
2718                 struct periph_list      *periph_head;
2719                 struct ccb_getdevlist   *cgdl;
2720                 u_int                   i;
2721                 struct cam_ed           *device;
2722                 int                     found;
2723
2724
2725                 found = 0;
2726
2727                 /*
2728                  * Don't want anyone mucking with our data.
2729                  */
2730                 device = path->device;
2731                 periph_head = &device->periphs;
2732                 cgdl = &start_ccb->cgdl;
2733
2734                 /*
2735                  * Check and see if the list has changed since the user
2736                  * last requested a list member.  If so, tell them that the
2737                  * list has changed, and therefore they need to start over
2738                  * from the beginning.
2739                  */
2740                 if ((cgdl->index != 0) &&
2741                     (cgdl->generation != device->generation)) {
2742                         cgdl->status = CAM_GDEVLIST_LIST_CHANGED;
2743                         break;
2744                 }
2745
2746                 /*
2747                  * Traverse the list of peripherals and attempt to find
2748                  * the requested peripheral.
2749                  */
2750                 for (nperiph = SLIST_FIRST(periph_head), i = 0;
2751                      (nperiph != NULL) && (i <= cgdl->index);
2752                      nperiph = SLIST_NEXT(nperiph, periph_links), i++) {
2753                         if (i == cgdl->index) {
2754                                 strncpy(cgdl->periph_name,
2755                                         nperiph->periph_name,
2756                                         DEV_IDLEN);
2757                                 cgdl->unit_number = nperiph->unit_number;
2758                                 found = 1;
2759                         }
2760                 }
2761                 if (found == 0) {
2762                         cgdl->status = CAM_GDEVLIST_ERROR;
2763                         break;
2764                 }
2765
2766                 if (nperiph == NULL)
2767                         cgdl->status = CAM_GDEVLIST_LAST_DEVICE;
2768                 else
2769                         cgdl->status = CAM_GDEVLIST_MORE_DEVS;
2770
2771                 cgdl->index++;
2772                 cgdl->generation = device->generation;
2773
2774                 cgdl->ccb_h.status = CAM_REQ_CMP;
2775                 break;
2776         }
2777         case XPT_DEV_MATCH:
2778         {
2779                 dev_pos_type position_type;
2780                 struct ccb_dev_match *cdm;
2781
2782                 cdm = &start_ccb->cdm;
2783
2784                 /*
2785                  * There are two ways of getting at information in the EDT.
2786                  * The first way is via the primary EDT tree.  It starts
2787                  * with a list of busses, then a list of targets on a bus,
2788                  * then devices/luns on a target, and then peripherals on a
2789                  * device/lun.  The "other" way is by the peripheral driver
2790                  * lists.  The peripheral driver lists are organized by
2791                  * peripheral driver.  (obviously)  So it makes sense to
2792                  * use the peripheral driver list if the user is looking
2793                  * for something like "da1", or all "da" devices.  If the
2794                  * user is looking for something on a particular bus/target
2795                  * or lun, it's generally better to go through the EDT tree.
2796                  */
2797
2798                 if (cdm->pos.position_type != CAM_DEV_POS_NONE)
2799                         position_type = cdm->pos.position_type;
2800                 else {
2801                         u_int i;
2802
2803                         position_type = CAM_DEV_POS_NONE;
2804
2805                         for (i = 0; i < cdm->num_patterns; i++) {
2806                                 if ((cdm->patterns[i].type == DEV_MATCH_BUS)
2807                                  ||(cdm->patterns[i].type == DEV_MATCH_DEVICE)){
2808                                         position_type = CAM_DEV_POS_EDT;
2809                                         break;
2810                                 }
2811                         }
2812
2813                         if (cdm->num_patterns == 0)
2814                                 position_type = CAM_DEV_POS_EDT;
2815                         else if (position_type == CAM_DEV_POS_NONE)
2816                                 position_type = CAM_DEV_POS_PDRV;
2817                 }
2818
2819                 switch(position_type & CAM_DEV_POS_TYPEMASK) {
2820                 case CAM_DEV_POS_EDT:
2821                         xptedtmatch(cdm);
2822                         break;
2823                 case CAM_DEV_POS_PDRV:
2824                         xptperiphlistmatch(cdm);
2825                         break;
2826                 default:
2827                         cdm->status = CAM_DEV_MATCH_ERROR;
2828                         break;
2829                 }
2830
2831                 if (cdm->status == CAM_DEV_MATCH_ERROR)
2832                         start_ccb->ccb_h.status = CAM_REQ_CMP_ERR;
2833                 else
2834                         start_ccb->ccb_h.status = CAM_REQ_CMP;
2835
2836                 break;
2837         }
2838         case XPT_SASYNC_CB:
2839         {
2840                 struct ccb_setasync *csa;
2841                 struct async_node *cur_entry;
2842                 struct async_list *async_head;
2843                 u_int32_t added;
2844
2845                 csa = &start_ccb->csa;
2846                 added = csa->event_enable;
2847                 async_head = &path->device->asyncs;
2848
2849                 /*
2850                  * If there is already an entry for us, simply
2851                  * update it.
2852                  */
2853                 cur_entry = SLIST_FIRST(async_head);
2854                 while (cur_entry != NULL) {
2855                         if ((cur_entry->callback_arg == csa->callback_arg)
2856                          && (cur_entry->callback == csa->callback))
2857                                 break;
2858                         cur_entry = SLIST_NEXT(cur_entry, links);
2859                 }
2860
2861                 if (cur_entry != NULL) {
2862                         /*
2863                          * If the request has no flags set,
2864                          * remove the entry.
2865                          */
2866                         added &= ~cur_entry->event_enable;
2867                         if (csa->event_enable == 0) {
2868                                 SLIST_REMOVE(async_head, cur_entry,
2869                                              async_node, links);
2870                                 xpt_release_device(path->device);
2871                                 free(cur_entry, M_CAMXPT);
2872                         } else {
2873                                 cur_entry->event_enable = csa->event_enable;
2874                         }
2875                         csa->event_enable = added;
2876                 } else {
2877                         cur_entry = malloc(sizeof(*cur_entry), M_CAMXPT,
2878                                            M_NOWAIT);
2879                         if (cur_entry == NULL) {
2880                                 csa->ccb_h.status = CAM_RESRC_UNAVAIL;
2881                                 break;
2882                         }
2883                         cur_entry->event_enable = csa->event_enable;
2884                         cur_entry->callback_arg = csa->callback_arg;
2885                         cur_entry->callback = csa->callback;
2886                         SLIST_INSERT_HEAD(async_head, cur_entry, links);
2887                         xpt_acquire_device(path->device);
2888                 }
2889                 start_ccb->ccb_h.status = CAM_REQ_CMP;
2890                 break;
2891         }
2892         case XPT_REL_SIMQ:
2893         {
2894                 struct ccb_relsim *crs;
2895                 struct cam_ed *dev;
2896
2897                 crs = &start_ccb->crs;
2898                 dev = path->device;
2899                 if (dev == NULL) {
2900
2901                         crs->ccb_h.status = CAM_DEV_NOT_THERE;
2902                         break;
2903                 }
2904
2905                 if ((crs->release_flags & RELSIM_ADJUST_OPENINGS) != 0) {
2906
2907                         /* Don't ever go below one opening */
2908                         if (crs->openings > 0) {
2909                                 xpt_dev_ccbq_resize(path, crs->openings);
2910                                 if (bootverbose) {
2911                                         xpt_print(path,
2912                                             "number of openings is now %d\n",
2913                                             crs->openings);
2914                                 }
2915                         }
2916                 }
2917
2918                 if ((crs->release_flags & RELSIM_RELEASE_AFTER_TIMEOUT) != 0) {
2919
2920                         if ((dev->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
2921
2922                                 /*
2923                                  * Just extend the old timeout and decrement
2924                                  * the freeze count so that a single timeout
2925                                  * is sufficient for releasing the queue.
2926                                  */
2927                                 start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
2928                                 callout_stop(&dev->callout);
2929                         } else {
2930
2931                                 start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
2932                         }
2933
2934                         callout_reset(&dev->callout,
2935                             (crs->release_timeout * hz) / 1000,
2936                             xpt_release_devq_timeout, dev);
2937
2938                         dev->flags |= CAM_DEV_REL_TIMEOUT_PENDING;
2939
2940                 }
2941
2942                 if ((crs->release_flags & RELSIM_RELEASE_AFTER_CMDCMPLT) != 0) {
2943
2944                         if ((dev->flags & CAM_DEV_REL_ON_COMPLETE) != 0) {
2945                                 /*
2946                                  * Decrement the freeze count so that a single
2947                                  * completion is still sufficient to unfreeze
2948                                  * the queue.
2949                                  */
2950                                 start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
2951                         } else {
2952
2953                                 dev->flags |= CAM_DEV_REL_ON_COMPLETE;
2954                                 start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
2955                         }
2956                 }
2957
2958                 if ((crs->release_flags & RELSIM_RELEASE_AFTER_QEMPTY) != 0) {
2959
2960                         if ((dev->flags & CAM_DEV_REL_ON_QUEUE_EMPTY) != 0
2961                          || (dev->ccbq.dev_active == 0)) {
2962
2963                                 start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
2964                         } else {
2965
2966                                 dev->flags |= CAM_DEV_REL_ON_QUEUE_EMPTY;
2967                                 start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
2968                         }
2969                 }
2970
2971                 if ((start_ccb->ccb_h.flags & CAM_DEV_QFREEZE) == 0) {
2972                         xpt_release_devq_rl(path, /*runlevel*/
2973                             (crs->release_flags & RELSIM_RELEASE_RUNLEVEL) ?
2974                                 crs->release_timeout : 0,
2975                             /*count*/1, /*run_queue*/TRUE);
2976                 }
2977                 start_ccb->crs.qfrozen_cnt = dev->ccbq.queue.qfrozen_cnt[0];
2978                 start_ccb->ccb_h.status = CAM_REQ_CMP;
2979                 break;
2980         }
2981         case XPT_DEBUG: {
2982                 /* Check that all request bits are supported. */
2983                 if (start_ccb->cdbg.flags & ~(CAM_DEBUG_COMPILE)) {
2984                         start_ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
2985                         break;
2986                 }
2987
2988                 cam_dflags = start_ccb->cdbg.flags;
2989                 if (cam_dpath != NULL) {
2990                         xpt_free_path(cam_dpath);
2991                         cam_dpath = NULL;
2992                 }
2993                 if (cam_dflags != CAM_DEBUG_NONE) {
2994                         if (xpt_create_path(&cam_dpath, xpt_periph,
2995                                             start_ccb->ccb_h.path_id,
2996                                             start_ccb->ccb_h.target_id,
2997                                             start_ccb->ccb_h.target_lun) !=
2998                                             CAM_REQ_CMP) {
2999                                 start_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
3000                                 cam_dflags = CAM_DEBUG_NONE;
3001                         } else {
3002                                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3003                                 xpt_print(cam_dpath, "debugging flags now %x\n",
3004                                     cam_dflags);
3005                         }
3006                 } else {
3007                         cam_dpath = NULL;
3008                         start_ccb->ccb_h.status = CAM_REQ_CMP;
3009                 }
3010                 break;
3011         }
3012         case XPT_FREEZE_QUEUE:
3013         {
3014                 struct ccb_relsim *crs = &start_ccb->crs;
3015
3016                 xpt_freeze_devq_rl(path, /*runlevel*/
3017                     (crs->release_flags & RELSIM_RELEASE_RUNLEVEL) ?
3018                     crs->release_timeout : 0, /*count*/1);
3019                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3020                 break;
3021         }
3022         case XPT_NOOP:
3023                 if ((start_ccb->ccb_h.flags & CAM_DEV_QFREEZE) != 0)
3024                         xpt_freeze_devq(path, 1);
3025                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3026                 break;
3027         default:
3028         case XPT_SDEV_TYPE:
3029         case XPT_TERM_IO:
3030         case XPT_ENG_INQ:
3031                 /* XXX Implement */
3032                 printf("%s: CCB type %#x not supported\n", __func__,
3033                        start_ccb->ccb_h.func_code);
3034                 start_ccb->ccb_h.status = CAM_PROVIDE_FAIL;
3035                 if (start_ccb->ccb_h.func_code & XPT_FC_DEV_QUEUED) {
3036                         xpt_done(start_ccb);
3037                 }
3038                 break;
3039         }
3040 }
3041
3042 void
3043 xpt_polled_action(union ccb *start_ccb)
3044 {
3045         u_int32_t timeout;
3046         struct    cam_sim *sim;
3047         struct    cam_devq *devq;
3048         struct    cam_ed *dev;
3049
3050
3051         timeout = start_ccb->ccb_h.timeout * 10;
3052         sim = start_ccb->ccb_h.path->bus->sim;
3053         devq = sim->devq;
3054         dev = start_ccb->ccb_h.path->device;
3055
3056         mtx_assert(sim->mtx, MA_OWNED);
3057
3058         /* Don't use ISR for this SIM while polling. */
3059         sim->flags |= CAM_SIM_POLLED;
3060
3061         /*
3062          * Steal an opening so that no other queued requests
3063          * can get it before us while we simulate interrupts.
3064          */
3065         dev->ccbq.devq_openings--;
3066         dev->ccbq.dev_openings--;
3067
3068         while(((devq != NULL && devq->send_openings <= 0) ||
3069            dev->ccbq.dev_openings < 0) && (--timeout > 0)) {
3070                 DELAY(100);
3071                 (*(sim->sim_poll))(sim);
3072                 camisr_runqueue(&sim->sim_doneq);
3073         }
3074
3075         dev->ccbq.devq_openings++;
3076         dev->ccbq.dev_openings++;
3077
3078         if (timeout != 0) {
3079                 xpt_action(start_ccb);
3080                 while(--timeout > 0) {
3081                         (*(sim->sim_poll))(sim);
3082                         camisr_runqueue(&sim->sim_doneq);
3083                         if ((start_ccb->ccb_h.status  & CAM_STATUS_MASK)
3084                             != CAM_REQ_INPROG)
3085                                 break;
3086                         DELAY(100);
3087                 }
3088                 if (timeout == 0) {
3089                         /*
3090                          * XXX Is it worth adding a sim_timeout entry
3091                          * point so we can attempt recovery?  If
3092                          * this is only used for dumps, I don't think
3093                          * it is.
3094                          */
3095                         start_ccb->ccb_h.status = CAM_CMD_TIMEOUT;
3096                 }
3097         } else {
3098                 start_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
3099         }
3100
3101         /* We will use CAM ISR for this SIM again. */
3102         sim->flags &= ~CAM_SIM_POLLED;
3103 }
3104
3105 /*
3106  * Schedule a peripheral driver to receive a ccb when it's
3107  * target device has space for more transactions.
3108  */
3109 void
3110 xpt_schedule(struct cam_periph *perph, u_int32_t new_priority)
3111 {
3112         struct cam_ed *device;
3113         int runq = 0;
3114
3115         mtx_assert(perph->sim->mtx, MA_OWNED);
3116
3117         CAM_DEBUG(perph->path, CAM_DEBUG_TRACE, ("xpt_schedule\n"));
3118         device = perph->path->device;
3119         if (periph_is_queued(perph)) {
3120                 /* Simply reorder based on new priority */
3121                 CAM_DEBUG(perph->path, CAM_DEBUG_SUBTRACE,
3122                           ("   change priority to %d\n", new_priority));
3123                 if (new_priority < perph->pinfo.priority) {
3124                         camq_change_priority(&device->drvq,
3125                                              perph->pinfo.index,
3126                                              new_priority);
3127                         runq = xpt_schedule_dev_allocq(perph->path->bus, device);
3128                 }
3129         } else {
3130                 /* New entry on the queue */
3131                 CAM_DEBUG(perph->path, CAM_DEBUG_SUBTRACE,
3132                           ("   added periph to queue\n"));
3133                 perph->pinfo.priority = new_priority;
3134                 perph->pinfo.generation = ++device->drvq.generation;
3135                 camq_insert(&device->drvq, &perph->pinfo);
3136                 runq = xpt_schedule_dev_allocq(perph->path->bus, device);
3137         }
3138         if (runq != 0) {
3139                 CAM_DEBUG(perph->path, CAM_DEBUG_SUBTRACE,
3140                           ("   calling xpt_run_devq\n"));
3141                 xpt_run_dev_allocq(perph->path->bus);
3142         }
3143 }
3144
3145
3146 /*
3147  * Schedule a device to run on a given queue.
3148  * If the device was inserted as a new entry on the queue,
3149  * return 1 meaning the device queue should be run. If we
3150  * were already queued, implying someone else has already
3151  * started the queue, return 0 so the caller doesn't attempt
3152  * to run the queue.
3153  */
3154 int
3155 xpt_schedule_dev(struct camq *queue, cam_pinfo *pinfo,
3156                  u_int32_t new_priority)
3157 {
3158         int retval;
3159         u_int32_t old_priority;
3160
3161         CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_schedule_dev\n"));
3162
3163         old_priority = pinfo->priority;
3164
3165         /*
3166          * Are we already queued?
3167          */
3168         if (pinfo->index != CAM_UNQUEUED_INDEX) {
3169                 /* Simply reorder based on new priority */
3170                 if (new_priority < old_priority) {
3171                         camq_change_priority(queue, pinfo->index,
3172                                              new_priority);
3173                         CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3174                                         ("changed priority to %d\n",
3175                                          new_priority));
3176                         retval = 1;
3177                 } else
3178                         retval = 0;
3179         } else {
3180                 /* New entry on the queue */
3181                 if (new_priority < old_priority)
3182                         pinfo->priority = new_priority;
3183
3184                 CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3185                                 ("Inserting onto queue\n"));
3186                 pinfo->generation = ++queue->generation;
3187                 camq_insert(queue, pinfo);
3188                 retval = 1;
3189         }
3190         return (retval);
3191 }
3192
3193 static void
3194 xpt_run_dev_allocq(struct cam_eb *bus)
3195 {
3196         struct  cam_devq *devq;
3197
3198         CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_dev_allocq\n"));
3199         devq = bus->sim->devq;
3200
3201         CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3202                         ("   qfrozen_cnt == 0x%x, entries == %d, "
3203                          "openings == %d, active == %d\n",
3204                          devq->alloc_queue.qfrozen_cnt[0],
3205                          devq->alloc_queue.entries,
3206                          devq->alloc_openings,
3207                          devq->alloc_active));
3208
3209         devq->alloc_queue.qfrozen_cnt[0]++;
3210         while ((devq->alloc_queue.entries > 0)
3211             && (devq->alloc_openings > 0)
3212             && (devq->alloc_queue.qfrozen_cnt[0] <= 1)) {
3213                 struct  cam_ed_qinfo *qinfo;
3214                 struct  cam_ed *device;
3215                 union   ccb *work_ccb;
3216                 struct  cam_periph *drv;
3217                 struct  camq *drvq;
3218
3219                 qinfo = (struct cam_ed_qinfo *)camq_remove(&devq->alloc_queue,
3220                                                            CAMQ_HEAD);
3221                 device = qinfo->device;
3222                 CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3223                                 ("running device %p\n", device));
3224
3225                 drvq = &device->drvq;
3226                 KASSERT(drvq->entries > 0, ("xpt_run_dev_allocq: "
3227                     "Device on queue without any work to do"));
3228                 if ((work_ccb = xpt_get_ccb(device)) != NULL) {
3229                         devq->alloc_openings--;
3230                         devq->alloc_active++;
3231                         drv = (struct cam_periph*)camq_remove(drvq, CAMQ_HEAD);
3232                         xpt_setup_ccb(&work_ccb->ccb_h, drv->path,
3233                                       drv->pinfo.priority);
3234                         CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3235                                         ("calling periph start\n"));
3236                         drv->periph_start(drv, work_ccb);
3237                 } else {
3238                         /*
3239                          * Malloc failure in alloc_ccb
3240                          */
3241                         /*
3242                          * XXX add us to a list to be run from free_ccb
3243                          * if we don't have any ccbs active on this
3244                          * device queue otherwise we may never get run
3245                          * again.
3246                          */
3247                         break;
3248                 }
3249
3250                 /* We may have more work. Attempt to reschedule. */
3251                 xpt_schedule_dev_allocq(bus, device);
3252         }
3253         devq->alloc_queue.qfrozen_cnt[0]--;
3254 }
3255
3256 static void
3257 xpt_run_dev_sendq(struct cam_eb *bus)
3258 {
3259         struct  cam_devq *devq;
3260
3261         CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_dev_sendq\n"));
3262
3263         devq = bus->sim->devq;
3264
3265         devq->send_queue.qfrozen_cnt[0]++;
3266         while ((devq->send_queue.entries > 0)
3267             && (devq->send_openings > 0)
3268             && (devq->send_queue.qfrozen_cnt[0] <= 1)) {
3269                 struct  cam_ed_qinfo *qinfo;
3270                 struct  cam_ed *device;
3271                 union ccb *work_ccb;
3272                 struct  cam_sim *sim;
3273
3274                 qinfo = (struct cam_ed_qinfo *)camq_remove(&devq->send_queue,
3275                                                            CAMQ_HEAD);
3276                 device = qinfo->device;
3277                 CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3278                                 ("running device %p\n", device));
3279
3280                 work_ccb = cam_ccbq_peek_ccb(&device->ccbq, CAMQ_HEAD);
3281                 if (work_ccb == NULL) {
3282                         printf("device on run queue with no ccbs???\n");
3283                         continue;
3284                 }
3285
3286                 if ((work_ccb->ccb_h.flags & CAM_HIGH_POWER) != 0) {
3287
3288                         mtx_lock(&xsoftc.xpt_lock);
3289                         if (xsoftc.num_highpower <= 0) {
3290                                 /*
3291                                  * We got a high power command, but we
3292                                  * don't have any available slots.  Freeze
3293                                  * the device queue until we have a slot
3294                                  * available.
3295                                  */
3296                                 xpt_freeze_devq(work_ccb->ccb_h.path, 1);
3297                                 STAILQ_INSERT_TAIL(&xsoftc.highpowerq,
3298                                                    &work_ccb->ccb_h,
3299                                                    xpt_links.stqe);
3300
3301                                 mtx_unlock(&xsoftc.xpt_lock);
3302                                 continue;
3303                         } else {
3304                                 /*
3305                                  * Consume a high power slot while
3306                                  * this ccb runs.
3307                                  */
3308                                 xsoftc.num_highpower--;
3309                         }
3310                         mtx_unlock(&xsoftc.xpt_lock);
3311                 }
3312                 cam_ccbq_remove_ccb(&device->ccbq, work_ccb);
3313                 cam_ccbq_send_ccb(&device->ccbq, work_ccb);
3314
3315                 devq->send_openings--;
3316                 devq->send_active++;
3317
3318                 xpt_schedule_dev_sendq(bus, device);
3319
3320                 if (work_ccb && (work_ccb->ccb_h.flags & CAM_DEV_QFREEZE) != 0){
3321                         /*
3322                          * The client wants to freeze the queue
3323                          * after this CCB is sent.
3324                          */
3325                         xpt_freeze_devq(work_ccb->ccb_h.path, 1);
3326                 }
3327
3328                 /* In Target mode, the peripheral driver knows best... */
3329                 if (work_ccb->ccb_h.func_code == XPT_SCSI_IO) {
3330                         if ((device->inq_flags & SID_CmdQue) != 0
3331                          && work_ccb->csio.tag_action != CAM_TAG_ACTION_NONE)
3332                                 work_ccb->ccb_h.flags |= CAM_TAG_ACTION_VALID;
3333                         else
3334                                 /*
3335                                  * Clear this in case of a retried CCB that
3336                                  * failed due to a rejected tag.
3337                                  */
3338                                 work_ccb->ccb_h.flags &= ~CAM_TAG_ACTION_VALID;
3339                 }
3340
3341                 /*
3342                  * Device queues can be shared among multiple sim instances
3343                  * that reside on different busses.  Use the SIM in the queue
3344                  * CCB's path, rather than the one in the bus that was passed
3345                  * into this function.
3346                  */
3347                 sim = work_ccb->ccb_h.path->bus->sim;
3348                 (*(sim->sim_action))(sim, work_ccb);
3349         }
3350         devq->send_queue.qfrozen_cnt[0]--;
3351 }
3352
3353 /*
3354  * This function merges stuff from the slave ccb into the master ccb, while
3355  * keeping important fields in the master ccb constant.
3356  */
3357 void
3358 xpt_merge_ccb(union ccb *master_ccb, union ccb *slave_ccb)
3359 {
3360
3361         /*
3362          * Pull fields that are valid for peripheral drivers to set
3363          * into the master CCB along with the CCB "payload".
3364          */
3365         master_ccb->ccb_h.retry_count = slave_ccb->ccb_h.retry_count;
3366         master_ccb->ccb_h.func_code = slave_ccb->ccb_h.func_code;
3367         master_ccb->ccb_h.timeout = slave_ccb->ccb_h.timeout;
3368         master_ccb->ccb_h.flags = slave_ccb->ccb_h.flags;
3369         bcopy(&(&slave_ccb->ccb_h)[1], &(&master_ccb->ccb_h)[1],
3370               sizeof(union ccb) - sizeof(struct ccb_hdr));
3371 }
3372
3373 void
3374 xpt_setup_ccb(struct ccb_hdr *ccb_h, struct cam_path *path, u_int32_t priority)
3375 {
3376
3377         CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_setup_ccb\n"));
3378         ccb_h->pinfo.priority = priority;
3379         ccb_h->path = path;
3380         ccb_h->path_id = path->bus->path_id;
3381         if (path->target)
3382                 ccb_h->target_id = path->target->target_id;
3383         else
3384                 ccb_h->target_id = CAM_TARGET_WILDCARD;
3385         if (path->device) {
3386                 ccb_h->target_lun = path->device->lun_id;
3387                 ccb_h->pinfo.generation = ++path->device->ccbq.queue.generation;
3388         } else {
3389                 ccb_h->target_lun = CAM_TARGET_WILDCARD;
3390         }
3391         ccb_h->pinfo.index = CAM_UNQUEUED_INDEX;
3392         ccb_h->flags = 0;
3393 }
3394
3395 /* Path manipulation functions */
3396 cam_status
3397 xpt_create_path(struct cam_path **new_path_ptr, struct cam_periph *perph,
3398                 path_id_t path_id, target_id_t target_id, lun_id_t lun_id)
3399 {
3400         struct     cam_path *path;
3401         cam_status status;
3402
3403         path = (struct cam_path *)malloc(sizeof(*path), M_CAMPATH, M_NOWAIT);
3404
3405         if (path == NULL) {
3406                 status = CAM_RESRC_UNAVAIL;
3407                 return(status);
3408         }
3409         status = xpt_compile_path(path, perph, path_id, target_id, lun_id);
3410         if (status != CAM_REQ_CMP) {
3411                 free(path, M_CAMPATH);
3412                 path = NULL;
3413         }
3414         *new_path_ptr = path;
3415         return (status);
3416 }
3417
3418 cam_status
3419 xpt_create_path_unlocked(struct cam_path **new_path_ptr,
3420                          struct cam_periph *periph, path_id_t path_id,
3421                          target_id_t target_id, lun_id_t lun_id)
3422 {
3423         struct     cam_path *path;
3424         struct     cam_eb *bus = NULL;
3425         cam_status status;
3426         int        need_unlock = 0;
3427
3428         path = (struct cam_path *)malloc(sizeof(*path), M_CAMPATH, M_WAITOK);
3429
3430         if (path_id != CAM_BUS_WILDCARD) {
3431                 bus = xpt_find_bus(path_id);
3432                 if (bus != NULL) {
3433                         need_unlock = 1;
3434                         CAM_SIM_LOCK(bus->sim);
3435                 }
3436         }
3437         status = xpt_compile_path(path, periph, path_id, target_id, lun_id);
3438         if (need_unlock) {
3439                 CAM_SIM_UNLOCK(bus->sim);
3440                 xpt_release_bus(bus);
3441         }
3442         if (status != CAM_REQ_CMP) {
3443                 free(path, M_CAMPATH);
3444                 path = NULL;
3445         }
3446         *new_path_ptr = path;
3447         return (status);
3448 }
3449
3450 cam_status
3451 xpt_compile_path(struct cam_path *new_path, struct cam_periph *perph,
3452                  path_id_t path_id, target_id_t target_id, lun_id_t lun_id)
3453 {
3454         struct       cam_eb *bus;
3455         struct       cam_et *target;
3456         struct       cam_ed *device;
3457         cam_status   status;
3458
3459         status = CAM_REQ_CMP;   /* Completed without error */
3460         target = NULL;          /* Wildcarded */
3461         device = NULL;          /* Wildcarded */
3462
3463         /*
3464          * We will potentially modify the EDT, so block interrupts
3465          * that may attempt to create cam paths.
3466          */
3467         bus = xpt_find_bus(path_id);
3468         if (bus == NULL) {
3469                 status = CAM_PATH_INVALID;
3470         } else {
3471                 target = xpt_find_target(bus, target_id);
3472                 if (target == NULL) {
3473                         /* Create one */
3474                         struct cam_et *new_target;
3475
3476                         new_target = xpt_alloc_target(bus, target_id);
3477                         if (new_target == NULL) {
3478                                 status = CAM_RESRC_UNAVAIL;
3479                         } else {
3480                                 target = new_target;
3481                         }
3482                 }
3483                 if (target != NULL) {
3484                         device = xpt_find_device(target, lun_id);
3485                         if (device == NULL) {
3486                                 /* Create one */
3487                                 struct cam_ed *new_device;
3488
3489                                 new_device =
3490                                     (*(bus->xport->alloc_device))(bus,
3491                                                                       target,
3492                                                                       lun_id);
3493                                 if (new_device == NULL) {
3494                                         status = CAM_RESRC_UNAVAIL;
3495                                 } else {
3496                                         device = new_device;
3497                                 }
3498                         }
3499                 }
3500         }
3501
3502         /*
3503          * Only touch the user's data if we are successful.
3504          */
3505         if (status == CAM_REQ_CMP) {
3506                 new_path->periph = perph;
3507                 new_path->bus = bus;
3508                 new_path->target = target;
3509                 new_path->device = device;
3510                 CAM_DEBUG(new_path, CAM_DEBUG_TRACE, ("xpt_compile_path\n"));
3511         } else {
3512                 if (device != NULL)
3513                         xpt_release_device(device);
3514                 if (target != NULL)
3515                         xpt_release_target(target);
3516                 if (bus != NULL)
3517                         xpt_release_bus(bus);
3518         }
3519         return (status);
3520 }
3521
3522 void
3523 xpt_release_path(struct cam_path *path)
3524 {
3525         CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_release_path\n"));
3526         if (path->device != NULL) {
3527                 xpt_release_device(path->device);
3528                 path->device = NULL;
3529         }
3530         if (path->target != NULL) {
3531                 xpt_release_target(path->target);
3532                 path->target = NULL;
3533         }
3534         if (path->bus != NULL) {
3535                 xpt_release_bus(path->bus);
3536                 path->bus = NULL;
3537         }
3538 }
3539
3540 void
3541 xpt_free_path(struct cam_path *path)
3542 {
3543
3544         CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_free_path\n"));
3545         xpt_release_path(path);
3546         free(path, M_CAMPATH);
3547 }
3548
3549 void
3550 xpt_path_counts(struct cam_path *path, uint32_t *bus_ref,
3551     uint32_t *periph_ref, uint32_t *target_ref, uint32_t *device_ref)
3552 {
3553
3554         mtx_lock(&xsoftc.xpt_topo_lock);
3555         if (bus_ref) {
3556                 if (path->bus)
3557                         *bus_ref = path->bus->refcount;
3558                 else
3559                         *bus_ref = 0;
3560         }
3561         mtx_unlock(&xsoftc.xpt_topo_lock);
3562         if (periph_ref) {
3563                 if (path->periph)
3564                         *periph_ref = path->periph->refcount;
3565                 else
3566                         *periph_ref = 0;
3567         }
3568         if (target_ref) {
3569                 if (path->target)
3570                         *target_ref = path->target->refcount;
3571                 else
3572                         *target_ref = 0;
3573         }
3574         if (device_ref) {
3575                 if (path->device)
3576                         *device_ref = path->device->refcount;
3577                 else
3578                         *device_ref = 0;
3579         }
3580 }
3581
3582 /*
3583  * Return -1 for failure, 0 for exact match, 1 for match with wildcards
3584  * in path1, 2 for match with wildcards in path2.
3585  */
3586 int
3587 xpt_path_comp(struct cam_path *path1, struct cam_path *path2)
3588 {
3589         int retval = 0;
3590
3591         if (path1->bus != path2->bus) {
3592                 if (path1->bus->path_id == CAM_BUS_WILDCARD)
3593                         retval = 1;
3594                 else if (path2->bus->path_id == CAM_BUS_WILDCARD)
3595                         retval = 2;
3596                 else
3597                         return (-1);
3598         }
3599         if (path1->target != path2->target) {
3600                 if (path1->target->target_id == CAM_TARGET_WILDCARD) {
3601                         if (retval == 0)
3602                                 retval = 1;
3603                 } else if (path2->target->target_id == CAM_TARGET_WILDCARD)
3604                         retval = 2;
3605                 else
3606                         return (-1);
3607         }
3608         if (path1->device != path2->device) {
3609                 if (path1->device->lun_id == CAM_LUN_WILDCARD) {
3610                         if (retval == 0)
3611                                 retval = 1;
3612                 } else if (path2->device->lun_id == CAM_LUN_WILDCARD)
3613                         retval = 2;
3614                 else
3615                         return (-1);
3616         }
3617         return (retval);
3618 }
3619
3620 void
3621 xpt_print_path(struct cam_path *path)
3622 {
3623
3624         if (path == NULL)
3625                 printf("(nopath): ");
3626         else {
3627                 if (path->periph != NULL)
3628                         printf("(%s%d:", path->periph->periph_name,
3629                                path->periph->unit_number);
3630                 else
3631                         printf("(noperiph:");
3632
3633                 if (path->bus != NULL)
3634                         printf("%s%d:%d:", path->bus->sim->sim_name,
3635                                path->bus->sim->unit_number,
3636                                path->bus->sim->bus_id);
3637                 else
3638                         printf("nobus:");
3639
3640                 if (path->target != NULL)
3641                         printf("%d:", path->target->target_id);
3642                 else
3643                         printf("X:");
3644
3645                 if (path->device != NULL)
3646                         printf("%d): ", path->device->lun_id);
3647                 else
3648                         printf("X): ");
3649         }
3650 }
3651
3652 void
3653 xpt_print(struct cam_path *path, const char *fmt, ...)
3654 {
3655         va_list ap;
3656         xpt_print_path(path);
3657         va_start(ap, fmt);
3658         vprintf(fmt, ap);
3659         va_end(ap);
3660 }
3661
3662 int
3663 xpt_path_string(struct cam_path *path, char *str, size_t str_len)
3664 {
3665         struct sbuf sb;
3666
3667 #ifdef INVARIANTS
3668         if (path != NULL && path->bus != NULL)
3669                 mtx_assert(path->bus->sim->mtx, MA_OWNED);
3670 #endif
3671
3672         sbuf_new(&sb, str, str_len, 0);
3673
3674         if (path == NULL)
3675                 sbuf_printf(&sb, "(nopath): ");
3676         else {
3677                 if (path->periph != NULL)
3678                         sbuf_printf(&sb, "(%s%d:", path->periph->periph_name,
3679                                     path->periph->unit_number);
3680                 else
3681                         sbuf_printf(&sb, "(noperiph:");
3682
3683                 if (path->bus != NULL)
3684                         sbuf_printf(&sb, "%s%d:%d:", path->bus->sim->sim_name,
3685                                     path->bus->sim->unit_number,
3686                                     path->bus->sim->bus_id);
3687                 else
3688                         sbuf_printf(&sb, "nobus:");
3689
3690                 if (path->target != NULL)
3691                         sbuf_printf(&sb, "%d:", path->target->target_id);
3692                 else
3693                         sbuf_printf(&sb, "X:");
3694
3695                 if (path->device != NULL)
3696                         sbuf_printf(&sb, "%d): ", path->device->lun_id);
3697                 else
3698                         sbuf_printf(&sb, "X): ");
3699         }
3700         sbuf_finish(&sb);
3701
3702         return(sbuf_len(&sb));
3703 }
3704
3705 path_id_t
3706 xpt_path_path_id(struct cam_path *path)
3707 {
3708         return(path->bus->path_id);
3709 }
3710
3711 target_id_t
3712 xpt_path_target_id(struct cam_path *path)
3713 {
3714         if (path->target != NULL)
3715                 return (path->target->target_id);
3716         else
3717                 return (CAM_TARGET_WILDCARD);
3718 }
3719
3720 lun_id_t
3721 xpt_path_lun_id(struct cam_path *path)
3722 {
3723         if (path->device != NULL)
3724                 return (path->device->lun_id);
3725         else
3726                 return (CAM_LUN_WILDCARD);
3727 }
3728
3729 struct cam_sim *
3730 xpt_path_sim(struct cam_path *path)
3731 {
3732
3733         return (path->bus->sim);
3734 }
3735
3736 struct cam_periph*
3737 xpt_path_periph(struct cam_path *path)
3738 {
3739         mtx_assert(path->bus->sim->mtx, MA_OWNED);
3740
3741         return (path->periph);
3742 }
3743
3744 int
3745 xpt_path_legacy_ata_id(struct cam_path *path)
3746 {
3747         struct cam_eb *bus;
3748         int bus_id;
3749
3750         if ((strcmp(path->bus->sim->sim_name, "ata") != 0) &&
3751             strcmp(path->bus->sim->sim_name, "ahcich") != 0 &&
3752             strcmp(path->bus->sim->sim_name, "mvsch") != 0 &&
3753             strcmp(path->bus->sim->sim_name, "siisch") != 0)
3754                 return (-1);
3755
3756         if (strcmp(path->bus->sim->sim_name, "ata") == 0 &&
3757             path->bus->sim->unit_number < 2) {
3758                 bus_id = path->bus->sim->unit_number;
3759         } else {
3760                 bus_id = 2;
3761                 xpt_lock_buses();
3762                 TAILQ_FOREACH(bus, &xsoftc.xpt_busses, links) {
3763                         if (bus == path->bus)
3764                                 break;
3765                         if ((strcmp(bus->sim->sim_name, "ata") == 0 &&
3766                              bus->sim->unit_number >= 2) ||
3767                             strcmp(bus->sim->sim_name, "ahcich") == 0 ||
3768                             strcmp(bus->sim->sim_name, "mvsch") == 0 ||
3769                             strcmp(bus->sim->sim_name, "siisch") == 0)
3770                                 bus_id++;
3771                 }
3772                 xpt_unlock_buses();
3773         }
3774         if (path->target != NULL) {
3775                 if (path->target->target_id < 2)
3776                         return (bus_id * 2 + path->target->target_id);
3777                 else
3778                         return (-1);
3779         } else
3780                 return (bus_id * 2);
3781 }
3782
3783 /*
3784  * Release a CAM control block for the caller.  Remit the cost of the structure
3785  * to the device referenced by the path.  If the this device had no 'credits'
3786  * and peripheral drivers have registered async callbacks for this notification
3787  * call them now.
3788  */
3789 void
3790 xpt_release_ccb(union ccb *free_ccb)
3791 {
3792         struct   cam_path *path;
3793         struct   cam_ed *device;
3794         struct   cam_eb *bus;
3795         struct   cam_sim *sim;
3796
3797         CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_release_ccb\n"));
3798         path = free_ccb->ccb_h.path;
3799         device = path->device;
3800         bus = path->bus;
3801         sim = bus->sim;
3802
3803         mtx_assert(sim->mtx, MA_OWNED);
3804
3805         cam_ccbq_release_opening(&device->ccbq);
3806         if (device->flags & CAM_DEV_RESIZE_QUEUE_NEEDED) {
3807                 device->flags &= ~CAM_DEV_RESIZE_QUEUE_NEEDED;
3808                 cam_ccbq_resize(&device->ccbq,
3809                     device->ccbq.dev_openings + device->ccbq.dev_active);
3810         }
3811         if (sim->ccb_count > sim->max_ccbs) {
3812                 xpt_free_ccb(free_ccb);
3813                 sim->ccb_count--;
3814         } else {
3815                 SLIST_INSERT_HEAD(&sim->ccb_freeq, &free_ccb->ccb_h,
3816                     xpt_links.sle);
3817         }
3818         if (sim->devq == NULL) {
3819                 return;
3820         }
3821         sim->devq->alloc_openings++;
3822         sim->devq->alloc_active--;
3823         if (device_is_alloc_queued(device) == 0)
3824                 xpt_schedule_dev_allocq(bus, device);
3825         xpt_run_dev_allocq(bus);
3826 }
3827
3828 /* Functions accessed by SIM drivers */
3829
3830 static struct xpt_xport xport_default = {
3831         .alloc_device = xpt_alloc_device_default,
3832         .action = xpt_action_default,
3833         .async = xpt_dev_async_default,
3834 };
3835
3836 /*
3837  * A sim structure, listing the SIM entry points and instance
3838  * identification info is passed to xpt_bus_register to hook the SIM
3839  * into the CAM framework.  xpt_bus_register creates a cam_eb entry
3840  * for this new bus and places it in the array of busses and assigns
3841  * it a path_id.  The path_id may be influenced by "hard wiring"
3842  * information specified by the user.  Once interrupt services are
3843  * available, the bus will be probed.
3844  */
3845 int32_t
3846 xpt_bus_register(struct cam_sim *sim, device_t parent, u_int32_t bus)
3847 {
3848         struct cam_eb *new_bus;
3849         struct cam_eb *old_bus;
3850         struct ccb_pathinq cpi;
3851         struct cam_path *path;
3852         cam_status status;
3853
3854         mtx_assert(sim->mtx, MA_OWNED);
3855
3856         sim->bus_id = bus;
3857         new_bus = (struct cam_eb *)malloc(sizeof(*new_bus),
3858                                           M_CAMXPT, M_NOWAIT);
3859         if (new_bus == NULL) {
3860                 /* Couldn't satisfy request */
3861                 return (CAM_RESRC_UNAVAIL);
3862         }
3863         if (strcmp(sim->sim_name, "xpt") != 0) {
3864                 sim->path_id =
3865                     xptpathid(sim->sim_name, sim->unit_number, sim->bus_id);
3866         }
3867
3868         TAILQ_INIT(&new_bus->et_entries);
3869         new_bus->path_id = sim->path_id;
3870         cam_sim_hold(sim);
3871         new_bus->sim = sim;
3872         timevalclear(&new_bus->last_reset);
3873         new_bus->flags = 0;
3874         new_bus->refcount = 1;  /* Held until a bus_deregister event */
3875         new_bus->generation = 0;
3876
3877         mtx_lock(&xsoftc.xpt_topo_lock);
3878         old_bus = TAILQ_FIRST(&xsoftc.xpt_busses);
3879         while (old_bus != NULL
3880             && old_bus->path_id < new_bus->path_id)
3881                 old_bus = TAILQ_NEXT(old_bus, links);
3882         if (old_bus != NULL)
3883                 TAILQ_INSERT_BEFORE(old_bus, new_bus, links);
3884         else
3885                 TAILQ_INSERT_TAIL(&xsoftc.xpt_busses, new_bus, links);
3886         xsoftc.bus_generation++;
3887         mtx_unlock(&xsoftc.xpt_topo_lock);
3888
3889         /*
3890          * Set a default transport so that a PATH_INQ can be issued to
3891          * the SIM.  This will then allow for probing and attaching of
3892          * a more appropriate transport.
3893          */
3894         new_bus->xport = &xport_default;
3895
3896         status = xpt_create_path(&path, /*periph*/NULL, sim->path_id,
3897                                   CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
3898         if (status != CAM_REQ_CMP) {
3899                 xpt_release_bus(new_bus);
3900                 free(path, M_CAMXPT);
3901                 return (CAM_RESRC_UNAVAIL);
3902         }
3903
3904         xpt_setup_ccb(&cpi.ccb_h, path, CAM_PRIORITY_NORMAL);
3905         cpi.ccb_h.func_code = XPT_PATH_INQ;
3906         xpt_action((union ccb *)&cpi);
3907
3908         if (cpi.ccb_h.status == CAM_REQ_CMP) {
3909                 switch (cpi.transport) {
3910                 case XPORT_SPI:
3911                 case XPORT_SAS:
3912                 case XPORT_FC:
3913                 case XPORT_USB:
3914                 case XPORT_ISCSI:
3915                 case XPORT_PPB:
3916                         new_bus->xport = scsi_get_xport();
3917                         break;
3918                 case XPORT_ATA:
3919                 case XPORT_SATA:
3920                         new_bus->xport = ata_get_xport();
3921                         break;
3922                 default:
3923                         new_bus->xport = &xport_default;
3924                         break;
3925                 }
3926         }
3927
3928         /* Notify interested parties */
3929         if (sim->path_id != CAM_XPT_PATH_ID) {
3930                 union   ccb *scan_ccb;
3931
3932                 xpt_async(AC_PATH_REGISTERED, path, &cpi);
3933                 /* Initiate bus rescan. */
3934                 scan_ccb = xpt_alloc_ccb_nowait();
3935                 scan_ccb->ccb_h.path = path;
3936                 scan_ccb->ccb_h.func_code = XPT_SCAN_BUS;
3937                 scan_ccb->crcn.flags = 0;
3938                 xpt_rescan(scan_ccb);
3939         } else
3940                 xpt_free_path(path);
3941         return (CAM_SUCCESS);
3942 }
3943
3944 int32_t
3945 xpt_bus_deregister(path_id_t pathid)
3946 {
3947         struct cam_path bus_path;
3948         cam_status status;
3949
3950         status = xpt_compile_path(&bus_path, NULL, pathid,
3951                                   CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
3952         if (status != CAM_REQ_CMP)
3953                 return (status);
3954
3955         xpt_async(AC_LOST_DEVICE, &bus_path, NULL);
3956         xpt_async(AC_PATH_DEREGISTERED, &bus_path, NULL);
3957
3958         /* Release the reference count held while registered. */
3959         xpt_release_bus(bus_path.bus);
3960         xpt_release_path(&bus_path);
3961
3962         return (CAM_REQ_CMP);
3963 }
3964
3965 static path_id_t
3966 xptnextfreepathid(void)
3967 {
3968         struct cam_eb *bus;
3969         path_id_t pathid;
3970         const char *strval;
3971
3972         pathid = 0;
3973         mtx_lock(&xsoftc.xpt_topo_lock);
3974         bus = TAILQ_FIRST(&xsoftc.xpt_busses);
3975 retry:
3976         /* Find an unoccupied pathid */
3977         while (bus != NULL && bus->path_id <= pathid) {
3978                 if (bus->path_id == pathid)
3979                         pathid++;
3980                 bus = TAILQ_NEXT(bus, links);
3981         }
3982         mtx_unlock(&xsoftc.xpt_topo_lock);
3983
3984         /*
3985          * Ensure that this pathid is not reserved for
3986          * a bus that may be registered in the future.
3987          */
3988         if (resource_string_value("scbus", pathid, "at", &strval) == 0) {
3989                 ++pathid;
3990                 /* Start the search over */
3991                 mtx_lock(&xsoftc.xpt_topo_lock);
3992                 goto retry;
3993         }
3994         return (pathid);
3995 }
3996
3997 static path_id_t
3998 xptpathid(const char *sim_name, int sim_unit, int sim_bus)
3999 {
4000         path_id_t pathid;
4001         int i, dunit, val;
4002         char buf[32];
4003         const char *dname;
4004
4005         pathid = CAM_XPT_PATH_ID;
4006         snprintf(buf, sizeof(buf), "%s%d", sim_name, sim_unit);
4007         i = 0;
4008         while ((resource_find_match(&i, &dname, &dunit, "at", buf)) == 0) {
4009                 if (strcmp(dname, "scbus")) {
4010                         /* Avoid a bit of foot shooting. */
4011                         continue;
4012                 }
4013                 if (dunit < 0)          /* unwired?! */
4014                         continue;
4015                 if (resource_int_value("scbus", dunit, "bus", &val) == 0) {
4016                         if (sim_bus == val) {
4017                                 pathid = dunit;
4018                                 break;
4019                         }
4020                 } else if (sim_bus == 0) {
4021                         /* Unspecified matches bus 0 */
4022                         pathid = dunit;
4023                         break;
4024                 } else {
4025                         printf("Ambiguous scbus configuration for %s%d "
4026                                "bus %d, cannot wire down.  The kernel "
4027                                "config entry for scbus%d should "
4028                                "specify a controller bus.\n"
4029                                "Scbus will be assigned dynamically.\n",
4030                                sim_name, sim_unit, sim_bus, dunit);
4031                         break;
4032                 }
4033         }
4034
4035         if (pathid == CAM_XPT_PATH_ID)
4036                 pathid = xptnextfreepathid();
4037         return (pathid);
4038 }
4039
4040 static const char *
4041 xpt_async_string(u_int32_t async_code)
4042 {
4043
4044         switch (async_code) {
4045         case AC_BUS_RESET: return ("AC_BUS_RESET");
4046         case AC_UNSOL_RESEL: return ("AC_UNSOL_RESEL");
4047         case AC_SCSI_AEN: return ("AC_SCSI_AEN");
4048         case AC_SENT_BDR: return ("AC_SENT_BDR");
4049         case AC_PATH_REGISTERED: return ("AC_PATH_REGISTERED");
4050         case AC_PATH_DEREGISTERED: return ("AC_PATH_DEREGISTERED");
4051         case AC_FOUND_DEVICE: return ("AC_FOUND_DEVICE");
4052         case AC_LOST_DEVICE: return ("AC_LOST_DEVICE");
4053         case AC_TRANSFER_NEG: return ("AC_TRANSFER_NEG");
4054         case AC_INQ_CHANGED: return ("AC_INQ_CHANGED");
4055         case AC_GETDEV_CHANGED: return ("AC_GETDEV_CHANGED");
4056         case AC_CONTRACT: return ("AC_CONTRACT");
4057         case AC_ADVINFO_CHANGED: return ("AC_ADVINFO_CHANGED");
4058         }
4059         return ("AC_UNKNOWN");
4060 }
4061
4062 void
4063 xpt_async(u_int32_t async_code, struct cam_path *path, void *async_arg)
4064 {
4065         struct cam_eb *bus;
4066         struct cam_et *target, *next_target;
4067         struct cam_ed *device, *next_device;
4068
4069         mtx_assert(path->bus->sim->mtx, MA_OWNED);
4070         CAM_DEBUG(path, CAM_DEBUG_TRACE | CAM_DEBUG_INFO,
4071             ("xpt_async(%s)\n", xpt_async_string(async_code)));
4072
4073         /*
4074          * Most async events come from a CAM interrupt context.  In
4075          * a few cases, the error recovery code at the peripheral layer,
4076          * which may run from our SWI or a process context, may signal
4077          * deferred events with a call to xpt_async.
4078          */
4079
4080         bus = path->bus;
4081
4082         if (async_code == AC_BUS_RESET) {
4083                 /* Update our notion of when the last reset occurred */
4084                 microtime(&bus->last_reset);
4085         }
4086
4087         for (target = TAILQ_FIRST(&bus->et_entries);
4088              target != NULL;
4089              target = next_target) {
4090
4091                 next_target = TAILQ_NEXT(target, links);
4092
4093                 if (path->target != target
4094                  && path->target->target_id != CAM_TARGET_WILDCARD
4095                  && target->target_id != CAM_TARGET_WILDCARD)
4096                         continue;
4097
4098                 if (async_code == AC_SENT_BDR) {
4099                         /* Update our notion of when the last reset occurred */
4100                         microtime(&path->target->last_reset);
4101                 }
4102
4103                 for (device = TAILQ_FIRST(&target->ed_entries);
4104                      device != NULL;
4105                      device = next_device) {
4106
4107                         next_device = TAILQ_NEXT(device, links);
4108
4109                         if (path->device != device
4110                          && path->device->lun_id != CAM_LUN_WILDCARD
4111                          && device->lun_id != CAM_LUN_WILDCARD)
4112                                 continue;
4113                         /*
4114                          * The async callback could free the device.
4115                          * If it is a broadcast async, it doesn't hold
4116                          * device reference, so take our own reference.
4117                          */
4118                         xpt_acquire_device(device);
4119                         (*(bus->xport->async))(async_code, bus,
4120                                                target, device,
4121                                                async_arg);
4122
4123                         xpt_async_bcast(&device->asyncs, async_code,
4124                                         path, async_arg);
4125                         xpt_release_device(device);
4126                 }
4127         }
4128
4129         /*
4130          * If this wasn't a fully wildcarded async, tell all
4131          * clients that want all async events.
4132          */
4133         if (bus != xpt_periph->path->bus)
4134                 xpt_async_bcast(&xpt_periph->path->device->asyncs, async_code,
4135                                 path, async_arg);
4136 }
4137
4138 static void
4139 xpt_async_bcast(struct async_list *async_head,
4140                 u_int32_t async_code,
4141                 struct cam_path *path, void *async_arg)
4142 {
4143         struct async_node *cur_entry;
4144
4145         cur_entry = SLIST_FIRST(async_head);
4146         while (cur_entry != NULL) {
4147                 struct async_node *next_entry;
4148                 /*
4149                  * Grab the next list entry before we call the current
4150                  * entry's callback.  This is because the callback function
4151                  * can delete its async callback entry.
4152                  */
4153                 next_entry = SLIST_NEXT(cur_entry, links);
4154                 if ((cur_entry->event_enable & async_code) != 0)
4155                         cur_entry->callback(cur_entry->callback_arg,
4156                                             async_code, path,
4157                                             async_arg);
4158                 cur_entry = next_entry;
4159         }
4160 }
4161
4162 static void
4163 xpt_dev_async_default(u_int32_t async_code, struct cam_eb *bus,
4164                       struct cam_et *target, struct cam_ed *device,
4165                       void *async_arg)
4166 {
4167         printf("%s called\n", __func__);
4168 }
4169
4170 u_int32_t
4171 xpt_freeze_devq_rl(struct cam_path *path, cam_rl rl, u_int count)
4172 {
4173         struct cam_ed *dev = path->device;
4174
4175         mtx_assert(path->bus->sim->mtx, MA_OWNED);
4176         dev->sim->devq->alloc_openings +=
4177             cam_ccbq_freeze(&dev->ccbq, rl, count);
4178         /* Remove frozen device from allocq. */
4179         if (device_is_alloc_queued(dev) &&
4180             cam_ccbq_frozen(&dev->ccbq, CAM_PRIORITY_TO_RL(
4181              CAMQ_GET_PRIO(&dev->drvq)))) {
4182                 camq_remove(&dev->sim->devq->alloc_queue,
4183                     dev->alloc_ccb_entry.pinfo.index);
4184         }
4185         /* Remove frozen device from sendq. */
4186         if (device_is_send_queued(dev) &&
4187             cam_ccbq_frozen_top(&dev->ccbq)) {
4188                 camq_remove(&dev->sim->devq->send_queue,
4189                     dev->send_ccb_entry.pinfo.index);
4190         }
4191         return (dev->ccbq.queue.qfrozen_cnt[rl]);
4192 }
4193
4194 u_int32_t
4195 xpt_freeze_devq(struct cam_path *path, u_int count)
4196 {
4197
4198         return (xpt_freeze_devq_rl(path, 0, count));
4199 }
4200
4201 u_int32_t
4202 xpt_freeze_simq(struct cam_sim *sim, u_int count)
4203 {
4204
4205         mtx_assert(sim->mtx, MA_OWNED);
4206         sim->devq->send_queue.qfrozen_cnt[0] += count;
4207         return (sim->devq->send_queue.qfrozen_cnt[0]);
4208 }
4209
4210 static void
4211 xpt_release_devq_timeout(void *arg)
4212 {
4213         struct cam_ed *device;
4214
4215         device = (struct cam_ed *)arg;
4216
4217         xpt_release_devq_device(device, /*rl*/0, /*count*/1, /*run_queue*/TRUE);
4218 }
4219
4220 void
4221 xpt_release_devq(struct cam_path *path, u_int count, int run_queue)
4222 {
4223         mtx_assert(path->bus->sim->mtx, MA_OWNED);
4224
4225         xpt_release_devq_device(path->device, /*rl*/0, count, run_queue);
4226 }
4227
4228 void
4229 xpt_release_devq_rl(struct cam_path *path, cam_rl rl, u_int count, int run_queue)
4230 {
4231         mtx_assert(path->bus->sim->mtx, MA_OWNED);
4232
4233         xpt_release_devq_device(path->device, rl, count, run_queue);
4234 }
4235
4236 static void
4237 xpt_release_devq_device(struct cam_ed *dev, cam_rl rl, u_int count, int run_queue)
4238 {
4239
4240         if (count > dev->ccbq.queue.qfrozen_cnt[rl]) {
4241 #ifdef INVARIANTS
4242                 printf("xpt_release_devq(%d): requested %u > present %u\n",
4243                     rl, count, dev->ccbq.queue.qfrozen_cnt[rl]);
4244 #endif
4245                 count = dev->ccbq.queue.qfrozen_cnt[rl];
4246         }
4247         dev->sim->devq->alloc_openings -=
4248             cam_ccbq_release(&dev->ccbq, rl, count);
4249         if (cam_ccbq_frozen(&dev->ccbq, CAM_PRIORITY_TO_RL(
4250             CAMQ_GET_PRIO(&dev->drvq))) == 0) {
4251                 if (xpt_schedule_dev_allocq(dev->target->bus, dev))
4252                         xpt_run_dev_allocq(dev->target->bus);
4253         }
4254         if (cam_ccbq_frozen_top(&dev->ccbq) == 0) {
4255                 /*
4256                  * No longer need to wait for a successful
4257                  * command completion.
4258                  */
4259                 dev->flags &= ~CAM_DEV_REL_ON_COMPLETE;
4260                 /*
4261                  * Remove any timeouts that might be scheduled
4262                  * to release this queue.
4263                  */
4264                 if ((dev->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
4265                         callout_stop(&dev->callout);
4266                         dev->flags &= ~CAM_DEV_REL_TIMEOUT_PENDING;
4267                 }
4268                 if (run_queue == 0)
4269                         return;
4270                 /*
4271                  * Now that we are unfrozen schedule the
4272                  * device so any pending transactions are
4273                  * run.
4274                  */
4275                 if (xpt_schedule_dev_sendq(dev->target->bus, dev))
4276                         xpt_run_dev_sendq(dev->target->bus);
4277         }
4278 }
4279
4280 void
4281 xpt_release_simq(struct cam_sim *sim, int run_queue)
4282 {
4283         struct  camq *sendq;
4284
4285         mtx_assert(sim->mtx, MA_OWNED);
4286         sendq = &(sim->devq->send_queue);
4287         if (sendq->qfrozen_cnt[0] <= 0) {
4288 #ifdef INVARIANTS
4289                 printf("xpt_release_simq: requested 1 > present %u\n",
4290                     sendq->qfrozen_cnt[0]);
4291 #endif
4292         } else
4293                 sendq->qfrozen_cnt[0]--;
4294         if (sendq->qfrozen_cnt[0] == 0) {
4295                 /*
4296                  * If there is a timeout scheduled to release this
4297                  * sim queue, remove it.  The queue frozen count is
4298                  * already at 0.
4299                  */
4300                 if ((sim->flags & CAM_SIM_REL_TIMEOUT_PENDING) != 0){
4301                         callout_stop(&sim->callout);
4302                         sim->flags &= ~CAM_SIM_REL_TIMEOUT_PENDING;
4303                 }
4304                 if (run_queue) {
4305                         struct cam_eb *bus;
4306
4307                         /*
4308                          * Now that we are unfrozen run the send queue.
4309                          */
4310                         bus = xpt_find_bus(sim->path_id);
4311                         xpt_run_dev_sendq(bus);
4312                         xpt_release_bus(bus);
4313                 }
4314         }
4315 }
4316
4317 /*
4318  * XXX Appears to be unused.
4319  */
4320 static void
4321 xpt_release_simq_timeout(void *arg)
4322 {
4323         struct cam_sim *sim;
4324
4325         sim = (struct cam_sim *)arg;
4326         xpt_release_simq(sim, /* run_queue */ TRUE);
4327 }
4328
4329 void
4330 xpt_done(union ccb *done_ccb)
4331 {
4332         struct cam_sim *sim;
4333         int     first;
4334
4335         CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("xpt_done\n"));
4336         if ((done_ccb->ccb_h.func_code & XPT_FC_QUEUED) != 0) {
4337                 /*
4338                  * Queue up the request for handling by our SWI handler
4339                  * any of the "non-immediate" type of ccbs.
4340                  */
4341                 sim = done_ccb->ccb_h.path->bus->sim;
4342                 TAILQ_INSERT_TAIL(&sim->sim_doneq, &done_ccb->ccb_h,
4343                     sim_links.tqe);
4344                 done_ccb->ccb_h.pinfo.index = CAM_DONEQ_INDEX;
4345                 if ((sim->flags & (CAM_SIM_ON_DONEQ | CAM_SIM_POLLED |
4346                     CAM_SIM_BATCH)) == 0) {
4347                         mtx_lock(&cam_simq_lock);
4348                         first = TAILQ_EMPTY(&cam_simq);
4349                         TAILQ_INSERT_TAIL(&cam_simq, sim, links);
4350                         mtx_unlock(&cam_simq_lock);
4351                         sim->flags |= CAM_SIM_ON_DONEQ;
4352                         if (first)
4353                                 swi_sched(cambio_ih, 0);
4354                 }
4355         }
4356 }
4357
4358 void
4359 xpt_batch_start(struct cam_sim *sim)
4360 {
4361
4362         KASSERT((sim->flags & CAM_SIM_BATCH) == 0, ("Batch flag already set"));
4363         sim->flags |= CAM_SIM_BATCH;
4364 }
4365
4366 void
4367 xpt_batch_done(struct cam_sim *sim)
4368 {
4369
4370         KASSERT((sim->flags & CAM_SIM_BATCH) != 0, ("Batch flag was not set"));
4371         sim->flags &= ~CAM_SIM_BATCH;
4372         if (!TAILQ_EMPTY(&sim->sim_doneq) &&
4373             (sim->flags & CAM_SIM_ON_DONEQ) == 0)
4374                 camisr_runqueue(&sim->sim_doneq);
4375 }
4376
4377 union ccb *
4378 xpt_alloc_ccb()
4379 {
4380         union ccb *new_ccb;
4381
4382         new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_WAITOK);
4383         return (new_ccb);
4384 }
4385
4386 union ccb *
4387 xpt_alloc_ccb_nowait()
4388 {
4389         union ccb *new_ccb;
4390
4391         new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_NOWAIT);
4392         return (new_ccb);
4393 }
4394
4395 void
4396 xpt_free_ccb(union ccb *free_ccb)
4397 {
4398         free(free_ccb, M_CAMCCB);
4399 }
4400
4401
4402
4403 /* Private XPT functions */
4404
4405 /*
4406  * Get a CAM control block for the caller. Charge the structure to the device
4407  * referenced by the path.  If the this device has no 'credits' then the
4408  * device already has the maximum number of outstanding operations under way
4409  * and we return NULL. If we don't have sufficient resources to allocate more
4410  * ccbs, we also return NULL.
4411  */
4412 static union ccb *
4413 xpt_get_ccb(struct cam_ed *device)
4414 {
4415         union ccb *new_ccb;
4416         struct cam_sim *sim;
4417
4418         sim = device->sim;
4419         if ((new_ccb = (union ccb *)SLIST_FIRST(&sim->ccb_freeq)) == NULL) {
4420                 new_ccb = xpt_alloc_ccb_nowait();
4421                 if (new_ccb == NULL) {
4422                         return (NULL);
4423                 }
4424                 if ((sim->flags & CAM_SIM_MPSAFE) == 0)
4425                         callout_handle_init(&new_ccb->ccb_h.timeout_ch);
4426                 SLIST_INSERT_HEAD(&sim->ccb_freeq, &new_ccb->ccb_h,
4427                                   xpt_links.sle);
4428                 sim->ccb_count++;
4429         }
4430         cam_ccbq_take_opening(&device->ccbq);
4431         SLIST_REMOVE_HEAD(&sim->ccb_freeq, xpt_links.sle);
4432         return (new_ccb);
4433 }
4434
4435 static void
4436 xpt_release_bus(struct cam_eb *bus)
4437 {
4438
4439         mtx_lock(&xsoftc.xpt_topo_lock);
4440         KASSERT(bus->refcount >= 1, ("bus->refcount >= 1"));
4441         if ((--bus->refcount == 0)
4442          && (TAILQ_FIRST(&bus->et_entries) == NULL)) {
4443                 TAILQ_REMOVE(&xsoftc.xpt_busses, bus, links);
4444                 xsoftc.bus_generation++;
4445                 mtx_unlock(&xsoftc.xpt_topo_lock);
4446                 cam_sim_release(bus->sim);
4447                 free(bus, M_CAMXPT);
4448         } else
4449                 mtx_unlock(&xsoftc.xpt_topo_lock);
4450 }
4451
4452 static struct cam_et *
4453 xpt_alloc_target(struct cam_eb *bus, target_id_t target_id)
4454 {
4455         struct cam_et *target;
4456
4457         target = (struct cam_et *)malloc(sizeof(*target), M_CAMXPT,
4458                                          M_NOWAIT|M_ZERO);
4459         if (target != NULL) {
4460                 struct cam_et *cur_target;
4461
4462                 TAILQ_INIT(&target->ed_entries);
4463                 target->bus = bus;
4464                 target->target_id = target_id;
4465                 target->refcount = 1;
4466                 target->generation = 0;
4467                 target->luns = NULL;
4468                 timevalclear(&target->last_reset);
4469                 /*
4470                  * Hold a reference to our parent bus so it
4471                  * will not go away before we do.
4472                  */
4473                 mtx_lock(&xsoftc.xpt_topo_lock);
4474                 bus->refcount++;
4475                 mtx_unlock(&xsoftc.xpt_topo_lock);
4476
4477                 /* Insertion sort into our bus's target list */
4478                 cur_target = TAILQ_FIRST(&bus->et_entries);
4479                 while (cur_target != NULL && cur_target->target_id < target_id)
4480                         cur_target = TAILQ_NEXT(cur_target, links);
4481
4482                 if (cur_target != NULL) {
4483                         TAILQ_INSERT_BEFORE(cur_target, target, links);
4484                 } else {
4485                         TAILQ_INSERT_TAIL(&bus->et_entries, target, links);
4486                 }
4487                 bus->generation++;
4488         }
4489         return (target);
4490 }
4491
4492 static void
4493 xpt_release_target(struct cam_et *target)
4494 {
4495
4496         if (target->refcount == 1) {
4497                 if (TAILQ_FIRST(&target->ed_entries) == NULL) {
4498                         TAILQ_REMOVE(&target->bus->et_entries, target, links);
4499                         target->bus->generation++;
4500                         xpt_release_bus(target->bus);
4501                         if (target->luns)
4502                                 free(target->luns, M_CAMXPT);
4503                         free(target, M_CAMXPT);
4504                 }
4505         } else
4506                 target->refcount--;
4507 }
4508
4509 static struct cam_ed *
4510 xpt_alloc_device_default(struct cam_eb *bus, struct cam_et *target,
4511                          lun_id_t lun_id)
4512 {
4513         struct cam_ed *device, *cur_device;
4514
4515         device = xpt_alloc_device(bus, target, lun_id);
4516         if (device == NULL)
4517                 return (NULL);
4518
4519         device->mintags = 1;
4520         device->maxtags = 1;
4521         bus->sim->max_ccbs += device->ccbq.devq_openings;
4522         cur_device = TAILQ_FIRST(&target->ed_entries);
4523         while (cur_device != NULL && cur_device->lun_id < lun_id)
4524                 cur_device = TAILQ_NEXT(cur_device, links);
4525         if (cur_device != NULL) {
4526                 TAILQ_INSERT_BEFORE(cur_device, device, links);
4527         } else {
4528                 TAILQ_INSERT_TAIL(&target->ed_entries, device, links);
4529         }
4530         target->generation++;
4531
4532         return (device);
4533 }
4534
4535 struct cam_ed *
4536 xpt_alloc_device(struct cam_eb *bus, struct cam_et *target, lun_id_t lun_id)
4537 {
4538         struct     cam_ed *device;
4539         struct     cam_devq *devq;
4540         cam_status status;
4541
4542         /* Make space for us in the device queue on our bus */
4543         devq = bus->sim->devq;
4544         status = cam_devq_resize(devq, devq->alloc_queue.array_size + 1);
4545
4546         if (status != CAM_REQ_CMP) {
4547                 device = NULL;
4548         } else {
4549                 device = (struct cam_ed *)malloc(sizeof(*device),
4550                                                  M_CAMDEV, M_NOWAIT|M_ZERO);
4551         }
4552
4553         if (device != NULL) {
4554                 cam_init_pinfo(&device->alloc_ccb_entry.pinfo);
4555                 device->alloc_ccb_entry.device = device;
4556                 cam_init_pinfo(&device->send_ccb_entry.pinfo);
4557                 device->send_ccb_entry.device = device;
4558                 device->target = target;
4559                 device->lun_id = lun_id;
4560                 device->sim = bus->sim;
4561                 /* Initialize our queues */
4562                 if (camq_init(&device->drvq, 0) != 0) {
4563                         free(device, M_CAMDEV);
4564                         return (NULL);
4565                 }
4566                 if (cam_ccbq_init(&device->ccbq,
4567                                   bus->sim->max_dev_openings) != 0) {
4568                         camq_fini(&device->drvq);
4569                         free(device, M_CAMDEV);
4570                         return (NULL);
4571                 }
4572                 SLIST_INIT(&device->asyncs);
4573                 SLIST_INIT(&device->periphs);
4574                 device->generation = 0;
4575                 device->owner = NULL;
4576                 device->flags = CAM_DEV_UNCONFIGURED;
4577                 device->tag_delay_count = 0;
4578                 device->tag_saved_openings = 0;
4579                 device->refcount = 1;
4580                 callout_init_mtx(&device->callout, bus->sim->mtx, 0);
4581
4582                 /*
4583                  * Hold a reference to our parent target so it
4584                  * will not go away before we do.
4585                  */
4586                 target->refcount++;
4587
4588         }
4589         return (device);
4590 }
4591
4592 void
4593 xpt_acquire_device(struct cam_ed *device)
4594 {
4595
4596         device->refcount++;
4597 }
4598
4599 void
4600 xpt_release_device(struct cam_ed *device)
4601 {
4602
4603         if (device->refcount == 1) {
4604                 struct cam_devq *devq;
4605
4606                 if (device->alloc_ccb_entry.pinfo.index != CAM_UNQUEUED_INDEX
4607                  || device->send_ccb_entry.pinfo.index != CAM_UNQUEUED_INDEX)
4608                         panic("Removing device while still queued for ccbs");
4609
4610                 if ((device->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0)
4611                         callout_stop(&device->callout);
4612
4613                 TAILQ_REMOVE(&device->target->ed_entries, device,links);
4614                 device->target->generation++;
4615                 device->target->bus->sim->max_ccbs -= device->ccbq.devq_openings;
4616                 /* Release our slot in the devq */
4617                 devq = device->target->bus->sim->devq;
4618                 cam_devq_resize(devq, devq->alloc_queue.array_size - 1);
4619                 camq_fini(&device->drvq);
4620                 cam_ccbq_fini(&device->ccbq);
4621                 xpt_release_target(device->target);
4622                 free(device, M_CAMDEV);
4623         } else
4624                 device->refcount--;
4625 }
4626
4627 u_int32_t
4628 xpt_dev_ccbq_resize(struct cam_path *path, int newopenings)
4629 {
4630         int     diff;
4631         int     result;
4632         struct  cam_ed *dev;
4633
4634         dev = path->device;
4635
4636         diff = newopenings - (dev->ccbq.dev_active + dev->ccbq.dev_openings);
4637         result = cam_ccbq_resize(&dev->ccbq, newopenings);
4638         if (result == CAM_REQ_CMP && (diff < 0)) {
4639                 dev->flags |= CAM_DEV_RESIZE_QUEUE_NEEDED;
4640         }
4641         if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
4642          || (dev->inq_flags & SID_CmdQue) != 0)
4643                 dev->tag_saved_openings = newopenings;
4644         /* Adjust the global limit */
4645         dev->sim->max_ccbs += diff;
4646         return (result);
4647 }
4648
4649 static struct cam_eb *
4650 xpt_find_bus(path_id_t path_id)
4651 {
4652         struct cam_eb *bus;
4653
4654         mtx_lock(&xsoftc.xpt_topo_lock);
4655         for (bus = TAILQ_FIRST(&xsoftc.xpt_busses);
4656              bus != NULL;
4657              bus = TAILQ_NEXT(bus, links)) {
4658                 if (bus->path_id == path_id) {
4659                         bus->refcount++;
4660                         break;
4661                 }
4662         }
4663         mtx_unlock(&xsoftc.xpt_topo_lock);
4664         return (bus);
4665 }
4666
4667 static struct cam_et *
4668 xpt_find_target(struct cam_eb *bus, target_id_t target_id)
4669 {
4670         struct cam_et *target;
4671
4672         for (target = TAILQ_FIRST(&bus->et_entries);
4673              target != NULL;
4674              target = TAILQ_NEXT(target, links)) {
4675                 if (target->target_id == target_id) {
4676                         target->refcount++;
4677                         break;
4678                 }
4679         }
4680         return (target);
4681 }
4682
4683 static struct cam_ed *
4684 xpt_find_device(struct cam_et *target, lun_id_t lun_id)
4685 {
4686         struct cam_ed *device;
4687
4688         for (device = TAILQ_FIRST(&target->ed_entries);
4689              device != NULL;
4690              device = TAILQ_NEXT(device, links)) {
4691                 if (device->lun_id == lun_id) {
4692                         device->refcount++;
4693                         break;
4694                 }
4695         }
4696         return (device);
4697 }
4698
4699 void
4700 xpt_start_tags(struct cam_path *path)
4701 {
4702         struct ccb_relsim crs;
4703         struct cam_ed *device;
4704         struct cam_sim *sim;
4705         int    newopenings;
4706
4707         device = path->device;
4708         sim = path->bus->sim;
4709         device->flags &= ~CAM_DEV_TAG_AFTER_COUNT;
4710         xpt_freeze_devq(path, /*count*/1);
4711         device->inq_flags |= SID_CmdQue;
4712         if (device->tag_saved_openings != 0)
4713                 newopenings = device->tag_saved_openings;
4714         else
4715                 newopenings = min(device->maxtags,
4716                                   sim->max_tagged_dev_openings);
4717         xpt_dev_ccbq_resize(path, newopenings);
4718         xpt_async(AC_GETDEV_CHANGED, path, NULL);
4719         xpt_setup_ccb(&crs.ccb_h, path, CAM_PRIORITY_NORMAL);
4720         crs.ccb_h.func_code = XPT_REL_SIMQ;
4721         crs.release_flags = RELSIM_RELEASE_AFTER_QEMPTY;
4722         crs.openings
4723             = crs.release_timeout
4724             = crs.qfrozen_cnt
4725             = 0;
4726         xpt_action((union ccb *)&crs);
4727 }
4728
4729 void
4730 xpt_stop_tags(struct cam_path *path)
4731 {
4732         struct ccb_relsim crs;
4733         struct cam_ed *device;
4734         struct cam_sim *sim;
4735
4736         device = path->device;
4737         sim = path->bus->sim;
4738         device->flags &= ~CAM_DEV_TAG_AFTER_COUNT;
4739         device->tag_delay_count = 0;
4740         xpt_freeze_devq(path, /*count*/1);
4741         device->inq_flags &= ~SID_CmdQue;
4742         xpt_dev_ccbq_resize(path, sim->max_dev_openings);
4743         xpt_async(AC_GETDEV_CHANGED, path, NULL);
4744         xpt_setup_ccb(&crs.ccb_h, path, CAM_PRIORITY_NORMAL);
4745         crs.ccb_h.func_code = XPT_REL_SIMQ;
4746         crs.release_flags = RELSIM_RELEASE_AFTER_QEMPTY;
4747         crs.openings
4748             = crs.release_timeout
4749             = crs.qfrozen_cnt
4750             = 0;
4751         xpt_action((union ccb *)&crs);
4752 }
4753
4754 static void
4755 xpt_boot_delay(void *arg)
4756 {
4757
4758         xpt_release_boot();
4759 }
4760
4761 static void
4762 xpt_config(void *arg)
4763 {
4764         /*
4765          * Now that interrupts are enabled, go find our devices
4766          */
4767
4768         /* Setup debugging path */
4769         if (cam_dflags != CAM_DEBUG_NONE) {
4770                 /*
4771                  * Locking is specifically omitted here.  No SIMs have
4772                  * registered yet, so xpt_create_path will only be searching
4773                  * empty lists of targets and devices.
4774                  */
4775                 if (xpt_create_path(&cam_dpath, xpt_periph,
4776                                     CAM_DEBUG_BUS, CAM_DEBUG_TARGET,
4777                                     CAM_DEBUG_LUN) != CAM_REQ_CMP) {
4778                         printf("xpt_config: xpt_create_path() failed for debug"
4779                                " target %d:%d:%d, debugging disabled\n",
4780                                CAM_DEBUG_BUS, CAM_DEBUG_TARGET, CAM_DEBUG_LUN);
4781                         cam_dflags = CAM_DEBUG_NONE;
4782                 }
4783         } else
4784                 cam_dpath = NULL;
4785
4786         periphdriver_init(1);
4787         xpt_hold_boot();
4788         callout_init(&xsoftc.boot_callout, 1);
4789         callout_reset(&xsoftc.boot_callout, hz * xsoftc.boot_delay / 1000,
4790             xpt_boot_delay, NULL);
4791         /* Fire up rescan thread. */
4792         if (kproc_create(xpt_scanner_thread, NULL, NULL, 0, 0, "xpt_thrd")) {
4793                 printf("xpt_config: failed to create rescan thread.\n");
4794         }
4795 }
4796
4797 void
4798 xpt_hold_boot(void)
4799 {
4800         xpt_lock_buses();
4801         xsoftc.buses_to_config++;
4802         xpt_unlock_buses();
4803 }
4804
4805 void
4806 xpt_release_boot(void)
4807 {
4808         xpt_lock_buses();
4809         xsoftc.buses_to_config--;
4810         if (xsoftc.buses_to_config == 0 && xsoftc.buses_config_done == 0) {
4811                 struct  xpt_task *task;
4812
4813                 xsoftc.buses_config_done = 1;
4814                 xpt_unlock_buses();
4815                 /* Call manually because we don't have any busses */
4816                 task = malloc(sizeof(struct xpt_task), M_CAMXPT, M_NOWAIT);
4817                 if (task != NULL) {
4818                         TASK_INIT(&task->task, 0, xpt_finishconfig_task, task);
4819                         taskqueue_enqueue(taskqueue_thread, &task->task);
4820                 }
4821         } else
4822                 xpt_unlock_buses();
4823 }
4824
4825 /*
4826  * If the given device only has one peripheral attached to it, and if that
4827  * peripheral is the passthrough driver, announce it.  This insures that the
4828  * user sees some sort of announcement for every peripheral in their system.
4829  */
4830 static int
4831 xptpassannouncefunc(struct cam_ed *device, void *arg)
4832 {
4833         struct cam_periph *periph;
4834         int i;
4835
4836         for (periph = SLIST_FIRST(&device->periphs), i = 0; periph != NULL;
4837              periph = SLIST_NEXT(periph, periph_links), i++);
4838
4839         periph = SLIST_FIRST(&device->periphs);
4840         if ((i == 1)
4841          && (strncmp(periph->periph_name, "pass", 4) == 0))
4842                 xpt_announce_periph(periph, NULL);
4843
4844         return(1);
4845 }
4846
4847 static void
4848 xpt_finishconfig_task(void *context, int pending)
4849 {
4850
4851         periphdriver_init(2);
4852         /*
4853          * Check for devices with no "standard" peripheral driver
4854          * attached.  For any devices like that, announce the
4855          * passthrough driver so the user will see something.
4856          */
4857         if (!bootverbose)
4858                 xpt_for_all_devices(xptpassannouncefunc, NULL);
4859
4860         /* Release our hook so that the boot can continue. */
4861         config_intrhook_disestablish(xsoftc.xpt_config_hook);
4862         free(xsoftc.xpt_config_hook, M_CAMXPT);
4863         xsoftc.xpt_config_hook = NULL;
4864
4865         free(context, M_CAMXPT);
4866 }
4867
4868 cam_status
4869 xpt_register_async(int event, ac_callback_t *cbfunc, void *cbarg,
4870                    struct cam_path *path)
4871 {
4872         struct ccb_setasync csa;
4873         cam_status status;
4874         int xptpath = 0;
4875
4876         if (path == NULL) {
4877                 mtx_lock(&xsoftc.xpt_lock);
4878                 status = xpt_create_path(&path, /*periph*/NULL, CAM_XPT_PATH_ID,
4879                                          CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
4880                 if (status != CAM_REQ_CMP) {
4881                         mtx_unlock(&xsoftc.xpt_lock);
4882                         return (status);
4883                 }
4884                 xptpath = 1;
4885         }
4886
4887         xpt_setup_ccb(&csa.ccb_h, path, CAM_PRIORITY_NORMAL);
4888         csa.ccb_h.func_code = XPT_SASYNC_CB;
4889         csa.event_enable = event;
4890         csa.callback = cbfunc;
4891         csa.callback_arg = cbarg;
4892         xpt_action((union ccb *)&csa);
4893         status = csa.ccb_h.status;
4894
4895         if (xptpath) {
4896                 xpt_free_path(path);
4897                 mtx_unlock(&xsoftc.xpt_lock);
4898         }
4899
4900         if ((status == CAM_REQ_CMP) &&
4901             (csa.event_enable & AC_FOUND_DEVICE)) {
4902                 /*
4903                  * Get this peripheral up to date with all
4904                  * the currently existing devices.
4905                  */
4906                 xpt_for_all_devices(xptsetasyncfunc, &csa);
4907         }
4908         if ((status == CAM_REQ_CMP) &&
4909             (csa.event_enable & AC_PATH_REGISTERED)) {
4910                 /*
4911                  * Get this peripheral up to date with all
4912                  * the currently existing busses.
4913                  */
4914                 xpt_for_all_busses(xptsetasyncbusfunc, &csa);
4915         }
4916
4917         return (status);
4918 }
4919
4920 static void
4921 xptaction(struct cam_sim *sim, union ccb *work_ccb)
4922 {
4923         CAM_DEBUG(work_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("xptaction\n"));
4924
4925         switch (work_ccb->ccb_h.func_code) {
4926         /* Common cases first */
4927         case XPT_PATH_INQ:              /* Path routing inquiry */
4928         {
4929                 struct ccb_pathinq *cpi;
4930
4931                 cpi = &work_ccb->cpi;
4932                 cpi->version_num = 1; /* XXX??? */
4933                 cpi->hba_inquiry = 0;
4934                 cpi->target_sprt = 0;
4935                 cpi->hba_misc = 0;
4936                 cpi->hba_eng_cnt = 0;
4937                 cpi->max_target = 0;
4938                 cpi->max_lun = 0;
4939                 cpi->initiator_id = 0;
4940                 strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
4941                 strncpy(cpi->hba_vid, "", HBA_IDLEN);
4942                 strncpy(cpi->dev_name, sim->sim_name, DEV_IDLEN);
4943                 cpi->unit_number = sim->unit_number;
4944                 cpi->bus_id = sim->bus_id;
4945                 cpi->base_transfer_speed = 0;
4946                 cpi->protocol = PROTO_UNSPECIFIED;
4947                 cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
4948                 cpi->transport = XPORT_UNSPECIFIED;
4949                 cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
4950                 cpi->ccb_h.status = CAM_REQ_CMP;
4951                 xpt_done(work_ccb);
4952                 break;
4953         }
4954         default:
4955                 work_ccb->ccb_h.status = CAM_REQ_INVALID;
4956                 xpt_done(work_ccb);
4957                 break;
4958         }
4959 }
4960
4961 /*
4962  * The xpt as a "controller" has no interrupt sources, so polling
4963  * is a no-op.
4964  */
4965 static void
4966 xptpoll(struct cam_sim *sim)
4967 {
4968 }
4969
4970 void
4971 xpt_lock_buses(void)
4972 {
4973         mtx_lock(&xsoftc.xpt_topo_lock);
4974 }
4975
4976 void
4977 xpt_unlock_buses(void)
4978 {
4979         mtx_unlock(&xsoftc.xpt_topo_lock);
4980 }
4981
4982 static void
4983 camisr(void *dummy)
4984 {
4985         cam_simq_t queue;
4986         struct cam_sim *sim;
4987
4988         mtx_lock(&cam_simq_lock);
4989         TAILQ_INIT(&queue);
4990         while (!TAILQ_EMPTY(&cam_simq)) {
4991                 TAILQ_CONCAT(&queue, &cam_simq, links);
4992                 mtx_unlock(&cam_simq_lock);
4993
4994                 while ((sim = TAILQ_FIRST(&queue)) != NULL) {
4995                         TAILQ_REMOVE(&queue, sim, links);
4996                         CAM_SIM_LOCK(sim);
4997                         camisr_runqueue(&sim->sim_doneq);
4998                         sim->flags &= ~CAM_SIM_ON_DONEQ;
4999                         CAM_SIM_UNLOCK(sim);
5000                 }
5001                 mtx_lock(&cam_simq_lock);
5002         }
5003         mtx_unlock(&cam_simq_lock);
5004 }
5005
5006 static void
5007 camisr_runqueue(void *V_queue)
5008 {
5009         cam_isrq_t *queue = V_queue;
5010         struct  ccb_hdr *ccb_h;
5011
5012         while ((ccb_h = TAILQ_FIRST(queue)) != NULL) {
5013                 int     runq;
5014
5015                 TAILQ_REMOVE(queue, ccb_h, sim_links.tqe);
5016                 ccb_h->pinfo.index = CAM_UNQUEUED_INDEX;
5017
5018                 CAM_DEBUG(ccb_h->path, CAM_DEBUG_TRACE,
5019                           ("camisr\n"));
5020
5021                 runq = FALSE;
5022
5023                 if (ccb_h->flags & CAM_HIGH_POWER) {
5024                         struct highpowerlist    *hphead;
5025                         union ccb               *send_ccb;
5026
5027                         mtx_lock(&xsoftc.xpt_lock);
5028                         hphead = &xsoftc.highpowerq;
5029
5030                         send_ccb = (union ccb *)STAILQ_FIRST(hphead);
5031
5032                         /*
5033                          * Increment the count since this command is done.
5034                          */
5035                         xsoftc.num_highpower++;
5036
5037                         /*
5038                          * Any high powered commands queued up?
5039                          */
5040                         if (send_ccb != NULL) {
5041
5042                                 STAILQ_REMOVE_HEAD(hphead, xpt_links.stqe);
5043                                 mtx_unlock(&xsoftc.xpt_lock);
5044
5045                                 xpt_release_devq(send_ccb->ccb_h.path,
5046                                                  /*count*/1, /*runqueue*/TRUE);
5047                         } else
5048                                 mtx_unlock(&xsoftc.xpt_lock);
5049                 }
5050
5051                 if ((ccb_h->func_code & XPT_FC_USER_CCB) == 0) {
5052                         struct cam_ed *dev;
5053
5054                         dev = ccb_h->path->device;
5055
5056                         cam_ccbq_ccb_done(&dev->ccbq, (union ccb *)ccb_h);
5057                         ccb_h->path->bus->sim->devq->send_active--;
5058                         ccb_h->path->bus->sim->devq->send_openings++;
5059                         runq = TRUE;
5060
5061                         if (((dev->flags & CAM_DEV_REL_ON_QUEUE_EMPTY) != 0
5062                           && (dev->ccbq.dev_active == 0))) {
5063                                 dev->flags &= ~CAM_DEV_REL_ON_QUEUE_EMPTY;
5064                                 xpt_release_devq(ccb_h->path, /*count*/1,
5065                                                  /*run_queue*/FALSE);
5066                         }
5067
5068                         if (((dev->flags & CAM_DEV_REL_ON_COMPLETE) != 0
5069                           && (ccb_h->status&CAM_STATUS_MASK) != CAM_REQUEUE_REQ)) {
5070                                 dev->flags &= ~CAM_DEV_REL_ON_COMPLETE;
5071                                 xpt_release_devq(ccb_h->path, /*count*/1,
5072                                                  /*run_queue*/FALSE);
5073                         }
5074
5075                         if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
5076                          && (--dev->tag_delay_count == 0))
5077                                 xpt_start_tags(ccb_h->path);
5078                         if (!device_is_send_queued(dev)) {
5079                                 (void)xpt_schedule_dev_sendq(ccb_h->path->bus, 
5080                                                              dev);
5081                         }
5082                 }
5083
5084                 if (ccb_h->status & CAM_RELEASE_SIMQ) {
5085                         xpt_release_simq(ccb_h->path->bus->sim,
5086                                          /*run_queue*/TRUE);
5087                         ccb_h->status &= ~CAM_RELEASE_SIMQ;
5088                         runq = FALSE;
5089                 }
5090
5091                 if ((ccb_h->flags & CAM_DEV_QFRZDIS)
5092                  && (ccb_h->status & CAM_DEV_QFRZN)) {
5093                         xpt_release_devq(ccb_h->path, /*count*/1,
5094                                          /*run_queue*/TRUE);
5095                         ccb_h->status &= ~CAM_DEV_QFRZN;
5096                 } else if (runq) {
5097                         xpt_run_dev_sendq(ccb_h->path->bus);
5098                 }
5099
5100                 /* Call the peripheral driver's callback */
5101                 (*ccb_h->cbfcnp)(ccb_h->path->periph, (union ccb *)ccb_h);
5102         }
5103 }