2 * Copyright (c) 2007 Ariff Abdullah <ariff@FreeBSD.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * $FreeBSD: head/sys/dev/sound/clone.c 193640 2009-06-07 19:12:08Z ariff $
29 #include <sys/param.h>
30 #include <sys/systm.h>
32 #include <sys/kernel.h>
33 #include <sys/malloc.h>
36 #ifdef HAVE_KERNEL_OPTION_HEADERS
40 #if defined(SND_DIAGNOSTIC) || defined(SND_DEBUG)
41 #include <dev/sound/pcm/sound.h>
44 #include <dev/sound/clone.h>
47 * So here we go again, another clonedevs manager. Unlike default clonedevs,
48 * this clone manager is designed to withstand various abusive behavior
49 * (such as 'while : ; do ls /dev/whatever ; done', etc.), reusable object
50 * after reaching certain expiration threshold, aggressive garbage collector,
51 * transparent device allocator and concurrency handling across multiple
52 * thread/proc. Due to limited information given by dev_clone EVENTHANDLER,
53 * we don't have much clues whether the caller wants a real open() or simply
54 * making fun of us with things like stat(), mtime() etc. Assuming that:
55 * 1) Time window between dev_clone EH <-> real open() should be small
56 * enough and 2) mtime()/stat() etc. always looks like a half way / stalled
57 * operation, we can decide whether a new cdev must be created, old
58 * (expired) cdev can be reused or an existing cdev can be shared.
60 * Most of the operations and logics are generic enough and can be applied
61 * on other places (such as if_tap, snp, etc). Perhaps this can be
62 * rearranged to complement clone_*(). However, due to this still being
63 * specific to the sound driver (and as a proof of concept on how it can be
64 * done), si_drv2 is used to keep the pointer of the clone list entry to
65 * avoid expensive lookup.
69 struct snd_clone_entry {
70 TAILQ_ENTRY(snd_clone_entry) link;
71 struct snd_clone *parent;
81 TAILQ_HEAD(link_head, snd_clone_entry) head;
92 #define SND_CLONE_ASSERT(x, y) do { \
97 #define SND_CLONE_ASSERT(...) KASSERT(__VA_ARGS__)
101 * Shamelessly ripped off from vfs_subr.c
102 * We need at least 1/HZ precision as default timestamping.
104 enum { SND_TSP_SEC, SND_TSP_HZ, SND_TSP_USEC, SND_TSP_NSEC };
106 static int snd_timestamp_precision = SND_TSP_HZ;
107 TUNABLE_INT("hw.snd.timestamp_precision", &snd_timestamp_precision);
110 snd_timestamp(struct timespec *tsp)
114 switch (snd_timestamp_precision) {
116 tsp->tv_sec = time_second;
124 TIMEVAL_TO_TIMESPEC(&tv, tsp);
130 snd_timestamp_precision = SND_TSP_HZ;
136 #if defined(SND_DIAGNOSTIC) || defined(SND_DEBUG)
138 sysctl_hw_snd_timestamp_precision(SYSCTL_HANDLER_ARGS)
142 val = snd_timestamp_precision;
143 err = sysctl_handle_int(oidp, &val, 0, req);
144 if (err == 0 && req->newptr != NULL) {
150 snd_timestamp_precision = val;
159 SYSCTL_PROC(_hw_snd, OID_AUTO, timestamp_precision, CTLTYPE_INT | CTLFLAG_RW,
160 0, sizeof(int), sysctl_hw_snd_timestamp_precision, "I",
161 "timestamp precision (0=s 1=hz 2=us 3=ns)");
165 * snd_clone_create() : Return opaque allocated clone manager.
168 snd_clone_create(int typemask, int maxunit, int deadline, uint32_t flags)
172 SND_CLONE_ASSERT(!(typemask & ~SND_CLONE_MAXUNIT),
173 ("invalid typemask: 0x%08x", typemask));
174 SND_CLONE_ASSERT(maxunit == -1 ||
175 !(maxunit & ~(~typemask & SND_CLONE_MAXUNIT)),
176 ("maxunit overflow: typemask=0x%08x maxunit=%d",
178 SND_CLONE_ASSERT(!(flags & ~SND_CLONE_MASK),
179 ("invalid clone flags=0x%08x", flags));
181 c = kmalloc(sizeof(*c), M_DEVBUF, M_WAITOK | M_ZERO);
184 c->typemask = typemask;
185 c->maxunit = (maxunit == -1) ? (~typemask & SND_CLONE_MAXUNIT) :
187 c->deadline = deadline;
189 snd_timestamp(&c->tsp);
190 TAILQ_INIT(&c->head);
196 snd_clone_busy(struct snd_clone *c)
198 struct snd_clone_entry *ce;
200 SND_CLONE_ASSERT(c != NULL, ("NULL snd_clone"));
205 TAILQ_FOREACH(ce, &c->head, link) {
206 if (ce->flags & SND_CLONE_BUSY)
214 * snd_clone_enable()/disable() : Suspend/resume clone allocation through
215 * snd_clone_alloc(). Everything else will not be affected by this.
218 snd_clone_enable(struct snd_clone *c)
220 SND_CLONE_ASSERT(c != NULL, ("NULL snd_clone"));
222 if (c->flags & SND_CLONE_ENABLE)
225 c->flags |= SND_CLONE_ENABLE;
231 snd_clone_disable(struct snd_clone *c)
233 SND_CLONE_ASSERT(c != NULL, ("NULL snd_clone"));
235 if (!(c->flags & SND_CLONE_ENABLE))
238 c->flags &= ~SND_CLONE_ENABLE;
244 * Getters / Setters. Not worth explaining :)
247 snd_clone_getsize(struct snd_clone *c)
249 SND_CLONE_ASSERT(c != NULL, ("NULL snd_clone"));
255 snd_clone_getmaxunit(struct snd_clone *c)
257 SND_CLONE_ASSERT(c != NULL, ("NULL snd_clone"));
263 snd_clone_setmaxunit(struct snd_clone *c, int maxunit)
265 SND_CLONE_ASSERT(c != NULL, ("NULL snd_clone"));
266 SND_CLONE_ASSERT(maxunit == -1 ||
267 !(maxunit & ~(~c->typemask & SND_CLONE_MAXUNIT)),
268 ("maxunit overflow: typemask=0x%08x maxunit=%d",
269 c->typemask, maxunit));
271 c->maxunit = (maxunit == -1) ? (~c->typemask & SND_CLONE_MAXUNIT) :
278 snd_clone_getdeadline(struct snd_clone *c)
280 SND_CLONE_ASSERT(c != NULL, ("NULL snd_clone"));
282 return (c->deadline);
286 snd_clone_setdeadline(struct snd_clone *c, int deadline)
288 SND_CLONE_ASSERT(c != NULL, ("NULL snd_clone"));
290 c->deadline = deadline;
292 return (c->deadline);
296 snd_clone_gettime(struct snd_clone *c, struct timespec *tsp)
298 SND_CLONE_ASSERT(c != NULL, ("NULL snd_clone"));
299 SND_CLONE_ASSERT(tsp != NULL, ("NULL timespec"));
307 snd_clone_getflags(struct snd_clone *c)
309 SND_CLONE_ASSERT(c != NULL, ("NULL snd_clone"));
315 snd_clone_setflags(struct snd_clone *c, uint32_t flags)
317 SND_CLONE_ASSERT(c != NULL, ("NULL snd_clone"));
318 SND_CLONE_ASSERT(!(flags & ~SND_CLONE_MASK),
319 ("invalid clone flags=0x%08x", flags));
327 snd_clone_getdevtime(struct cdev *dev, struct timespec *tsp)
329 struct snd_clone_entry *ce;
331 SND_CLONE_ASSERT(dev != NULL, ("NULL dev"));
332 SND_CLONE_ASSERT(tsp != NULL, ("NULL timespec"));
338 SND_CLONE_ASSERT(ce->parent != NULL, ("NULL parent"));
346 snd_clone_getdevflags(struct cdev *dev)
348 struct snd_clone_entry *ce;
350 SND_CLONE_ASSERT(dev != NULL, ("NULL dev"));
356 SND_CLONE_ASSERT(ce->parent != NULL, ("NULL parent"));
362 snd_clone_setdevflags(struct cdev *dev, uint32_t flags)
364 struct snd_clone_entry *ce;
366 SND_CLONE_ASSERT(dev != NULL, ("NULL dev"));
367 SND_CLONE_ASSERT(!(flags & ~SND_CLONE_DEVMASK),
368 ("invalid clone dev flags=0x%08x", flags));
374 SND_CLONE_ASSERT(ce->parent != NULL, ("NULL parent"));
381 /* Elapsed time conversion to ms */
382 #define SND_CLONE_ELAPSED(x, y) \
383 ((((x)->tv_sec - (y)->tv_sec) * 1000) + \
384 (((y)->tv_nsec > (x)->tv_nsec) ? \
385 (((1000000000L + (x)->tv_nsec - \
386 (y)->tv_nsec) / 1000000) - 1000) : \
387 (((x)->tv_nsec - (y)->tv_nsec) / 1000000)))
389 #define SND_CLONE_EXPIRED(x, y, z) \
390 ((x)->deadline < 1 || \
391 ((y)->tv_sec - (z)->tv_sec) > ((x)->deadline / 1000) || \
392 SND_CLONE_ELAPSED(y, z) > (x)->deadline)
395 * snd_clone_gc() : Garbage collector for stalled, expired objects. Refer to
396 * clone.h for explanations on GC settings.
399 snd_clone_gc(struct snd_clone *c)
401 struct snd_clone_entry *ce, *tce;
405 SND_CLONE_ASSERT(c != NULL, ("NULL snd_clone"));
407 if (!(c->flags & SND_CLONE_GC_ENABLE) || c->size == 0)
413 * Bail out if the last clone handler was invoked below the deadline
416 if ((c->flags & SND_CLONE_GC_EXPIRED) &&
417 !SND_CLONE_EXPIRED(c, &now, &c->tsp))
423 * Visit each object in reverse order. If the object is still being
424 * referenced by a valid open(), skip it. Look for expired objects
425 * and either revoke its clone invocation status or mercilessly
428 TAILQ_FOREACH_REVERSE_MUTABLE(ce, &c->head, link_head, link, tce) {
429 if (!(ce->flags & SND_CLONE_BUSY) &&
430 (!(ce->flags & SND_CLONE_INVOKE) ||
431 SND_CLONE_EXPIRED(c, &now, &ce->tsp))) {
432 if (c->flags & SND_CLONE_GC_REVOKE) {
433 ce->flags &= ~SND_CLONE_INVOKE;
436 TAILQ_REMOVE(&c->head, ce, link);
437 destroy_dev(ce->devt);
445 /* return total pruned objects */
450 snd_clone_destroy(struct snd_clone *c)
452 struct snd_clone_entry *ce, *tmp;
454 SND_CLONE_ASSERT(c != NULL, ("NULL snd_clone"));
456 ce = TAILQ_FIRST(&c->head);
458 tmp = TAILQ_NEXT(ce, link);
459 if (ce->devt != NULL)
460 destroy_dev(ce->devt);
469 * snd_clone_acquire() : The vital part of concurrency management. Must be
470 * called somewhere at the beginning of open() handler. ENODEV is not really
471 * fatal since it just tell the caller that this is not cloned stuff.
472 * EBUSY is *real*, don't forget that!
475 snd_clone_acquire(struct cdev *dev)
477 struct snd_clone_entry *ce;
479 SND_CLONE_ASSERT(dev != NULL, ("NULL dev"));
485 SND_CLONE_ASSERT(ce->parent != NULL, ("NULL parent"));
487 ce->flags &= ~SND_CLONE_INVOKE;
489 if (ce->flags & SND_CLONE_BUSY)
492 ce->flags |= SND_CLONE_BUSY;
498 * snd_clone_release() : Release busy status. Must be called somewhere at
499 * the end of close() handler, or somewhere after fail open().
502 snd_clone_release(struct cdev *dev)
504 struct snd_clone_entry *ce;
506 SND_CLONE_ASSERT(dev != NULL, ("NULL dev"));
512 SND_CLONE_ASSERT(ce->parent != NULL, ("NULL parent"));
514 ce->flags &= ~SND_CLONE_INVOKE;
516 if (!(ce->flags & SND_CLONE_BUSY))
519 ce->flags &= ~SND_CLONE_BUSY;
526 * snd_clone_ref/unref() : Garbage collector reference counter. To make
527 * garbage collector run automatically, the sequence must be something like
528 * this (both in open() and close() handlers):
530 * open() - 1) snd_clone_acquire()
531 * 2) .... check check ... if failed, snd_clone_release()
532 * 3) Success. Call snd_clone_ref()
534 * close() - 1) .... check check check ....
535 * 2) Success. snd_clone_release()
536 * 3) snd_clone_unref() . Garbage collector will run at this point
537 * if this is the last referenced object.
540 snd_clone_ref(struct cdev *dev)
542 struct snd_clone_entry *ce;
545 SND_CLONE_ASSERT(dev != NULL, ("NULL dev"));
552 SND_CLONE_ASSERT(c != NULL, ("NULL parent"));
553 SND_CLONE_ASSERT(c->refcount >= 0, ("refcount < 0"));
555 return (++c->refcount);
559 snd_clone_unref(struct cdev *dev)
561 struct snd_clone_entry *ce;
564 SND_CLONE_ASSERT(dev != NULL, ("NULL dev"));
571 SND_CLONE_ASSERT(c != NULL, ("NULL parent"));
572 SND_CLONE_ASSERT(c->refcount > 0, ("refcount <= 0"));
577 * Run automatic garbage collector, if needed.
579 if ((c->flags & SND_CLONE_GC_UNREF) &&
580 (!(c->flags & SND_CLONE_GC_LASTREF) ||
581 (c->refcount == 0 && (c->flags & SND_CLONE_GC_LASTREF))))
582 (void)snd_clone_gc(c);
584 return (c->refcount);
588 snd_clone_register(struct snd_clone_entry *ce, struct cdev *dev)
590 SND_CLONE_ASSERT(ce != NULL, ("NULL snd_clone_entry"));
591 SND_CLONE_ASSERT(dev != NULL, ("NULL dev"));
592 SND_CLONE_ASSERT(dev->si_drv2 == NULL, ("dev->si_drv2 not NULL"));
593 SND_CLONE_ASSERT((ce->flags & SND_CLONE_ALLOC) == SND_CLONE_ALLOC,
594 ("invalid clone alloc flags=0x%08x", ce->flags));
595 SND_CLONE_ASSERT(ce->devt == NULL, ("ce->devt not NULL"));
596 SND_CLONE_ASSERT(ce->unit == dev2unit(dev),
597 ("invalid unit ce->unit=0x%08x dev2unit=0x%08x",
598 ce->unit, dev2unit(dev)));
600 SND_CLONE_ASSERT(ce->parent != NULL, ("NULL parent"));
604 ce->flags &= ~SND_CLONE_ALLOC;
605 ce->flags |= SND_CLONE_INVOKE;
608 struct snd_clone_entry *
609 snd_clone_alloc(struct snd_clone *c, struct cdev **dev, int *unit, int tmask)
611 struct snd_clone_entry *ce, *after, *bce, *cce, *nce, *tce;
613 int cunit, allocunit;
616 SND_CLONE_ASSERT(c != NULL, ("NULL snd_clone"));
617 SND_CLONE_ASSERT(dev != NULL, ("NULL dev pointer"));
618 SND_CLONE_ASSERT((c->typemask & tmask) == tmask,
619 ("invalid tmask: typemask=0x%08x tmask=0x%08x",
620 c->typemask, tmask));
621 SND_CLONE_ASSERT(unit != NULL, ("NULL unit pointer"));
622 SND_CLONE_ASSERT(*unit == -1 || !(*unit & (c->typemask | tmask)),
623 ("typemask collision: typemask=0x%08x tmask=0x%08x *unit=%d",
624 c->typemask, tmask, *unit));
626 if (!(c->flags & SND_CLONE_ENABLE) ||
627 (*unit != -1 && *unit > c->maxunit))
632 bce = NULL; /* "b"usy candidate */
633 cce = NULL; /* "c"urthread/proc candidate */
634 nce = NULL; /* "n"ull, totally unbusy candidate */
635 tce = NULL; /* Last "t"ry candidate */
637 allocunit = (*unit == -1) ? 0 : *unit;
638 curpid = curthread->td_proc->p_pid;
642 TAILQ_FOREACH(ce, &c->head, link) {
644 * Sort incrementally according to device type.
646 if (tmask > (ce->unit & c->typemask)) {
650 } else if (tmask < (ce->unit & c->typemask))
654 * Shoot.. this is where the grumpiness begin. Just
655 * return immediately.
657 if (*unit != -1 && *unit == (ce->unit & ~tmask))
658 goto snd_clone_alloc_out;
662 * Simmilar device type. Sort incrementally according
663 * to allocation unit. While here, look for free slot
664 * and possible collision for new / future allocation.
666 if (*unit == -1 && (ce->unit & ~tmask) == allocunit)
668 if ((ce->unit & ~tmask) < allocunit)
672 * 1. Look for non busy, but keep track of the best
673 * possible busy cdev.
674 * 2. Look for the best (oldest referenced) entry that is
675 * in a same process / thread.
676 * 3. Look for the best (oldest referenced), absolute free
678 * 4. Lastly, look for the best (oldest referenced)
679 * any entries that doesn't fit with anything above.
681 if (ce->flags & SND_CLONE_BUSY) {
682 if (ce->devt != NULL && (bce == NULL ||
683 timespeccmp(&ce->tsp, &bce->tsp, <)))
687 if (ce->pid == curpid &&
688 (cce == NULL || timespeccmp(&ce->tsp, &cce->tsp, <)))
690 else if (!(ce->flags & SND_CLONE_INVOKE) &&
691 (nce == NULL || timespeccmp(&ce->tsp, &nce->tsp, <)))
693 else if (tce == NULL || timespeccmp(&ce->tsp, &tce->tsp, <))
697 goto snd_clone_alloc_new;
698 else if (cce != NULL) {
699 /* Same proc entry found, go for it */
701 goto snd_clone_alloc_out;
702 } else if (nce != NULL) {
704 * Next, try absolute free entry. If the calculated
705 * allocunit is smaller, create new entry instead.
707 if (allocunit < (nce->unit & ~tmask))
708 goto snd_clone_alloc_new;
710 goto snd_clone_alloc_out;
711 } else if (allocunit > c->maxunit) {
713 * Maximum allowable unit reached. Try returning any
714 * available cdev and hope for the best. If the lookup is
715 * done for things like stat(), mtime() etc. , things should
716 * be ok. Otherwise, open() handler should do further checks
717 * and decide whether to return correct error code or not.
721 goto snd_clone_alloc_out;
722 } else if (bce != NULL) {
724 goto snd_clone_alloc_out;
731 * No free entries found, and we still haven't reached maximum
732 * allowable units. Allocate, setup a minimal unique entry with busy
733 * status so nobody will monkey on this new entry. Unit magic is set
734 * right here to avoid collision with other contesting handler.
735 * The caller must be carefull here to maintain its own
736 * synchronization, as long as it will not conflict with malloc(9)
739 * That said, go figure.
741 ce = kmalloc(sizeof(*ce), M_DEVBUF, M_WAITOK | M_ZERO);
746 * We're being dense, ignorance is bliss,
747 * Super Regulatory Measure (TM).. TRY AGAIN!
751 goto snd_clone_alloc_out;
752 } else if (tce != NULL) {
754 goto snd_clone_alloc_out;
755 } else if (bce != NULL) {
757 goto snd_clone_alloc_out;
761 /* Setup new entry */
763 ce->unit = tmask | allocunit;
766 ce->flags |= SND_CLONE_ALLOC;
768 TAILQ_INSERT_AFTER(&c->head, after, ce, link);
770 TAILQ_INSERT_HEAD(&c->head, ce, link);
775 * Save new allocation unit for caller which will be used
784 * Set, mark, timestamp the entry if this is a truly free entry.
785 * Leave busy entry alone.
787 if (!(ce->flags & SND_CLONE_BUSY)) {
790 ce->flags |= SND_CLONE_INVOKE;