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