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