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