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