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