udev: make sure we get events only for sound devices
[profile/ivi/pulseaudio.git] / src / modules / module-udev-detect.c
1 /***
2   This file is part of PulseAudio.
3
4   Copyright 2009 Lennart Poettering
5
6   PulseAudio is free software; you can redistribute it and/or modify
7   it under the terms of the GNU Lesser General Public License as
8   published by the Free Software Foundation; either version 2.1 of the
9   License, or (at your option) any later version.
10
11   PulseAudio is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   General Public License for more details.
15
16   You should have received a copy of the GNU Lesser General Public
17   License along with PulseAudio; if not, write to the Free Software
18   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19   USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <errno.h>
27 #include <limits.h>
28 #include <dirent.h>
29 #include <sys/inotify.h>
30 #include <libudev.h>
31
32 #include <pulse/timeval.h>
33
34 #include <pulsecore/modargs.h>
35 #include <pulsecore/core-error.h>
36 #include <pulsecore/core-util.h>
37 #include <pulsecore/namereg.h>
38 #include <pulsecore/ratelimit.h>
39
40 #include "module-udev-detect-symdef.h"
41
42 PA_MODULE_AUTHOR("Lennart Poettering");
43 PA_MODULE_DESCRIPTION("Detect available audio hardware and load matching drivers");
44 PA_MODULE_VERSION(PACKAGE_VERSION);
45 PA_MODULE_LOAD_ONCE(TRUE);
46 PA_MODULE_USAGE(
47         "tsched=<enable system timer based scheduling mode?> "
48         "ignore_dB=<ignore dB information from the device?>");
49
50 struct device {
51     char *path;
52     pa_bool_t need_verify;
53     char *card_name;
54     char *args;
55     uint32_t module;
56     pa_ratelimit ratelimit;
57 };
58
59 struct userdata {
60     pa_core *core;
61     pa_hashmap *devices;
62
63     pa_bool_t use_tsched:1;
64     pa_bool_t ignore_dB:1;
65
66     struct udev* udev;
67     struct udev_monitor *monitor;
68     pa_io_event *udev_io;
69
70     int inotify_fd;
71     pa_io_event *inotify_io;
72 };
73
74 static const char* const valid_modargs[] = {
75     "tsched",
76     "ignore_dB",
77     NULL
78 };
79
80 static int setup_inotify(struct userdata *u);
81
82 static void device_free(struct device *d) {
83     pa_assert(d);
84
85     pa_xfree(d->path);
86     pa_xfree(d->card_name);
87     pa_xfree(d->args);
88     pa_xfree(d);
89 }
90
91 static const char *path_get_card_id(const char *path) {
92     const char *e;
93
94     if (!path)
95         return NULL;
96
97     if (!(e = strrchr(path, '/')))
98         return NULL;
99
100     if (!pa_startswith(e, "/card"))
101         return NULL;
102
103     return e + 5;
104 }
105
106 static pa_bool_t is_card_busy(const char *id) {
107     char *card_path = NULL, *pcm_path = NULL, *sub_status = NULL;
108     DIR *card_dir = NULL, *pcm_dir = NULL;
109     FILE *status_file = NULL;
110     size_t len;
111     struct dirent *space = NULL, *de;
112     pa_bool_t busy = FALSE;
113     int r;
114
115     pa_assert(id);
116
117     /* This simply uses /proc/asound/card.../pcm.../sub.../status to
118      * check whether there is still a process using this audio device. */
119
120     card_path = pa_sprintf_malloc("/proc/asound/card%s", id);
121
122     if (!(card_dir = opendir(card_path))) {
123         pa_log_warn("Failed to open %s: %s", card_path, pa_cstrerror(errno));
124         goto fail;
125     }
126
127     len = offsetof(struct dirent, d_name) + fpathconf(dirfd(card_dir), _PC_NAME_MAX) + 1;
128     space = pa_xmalloc(len);
129
130     for (;;) {
131         de = NULL;
132
133         if ((r = readdir_r(card_dir, space, &de)) != 0) {
134             pa_log_warn("readdir_r() failed: %s", pa_cstrerror(r));
135             goto fail;
136         }
137
138         if (!de)
139             break;
140
141         if (!pa_startswith(de->d_name, "pcm"))
142             continue;
143
144         pa_xfree(pcm_path);
145         pcm_path = pa_sprintf_malloc("%s/%s", card_path, de->d_name);
146
147         if (pcm_dir)
148             closedir(pcm_dir);
149
150         if (!(pcm_dir = opendir(pcm_path))) {
151             pa_log_warn("Failed to open %s: %s", pcm_path, pa_cstrerror(errno));
152             continue;
153         }
154
155         for (;;) {
156             char line[32];
157
158             if ((r = readdir_r(pcm_dir, space, &de)) != 0) {
159                 pa_log_warn("readdir_r() failed: %s", pa_cstrerror(r));
160                 goto fail;
161             }
162
163             if (!de)
164                 break;
165
166             if (!pa_startswith(de->d_name, "sub"))
167                 continue;
168
169             pa_xfree(sub_status);
170             sub_status = pa_sprintf_malloc("%s/%s/status", pcm_path, de->d_name);
171
172             if (status_file)
173                 fclose(status_file);
174
175             if (!(status_file = pa_fopen_cloexec(sub_status, "r"))) {
176                 pa_log_warn("Failed to open %s: %s", sub_status, pa_cstrerror(errno));
177                 continue;
178             }
179
180             if (!(fgets(line, sizeof(line)-1, status_file))) {
181                 pa_log_warn("Failed to read from %s: %s", sub_status, pa_cstrerror(errno));
182                 continue;
183             }
184
185             if (!pa_streq(line, "closed\n")) {
186                 busy = TRUE;
187                 break;
188             }
189         }
190     }
191
192 fail:
193
194     pa_xfree(card_path);
195     pa_xfree(pcm_path);
196     pa_xfree(sub_status);
197     pa_xfree(space);
198
199     if (card_dir)
200         closedir(card_dir);
201
202     if (pcm_dir)
203         closedir(pcm_dir);
204
205     if (status_file)
206         fclose(status_file);
207
208     return busy;
209 }
210
211 static void verify_access(struct userdata *u, struct device *d) {
212     char *cd;
213     pa_card *card;
214     pa_bool_t accessible;
215
216     pa_assert(u);
217     pa_assert(d);
218
219     cd = pa_sprintf_malloc("%s/snd/controlC%s", udev_get_dev_path(u->udev), path_get_card_id(d->path));
220     accessible = access(cd, R_OK|W_OK) >= 0;
221     pa_log_debug("%s is accessible: %s", cd, pa_yes_no(accessible));
222
223     pa_xfree(cd);
224
225     if (d->module == PA_INVALID_INDEX) {
226
227         /* If we are not loaded, try to load */
228
229         if (accessible) {
230             pa_module *m;
231             pa_bool_t busy;
232
233             /* Check if any of the PCM devices that belong to this
234              * card are currently busy. If they are, don't try to load
235              * right now, to make sure the probing phase can
236              * successfully complete. When the current user of the
237              * device closes it we will get another notification via
238              * inotify and can then recheck. */
239
240             busy = is_card_busy(path_get_card_id(d->path));
241             pa_log_debug("%s is busy: %s", d->path, pa_yes_no(busy));
242
243             if (!busy) {
244
245                 /* So, why do we rate limit here? It's certainly ugly,
246                  * but there seems to be no other way. Problem is
247                  * this: if we are unable to configure/probe an audio
248                  * device after opening it we will close it again and
249                  * the module initialization will fail. This will then
250                  * cause an inotify event on the device node which
251                  * will be forwarded to us. We then try to reopen the
252                  * audio device again, practically entering a busy
253                  * loop.
254                  *
255                  * A clean fix would be if we would be able to ignore
256                  * our own inotify close events. However, inotify
257                  * lacks such functionality. Also, during probing of
258                  * the device we cannot really distuingish between
259                  * other processes causing EBUSY or ourselves, which
260                  * means we have no way to figure out if the probing
261                  * during opening was canceled by a "try again"
262                  * failure or a "fatal" failure. */
263
264                 if (pa_ratelimit_test(&d->ratelimit)) {
265                     pa_log_debug("Loading module-alsa-card with arguments '%s'", d->args);
266                     m = pa_module_load(u->core, "module-alsa-card", d->args);
267
268                     if (m) {
269                         d->module = m->index;
270                         pa_log_info("Card %s (%s) module loaded.", d->path, d->card_name);
271                     } else
272                         pa_log_info("Card %s (%s) failed to load module.", d->path, d->card_name);
273                 } else
274                     pa_log_warn("Tried to configure %s (%s) more often than %u times in %llus",
275                                 d->path,
276                                 d->card_name,
277                                 d->ratelimit.burst,
278                                 (long long unsigned) (d->ratelimit.interval / PA_USEC_PER_SEC));
279             }
280         }
281
282     } else {
283
284         /* If we are already loaded update suspend status with
285          * accessible boolean */
286
287         if ((card = pa_namereg_get(u->core, d->card_name, PA_NAMEREG_CARD)))
288             pa_card_suspend(card, !accessible, PA_SUSPEND_SESSION);
289     }
290 }
291
292 static void card_changed(struct userdata *u, struct udev_device *dev) {
293     struct device *d;
294     const char *path;
295     const char *t;
296     char *n;
297
298     pa_assert(u);
299     pa_assert(dev);
300
301     /* Maybe /dev/snd is now available? */
302     setup_inotify(u);
303
304     path = udev_device_get_devpath(dev);
305
306     if ((d = pa_hashmap_get(u->devices, path))) {
307         verify_access(u, d);
308         return;
309     }
310
311     d = pa_xnew0(struct device, 1);
312     d->path = pa_xstrdup(path);
313     d->module = PA_INVALID_INDEX;
314     PA_INIT_RATELIMIT(d->ratelimit, 10*PA_USEC_PER_SEC, 5);
315
316     if (!(t = udev_device_get_property_value(dev, "PULSE_NAME")))
317         if (!(t = udev_device_get_property_value(dev, "ID_ID")))
318             if (!(t = udev_device_get_property_value(dev, "ID_PATH")))
319                 t = path_get_card_id(path);
320
321     n = pa_namereg_make_valid_name(t);
322     d->card_name = pa_sprintf_malloc("alsa_card.%s", n);
323     d->args = pa_sprintf_malloc("device_id=\"%s\" "
324                                 "name=\"%s\" "
325                                 "card_name=\"%s\" "
326                                 "tsched=%s "
327                                 "ignore_dB=%s "
328                                 "card_properties=\"module-udev-detect.discovered=1\"",
329                                 path_get_card_id(path),
330                                 n,
331                                 d->card_name,
332                                 pa_yes_no(u->use_tsched),
333                                 pa_yes_no(u->ignore_dB));
334     pa_xfree(n);
335
336     pa_hashmap_put(u->devices, d->path, d);
337
338     verify_access(u, d);
339 }
340
341 static void remove_card(struct userdata *u, struct udev_device *dev) {
342     struct device *d;
343
344     pa_assert(u);
345     pa_assert(dev);
346
347     if (!(d = pa_hashmap_remove(u->devices, udev_device_get_devpath(dev))))
348         return;
349
350     pa_log_info("Card %s removed.", d->path);
351
352     if (d->module != PA_INVALID_INDEX)
353         pa_module_unload_request_by_index(u->core, d->module, TRUE);
354
355     device_free(d);
356 }
357
358 static void process_device(struct userdata *u, struct udev_device *dev) {
359     const char *action, *ff;
360
361     pa_assert(u);
362     pa_assert(dev);
363
364     if (udev_device_get_property_value(dev, "PULSE_IGNORE")) {
365         pa_log_debug("Ignoring %s, because marked so.", udev_device_get_devpath(dev));
366         return;
367     }
368
369     if ((ff = udev_device_get_property_value(dev, "SOUND_CLASS")) &&
370         pa_streq(ff, "modem")) {
371         pa_log_debug("Ignoring %s, because it is a modem.", udev_device_get_devpath(dev));
372         return;
373     }
374
375     action = udev_device_get_action(dev);
376
377     if (action && pa_streq(action, "remove"))
378         remove_card(u, dev);
379     else if ((!action || pa_streq(action, "change")) &&
380              udev_device_get_property_value(dev, "SOUND_INITIALIZED"))
381         card_changed(u, dev);
382
383     /* For an explanation why we don't look for 'add' events here
384      * have a look into /lib/udev/rules.d/78-sound-card.rules! */
385 }
386
387 static void process_path(struct userdata *u, const char *path) {
388     struct udev_device *dev;
389
390     if (!path_get_card_id(path))
391         return;
392
393     if (!(dev = udev_device_new_from_syspath(u->udev, path))) {
394         pa_log("Failed to get udev device object from udev.");
395         return;
396     }
397
398     process_device(u, dev);
399     udev_device_unref(dev);
400 }
401
402 static void monitor_cb(
403         pa_mainloop_api*a,
404         pa_io_event* e,
405         int fd,
406         pa_io_event_flags_t events,
407         void *userdata) {
408
409     struct userdata *u = userdata;
410     struct udev_device *dev;
411
412     pa_assert(a);
413
414     if (!(dev = udev_monitor_receive_device(u->monitor))) {
415         pa_log("Failed to get udev device object from monitor.");
416         goto fail;
417     }
418
419     if (!path_get_card_id(udev_device_get_devpath(dev))) {
420         udev_device_unref(dev);
421         return;
422     }
423
424     process_device(u, dev);
425     udev_device_unref(dev);
426     return;
427
428 fail:
429     a->io_free(u->udev_io);
430     u->udev_io = NULL;
431 }
432
433 static pa_bool_t pcm_node_belongs_to_device(
434         struct device *d,
435         const char *node) {
436
437     char *cd;
438     pa_bool_t b;
439
440     cd = pa_sprintf_malloc("pcmC%sD", path_get_card_id(d->path));
441     b = pa_startswith(node, cd);
442     pa_xfree(cd);
443
444     return b;
445 }
446
447 static pa_bool_t control_node_belongs_to_device(
448         struct device *d,
449         const char *node) {
450
451     char *cd;
452     pa_bool_t b;
453
454     cd = pa_sprintf_malloc("controlC%s", path_get_card_id(d->path));
455     b = pa_streq(node, cd);
456     pa_xfree(cd);
457
458     return b;
459 }
460
461 static void inotify_cb(
462         pa_mainloop_api*a,
463         pa_io_event* e,
464         int fd,
465         pa_io_event_flags_t events,
466         void *userdata) {
467
468     struct {
469         struct inotify_event e;
470         char name[NAME_MAX];
471     } buf;
472     struct userdata *u = userdata;
473     static int type = 0;
474     pa_bool_t deleted = FALSE;
475     struct device *d;
476     void *state;
477
478     for (;;) {
479         ssize_t r;
480         struct inotify_event *event;
481
482         pa_zero(buf);
483         if ((r = pa_read(fd, &buf, sizeof(buf), &type)) <= 0) {
484
485             if (r < 0 && errno == EAGAIN)
486                 break;
487
488             pa_log("read() from inotify failed: %s", r < 0 ? pa_cstrerror(errno) : "EOF");
489             goto fail;
490         }
491
492         event = &buf.e;
493         while (r > 0) {
494             size_t len;
495
496             if ((size_t) r < sizeof(struct inotify_event)) {
497                 pa_log("read() too short.");
498                 goto fail;
499             }
500
501             len = sizeof(struct inotify_event) + event->len;
502
503             if ((size_t) r < len) {
504                 pa_log("Payload missing.");
505                 goto fail;
506             }
507
508             /* From udev we get the guarantee that the control
509              * device's ACL is changed last. To avoid races when ACLs
510              * are changed we hence watch only the control device */
511             if (((event->mask & IN_ATTRIB) && pa_startswith(event->name, "controlC")))
512                 PA_HASHMAP_FOREACH(d, u->devices, state)
513                     if (control_node_belongs_to_device(d, event->name))
514                         d->need_verify = TRUE;
515
516             /* ALSA doesn't really give us any guarantee on the closing
517              * order, so let's simply hope */
518             if (((event->mask & IN_CLOSE_WRITE) && pa_startswith(event->name, "pcmC")))
519                 PA_HASHMAP_FOREACH(d, u->devices, state)
520                     if (pcm_node_belongs_to_device(d, event->name))
521                         d->need_verify = TRUE;
522
523             /* /dev/snd/ might have been removed */
524             if ((event->mask & (IN_DELETE_SELF|IN_MOVE_SELF)))
525                 deleted = TRUE;
526
527             event = (struct inotify_event*) ((uint8_t*) event + len);
528             r -= len;
529         }
530     }
531
532     PA_HASHMAP_FOREACH(d, u->devices, state)
533         if (d->need_verify) {
534             d->need_verify = FALSE;
535             verify_access(u, d);
536         }
537
538     if (!deleted)
539         return;
540
541 fail:
542     if (u->inotify_io) {
543         a->io_free(u->inotify_io);
544         u->inotify_io = NULL;
545     }
546
547     if (u->inotify_fd >= 0) {
548         pa_close(u->inotify_fd);
549         u->inotify_fd = -1;
550     }
551 }
552
553 static int setup_inotify(struct userdata *u) {
554     char *dev_snd;
555     int r;
556
557     if (u->inotify_fd >= 0)
558         return 0;
559
560     if ((u->inotify_fd = inotify_init1(IN_CLOEXEC|IN_NONBLOCK)) < 0) {
561         pa_log("inotify_init1() failed: %s", pa_cstrerror(errno));
562         return -1;
563     }
564
565     dev_snd = pa_sprintf_malloc("%s/snd", udev_get_dev_path(u->udev));
566     r = inotify_add_watch(u->inotify_fd, dev_snd, IN_ATTRIB|IN_CLOSE_WRITE|IN_DELETE_SELF|IN_MOVE_SELF);
567     pa_xfree(dev_snd);
568
569     if (r < 0) {
570         int saved_errno = errno;
571
572         pa_close(u->inotify_fd);
573         u->inotify_fd = -1;
574
575         if (saved_errno == ENOENT) {
576             pa_log_debug("/dev/snd/ is apparently not existing yet, retrying to create inotify watch later.");
577             return 0;
578         }
579
580         if (saved_errno == ENOSPC) {
581             pa_log("You apparently ran out of inotify watches, probably because Tracker/Beagle took them all away. "
582                    "I wished people would do their homework first and fix inotify before using it for watching whole "
583                    "directory trees which is something the current inotify is certainly not useful for. "
584                    "Please make sure to drop the Tracker/Beagle guys a line complaining about their broken use of inotify.");
585             return 0;
586         }
587
588         pa_log("inotify_add_watch() failed: %s", pa_cstrerror(saved_errno));
589         return -1;
590     }
591
592     pa_assert_se(u->inotify_io = u->core->mainloop->io_new(u->core->mainloop, u->inotify_fd, PA_IO_EVENT_INPUT, inotify_cb, u));
593
594     return 0;
595 }
596
597 int pa__init(pa_module *m) {
598     struct userdata *u = NULL;
599     pa_modargs *ma;
600     struct udev_enumerate *enumerate = NULL;
601     struct udev_list_entry *item = NULL, *first = NULL;
602     int fd;
603     pa_bool_t use_tsched = TRUE, ignore_dB = FALSE;
604
605     pa_assert(m);
606
607     if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
608         pa_log("Failed to parse module arguments");
609         goto fail;
610     }
611
612     m->userdata = u = pa_xnew0(struct userdata, 1);
613     u->core = m->core;
614     u->devices = pa_hashmap_new(pa_idxset_string_hash_func, pa_idxset_string_compare_func);
615     u->inotify_fd = -1;
616
617     if (pa_modargs_get_value_boolean(ma, "tsched", &use_tsched) < 0) {
618         pa_log("Failed to parse tsched= argument.");
619         goto fail;
620     }
621     u->use_tsched = use_tsched;
622
623     if (pa_modargs_get_value_boolean(ma, "ignore_dB", &ignore_dB) < 0) {
624         pa_log("Failed to parse ignore_dB= argument.");
625         goto fail;
626     }
627     u->ignore_dB = ignore_dB;
628
629     if (!(u->udev = udev_new())) {
630         pa_log("Failed to initialize udev library.");
631         goto fail;
632     }
633
634     if (setup_inotify(u) < 0)
635         goto fail;
636
637     if (!(u->monitor = udev_monitor_new_from_netlink(u->udev, "udev"))) {
638         pa_log("Failed to initialize monitor.");
639         goto fail;
640     }
641
642     if (udev_monitor_filter_add_match_subsystem_devtype(u->monitor, "sound", NULL) < 0) {
643         pa_log("Failed to subscribe to sound devices.");
644         goto fail;
645     }
646
647     errno = 0;
648     if (udev_monitor_enable_receiving(u->monitor) < 0) {
649         pa_log("Failed to enable monitor: %s", pa_cstrerror(errno));
650         if (errno == EPERM)
651             pa_log_info("Most likely your kernel is simply too old and "
652                         "allows only priviliged processes to listen to device events. "
653                         "Please upgrade your kernel to at least 2.6.30.");
654         goto fail;
655     }
656
657     if ((fd = udev_monitor_get_fd(u->monitor)) < 0) {
658         pa_log("Failed to get udev monitor fd.");
659         goto fail;
660     }
661
662     pa_assert_se(u->udev_io = u->core->mainloop->io_new(u->core->mainloop, fd, PA_IO_EVENT_INPUT, monitor_cb, u));
663
664     if (!(enumerate = udev_enumerate_new(u->udev))) {
665         pa_log("Failed to initialize udev enumerator.");
666         goto fail;
667     }
668
669     if (udev_enumerate_add_match_subsystem(enumerate, "sound") < 0) {
670         pa_log("Failed to match to subsystem.");
671         goto fail;
672     }
673
674     if (udev_enumerate_scan_devices(enumerate) < 0) {
675         pa_log("Failed to scan for devices.");
676         goto fail;
677     }
678
679     first = udev_enumerate_get_list_entry(enumerate);
680     udev_list_entry_foreach(item, first)
681         process_path(u, udev_list_entry_get_name(item));
682
683     udev_enumerate_unref(enumerate);
684
685     pa_log_info("Found %u cards.", pa_hashmap_size(u->devices));
686
687     pa_modargs_free(ma);
688
689     return 0;
690
691 fail:
692
693     if (enumerate)
694         udev_enumerate_unref(enumerate);
695
696     if (ma)
697         pa_modargs_free(ma);
698
699     pa__done(m);
700
701     return -1;
702 }
703
704 void pa__done(pa_module *m) {
705     struct userdata *u;
706
707     pa_assert(m);
708
709     if (!(u = m->userdata))
710         return;
711
712     if (u->udev_io)
713         m->core->mainloop->io_free(u->udev_io);
714
715     if (u->monitor)
716         udev_monitor_unref(u->monitor);
717
718     if (u->udev)
719         udev_unref(u->udev);
720
721     if (u->inotify_io)
722         m->core->mainloop->io_free(u->inotify_io);
723
724     if (u->inotify_fd >= 0)
725         pa_close(u->inotify_fd);
726
727     if (u->devices) {
728         struct device *d;
729
730         while ((d = pa_hashmap_steal_first(u->devices)))
731             device_free(d);
732
733         pa_hashmap_free(u->devices, NULL, NULL);
734     }
735
736     pa_xfree(u);
737 }