]> code.delx.au - pulseaudio/blobdiff - src/modules/module-udev-detect.c
volume: Rename 'sync volume' to 'deferred volume'.
[pulseaudio] / src / modules / module-udev-detect.c
index f2e7b0dfb74522b8abb5358cebf48484cfb323fb..c5312a811446f01049702b7f1b5ec952e046767e 100644 (file)
 
 #include <errno.h>
 #include <limits.h>
+#include <dirent.h>
 #include <sys/inotify.h>
 #include <libudev.h>
 
+#include <pulse/timeval.h>
+
 #include <pulsecore/modargs.h>
 #include <pulsecore/core-error.h>
 #include <pulsecore/core-util.h>
 #include <pulsecore/namereg.h>
+#include <pulsecore/ratelimit.h>
 
 #include "module-udev-detect-symdef.h"
 
@@ -41,14 +45,16 @@ PA_MODULE_VERSION(PACKAGE_VERSION);
 PA_MODULE_LOAD_ONCE(TRUE);
 PA_MODULE_USAGE(
         "tsched=<enable system timer based scheduling mode?> "
-        "ignore_dB=<ignore dB information from the device?>");
+        "ignore_dB=<ignore dB information from the device?> "
+        "deferred_volume=<syncronize sw and hw volume changes in IO-thread?>");
 
 struct device {
     char *path;
-    pa_bool_t accessible;
+    pa_bool_t need_verify;
     char *card_name;
     char *args;
     uint32_t module;
+    pa_ratelimit ratelimit;
 };
 
 struct userdata {
@@ -57,6 +63,7 @@ struct userdata {
 
     pa_bool_t use_tsched:1;
     pa_bool_t ignore_dB:1;
+    pa_bool_t deferred_volume:1;
 
     struct udev* udev;
     struct udev_monitor *monitor;
@@ -69,6 +76,7 @@ struct userdata {
 static const char* const valid_modargs[] = {
     "tsched",
     "ignore_dB",
+    "deferred_volume",
     NULL
 };
 
@@ -98,34 +106,240 @@ static const char *path_get_card_id(const char *path) {
     return e + 5;
 }
 
+static char *card_get_sysattr(const char *card_idx, const char *name) {
+    struct udev *udev;
+    struct udev_device *card = NULL;
+    char *t, *r = NULL;
+    const char *v;
+
+    pa_assert(card_idx);
+    pa_assert(name);
+
+    if (!(udev = udev_new())) {
+        pa_log_error("Failed to allocate udev context.");
+        goto finish;
+    }
+
+    t = pa_sprintf_malloc("%s/class/sound/card%s", udev_get_sys_path(udev), card_idx);
+    card = udev_device_new_from_syspath(udev, t);
+    pa_xfree(t);
+
+    if (!card) {
+        pa_log_error("Failed to get card object.");
+        goto finish;
+    }
+
+    if ((v = udev_device_get_sysattr_value(card, name)) && *v)
+        r = pa_xstrdup(v);
+
+finish:
+
+    if (card)
+        udev_device_unref(card);
+
+    if (udev)
+        udev_unref(udev);
+
+    return r;
+}
+
+static pa_bool_t pcm_is_modem(const char *card_idx, const char *pcm) {
+    char *sysfs_path, *pcm_class;
+    pa_bool_t is_modem;
+
+    pa_assert(card_idx);
+    pa_assert(pcm);
+
+    /* Check /sys/class/sound/card.../pcmC...../pcm_class. An HDA
+     * modem can be used simultaneously with generic
+     * playback/record. */
+
+    sysfs_path = pa_sprintf_malloc("pcmC%sD%s/pcm_class", card_idx, pcm);
+    pcm_class = card_get_sysattr(card_idx, sysfs_path);
+    is_modem = pcm_class && pa_streq(pcm_class, "modem");
+    pa_xfree(pcm_class);
+    pa_xfree(sysfs_path);
+
+    return is_modem;
+}
+
+static pa_bool_t is_card_busy(const char *id) {
+    char *card_path = NULL, *pcm_path = NULL, *sub_status = NULL;
+    DIR *card_dir = NULL, *pcm_dir = NULL;
+    FILE *status_file = NULL;
+    size_t len;
+    struct dirent *space = NULL, *de;
+    pa_bool_t busy = FALSE;
+    int r;
+
+    pa_assert(id);
+
+    /* This simply uses /proc/asound/card.../pcm.../sub.../status to
+     * check whether there is still a process using this audio device. */
+
+    card_path = pa_sprintf_malloc("/proc/asound/card%s", id);
+
+    if (!(card_dir = opendir(card_path))) {
+        pa_log_warn("Failed to open %s: %s", card_path, pa_cstrerror(errno));
+        goto fail;
+    }
+
+    len = offsetof(struct dirent, d_name) + fpathconf(dirfd(card_dir), _PC_NAME_MAX) + 1;
+    space = pa_xmalloc(len);
+
+    for (;;) {
+        de = NULL;
+
+        if ((r = readdir_r(card_dir, space, &de)) != 0) {
+            pa_log_warn("readdir_r() failed: %s", pa_cstrerror(r));
+            goto fail;
+        }
+
+        if (!de)
+            break;
+
+        if (!pa_startswith(de->d_name, "pcm"))
+            continue;
+
+        if (pcm_is_modem(id, de->d_name + 3))
+            continue;
+
+        pa_xfree(pcm_path);
+        pcm_path = pa_sprintf_malloc("%s/%s", card_path, de->d_name);
+
+        if (pcm_dir)
+            closedir(pcm_dir);
+
+        if (!(pcm_dir = opendir(pcm_path))) {
+            pa_log_warn("Failed to open %s: %s", pcm_path, pa_cstrerror(errno));
+            continue;
+        }
+
+        for (;;) {
+            char line[32];
+
+            if ((r = readdir_r(pcm_dir, space, &de)) != 0) {
+                pa_log_warn("readdir_r() failed: %s", pa_cstrerror(r));
+                goto fail;
+            }
+
+            if (!de)
+                break;
+
+            if (!pa_startswith(de->d_name, "sub"))
+                continue;
+
+            pa_xfree(sub_status);
+            sub_status = pa_sprintf_malloc("%s/%s/status", pcm_path, de->d_name);
+
+            if (status_file)
+                fclose(status_file);
+
+            if (!(status_file = pa_fopen_cloexec(sub_status, "r"))) {
+                pa_log_warn("Failed to open %s: %s", sub_status, pa_cstrerror(errno));
+                continue;
+            }
+
+            if (!(fgets(line, sizeof(line)-1, status_file))) {
+                pa_log_warn("Failed to read from %s: %s", sub_status, pa_cstrerror(errno));
+                continue;
+            }
+
+            if (!pa_streq(line, "closed\n")) {
+                busy = TRUE;
+                break;
+            }
+        }
+    }
+
+fail:
+
+    pa_xfree(card_path);
+    pa_xfree(pcm_path);
+    pa_xfree(sub_status);
+    pa_xfree(space);
+
+    if (card_dir)
+        closedir(card_dir);
+
+    if (pcm_dir)
+        closedir(pcm_dir);
+
+    if (status_file)
+        fclose(status_file);
+
+    return busy;
+}
+
 static void verify_access(struct userdata *u, struct device *d) {
     char *cd;
     pa_card *card;
+    pa_bool_t accessible;
 
     pa_assert(u);
     pa_assert(d);
 
     cd = pa_sprintf_malloc("%s/snd/controlC%s", udev_get_dev_path(u->udev), path_get_card_id(d->path));
-    d->accessible = access(cd, R_OK|W_OK) >= 0;
+    accessible = access(cd, R_OK|W_OK) >= 0;
+    pa_log_debug("%s is accessible: %s", cd, pa_yes_no(accessible));
 
-    pa_log_info("%s is accessible: %s", cd, pa_yes_no(d->accessible));
     pa_xfree(cd);
 
     if (d->module == PA_INVALID_INDEX) {
 
-        /* If we not loaded, try to load */
+        /* If we are not loaded, try to load */
 
-        if (d->accessible) {
+        if (accessible) {
             pa_module *m;
-
-            pa_log_debug("Loading module-alsa-card with arguments '%s'", d->args);
-            m = pa_module_load(u->core, "module-alsa-card", d->args);
-
-            if (m) {
-                d->module = m->index;
-                pa_log_info("Card %s (%s) module loaded.", d->path, d->card_name);
-            } else
-                pa_log_info("Card %s (%s) failed to load module.", d->path, d->card_name);
+            pa_bool_t busy;
+
+            /* Check if any of the PCM devices that belong to this
+             * card are currently busy. If they are, don't try to load
+             * right now, to make sure the probing phase can
+             * successfully complete. When the current user of the
+             * device closes it we will get another notification via
+             * inotify and can then recheck. */
+
+            busy = is_card_busy(path_get_card_id(d->path));
+            pa_log_debug("%s is busy: %s", d->path, pa_yes_no(busy));
+
+            if (!busy) {
+
+                /* So, why do we rate limit here? It's certainly ugly,
+                 * but there seems to be no other way. Problem is
+                 * this: if we are unable to configure/probe an audio
+                 * device after opening it we will close it again and
+                 * the module initialization will fail. This will then
+                 * cause an inotify event on the device node which
+                 * will be forwarded to us. We then try to reopen the
+                 * audio device again, practically entering a busy
+                 * loop.
+                 *
+                 * A clean fix would be if we would be able to ignore
+                 * our own inotify close events. However, inotify
+                 * lacks such functionality. Also, during probing of
+                 * the device we cannot really distinguish between
+                 * other processes causing EBUSY or ourselves, which
+                 * means we have no way to figure out if the probing
+                 * during opening was canceled by a "try again"
+                 * failure or a "fatal" failure. */
+
+                if (pa_ratelimit_test(&d->ratelimit, PA_LOG_DEBUG)) {
+                    pa_log_debug("Loading module-alsa-card with arguments '%s'", d->args);
+                    m = pa_module_load(u->core, "module-alsa-card", d->args);
+
+                    if (m) {
+                        d->module = m->index;
+                        pa_log_info("Card %s (%s) module loaded.", d->path, d->card_name);
+                    } else
+                        pa_log_info("Card %s (%s) failed to load module.", d->path, d->card_name);
+                } else
+                    pa_log_warn("Tried to configure %s (%s) more often than %u times in %llus",
+                                d->path,
+                                d->card_name,
+                                d->ratelimit.burst,
+                                (long long unsigned) (d->ratelimit.interval / PA_USEC_PER_SEC));
+            }
         }
 
     } else {
@@ -134,7 +348,7 @@ static void verify_access(struct userdata *u, struct device *d) {
          * accessible boolean */
 
         if ((card = pa_namereg_get(u->core, d->card_name, PA_NAMEREG_CARD)))
-            pa_card_suspend(card, !d->accessible, PA_SUSPEND_SESSION);
+            pa_card_suspend(card, !accessible, PA_SUSPEND_SESSION);
     }
 }
 
@@ -159,8 +373,8 @@ static void card_changed(struct userdata *u, struct udev_device *dev) {
 
     d = pa_xnew0(struct device, 1);
     d->path = pa_xstrdup(path);
-    d->accessible = TRUE;
     d->module = PA_INVALID_INDEX;
+    PA_INIT_RATELIMIT(d->ratelimit, 10*PA_USEC_PER_SEC, 5);
 
     if (!(t = udev_device_get_property_value(dev, "PULSE_NAME")))
         if (!(t = udev_device_get_property_value(dev, "ID_ID")))
@@ -172,14 +386,17 @@ static void card_changed(struct userdata *u, struct udev_device *dev) {
     d->args = pa_sprintf_malloc("device_id=\"%s\" "
                                 "name=\"%s\" "
                                 "card_name=\"%s\" "
+                                "namereg_fail=false "
                                 "tsched=%s "
                                 "ignore_dB=%s "
+                                "deferred_volume=%s "
                                 "card_properties=\"module-udev-detect.discovered=1\"",
                                 path_get_card_id(path),
                                 n,
                                 d->card_name,
                                 pa_yes_no(u->use_tsched),
-                                pa_yes_no(u->ignore_dB));
+                                pa_yes_no(u->ignore_dB),
+                                pa_yes_no(u->deferred_volume));
     pa_xfree(n);
 
     pa_hashmap_put(u->devices, d->path, d);
@@ -215,7 +432,7 @@ static void process_device(struct userdata *u, struct udev_device *dev) {
         return;
     }
 
-    if ((ff = udev_device_get_property_value(dev, "SOUND_FORM_FACTOR")) &&
+    if ((ff = udev_device_get_property_value(dev, "SOUND_CLASS")) &&
         pa_streq(ff, "modem")) {
         pa_log_debug("Ignoring %s, because it is a modem.", udev_device_get_devpath(dev));
         return;
@@ -225,8 +442,7 @@ static void process_device(struct userdata *u, struct udev_device *dev) {
 
     if (action && pa_streq(action, "remove"))
         remove_card(u, dev);
-    else if ((!action || pa_streq(action, "change")) &&
-             udev_device_get_property_value(dev, "SOUND_INITIALIZED"))
+    else if ((!action || pa_streq(action, "change")) && udev_device_get_property_value(dev, "SOUND_INITIALIZED"))
         card_changed(u, dev);
 
     /* For an explanation why we don't look for 'add' events here
@@ -265,8 +481,10 @@ static void monitor_cb(
         goto fail;
     }
 
-    if (!path_get_card_id(udev_device_get_devpath(dev)))
+    if (!path_get_card_id(udev_device_get_devpath(dev))) {
+        udev_device_unref(dev);
         return;
+    }
 
     process_device(u, dev);
     udev_device_unref(dev);
@@ -277,6 +495,34 @@ fail:
     u->udev_io = NULL;
 }
 
+static pa_bool_t pcm_node_belongs_to_device(
+        struct device *d,
+        const char *node) {
+
+    char *cd;
+    pa_bool_t b;
+
+    cd = pa_sprintf_malloc("pcmC%sD", path_get_card_id(d->path));
+    b = pa_startswith(node, cd);
+    pa_xfree(cd);
+
+    return b;
+}
+
+static pa_bool_t control_node_belongs_to_device(
+        struct device *d,
+        const char *node) {
+
+    char *cd;
+    pa_bool_t b;
+
+    cd = pa_sprintf_malloc("controlC%s", path_get_card_id(d->path));
+    b = pa_streq(node, cd);
+    pa_xfree(cd);
+
+    return b;
+}
+
 static void inotify_cb(
         pa_mainloop_api*a,
         pa_io_event* e,
@@ -290,10 +536,13 @@ static void inotify_cb(
     } buf;
     struct userdata *u = userdata;
     static int type = 0;
-    pa_bool_t verify = FALSE, deleted = FALSE;
+    pa_bool_t deleted = FALSE;
+    struct device *d;
+    void *state;
 
     for (;;) {
         ssize_t r;
+        struct inotify_event *event;
 
         pa_zero(buf);
         if ((r = pa_read(fd, &buf, sizeof(buf), &type)) <= 0) {
@@ -305,22 +554,51 @@ static void inotify_cb(
             goto fail;
         }
 
-        if ((buf.e.mask & IN_CLOSE_WRITE) && pa_startswith(buf.e.name, "pcmC"))
-            verify = TRUE;
-
-        if ((buf.e.mask & (IN_DELETE_SELF|IN_MOVE_SELF)))
-            deleted = TRUE;
+        event = &buf.e;
+        while (r > 0) {
+            size_t len;
+
+            if ((size_t) r < sizeof(struct inotify_event)) {
+                pa_log("read() too short.");
+                goto fail;
+            }
+
+            len = sizeof(struct inotify_event) + event->len;
+
+            if ((size_t) r < len) {
+                pa_log("Payload missing.");
+                goto fail;
+            }
+
+            /* From udev we get the guarantee that the control
+             * device's ACL is changed last. To avoid races when ACLs
+             * are changed we hence watch only the control device */
+            if (((event->mask & IN_ATTRIB) && pa_startswith(event->name, "controlC")))
+                PA_HASHMAP_FOREACH(d, u->devices, state)
+                    if (control_node_belongs_to_device(d, event->name))
+                        d->need_verify = TRUE;
+
+            /* ALSA doesn't really give us any guarantee on the closing
+             * order, so let's simply hope */
+            if (((event->mask & IN_CLOSE_WRITE) && pa_startswith(event->name, "pcmC")))
+                PA_HASHMAP_FOREACH(d, u->devices, state)
+                    if (pcm_node_belongs_to_device(d, event->name))
+                        d->need_verify = TRUE;
+
+            /* /dev/snd/ might have been removed */
+            if ((event->mask & (IN_DELETE_SELF|IN_MOVE_SELF)))
+                deleted = TRUE;
+
+            event = (struct inotify_event*) ((uint8_t*) event + len);
+            r -= len;
+        }
     }
 
-    if (verify) {
-        struct device *d;
-        void *state;
-
-        pa_log_debug("Verifying access.");
-
-        PA_HASHMAP_FOREACH(d, u->devices, state)
+    PA_HASHMAP_FOREACH(d, u->devices, state)
+        if (d->need_verify) {
+            d->need_verify = FALSE;
             verify_access(u, d);
-    }
+        }
 
     if (!deleted)
         return;
@@ -350,7 +628,7 @@ static int setup_inotify(struct userdata *u) {
     }
 
     dev_snd = pa_sprintf_malloc("%s/snd", udev_get_dev_path(u->udev));
-    r = inotify_add_watch(u->inotify_fd, dev_snd, IN_CLOSE_WRITE|IN_DELETE_SELF|IN_MOVE_SELF);
+    r = inotify_add_watch(u->inotify_fd, dev_snd, IN_ATTRIB|IN_CLOSE_WRITE|IN_DELETE_SELF|IN_MOVE_SELF);
     pa_xfree(dev_snd);
 
     if (r < 0) {
@@ -387,7 +665,8 @@ int pa__init(pa_module *m) {
     struct udev_enumerate *enumerate = NULL;
     struct udev_list_entry *item = NULL, *first = NULL;
     int fd;
-    pa_bool_t use_tsched = TRUE, ignore_dB = FALSE;
+    pa_bool_t use_tsched = TRUE, ignore_dB = FALSE, deferred_volume = m->core->deferred_volume;
+
 
     pa_assert(m);
 
@@ -413,6 +692,12 @@ int pa__init(pa_module *m) {
     }
     u->ignore_dB = ignore_dB;
 
+    if (pa_modargs_get_value_boolean(ma, "deferred_volume", &deferred_volume) < 0) {
+        pa_log("Failed to parse deferred_volume= argument.");
+        goto fail;
+    }
+    u->deferred_volume = deferred_volume;
+
     if (!(u->udev = udev_new())) {
         pa_log("Failed to initialize udev library.");
         goto fail;
@@ -426,12 +711,17 @@ int pa__init(pa_module *m) {
         goto fail;
     }
 
+    if (udev_monitor_filter_add_match_subsystem_devtype(u->monitor, "sound", NULL) < 0) {
+        pa_log("Failed to subscribe to sound devices.");
+        goto fail;
+    }
+
     errno = 0;
     if (udev_monitor_enable_receiving(u->monitor) < 0) {
         pa_log("Failed to enable monitor: %s", pa_cstrerror(errno));
         if (errno == EPERM)
             pa_log_info("Most likely your kernel is simply too old and "
-                        "allows only priviliged processes to listen to device events. "
+                        "allows only privileged processes to listen to device events. "
                         "Please upgrade your kernel to at least 2.6.30.");
         goto fail;
     }