udev-detect: Changes default latency 50ms to 25ms
[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, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
23
24 #include <errno.h>
25 #include <limits.h>
26 #include <dirent.h>
27 #include <sys/inotify.h>
28 #include <libudev.h>
29
30 #include <pulse/timeval.h>
31
32 #include <pulsecore/modargs.h>
33 #include <pulsecore/core-error.h>
34 #include <pulsecore/core-util.h>
35 #include <pulsecore/namereg.h>
36 #include <pulsecore/ratelimit.h>
37 #include <pulsecore/strbuf.h>
38
39 #ifdef __TIZEN__
40 #define DEFAULT_FRAGMENT_MSEC                25
41 #endif
42
43 PA_MODULE_AUTHOR("Lennart Poettering");
44 PA_MODULE_DESCRIPTION("Detect available audio hardware and load matching drivers");
45 PA_MODULE_VERSION(PACKAGE_VERSION);
46 PA_MODULE_LOAD_ONCE(true);
47 PA_MODULE_USAGE(
48         "tsched=<enable system timer based scheduling mode?> "
49         "tsched_buffer_size=<buffer size when using timer based scheduling> "
50         "fixed_latency_range=<disable latency range changes on underrun?> "
51         "ignore_dB=<ignore dB information from the device?> "
52         "deferred_volume=<syncronize sw and hw volume changes in IO-thread?> "
53         "use_ucm=<use ALSA UCM for card configuration?> "
54         "avoid_resampling=<use stream original sample rate if possible?>"
55 #ifdef __TIZEN__
56         "use_tizen_hal=<use tizen hal through tizenaudio-sink2/source2, it must be 'both', 'sink', 'source'>"
57         "fixed_latency_msec=<use fixed latency based on millisecond>"
58 #endif
59         );
60
61 struct device {
62     char *path;
63     bool need_verify;
64     bool ignore;
65     char *card_name;
66     char *args;
67     uint32_t module;
68     pa_ratelimit ratelimit;
69 };
70
71 struct userdata {
72     pa_core *core;
73     pa_hashmap *devices;
74
75     bool use_tsched:1;
76     bool tsched_buffer_size_valid:1;
77     bool fixed_latency_range:1;
78     bool ignore_dB:1;
79     bool deferred_volume:1;
80     bool use_ucm:1;
81     bool avoid_resampling:1;
82
83     uint32_t tsched_buffer_size;
84
85     struct udev* udev;
86     struct udev_monitor *monitor;
87     pa_io_event *udev_io;
88
89     int inotify_fd;
90     pa_io_event *inotify_io;
91 #ifdef __TIZEN__
92     char *use_tizen_hal;
93     uint32_t fixed_latency_msec;
94 #endif
95 };
96
97 static const char* const valid_modargs[] = {
98     "tsched",
99     "tsched_buffer_size",
100     "fixed_latency_range",
101     "ignore_dB",
102     "deferred_volume",
103     "use_ucm",
104     "avoid_resampling",
105 #ifdef __TIZEN__
106     "use_tizen_hal",
107     "fixed_latency_msec",
108 #endif
109     NULL
110 };
111
112 static int setup_inotify(struct userdata *u);
113
114 static void device_free(struct device *d) {
115     pa_assert(d);
116
117     pa_xfree(d->path);
118     pa_xfree(d->card_name);
119     pa_xfree(d->args);
120     pa_xfree(d);
121 }
122
123 static const char *path_get_card_id(const char *path) {
124     const char *e;
125
126     if (!path)
127         return NULL;
128
129     if (!(e = strrchr(path, '/')))
130         return NULL;
131
132     if (!pa_startswith(e, "/card"))
133         return NULL;
134
135     return e + 5;
136 }
137
138 static char *card_get_sysattr(const char *card_idx, const char *name) {
139     struct udev *udev;
140     struct udev_device *card = NULL;
141     char *t, *r = NULL;
142     const char *v;
143
144     pa_assert(card_idx);
145     pa_assert(name);
146
147     if (!(udev = udev_new())) {
148         pa_log_error("Failed to allocate udev context.");
149         goto finish;
150     }
151
152     t = pa_sprintf_malloc("/sys/class/sound/card%s", card_idx);
153     card = udev_device_new_from_syspath(udev, t);
154     pa_xfree(t);
155
156     if (!card) {
157         pa_log_error("Failed to get card object.");
158         goto finish;
159     }
160
161     if ((v = udev_device_get_sysattr_value(card, name)) && *v)
162         r = pa_xstrdup(v);
163
164 finish:
165
166     if (card)
167         udev_device_unref(card);
168
169     if (udev)
170         udev_unref(udev);
171
172     return r;
173 }
174
175 static bool pcm_is_modem(const char *card_idx, const char *pcm) {
176     char *sysfs_path, *pcm_class;
177     bool is_modem;
178
179     pa_assert(card_idx);
180     pa_assert(pcm);
181
182     /* Check /sys/class/sound/card.../pcmC...../pcm_class. An HDA
183      * modem can be used simultaneously with generic
184      * playback/record. */
185
186     sysfs_path = pa_sprintf_malloc("pcmC%sD%s/pcm_class", card_idx, pcm);
187     pcm_class = card_get_sysattr(card_idx, sysfs_path);
188     is_modem = pcm_class && pa_streq(pcm_class, "modem");
189     pa_xfree(pcm_class);
190     pa_xfree(sysfs_path);
191
192     return is_modem;
193 }
194
195 static bool is_card_busy(const char *id) {
196     char *card_path = NULL, *pcm_path = NULL, *sub_status = NULL;
197     DIR *card_dir = NULL, *pcm_dir = NULL;
198     FILE *status_file = NULL;
199     struct dirent *de;
200     bool busy = false;
201
202     pa_assert(id);
203
204     /* This simply uses /proc/asound/card.../pcm.../sub.../status to
205      * check whether there is still a process using this audio device. */
206
207     card_path = pa_sprintf_malloc("/proc/asound/card%s", id);
208
209     if (!(card_dir = opendir(card_path))) {
210         pa_log_warn("Failed to open %s: %s", card_path, pa_cstrerror(errno));
211         goto fail;
212     }
213
214     for (;;) {
215         errno = 0;
216         de = readdir(card_dir);
217         if (!de && errno) {
218             pa_log_warn("readdir() failed: %s", pa_cstrerror(errno));
219             goto fail;
220         }
221
222         if (!de)
223             break;
224
225         if (!pa_startswith(de->d_name, "pcm"))
226             continue;
227
228         if (pcm_is_modem(id, de->d_name + 3))
229             continue;
230
231         pa_xfree(pcm_path);
232         pcm_path = pa_sprintf_malloc("%s/%s", card_path, de->d_name);
233
234         if (pcm_dir)
235             closedir(pcm_dir);
236
237         if (!(pcm_dir = opendir(pcm_path))) {
238             pa_log_warn("Failed to open %s: %s", pcm_path, pa_cstrerror(errno));
239             continue;
240         }
241
242         for (;;) {
243             char line[32];
244
245             errno = 0;
246             de = readdir(pcm_dir);
247             if (!de && errno) {
248                 pa_log_warn("readdir() failed: %s", pa_cstrerror(errno));
249                 goto fail;
250             }
251
252             if (!de)
253                 break;
254
255             if (!pa_startswith(de->d_name, "sub"))
256                 continue;
257
258             pa_xfree(sub_status);
259             sub_status = pa_sprintf_malloc("%s/%s/status", pcm_path, de->d_name);
260
261             if (status_file)
262                 fclose(status_file);
263
264             if (!(status_file = pa_fopen_cloexec(sub_status, "r"))) {
265                 pa_log_warn("Failed to open %s: %s", sub_status, pa_cstrerror(errno));
266                 continue;
267             }
268
269             if (!(fgets(line, sizeof(line)-1, status_file))) {
270                 pa_log_warn("Failed to read from %s: %s", sub_status, pa_cstrerror(errno));
271                 continue;
272             }
273
274             if (!pa_streq(line, "closed\n")) {
275                 busy = true;
276                 break;
277             }
278         }
279     }
280
281 fail:
282
283     pa_xfree(card_path);
284     pa_xfree(pcm_path);
285     pa_xfree(sub_status);
286
287     if (card_dir)
288         closedir(card_dir);
289
290     if (pcm_dir)
291         closedir(pcm_dir);
292
293     if (status_file)
294         fclose(status_file);
295
296     return busy;
297 }
298
299 static void verify_access(struct userdata *u, struct device *d) {
300     char *cd;
301     pa_card *card;
302     bool accessible;
303
304     pa_assert(u);
305     pa_assert(d);
306
307     if (d->ignore)
308         return;
309
310     cd = pa_sprintf_malloc("/dev/snd/controlC%s", path_get_card_id(d->path));
311     accessible = access(cd, R_OK|W_OK) >= 0;
312     pa_log_debug("%s is accessible: %s", cd, pa_yes_no(accessible));
313
314     pa_xfree(cd);
315
316     if (d->module == PA_INVALID_INDEX) {
317
318         /* If we are not loaded, try to load */
319
320         if (accessible) {
321             pa_module *m;
322             bool busy;
323
324             /* Check if any of the PCM devices that belong to this
325              * card are currently busy. If they are, don't try to load
326              * right now, to make sure the probing phase can
327              * successfully complete. When the current user of the
328              * device closes it we will get another notification via
329              * inotify and can then recheck. */
330
331             busy = is_card_busy(path_get_card_id(d->path));
332             pa_log_debug("%s is busy: %s", d->path, pa_yes_no(busy));
333
334             if (!busy) {
335
336                 /* So, why do we rate limit here? It's certainly ugly,
337                  * but there seems to be no other way. Problem is
338                  * this: if we are unable to configure/probe an audio
339                  * device after opening it we will close it again and
340                  * the module initialization will fail. This will then
341                  * cause an inotify event on the device node which
342                  * will be forwarded to us. We then try to reopen the
343                  * audio device again, practically entering a busy
344                  * loop.
345                  *
346                  * A clean fix would be if we would be able to ignore
347                  * our own inotify close events. However, inotify
348                  * lacks such functionality. Also, during probing of
349                  * the device we cannot really distinguish between
350                  * other processes causing EBUSY or ourselves, which
351                  * means we have no way to figure out if the probing
352                  * during opening was canceled by a "try again"
353                  * failure or a "fatal" failure. */
354
355                 if (pa_ratelimit_test(&d->ratelimit, PA_LOG_DEBUG)) {
356                     int err;
357
358                     pa_log_debug("Loading module-alsa-card with arguments '%s'", d->args);
359                     err = pa_module_load(&m, u->core, "module-alsa-card", d->args);
360
361                     if (m) {
362                         d->module = m->index;
363                         pa_log_info("Card %s (%s) module loaded.", d->path, d->card_name);
364                     } else if (err == -PA_ERR_NOENTITY) {
365                         pa_log_info("Card %s (%s) module skipped.", d->path, d->card_name);
366                         d->ignore = true;
367                     } else {
368                         pa_log_info("Card %s (%s) failed to load module.", d->path, d->card_name);
369                     }
370                 } else
371                     pa_log_warn("Tried to configure %s (%s) more often than %u times in %llus",
372                                 d->path,
373                                 d->card_name,
374                                 d->ratelimit.burst,
375                                 (long long unsigned) (d->ratelimit.interval / PA_USEC_PER_SEC));
376             }
377         }
378
379     } else {
380
381         /* If we are already loaded update suspend status with
382          * accessible boolean */
383
384         if ((card = pa_namereg_get(u->core, d->card_name, PA_NAMEREG_CARD))) {
385             pa_log_debug("%s all sinks and sources of card %s.", accessible ? "Resuming" : "Suspending", d->card_name);
386             pa_card_suspend(card, !accessible, PA_SUSPEND_SESSION);
387         }
388     }
389 }
390
391 static void card_changed(struct userdata *u, struct udev_device *dev) {
392     struct device *d;
393     const char *path;
394     const char *t;
395     char *n;
396     pa_strbuf *args_buf;
397
398     pa_assert(u);
399     pa_assert(dev);
400
401     /* Maybe /dev/snd is now available? */
402     setup_inotify(u);
403
404     path = udev_device_get_devpath(dev);
405
406     if ((d = pa_hashmap_get(u->devices, path))) {
407         verify_access(u, d);
408         return;
409     }
410
411     d = pa_xnew0(struct device, 1);
412     d->path = pa_xstrdup(path);
413     d->module = PA_INVALID_INDEX;
414     PA_INIT_RATELIMIT(d->ratelimit, 10*PA_USEC_PER_SEC, 5);
415
416     if (!(t = udev_device_get_property_value(dev, "PULSE_NAME")))
417         if (!(t = udev_device_get_property_value(dev, "ID_ID")))
418             if (!(t = udev_device_get_property_value(dev, "ID_PATH")))
419                 t = path_get_card_id(path);
420
421     n = pa_namereg_make_valid_name(t);
422     d->card_name = pa_sprintf_malloc("alsa_card.%s", n);
423     args_buf = pa_strbuf_new();
424     pa_strbuf_printf(args_buf,
425                      "device_id=\"%s\" "
426                      "name=\"%s\" "
427                      "card_name=\"%s\" "
428 #ifdef __TIZEN__
429                      "use_tizen_hal=\"%s\" "
430                      "fixed_latency_msec=%d "
431 #endif
432                      "namereg_fail=false "
433                      "tsched=%s "
434                      "fixed_latency_range=%s "
435                      "ignore_dB=%s "
436                      "deferred_volume=%s "
437                      "use_ucm=%s "
438                      "avoid_resampling=%s "
439                      "card_properties=\"module-udev-detect.discovered=1\"",
440                      path_get_card_id(path),
441                      n,
442                      d->card_name,
443 #ifdef __TIZEN__
444                      u->use_tizen_hal,
445                      u->fixed_latency_msec,
446 #endif
447                      pa_yes_no(u->use_tsched),
448                      pa_yes_no(u->fixed_latency_range),
449                      pa_yes_no(u->ignore_dB),
450                      pa_yes_no(u->deferred_volume),
451                      pa_yes_no(u->use_ucm),
452                      pa_yes_no(u->avoid_resampling));
453     pa_xfree(n);
454
455     if (u->tsched_buffer_size_valid)
456         pa_strbuf_printf(args_buf, " tsched_buffer_size=%" PRIu32, u->tsched_buffer_size);
457
458     d->args = pa_strbuf_to_string_free(args_buf);
459
460     pa_hashmap_put(u->devices, d->path, d);
461
462     verify_access(u, d);
463 }
464
465 static void remove_card(struct userdata *u, struct udev_device *dev) {
466     struct device *d;
467
468     pa_assert(u);
469     pa_assert(dev);
470
471     if (!(d = pa_hashmap_remove(u->devices, udev_device_get_devpath(dev))))
472         return;
473
474     pa_log_info("Card %s removed.", d->path);
475
476     if (d->module != PA_INVALID_INDEX)
477         pa_module_unload_request_by_index(u->core, d->module, true);
478
479     device_free(d);
480 }
481
482 #ifdef __TIZEN__
483 static void dump_device(struct udev_device *dev) {
484     pa_log_debug("[ devpath = %s", udev_device_get_devpath(dev));
485     pa_log_debug("  subsystem = %s", udev_device_get_subsystem(dev));
486     pa_log_debug("  devtype = %s", udev_device_get_devtype(dev));
487     pa_log_debug("  syspath = %s", udev_device_get_syspath(dev));
488     pa_log_debug("  sysname = %s", udev_device_get_sysname(dev));
489     pa_log_debug("  sysnum = %s", udev_device_get_sysnum(dev));
490     pa_log_debug("  devnode = %s", udev_device_get_devnode(dev));
491     pa_log_debug("  parent subsystem = %s ]", udev_device_get_subsystem(udev_device_get_parent(dev)));
492 }
493
494 static bool is_devpath_hdmi_extcon(struct udev_device *dev) {
495     const char *devpath = udev_device_get_devpath(dev);
496     if (!devpath)
497         return false;
498
499     return (bool)strstr(devpath, "hdmi");
500 }
501
502 static void add_hdmi_card(struct userdata *u, const char *card) {
503     struct udev *udev;
504     struct udev_device *card_dev;
505     char *syspath;
506
507     if (!(udev = udev_new())) {
508         pa_log_error("Failed to allocate udev context.");
509         return;
510     }
511
512     syspath = pa_sprintf_malloc("/sys/class/sound/%s", card);
513
514     if ((card_dev = udev_device_new_from_syspath(udev, syspath))) {
515         card_changed(u, card_dev);
516         udev_device_unref(card_dev);
517     } else {
518         pa_log_error("Failed to get card object.");
519     }
520
521     pa_xfree(syspath);
522     udev_unref(udev);
523 }
524
525 /* NOTE : based from pa_card_choose_initial_profile() */
526 pa_card_profile *find_best_card_profile(pa_card *card) {
527     pa_card_profile *profile;
528     void *state;
529     pa_card_profile *best = NULL;
530
531     pa_assert(card);
532
533     pa_log_info("Looking for best profile for card %s", card->name);
534     PA_HASHMAP_FOREACH(profile, card->profiles, state) {
535         pa_log_debug(" name(%s), avail(%s)", profile->name, pa_available_to_string(profile->available));
536         if (profile->available == PA_AVAILABLE_NO)
537             continue;
538
539         if (!best || profile->priority > best->priority)
540             best = profile;
541     }
542
543     if (!best) {
544         PA_HASHMAP_FOREACH(profile, card->profiles, state) {
545             if (!best || profile->priority > best->priority)
546                 best = profile;
547         }
548     }
549
550     if (best)
551         pa_log_info("Found best profile %s", best->name);
552     else
553         pa_log_error("No best profile!");
554
555     return best;
556 }
557
558 static void process_hdmi_device(struct userdata *u, struct udev_device *dev) {
559     pa_card *card;
560     uint32_t idx;
561     bool is_removed;
562     const char *devtype;
563     const char *event_str[] = { "Added", "Removed" };
564     const char *sysfs_path;
565     char *card_to_find;
566     pa_card_profile *profile_to_set;
567
568     pa_assert(u);
569     pa_assert(dev);
570
571     devtype = udev_device_get_devtype(dev);
572     if (!devtype) {
573         pa_log_error("no parent devtype exist!");
574         return;
575     }
576
577     dump_device(dev);
578     is_removed = pa_safe_streq(udev_device_get_property_value(dev, "STATE"), "HDMI=0");
579
580     if (!pa_startswith(devtype, "extcon")) {
581         pa_log_error("invalid devtype %s", devtype);
582         return;
583     }
584
585     card_to_find = pa_replace(devtype, "extcon", "card");
586
587     pa_log_info("%s %s, devtype : %s", card_to_find, event_str[is_removed], devtype);
588
589     PA_IDXSET_FOREACH(card, u->core->cards, idx) {
590         sysfs_path = pa_proplist_gets(card->proplist, "sysfs.path");
591         if (!sysfs_path) {
592             pa_log_warn("no sysfs.path property...");
593             continue;
594         }
595         pa_log_info("sysfs.path : %s, finding : %s", sysfs_path, card_to_find);
596
597         if (pa_endswith(sysfs_path, card_to_find)) {
598             pa_log_info(" card exists, update proper profile for event (%s)", event_str[is_removed]);
599
600             profile_to_set = is_removed ? pa_hashmap_get(card->profiles, "off") : find_best_card_profile(card);
601
602             if (profile_to_set)
603                 pa_card_set_profile(card, profile_to_set, false);
604             else
605                 pa_log_error("no profile to set!");
606
607             goto profile_done;
608         }
609     }
610
611     pa_log_info("No card found, add new card (%s)", card_to_find);
612     add_hdmi_card(u, card_to_find);
613
614 profile_done:
615     pa_xfree(card_to_find);
616 }
617 #endif /* __TIZEN__ */
618
619 static void process_device(struct userdata *u, struct udev_device *dev) {
620     const char *action, *ff;
621
622     pa_assert(u);
623     pa_assert(dev);
624
625     if (udev_device_get_property_value(dev, "PULSE_IGNORE")) {
626         pa_log_debug("Ignoring %s, because marked so.", udev_device_get_devpath(dev));
627         return;
628     }
629
630     if ((ff = udev_device_get_property_value(dev, "SOUND_CLASS")) &&
631         pa_streq(ff, "modem")) {
632         pa_log_debug("Ignoring %s, because it is a modem.", udev_device_get_devpath(dev));
633         return;
634     }
635
636 #ifdef __TIZEN__
637     dump_device(dev);
638 #endif
639     action = udev_device_get_action(dev);
640
641     if (action && pa_streq(action, "remove"))
642         remove_card(u, dev);
643     else if ((!action || pa_streq(action, "change")) && udev_device_get_property_value(dev, "SOUND_INITIALIZED"))
644         card_changed(u, dev);
645
646     /* For an explanation why we don't look for 'add' events here
647      * have a look into /lib/udev/rules.d/78-sound-card.rules! */
648 }
649
650 static void process_path(struct userdata *u, const char *path) {
651     struct udev_device *dev;
652
653     if (!path_get_card_id(path))
654         return;
655
656     if (!(dev = udev_device_new_from_syspath(u->udev, path))) {
657         pa_log("Failed to get udev device object from udev.");
658         return;
659     }
660
661     process_device(u, dev);
662     udev_device_unref(dev);
663 }
664
665 static void monitor_cb(
666         pa_mainloop_api*a,
667         pa_io_event* e,
668         int fd,
669         pa_io_event_flags_t events,
670         void *userdata) {
671
672     struct userdata *u = userdata;
673     struct udev_device *dev;
674
675     pa_assert(a);
676
677     if (!(dev = udev_monitor_receive_device(u->monitor))) {
678         pa_log("Failed to get udev device object from monitor.");
679         goto fail;
680     }
681
682 #ifdef __TIZEN__
683     if (is_devpath_hdmi_extcon(dev)) {
684         pa_log_info("HDMI, devpath : %s", udev_device_get_devpath(dev));
685         process_hdmi_device(u, dev);
686         udev_device_unref(dev);
687         return;
688     }
689 #endif
690     if (!path_get_card_id(udev_device_get_devpath(dev))) {
691         udev_device_unref(dev);
692         return;
693     }
694
695     process_device(u, dev);
696     udev_device_unref(dev);
697     return;
698
699 fail:
700     a->io_free(u->udev_io);
701     u->udev_io = NULL;
702 }
703
704 static bool pcm_node_belongs_to_device(
705         struct device *d,
706         const char *node) {
707
708     char *cd;
709     bool b;
710
711     cd = pa_sprintf_malloc("pcmC%sD", path_get_card_id(d->path));
712     b = pa_startswith(node, cd);
713     pa_xfree(cd);
714
715     return b;
716 }
717
718 static bool control_node_belongs_to_device(
719         struct device *d,
720         const char *node) {
721
722     char *cd;
723     bool b;
724
725     cd = pa_sprintf_malloc("controlC%s", path_get_card_id(d->path));
726     b = pa_streq(node, cd);
727     pa_xfree(cd);
728
729     return b;
730 }
731
732 static void inotify_cb(
733         pa_mainloop_api*a,
734         pa_io_event* e,
735         int fd,
736         pa_io_event_flags_t events,
737         void *userdata) {
738
739     struct {
740         struct inotify_event e;
741         char name[NAME_MAX];
742     } buf;
743     struct userdata *u = userdata;
744     static int type = 0;
745     bool deleted = false;
746     struct device *d;
747     void *state;
748
749     for (;;) {
750         ssize_t r;
751         struct inotify_event *event;
752
753         pa_zero(buf);
754         if ((r = pa_read(fd, &buf, sizeof(buf), &type)) <= 0) {
755
756             if (r < 0 && errno == EAGAIN)
757                 break;
758
759             pa_log("read() from inotify failed: %s", r < 0 ? pa_cstrerror(errno) : "EOF");
760             goto fail;
761         }
762
763         event = &buf.e;
764         while (r > 0) {
765             size_t len;
766
767             if ((size_t) r < sizeof(struct inotify_event)) {
768                 pa_log("read() too short.");
769                 goto fail;
770             }
771
772             len = sizeof(struct inotify_event) + event->len;
773
774             if ((size_t) r < len) {
775                 pa_log("Payload missing.");
776                 goto fail;
777             }
778
779             /* From udev we get the guarantee that the control
780              * device's ACL is changed last. To avoid races when ACLs
781              * are changed we hence watch only the control device */
782             if (((event->mask & IN_ATTRIB) && pa_startswith(event->name, "controlC")))
783                 PA_HASHMAP_FOREACH(d, u->devices, state)
784                     if (control_node_belongs_to_device(d, event->name))
785                         d->need_verify = true;
786
787             /* ALSA doesn't really give us any guarantee on the closing
788              * order, so let's simply hope */
789             if (((event->mask & IN_CLOSE_WRITE) && pa_startswith(event->name, "pcmC")))
790                 PA_HASHMAP_FOREACH(d, u->devices, state)
791                     if (pcm_node_belongs_to_device(d, event->name))
792                         d->need_verify = true;
793
794             /* /dev/snd/ might have been removed */
795             if ((event->mask & (IN_DELETE_SELF|IN_MOVE_SELF)))
796                 deleted = true;
797
798             event = (struct inotify_event*) ((uint8_t*) event + len);
799             r -= len;
800         }
801     }
802
803     PA_HASHMAP_FOREACH(d, u->devices, state)
804         if (d->need_verify) {
805             d->need_verify = false;
806             verify_access(u, d);
807         }
808
809     if (!deleted)
810         return;
811
812 fail:
813     if (u->inotify_io) {
814         a->io_free(u->inotify_io);
815         u->inotify_io = NULL;
816     }
817
818     if (u->inotify_fd >= 0) {
819         pa_close(u->inotify_fd);
820         u->inotify_fd = -1;
821     }
822 }
823
824 static int setup_inotify(struct userdata *u) {
825     int r;
826
827     if (u->inotify_fd >= 0)
828         return 0;
829
830     if ((u->inotify_fd = inotify_init1(IN_CLOEXEC|IN_NONBLOCK)) < 0) {
831         pa_log("inotify_init1() failed: %s", pa_cstrerror(errno));
832         return -1;
833     }
834
835     r = inotify_add_watch(u->inotify_fd, "/dev/snd", IN_ATTRIB|IN_CLOSE_WRITE|IN_DELETE_SELF|IN_MOVE_SELF);
836
837     if (r < 0) {
838         int saved_errno = errno;
839
840         pa_close(u->inotify_fd);
841         u->inotify_fd = -1;
842
843         if (saved_errno == ENOENT) {
844             pa_log_debug("/dev/snd/ is apparently not existing yet, retrying to create inotify watch later.");
845             return 0;
846         }
847
848         if (saved_errno == ENOSPC) {
849             pa_log("You apparently ran out of inotify watches, probably because Tracker/Beagle took them all away. "
850                    "I wished people would do their homework first and fix inotify before using it for watching whole "
851                    "directory trees which is something the current inotify is certainly not useful for. "
852                    "Please make sure to drop the Tracker/Beagle guys a line complaining about their broken use of inotify.");
853             return 0;
854         }
855
856         pa_log("inotify_add_watch() failed: %s", pa_cstrerror(saved_errno));
857         return -1;
858     }
859
860     pa_assert_se(u->inotify_io = u->core->mainloop->io_new(u->core->mainloop, u->inotify_fd, PA_IO_EVENT_INPUT, inotify_cb, u));
861
862     return 0;
863 }
864
865 int pa__init(pa_module *m) {
866     struct userdata *u = NULL;
867     pa_modargs *ma;
868     struct udev_enumerate *enumerate = NULL;
869     struct udev_list_entry *item = NULL, *first = NULL;
870     int fd;
871     bool use_tsched = true, fixed_latency_range = false, ignore_dB = false, deferred_volume = m->core->deferred_volume;
872     bool use_ucm = true;
873     bool avoid_resampling;
874
875     pa_assert(m);
876
877     if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
878         pa_log("Failed to parse module arguments");
879         goto fail;
880     }
881
882     m->userdata = u = pa_xnew0(struct userdata, 1);
883     u->core = m->core;
884     u->devices = pa_hashmap_new_full(pa_idxset_string_hash_func, pa_idxset_string_compare_func, NULL, (pa_free_cb_t) device_free);
885     u->inotify_fd = -1;
886
887     if (pa_modargs_get_value_boolean(ma, "tsched", &use_tsched) < 0) {
888         pa_log("Failed to parse tsched= argument.");
889         goto fail;
890     }
891     u->use_tsched = use_tsched;
892
893     if (pa_modargs_get_value(ma, "tsched_buffer_size", NULL)) {
894         if (pa_modargs_get_value_u32(ma, "tsched_buffer_size", &u->tsched_buffer_size) < 0) {
895             pa_log("Failed to parse tsched_buffer_size= argument.");
896             goto fail;
897         }
898
899         u->tsched_buffer_size_valid = true;
900     }
901
902     if (pa_modargs_get_value_boolean(ma, "fixed_latency_range", &fixed_latency_range) < 0) {
903         pa_log("Failed to parse fixed_latency_range= argument.");
904         goto fail;
905     }
906     u->fixed_latency_range = fixed_latency_range;
907
908     if (pa_modargs_get_value_boolean(ma, "ignore_dB", &ignore_dB) < 0) {
909         pa_log("Failed to parse ignore_dB= argument.");
910         goto fail;
911     }
912     u->ignore_dB = ignore_dB;
913
914     if (pa_modargs_get_value_boolean(ma, "deferred_volume", &deferred_volume) < 0) {
915         pa_log("Failed to parse deferred_volume= argument.");
916         goto fail;
917     }
918     u->deferred_volume = deferred_volume;
919
920     if (pa_modargs_get_value_boolean(ma, "use_ucm", &use_ucm) < 0) {
921         pa_log("Failed to parse use_ucm= argument.");
922         goto fail;
923     }
924     u->use_ucm = use_ucm;
925
926     avoid_resampling = m->core->avoid_resampling;
927     if (pa_modargs_get_value_boolean(ma, "avoid_resampling", &avoid_resampling) < 0) {
928         pa_log("Failed to parse avoid_resampling= argument.");
929         goto fail;
930     }
931     u->avoid_resampling = avoid_resampling;
932
933 #ifdef __TIZEN__
934     u->use_tizen_hal = pa_xstrdup(pa_modargs_get_value(ma, "use_tizen_hal", "empty"));
935     u->fixed_latency_msec = DEFAULT_FRAGMENT_MSEC;
936     if (pa_modargs_get_value_u32(ma, "fixed_latency_msec", &u->fixed_latency_msec) < 0)
937         pa_log("Failed to get fixed_latency_msec args");
938 #endif
939
940     if (!(u->udev = udev_new())) {
941         pa_log("Failed to initialize udev library.");
942         goto fail;
943     }
944
945     if (setup_inotify(u) < 0)
946         goto fail;
947
948     if (!(u->monitor = udev_monitor_new_from_netlink(u->udev, "udev"))) {
949         pa_log("Failed to initialize monitor.");
950         goto fail;
951     }
952
953     if (udev_monitor_filter_add_match_subsystem_devtype(u->monitor, "sound", NULL) < 0) {
954         pa_log("Failed to subscribe to sound devices.");
955         goto fail;
956     }
957 #ifdef __TIZEN__
958 #ifndef TIZEN_TV_PROD
959     if (udev_monitor_filter_add_match_subsystem_devtype(u->monitor, "extcon", NULL) < 0) {
960         pa_log("Failed to subscribe to extcon devices.");
961         goto fail;
962     }
963 #endif
964 #endif
965
966     errno = 0;
967     if (udev_monitor_enable_receiving(u->monitor) < 0) {
968         pa_log("Failed to enable monitor: %s", pa_cstrerror(errno));
969         if (errno == EPERM)
970             pa_log_info("Most likely your kernel is simply too old and "
971                         "allows only privileged processes to listen to device events. "
972                         "Please upgrade your kernel to at least 2.6.30.");
973         goto fail;
974     }
975
976     if ((fd = udev_monitor_get_fd(u->monitor)) < 0) {
977         pa_log("Failed to get udev monitor fd.");
978         goto fail;
979     }
980
981     pa_assert_se(u->udev_io = u->core->mainloop->io_new(u->core->mainloop, fd, PA_IO_EVENT_INPUT, monitor_cb, u));
982
983     if (!(enumerate = udev_enumerate_new(u->udev))) {
984         pa_log("Failed to initialize udev enumerator.");
985         goto fail;
986     }
987
988     if (udev_enumerate_add_match_subsystem(enumerate, "sound") < 0) {
989         pa_log("Failed to match to subsystem.");
990         goto fail;
991     }
992
993     if (udev_enumerate_scan_devices(enumerate) < 0) {
994         pa_log("Failed to scan for devices.");
995         goto fail;
996     }
997
998     first = udev_enumerate_get_list_entry(enumerate);
999     udev_list_entry_foreach(item, first)
1000         process_path(u, udev_list_entry_get_name(item));
1001
1002     udev_enumerate_unref(enumerate);
1003
1004     pa_log_info("Found %u cards.", pa_hashmap_size(u->devices));
1005
1006     pa_modargs_free(ma);
1007
1008     return 0;
1009
1010 fail:
1011
1012     if (enumerate)
1013         udev_enumerate_unref(enumerate);
1014
1015     if (ma)
1016         pa_modargs_free(ma);
1017
1018     pa__done(m);
1019
1020     return -1;
1021 }
1022
1023 void pa__done(pa_module *m) {
1024     struct userdata *u;
1025
1026     pa_assert(m);
1027
1028     if (!(u = m->userdata))
1029         return;
1030
1031     if (u->udev_io)
1032         m->core->mainloop->io_free(u->udev_io);
1033
1034     if (u->monitor)
1035         udev_monitor_unref(u->monitor);
1036
1037     if (u->udev)
1038         udev_unref(u->udev);
1039
1040     if (u->inotify_io)
1041         m->core->mainloop->io_free(u->inotify_io);
1042
1043     if (u->inotify_fd >= 0)
1044         pa_close(u->inotify_fd);
1045
1046     if (u->devices)
1047         pa_hashmap_free(u->devices);
1048
1049 #ifdef __TIZEN__
1050     pa_xfree(u->use_tizen_hal);
1051 #endif
1052
1053     pa_xfree(u);
1054 }