devices.cpp revision 56a0656ed91a01fdf09f9704a1f8a8aeb5d9f3b7
1/*
2 * Copyright (C) 2007-2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <errno.h>
18#include <fnmatch.h>
19#include <stddef.h>
20#include <stdio.h>
21#include <stdlib.h>
22#include <sys/stat.h>
23#include <sys/types.h>
24
25#include <fcntl.h>
26#include <dirent.h>
27#include <unistd.h>
28#include <string.h>
29
30#include <sys/socket.h>
31#include <sys/un.h>
32#include <linux/netlink.h>
33
34#include <selinux/selinux.h>
35#include <selinux/label.h>
36#include <selinux/android.h>
37#include <selinux/avc.h>
38
39#include <private/android_filesystem_config.h>
40#include <sys/time.h>
41#include <sys/wait.h>
42
43#include <cutils/list.h>
44#include <cutils/uevent.h>
45
46#include "devices.h"
47#include "ueventd_parser.h"
48#include "util.h"
49#include "log.h"
50
51#define SYSFS_PREFIX    "/sys"
52static const char *firmware_dirs[] = { "/etc/firmware",
53                                       "/vendor/firmware",
54                                       "/firmware/image" };
55
56extern struct selabel_handle *sehandle;
57
58static int device_fd = -1;
59
60struct uevent {
61    const char *action;
62    const char *path;
63    const char *subsystem;
64    const char *firmware;
65    const char *partition_name;
66    const char *device_name;
67    int partition_num;
68    int major;
69    int minor;
70};
71
72struct perms_ {
73    char *name;
74    char *attr;
75    mode_t perm;
76    unsigned int uid;
77    unsigned int gid;
78    unsigned short prefix;
79    unsigned short wildcard;
80};
81
82struct perm_node {
83    struct perms_ dp;
84    struct listnode plist;
85};
86
87struct platform_node {
88    char *name;
89    char *path;
90    int path_len;
91    struct listnode list;
92};
93
94static list_declare(sys_perms);
95static list_declare(dev_perms);
96static list_declare(platform_names);
97
98int add_dev_perms(const char *name, const char *attr,
99                  mode_t perm, unsigned int uid, unsigned int gid,
100                  unsigned short prefix,
101                  unsigned short wildcard) {
102    struct perm_node *node = (perm_node*) calloc(1, sizeof(*node));
103    if (!node)
104        return -ENOMEM;
105
106    node->dp.name = strdup(name);
107    if (!node->dp.name)
108        return -ENOMEM;
109
110    if (attr) {
111        node->dp.attr = strdup(attr);
112        if (!node->dp.attr)
113            return -ENOMEM;
114    }
115
116    node->dp.perm = perm;
117    node->dp.uid = uid;
118    node->dp.gid = gid;
119    node->dp.prefix = prefix;
120    node->dp.wildcard = wildcard;
121
122    if (attr)
123        list_add_tail(&sys_perms, &node->plist);
124    else
125        list_add_tail(&dev_perms, &node->plist);
126
127    return 0;
128}
129
130void fixup_sys_perms(const char *upath)
131{
132    char buf[512];
133    struct listnode *node;
134    struct perms_ *dp;
135
136    /* upaths omit the "/sys" that paths in this list
137     * contain, so we add 4 when comparing...
138     */
139    list_for_each(node, &sys_perms) {
140        dp = &(node_to_item(node, struct perm_node, plist))->dp;
141        if (dp->prefix) {
142            if (strncmp(upath, dp->name + 4, strlen(dp->name + 4)))
143                continue;
144        } else if (dp->wildcard) {
145            if (fnmatch(dp->name + 4, upath, FNM_PATHNAME) != 0)
146                continue;
147        } else {
148            if (strcmp(upath, dp->name + 4))
149                continue;
150        }
151
152        if ((strlen(upath) + strlen(dp->attr) + 6) > sizeof(buf))
153            break;
154
155        snprintf(buf, sizeof(buf), "/sys%s/%s", upath, dp->attr);
156        INFO("fixup %s %d %d 0%o\n", buf, dp->uid, dp->gid, dp->perm);
157        chown(buf, dp->uid, dp->gid);
158        chmod(buf, dp->perm);
159    }
160
161    // Now fixup SELinux file labels
162    int len = snprintf(buf, sizeof(buf), "/sys%s", upath);
163    if ((len < 0) || ((size_t) len >= sizeof(buf))) {
164        // Overflow
165        return;
166    }
167    if (access(buf, F_OK) == 0) {
168        INFO("restorecon_recursive: %s\n", buf);
169        restorecon_recursive(buf);
170    }
171}
172
173static bool perm_path_matches(const char *path, struct perms_ *dp)
174{
175    if (dp->prefix) {
176        if (strncmp(path, dp->name, strlen(dp->name)) == 0)
177            return true;
178    } else if (dp->wildcard) {
179        if (fnmatch(dp->name, path, FNM_PATHNAME) == 0)
180            return true;
181    } else {
182        if (strcmp(path, dp->name) == 0)
183            return true;
184    }
185
186    return false;
187}
188
189static mode_t get_device_perm(const char *path, const char **links,
190                unsigned *uid, unsigned *gid)
191{
192    struct listnode *node;
193    struct perm_node *perm_node;
194    struct perms_ *dp;
195
196    /* search the perms list in reverse so that ueventd.$hardware can
197     * override ueventd.rc
198     */
199    list_for_each_reverse(node, &dev_perms) {
200        bool match = false;
201
202        perm_node = node_to_item(node, struct perm_node, plist);
203        dp = &perm_node->dp;
204
205        if (perm_path_matches(path, dp)) {
206            match = true;
207        } else {
208            if (links) {
209                int i;
210                for (i = 0; links[i]; i++) {
211                    if (perm_path_matches(links[i], dp)) {
212                        match = true;
213                        break;
214                    }
215                }
216            }
217        }
218
219        if (match) {
220            *uid = dp->uid;
221            *gid = dp->gid;
222            return dp->perm;
223        }
224    }
225    /* Default if nothing found. */
226    *uid = 0;
227    *gid = 0;
228    return 0600;
229}
230
231static void make_device(const char *path,
232                        const char */*upath*/,
233                        int block, int major, int minor,
234                        const char **links)
235{
236    unsigned uid;
237    unsigned gid;
238    mode_t mode;
239    dev_t dev;
240    char *secontext = NULL;
241
242    mode = get_device_perm(path, links, &uid, &gid) | (block ? S_IFBLK : S_IFCHR);
243
244    if (sehandle) {
245        selabel_lookup_best_match(sehandle, &secontext, path, links, mode);
246        setfscreatecon(secontext);
247    }
248
249    dev = makedev(major, minor);
250    /* Temporarily change egid to avoid race condition setting the gid of the
251     * device node. Unforunately changing the euid would prevent creation of
252     * some device nodes, so the uid has to be set with chown() and is still
253     * racy. Fixing the gid race at least fixed the issue with system_server
254     * opening dynamic input devices under the AID_INPUT gid. */
255    setegid(gid);
256    mknod(path, mode, dev);
257    chown(path, uid, -1);
258    setegid(AID_ROOT);
259
260    if (secontext) {
261        freecon(secontext);
262        setfscreatecon(NULL);
263    }
264}
265
266static void add_platform_device(const char *path)
267{
268    int path_len = strlen(path);
269    struct listnode *node;
270    struct platform_node *bus;
271    const char *name = path;
272
273    if (!strncmp(path, "/devices/", 9)) {
274        name += 9;
275        if (!strncmp(name, "platform/", 9))
276            name += 9;
277    }
278
279    list_for_each_reverse(node, &platform_names) {
280        bus = node_to_item(node, struct platform_node, list);
281        if ((bus->path_len < path_len) &&
282                (path[bus->path_len] == '/') &&
283                !strncmp(path, bus->path, bus->path_len))
284            /* subdevice of an existing platform, ignore it */
285            return;
286    }
287
288    INFO("adding platform device %s (%s)\n", name, path);
289
290    bus = (platform_node*) calloc(1, sizeof(struct platform_node));
291    bus->path = strdup(path);
292    bus->path_len = path_len;
293    bus->name = bus->path + (name - path);
294    list_add_tail(&platform_names, &bus->list);
295}
296
297/*
298 * given a path that may start with a platform device, find the length of the
299 * platform device prefix.  If it doesn't start with a platform device, return
300 * 0.
301 */
302static struct platform_node *find_platform_device(const char *path)
303{
304    int path_len = strlen(path);
305    struct listnode *node;
306    struct platform_node *bus;
307
308    list_for_each_reverse(node, &platform_names) {
309        bus = node_to_item(node, struct platform_node, list);
310        if ((bus->path_len < path_len) &&
311                (path[bus->path_len] == '/') &&
312                !strncmp(path, bus->path, bus->path_len))
313            return bus;
314    }
315
316    return NULL;
317}
318
319static void remove_platform_device(const char *path)
320{
321    struct listnode *node;
322    struct platform_node *bus;
323
324    list_for_each_reverse(node, &platform_names) {
325        bus = node_to_item(node, struct platform_node, list);
326        if (!strcmp(path, bus->path)) {
327            INFO("removing platform device %s\n", bus->name);
328            free(bus->path);
329            list_remove(node);
330            free(bus);
331            return;
332        }
333    }
334}
335
336/* Given a path that may start with a PCI device, populate the supplied buffer
337 * with the PCI domain/bus number and the peripheral ID and return 0.
338 * If it doesn't start with a PCI device, or there is some error, return -1 */
339static int find_pci_device_prefix(const char *path, char *buf, ssize_t buf_sz)
340{
341    const char *start, *end;
342
343    if (strncmp(path, "/devices/pci", 12))
344        return -1;
345
346    /* Beginning of the prefix is the initial "pci" after "/devices/" */
347    start = path + 9;
348
349    /* End of the prefix is two path '/' later, capturing the domain/bus number
350     * and the peripheral ID. Example: pci0000:00/0000:00:1f.2 */
351    end = strchr(start, '/');
352    if (!end)
353        return -1;
354    end = strchr(end + 1, '/');
355    if (!end)
356        return -1;
357
358    /* Make sure we have enough room for the string plus null terminator */
359    if (end - start + 1 > buf_sz)
360        return -1;
361
362    strncpy(buf, start, end - start);
363    buf[end - start] = '\0';
364    return 0;
365}
366
367static void parse_event(const char *msg, struct uevent *uevent)
368{
369    uevent->action = "";
370    uevent->path = "";
371    uevent->subsystem = "";
372    uevent->firmware = "";
373    uevent->major = -1;
374    uevent->minor = -1;
375    uevent->partition_name = NULL;
376    uevent->partition_num = -1;
377    uevent->device_name = NULL;
378
379        /* currently ignoring SEQNUM */
380    while(*msg) {
381        if(!strncmp(msg, "ACTION=", 7)) {
382            msg += 7;
383            uevent->action = msg;
384        } else if(!strncmp(msg, "DEVPATH=", 8)) {
385            msg += 8;
386            uevent->path = msg;
387        } else if(!strncmp(msg, "SUBSYSTEM=", 10)) {
388            msg += 10;
389            uevent->subsystem = msg;
390        } else if(!strncmp(msg, "FIRMWARE=", 9)) {
391            msg += 9;
392            uevent->firmware = msg;
393        } else if(!strncmp(msg, "MAJOR=", 6)) {
394            msg += 6;
395            uevent->major = atoi(msg);
396        } else if(!strncmp(msg, "MINOR=", 6)) {
397            msg += 6;
398            uevent->minor = atoi(msg);
399        } else if(!strncmp(msg, "PARTN=", 6)) {
400            msg += 6;
401            uevent->partition_num = atoi(msg);
402        } else if(!strncmp(msg, "PARTNAME=", 9)) {
403            msg += 9;
404            uevent->partition_name = msg;
405        } else if(!strncmp(msg, "DEVNAME=", 8)) {
406            msg += 8;
407            uevent->device_name = msg;
408        }
409
410        /* advance to after the next \0 */
411        while(*msg++)
412            ;
413    }
414
415    if (LOG_UEVENTS) {
416        INFO("event { '%s', '%s', '%s', '%s', %d, %d }\n",
417             uevent->action, uevent->path, uevent->subsystem,
418             uevent->firmware, uevent->major, uevent->minor);
419    }
420}
421
422static char **get_character_device_symlinks(struct uevent *uevent)
423{
424    const char *parent;
425    char *slash;
426    char **links;
427    int link_num = 0;
428    int width;
429    struct platform_node *pdev;
430
431    pdev = find_platform_device(uevent->path);
432    if (!pdev)
433        return NULL;
434
435    links = (char**) malloc(sizeof(char *) * 2);
436    if (!links)
437        return NULL;
438    memset(links, 0, sizeof(char *) * 2);
439
440    /* skip "/devices/platform/<driver>" */
441    parent = strchr(uevent->path + pdev->path_len, '/');
442    if (!parent)
443        goto err;
444
445    if (!strncmp(parent, "/usb", 4)) {
446        /* skip root hub name and device. use device interface */
447        while (*++parent && *parent != '/');
448        if (*parent)
449            while (*++parent && *parent != '/');
450        if (!*parent)
451            goto err;
452        slash = strchr(++parent, '/');
453        if (!slash)
454            goto err;
455        width = slash - parent;
456        if (width <= 0)
457            goto err;
458
459        if (asprintf(&links[link_num], "/dev/usb/%s%.*s", uevent->subsystem, width, parent) > 0)
460            link_num++;
461        else
462            links[link_num] = NULL;
463        mkdir("/dev/usb", 0755);
464    }
465    else {
466        goto err;
467    }
468
469    return links;
470err:
471    free(links);
472    return NULL;
473}
474
475static char **get_block_device_symlinks(struct uevent *uevent)
476{
477    const char *device;
478    struct platform_node *pdev;
479    char *slash;
480    const char *type;
481    char buf[256];
482    char link_path[256];
483    int link_num = 0;
484    char *p;
485
486    pdev = find_platform_device(uevent->path);
487    if (pdev) {
488        device = pdev->name;
489        type = "platform";
490    } else if (!find_pci_device_prefix(uevent->path, buf, sizeof(buf))) {
491        device = buf;
492        type = "pci";
493    } else {
494        return NULL;
495    }
496
497    char **links = (char**) malloc(sizeof(char *) * 4);
498    if (!links)
499        return NULL;
500    memset(links, 0, sizeof(char *) * 4);
501
502    INFO("found %s device %s\n", type, device);
503
504    snprintf(link_path, sizeof(link_path), "/dev/block/%s/%s", type, device);
505
506    if (uevent->partition_name) {
507        p = strdup(uevent->partition_name);
508        sanitize(p);
509        if (strcmp(uevent->partition_name, p))
510            NOTICE("Linking partition '%s' as '%s'\n", uevent->partition_name, p);
511        if (asprintf(&links[link_num], "%s/by-name/%s", link_path, p) > 0)
512            link_num++;
513        else
514            links[link_num] = NULL;
515        free(p);
516    }
517
518    if (uevent->partition_num >= 0) {
519        if (asprintf(&links[link_num], "%s/by-num/p%d", link_path, uevent->partition_num) > 0)
520            link_num++;
521        else
522            links[link_num] = NULL;
523    }
524
525    slash = strrchr(uevent->path, '/');
526    if (asprintf(&links[link_num], "%s/%s", link_path, slash + 1) > 0)
527        link_num++;
528    else
529        links[link_num] = NULL;
530
531    return links;
532}
533
534static void handle_device(const char *action, const char *devpath,
535        const char *path, int block, int major, int minor, char **links)
536{
537    int i;
538
539    if(!strcmp(action, "add")) {
540        make_device(devpath, path, block, major, minor, (const char **)links);
541        if (links) {
542            for (i = 0; links[i]; i++)
543                make_link(devpath, links[i]);
544        }
545    }
546
547    if(!strcmp(action, "remove")) {
548        if (links) {
549            for (i = 0; links[i]; i++)
550                remove_link(devpath, links[i]);
551        }
552        unlink(devpath);
553    }
554
555    if (links) {
556        for (i = 0; links[i]; i++)
557            free(links[i]);
558        free(links);
559    }
560}
561
562static void handle_platform_device_event(struct uevent *uevent)
563{
564    const char *path = uevent->path;
565
566    if (!strcmp(uevent->action, "add"))
567        add_platform_device(path);
568    else if (!strcmp(uevent->action, "remove"))
569        remove_platform_device(path);
570}
571
572static const char *parse_device_name(struct uevent *uevent, unsigned int len)
573{
574    const char *name;
575
576    /* if it's not a /dev device, nothing else to do */
577    if((uevent->major < 0) || (uevent->minor < 0))
578        return NULL;
579
580    /* do we have a name? */
581    name = strrchr(uevent->path, '/');
582    if(!name)
583        return NULL;
584    name++;
585
586    /* too-long names would overrun our buffer */
587    if(strlen(name) > len) {
588        ERROR("DEVPATH=%s exceeds %u-character limit on filename; ignoring event\n",
589                name, len);
590        return NULL;
591    }
592
593    return name;
594}
595
596static void handle_block_device_event(struct uevent *uevent)
597{
598    const char *base = "/dev/block/";
599    const char *name;
600    char devpath[96];
601    char **links = NULL;
602
603    name = parse_device_name(uevent, 64);
604    if (!name)
605        return;
606
607    snprintf(devpath, sizeof(devpath), "%s%s", base, name);
608    make_dir(base, 0755);
609
610    if (!strncmp(uevent->path, "/devices/", 9))
611        links = get_block_device_symlinks(uevent);
612
613    handle_device(uevent->action, devpath, uevent->path, 1,
614            uevent->major, uevent->minor, links);
615}
616
617#define DEVPATH_LEN 96
618
619static bool assemble_devpath(char *devpath, const char *dirname,
620        const char *devname)
621{
622    int s = snprintf(devpath, DEVPATH_LEN, "%s/%s", dirname, devname);
623    if (s < 0) {
624        ERROR("failed to assemble device path (%s); ignoring event\n",
625                strerror(errno));
626        return false;
627    } else if (s >= DEVPATH_LEN) {
628        ERROR("%s/%s exceeds %u-character limit on path; ignoring event\n",
629                dirname, devname, DEVPATH_LEN);
630        return false;
631    }
632    return true;
633}
634
635static void mkdir_recursive_for_devpath(const char *devpath)
636{
637    char dir[DEVPATH_LEN];
638    char *slash;
639
640    strcpy(dir, devpath);
641    slash = strrchr(dir, '/');
642    *slash = '\0';
643    mkdir_recursive(dir, 0755);
644}
645
646static void handle_generic_device_event(struct uevent *uevent)
647{
648    const char *base;
649    const char *name;
650    char devpath[DEVPATH_LEN] = {0};
651    char **links = NULL;
652
653    name = parse_device_name(uevent, 64);
654    if (!name)
655        return;
656
657    struct ueventd_subsystem *subsystem =
658            ueventd_subsystem_find_by_name(uevent->subsystem);
659
660    if (subsystem) {
661        const char *devname;
662
663        switch (subsystem->devname_src) {
664        case DEVNAME_UEVENT_DEVNAME:
665            devname = uevent->device_name;
666            break;
667
668        case DEVNAME_UEVENT_DEVPATH:
669            devname = name;
670            break;
671
672        default:
673            ERROR("%s subsystem's devpath option is not set; ignoring event\n",
674                    uevent->subsystem);
675            return;
676        }
677
678        if (!assemble_devpath(devpath, subsystem->dirname, devname))
679            return;
680        mkdir_recursive_for_devpath(devpath);
681    } else if (!strncmp(uevent->subsystem, "usb", 3)) {
682         if (!strcmp(uevent->subsystem, "usb")) {
683            if (uevent->device_name) {
684                if (!assemble_devpath(devpath, "/dev", uevent->device_name))
685                    return;
686                mkdir_recursive_for_devpath(devpath);
687             }
688             else {
689                 /* This imitates the file system that would be created
690                  * if we were using devfs instead.
691                  * Minors are broken up into groups of 128, starting at "001"
692                  */
693                 int bus_id = uevent->minor / 128 + 1;
694                 int device_id = uevent->minor % 128 + 1;
695                 /* build directories */
696                 make_dir("/dev/bus", 0755);
697                 make_dir("/dev/bus/usb", 0755);
698                 snprintf(devpath, sizeof(devpath), "/dev/bus/usb/%03d", bus_id);
699                 make_dir(devpath, 0755);
700                 snprintf(devpath, sizeof(devpath), "/dev/bus/usb/%03d/%03d", bus_id, device_id);
701             }
702         } else {
703             /* ignore other USB events */
704             return;
705         }
706     } else if (!strncmp(uevent->subsystem, "graphics", 8)) {
707         base = "/dev/graphics/";
708         make_dir(base, 0755);
709     } else if (!strncmp(uevent->subsystem, "drm", 3)) {
710         base = "/dev/dri/";
711         make_dir(base, 0755);
712     } else if (!strncmp(uevent->subsystem, "oncrpc", 6)) {
713         base = "/dev/oncrpc/";
714         make_dir(base, 0755);
715     } else if (!strncmp(uevent->subsystem, "adsp", 4)) {
716         base = "/dev/adsp/";
717         make_dir(base, 0755);
718     } else if (!strncmp(uevent->subsystem, "msm_camera", 10)) {
719         base = "/dev/msm_camera/";
720         make_dir(base, 0755);
721     } else if(!strncmp(uevent->subsystem, "input", 5)) {
722         base = "/dev/input/";
723         make_dir(base, 0755);
724     } else if(!strncmp(uevent->subsystem, "mtd", 3)) {
725         base = "/dev/mtd/";
726         make_dir(base, 0755);
727     } else if(!strncmp(uevent->subsystem, "sound", 5)) {
728         base = "/dev/snd/";
729         make_dir(base, 0755);
730     } else if(!strncmp(uevent->subsystem, "misc", 4) &&
731                 !strncmp(name, "log_", 4)) {
732         INFO("kernel logger is deprecated\n");
733         base = "/dev/log/";
734         make_dir(base, 0755);
735         name += 4;
736     } else
737         base = "/dev/";
738     links = get_character_device_symlinks(uevent);
739
740     if (!devpath[0])
741         snprintf(devpath, sizeof(devpath), "%s%s", base, name);
742
743     handle_device(uevent->action, devpath, uevent->path, 0,
744             uevent->major, uevent->minor, links);
745}
746
747static void handle_device_event(struct uevent *uevent)
748{
749    if (!strcmp(uevent->action,"add") || !strcmp(uevent->action, "change") || !strcmp(uevent->action, "online"))
750        fixup_sys_perms(uevent->path);
751
752    if (!strncmp(uevent->subsystem, "block", 5)) {
753        handle_block_device_event(uevent);
754    } else if (!strncmp(uevent->subsystem, "platform", 8)) {
755        handle_platform_device_event(uevent);
756    } else {
757        handle_generic_device_event(uevent);
758    }
759}
760
761static int load_firmware(int fw_fd, int loading_fd, int data_fd)
762{
763    struct stat st;
764    long len_to_copy;
765    int ret = 0;
766
767    if(fstat(fw_fd, &st) < 0)
768        return -1;
769    len_to_copy = st.st_size;
770
771    write(loading_fd, "1", 1);  /* start transfer */
772
773    while (len_to_copy > 0) {
774        char buf[PAGE_SIZE];
775        ssize_t nr;
776
777        nr = read(fw_fd, buf, sizeof(buf));
778        if(!nr)
779            break;
780        if(nr < 0) {
781            ret = -1;
782            break;
783        }
784
785        len_to_copy -= nr;
786        while (nr > 0) {
787            ssize_t nw = 0;
788
789            nw = write(data_fd, buf + nw, nr);
790            if(nw <= 0) {
791                ret = -1;
792                goto out;
793            }
794            nr -= nw;
795        }
796    }
797
798out:
799    if(!ret)
800        write(loading_fd, "0", 1);  /* successful end of transfer */
801    else
802        write(loading_fd, "-1", 2); /* abort transfer */
803
804    return ret;
805}
806
807static int is_booting(void)
808{
809    return access("/dev/.booting", F_OK) == 0;
810}
811
812static void process_firmware_event(struct uevent *uevent)
813{
814    char *root, *loading, *data;
815    int l, loading_fd, data_fd, fw_fd;
816    size_t i;
817    int booting = is_booting();
818
819    INFO("firmware: loading '%s' for '%s'\n",
820         uevent->firmware, uevent->path);
821
822    l = asprintf(&root, SYSFS_PREFIX"%s/", uevent->path);
823    if (l == -1)
824        return;
825
826    l = asprintf(&loading, "%sloading", root);
827    if (l == -1)
828        goto root_free_out;
829
830    l = asprintf(&data, "%sdata", root);
831    if (l == -1)
832        goto loading_free_out;
833
834    loading_fd = open(loading, O_WRONLY|O_CLOEXEC);
835    if(loading_fd < 0)
836        goto data_free_out;
837
838    data_fd = open(data, O_WRONLY|O_CLOEXEC);
839    if(data_fd < 0)
840        goto loading_close_out;
841
842try_loading_again:
843    for (i = 0; i < ARRAY_SIZE(firmware_dirs); i++) {
844        char *file = NULL;
845        l = asprintf(&file, "%s/%s", firmware_dirs[i], uevent->firmware);
846        if (l == -1)
847            goto data_free_out;
848        fw_fd = open(file, O_RDONLY|O_CLOEXEC);
849        free(file);
850        if (fw_fd >= 0) {
851            if(!load_firmware(fw_fd, loading_fd, data_fd))
852                INFO("firmware: copy success { '%s', '%s' }\n", root, uevent->firmware);
853            else
854                INFO("firmware: copy failure { '%s', '%s' }\n", root, uevent->firmware);
855            break;
856        }
857    }
858    if (fw_fd < 0) {
859        if (booting) {
860            /* If we're not fully booted, we may be missing
861             * filesystems needed for firmware, wait and retry.
862             */
863            usleep(100000);
864            booting = is_booting();
865            goto try_loading_again;
866        }
867        INFO("firmware: could not open '%s': %s\n", uevent->firmware, strerror(errno));
868        write(loading_fd, "-1", 2);
869        goto data_close_out;
870    }
871
872    close(fw_fd);
873data_close_out:
874    close(data_fd);
875loading_close_out:
876    close(loading_fd);
877data_free_out:
878    free(data);
879loading_free_out:
880    free(loading);
881root_free_out:
882    free(root);
883}
884
885static void handle_firmware_event(struct uevent *uevent)
886{
887    pid_t pid;
888
889    if(strcmp(uevent->subsystem, "firmware"))
890        return;
891
892    if(strcmp(uevent->action, "add"))
893        return;
894
895    /* we fork, to avoid making large memory allocations in init proper */
896    pid = fork();
897    if (!pid) {
898        process_firmware_event(uevent);
899        _exit(EXIT_SUCCESS);
900    } else if (pid < 0) {
901        ERROR("could not fork to process firmware event: %s\n", strerror(errno));
902    }
903}
904
905#define UEVENT_MSG_LEN  2048
906void handle_device_fd()
907{
908    char msg[UEVENT_MSG_LEN+2];
909    int n;
910    while ((n = uevent_kernel_multicast_recv(device_fd, msg, UEVENT_MSG_LEN)) > 0) {
911        if(n >= UEVENT_MSG_LEN)   /* overflow -- discard */
912            continue;
913
914        msg[n] = '\0';
915        msg[n+1] = '\0';
916
917        struct uevent uevent;
918        parse_event(msg, &uevent);
919
920        if (sehandle && selinux_status_updated() > 0) {
921            struct selabel_handle *sehandle2;
922            sehandle2 = selinux_android_file_context_handle();
923            if (sehandle2) {
924                selabel_close(sehandle);
925                sehandle = sehandle2;
926            }
927        }
928
929        handle_device_event(&uevent);
930        handle_firmware_event(&uevent);
931    }
932}
933
934/* Coldboot walks parts of the /sys tree and pokes the uevent files
935** to cause the kernel to regenerate device add events that happened
936** before init's device manager was started
937**
938** We drain any pending events from the netlink socket every time
939** we poke another uevent file to make sure we don't overrun the
940** socket's buffer.
941*/
942
943static void do_coldboot(DIR *d)
944{
945    struct dirent *de;
946    int dfd, fd;
947
948    dfd = dirfd(d);
949
950    fd = openat(dfd, "uevent", O_WRONLY);
951    if(fd >= 0) {
952        write(fd, "add\n", 4);
953        close(fd);
954        handle_device_fd();
955    }
956
957    while((de = readdir(d))) {
958        DIR *d2;
959
960        if(de->d_type != DT_DIR || de->d_name[0] == '.')
961            continue;
962
963        fd = openat(dfd, de->d_name, O_RDONLY | O_DIRECTORY);
964        if(fd < 0)
965            continue;
966
967        d2 = fdopendir(fd);
968        if(d2 == 0)
969            close(fd);
970        else {
971            do_coldboot(d2);
972            closedir(d2);
973        }
974    }
975}
976
977static void coldboot(const char *path)
978{
979    DIR *d = opendir(path);
980    if(d) {
981        do_coldboot(d);
982        closedir(d);
983    }
984}
985
986void device_init() {
987    sehandle = NULL;
988    if (is_selinux_enabled() > 0) {
989        sehandle = selinux_android_file_context_handle();
990        selinux_status_open(true);
991    }
992
993    /* is 256K enough? udev uses 16MB! */
994    device_fd = uevent_open_socket(256*1024, true);
995    if (device_fd == -1) {
996        return;
997    }
998    fcntl(device_fd, F_SETFL, O_NONBLOCK);
999
1000    if (access(COLDBOOT_DONE, F_OK) == 0) {
1001        NOTICE("Skipping coldboot, already done!\n");
1002        return;
1003    }
1004
1005    Timer t;
1006    coldboot("/sys/class");
1007    coldboot("/sys/block");
1008    coldboot("/sys/devices");
1009    close(open(COLDBOOT_DONE, O_WRONLY|O_CREAT|O_CLOEXEC, 0000));
1010    NOTICE("Coldboot took %.2fs.\n", t.duration());
1011}
1012
1013int get_device_fd()
1014{
1015    return device_fd;
1016}
1017