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