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