devices.cpp revision 482f36cf74c0461bbad4a33df27d1b8e72ccc2d2
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 "devices.h"
18
19#include <dirent.h>
20#include <errno.h>
21#include <fcntl.h>
22#include <fnmatch.h>
23#include <grp.h>
24#include <libgen.h>
25#include <linux/netlink.h>
26#include <pwd.h>
27#include <stddef.h>
28#include <stdio.h>
29#include <stdlib.h>
30#include <string.h>
31#include <sys/sendfile.h>
32#include <sys/socket.h>
33#include <sys/time.h>
34#include <sys/un.h>
35#include <sys/wait.h>
36#include <unistd.h>
37
38#include <algorithm>
39#include <memory>
40#include <thread>
41
42#include <android-base/file.h>
43#include <android-base/logging.h>
44#include <android-base/stringprintf.h>
45#include <android-base/strings.h>
46#include <android-base/unique_fd.h>
47#include <cutils/uevent.h>
48#include <private/android_filesystem_config.h>
49#include <selinux/android.h>
50#include <selinux/label.h>
51#include <selinux/selinux.h>
52
53#include "keyword_map.h"
54#include "ueventd.h"
55#include "util.h"
56
57#ifdef _INIT_INIT_H
58#error "Do not include init.h in files used by ueventd or watchdogd; it will expose init's globals"
59#endif
60
61static selabel_handle* sehandle;
62
63static android::base::unique_fd device_fd;
64
65Permissions::Permissions(const std::string& name, mode_t perm, uid_t uid, gid_t gid)
66    : name_(name), perm_(perm), uid_(uid), gid_(gid), prefix_(false), wildcard_(false) {
67    // If the first * is the last character, then we'll treat name_ as a prefix
68    // Otherwise, if a * is present, then we do a full fnmatch().
69    auto wildcard_position = name_.find('*');
70    if (wildcard_position == name_.length() - 1) {
71        prefix_ = true;
72        name_.pop_back();
73    } else if (wildcard_position != std::string::npos) {
74        wildcard_ = true;
75    }
76}
77
78bool Permissions::Match(const std::string& path) const {
79    if (prefix_) {
80        return android::base::StartsWith(path, name_.c_str());
81    } else if (wildcard_) {
82        return fnmatch(name_.c_str(), path.c_str(), FNM_PATHNAME) == 0;
83    } else {
84        return path == name_;
85    }
86
87    return false;
88}
89
90bool SysfsPermissions::MatchWithSubsystem(const std::string& path,
91                                          const std::string& subsystem) const {
92    std::string path_basename = android::base::Basename(path);
93    if (name().find(subsystem) != std::string::npos) {
94        if (Match("/sys/class/" + subsystem + "/" + path_basename)) return true;
95        if (Match("/sys/bus/" + subsystem + "/devices/" + path_basename)) return true;
96    }
97    return Match(path);
98}
99
100void SysfsPermissions::SetPermissions(const std::string& path) const {
101    std::string attribute_file = path + "/" + attribute_;
102    LOG(INFO) << "fixup " << attribute_file << " " << uid() << " " << gid() << " " << std::oct
103              << perm();
104    chown(attribute_file.c_str(), uid(), gid());
105    chmod(attribute_file.c_str(), perm());
106}
107
108// TODO: Move these to be member variables of a future devices class.
109std::vector<Permissions> dev_permissions;
110std::vector<SysfsPermissions> sysfs_permissions;
111
112bool ParsePermissionsLine(std::vector<std::string>&& args, std::string* err, bool is_sysfs) {
113    if (is_sysfs && args.size() != 5) {
114        *err = "/sys/ lines must have 5 entries";
115        return false;
116    }
117
118    if (!is_sysfs && args.size() != 4) {
119        *err = "/dev/ lines must have 4 entries";
120        return false;
121    }
122
123    auto it = args.begin();
124    const std::string& name = *it++;
125
126    std::string sysfs_attribute;
127    if (is_sysfs) sysfs_attribute = *it++;
128
129    // args is now common to both sys and dev entries and contains: <perm> <uid> <gid>
130    std::string& perm_string = *it++;
131    char* end_pointer = 0;
132    mode_t perm = strtol(perm_string.c_str(), &end_pointer, 8);
133    if (end_pointer == nullptr || *end_pointer != '\0') {
134        *err = "invalid mode '" + perm_string + "'";
135        return false;
136    }
137
138    std::string& uid_string = *it++;
139    passwd* pwd = getpwnam(uid_string.c_str());
140    if (!pwd) {
141        *err = "invalid uid '" + uid_string + "'";
142        return false;
143    }
144    uid_t uid = pwd->pw_uid;
145
146    std::string& gid_string = *it++;
147    struct group* grp = getgrnam(gid_string.c_str());
148    if (!grp) {
149        *err = "invalid gid '" + gid_string + "'";
150        return false;
151    }
152    gid_t gid = grp->gr_gid;
153
154    if (is_sysfs) {
155        sysfs_permissions.emplace_back(name, sysfs_attribute, perm, uid, gid);
156    } else {
157        dev_permissions.emplace_back(name, perm, uid, gid);
158    }
159    return true;
160}
161
162// TODO: Move this to be a member variable of a future devices class.
163static std::vector<Subsystem> subsystems;
164
165std::string Subsystem::ParseDevPath(uevent* uevent) const {
166    std::string devname = devname_source_ == DevnameSource::DEVNAME_UEVENT_DEVNAME
167                              ? uevent->device_name
168                              : android::base::Basename(uevent->path);
169
170    return dir_name_ + "/" + devname;
171}
172
173bool SubsystemParser::ParseSection(std::vector<std::string>&& args, const std::string& filename,
174                                   int line, std::string* err) {
175    if (args.size() != 2) {
176        *err = "subsystems must have exactly one name";
177        return false;
178    }
179
180    if (std::find(subsystems.begin(), subsystems.end(), args[1]) != subsystems.end()) {
181        *err = "ignoring duplicate subsystem entry";
182        return false;
183    }
184
185    subsystem_.name_ = args[1];
186
187    return true;
188}
189
190bool SubsystemParser::ParseDevName(std::vector<std::string>&& args, std::string* err) {
191    if (args[1] == "uevent_devname") {
192        subsystem_.devname_source_ = Subsystem::DevnameSource::DEVNAME_UEVENT_DEVNAME;
193        return true;
194    }
195    if (args[1] == "uevent_devpath") {
196        subsystem_.devname_source_ = Subsystem::DevnameSource::DEVNAME_UEVENT_DEVPATH;
197        return true;
198    }
199
200    *err = "invalid devname '" + args[1] + "'";
201    return false;
202}
203
204bool SubsystemParser::ParseDirName(std::vector<std::string>&& args, std::string* err) {
205    if (args[1].front() != '/') {
206        *err = "dirname '" + args[1] + " ' does not start with '/'";
207        return false;
208    }
209
210    subsystem_.dir_name_ = args[1];
211    return true;
212}
213
214bool SubsystemParser::ParseLineSection(std::vector<std::string>&& args, int line, std::string* err) {
215    using OptionParser =
216        bool (SubsystemParser::*)(std::vector<std::string> && args, std::string * err);
217    static class OptionParserMap : public KeywordMap<OptionParser> {
218      private:
219        const Map& map() const override {
220            // clang-format off
221            static const Map option_parsers = {
222                {"devname",     {1,     1,      &SubsystemParser::ParseDevName}},
223                {"dirname",     {1,     1,      &SubsystemParser::ParseDirName}},
224            };
225            // clang-format on
226            return option_parsers;
227        }
228    } parser_map;
229
230    auto parser = parser_map.FindFunction(args, err);
231
232    if (!parser) {
233        return false;
234    }
235
236    return (this->*parser)(std::move(args), err);
237}
238
239void SubsystemParser::EndSection() {
240    subsystems.emplace_back(std::move(subsystem_));
241}
242
243static void fixup_sys_permissions(const std::string& upath, const std::string& subsystem) {
244    // upaths omit the "/sys" that paths in this list
245    // contain, so we prepend it...
246    std::string path = "/sys" + upath;
247
248    for (const auto& s : sysfs_permissions) {
249        if (s.MatchWithSubsystem(path, subsystem)) s.SetPermissions(path);
250    }
251
252    if (access(path.c_str(), F_OK) == 0) {
253        LOG(VERBOSE) << "restorecon_recursive: " << path;
254        selinux_android_restorecon(path.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE);
255    }
256}
257
258static std::tuple<mode_t, uid_t, gid_t> get_device_permissions(
259    const std::string& path, const std::vector<std::string>& links) {
260    // Search the perms list in reverse so that ueventd.$hardware can override ueventd.rc.
261    for (auto it = dev_permissions.rbegin(); it != dev_permissions.rend(); ++it) {
262        if (it->Match(path) || std::any_of(links.begin(), links.end(),
263                                           [it](const auto& link) { return it->Match(link); })) {
264            return {it->perm(), it->uid(), it->gid()};
265        }
266    }
267    /* Default if nothing found. */
268    return {0600, 0, 0};
269}
270
271static void make_device(const std::string& path, int block, int major, int minor,
272                        const std::vector<std::string>& links) {
273    dev_t dev;
274    char *secontext = NULL;
275
276    auto [mode, uid, gid] = get_device_permissions(path, links);
277    mode |= (block ? S_IFBLK : S_IFCHR);
278
279    if (sehandle) {
280        std::vector<const char*> c_links;
281        for (const auto& link : links) {
282            c_links.emplace_back(link.c_str());
283        }
284        c_links.emplace_back(nullptr);
285        if (selabel_lookup_best_match(sehandle, &secontext, path.c_str(), &c_links[0], mode)) {
286            PLOG(ERROR) << "Device '" << path << "' not created; cannot find SELinux label";
287            return;
288        }
289        setfscreatecon(secontext);
290    }
291
292    dev = makedev(major, minor);
293    /* Temporarily change egid to avoid race condition setting the gid of the
294     * device node. Unforunately changing the euid would prevent creation of
295     * some device nodes, so the uid has to be set with chown() and is still
296     * racy. Fixing the gid race at least fixed the issue with system_server
297     * opening dynamic input devices under the AID_INPUT gid. */
298    if (setegid(gid)) {
299        PLOG(ERROR) << "setegid(" << gid << ") for " << path << " device failed";
300        goto out;
301    }
302    /* If the node already exists update its SELinux label to handle cases when
303     * it was created with the wrong context during coldboot procedure. */
304    if (mknod(path.c_str(), mode, dev) && (errno == EEXIST) && secontext) {
305        char* fcon = nullptr;
306        int rc = lgetfilecon(path.c_str(), &fcon);
307        if (rc < 0) {
308            PLOG(ERROR) << "Cannot get SELinux label on '" << path << "' device";
309            goto out;
310        }
311
312        bool different = strcmp(fcon, secontext) != 0;
313        freecon(fcon);
314
315        if (different && lsetfilecon(path.c_str(), secontext)) {
316            PLOG(ERROR) << "Cannot set '" << secontext << "' SELinux label on '" << path << "' device";
317        }
318    }
319
320out:
321    chown(path.c_str(), uid, -1);
322    if (setegid(AID_ROOT)) {
323        PLOG(FATAL) << "setegid(AID_ROOT) failed";
324    }
325
326    if (secontext) {
327        freecon(secontext);
328        setfscreatecon(NULL);
329    }
330}
331
332// TODO: Move this to be a member variable of a future devices class.
333std::vector<std::string> platform_devices;
334
335// Given a path that may start with a platform device, find the length of the
336// platform device prefix.  If it doesn't start with a platform device, return false
337bool find_platform_device(const std::string& path, std::string* out_path) {
338    out_path->clear();
339    // platform_devices is searched backwards, since parents are added before their children,
340    // and we want to match as deep of a child as we can.
341    for (auto it = platform_devices.rbegin(); it != platform_devices.rend(); ++it) {
342        auto platform_device_path_length = it->length();
343        if (platform_device_path_length < path.length() &&
344            path[platform_device_path_length] == '/' &&
345            android::base::StartsWith(path, it->c_str())) {
346            *out_path = *it;
347            return true;
348        }
349    }
350    return false;
351}
352
353/* Given a path that may start with a PCI device, populate the supplied buffer
354 * with the PCI domain/bus number and the peripheral ID and return 0.
355 * If it doesn't start with a PCI device, or there is some error, return -1 */
356static bool find_pci_device_prefix(const std::string& path, std::string* result) {
357    result->clear();
358
359    if (!android::base::StartsWith(path, "/devices/pci")) return false;
360
361    /* Beginning of the prefix is the initial "pci" after "/devices/" */
362    std::string::size_type start = 9;
363
364    /* End of the prefix is two path '/' later, capturing the domain/bus number
365     * and the peripheral ID. Example: pci0000:00/0000:00:1f.2 */
366    auto end = path.find('/', start);
367    if (end == std::string::npos) return false;
368
369    end = path.find('/', end + 1);
370    if (end == std::string::npos) return false;
371
372    auto length = end - start;
373    if (length <= 4) {
374        // The minimum string that will get to this check is 'pci/', which is malformed,
375        // so return false
376        return false;
377    }
378
379    *result = path.substr(start, length);
380    return true;
381}
382
383/* Given a path that may start with a virtual block device, populate
384 * the supplied buffer with the virtual block device ID and return 0.
385 * If it doesn't start with a virtual block device, or there is some
386 * error, return -1 */
387static bool find_vbd_device_prefix(const std::string& path, std::string* result) {
388    result->clear();
389
390    if (!android::base::StartsWith(path, "/devices/vbd-")) return false;
391
392    /* Beginning of the prefix is the initial "vbd-" after "/devices/" */
393    std::string::size_type start = 13;
394
395    /* End of the prefix is one path '/' later, capturing the
396       virtual block device ID. Example: 768 */
397    auto end = path.find('/', start);
398    if (end == std::string::npos) return false;
399
400    auto length = end - start;
401    if (length == 0) return false;
402
403    *result = path.substr(start, length);
404    return true;
405}
406
407void parse_event(const char* msg, uevent* uevent) {
408    uevent->partition_num = -1;
409    uevent->major = -1;
410    uevent->minor = -1;
411    // currently ignoring SEQNUM
412    while(*msg) {
413        if(!strncmp(msg, "ACTION=", 7)) {
414            msg += 7;
415            uevent->action = msg;
416        } else if(!strncmp(msg, "DEVPATH=", 8)) {
417            msg += 8;
418            uevent->path = msg;
419        } else if(!strncmp(msg, "SUBSYSTEM=", 10)) {
420            msg += 10;
421            uevent->subsystem = msg;
422        } else if(!strncmp(msg, "FIRMWARE=", 9)) {
423            msg += 9;
424            uevent->firmware = msg;
425        } else if(!strncmp(msg, "MAJOR=", 6)) {
426            msg += 6;
427            uevent->major = atoi(msg);
428        } else if(!strncmp(msg, "MINOR=", 6)) {
429            msg += 6;
430            uevent->minor = atoi(msg);
431        } else if(!strncmp(msg, "PARTN=", 6)) {
432            msg += 6;
433            uevent->partition_num = atoi(msg);
434        } else if(!strncmp(msg, "PARTNAME=", 9)) {
435            msg += 9;
436            uevent->partition_name = msg;
437        } else if(!strncmp(msg, "DEVNAME=", 8)) {
438            msg += 8;
439            uevent->device_name = msg;
440        }
441
442        // advance to after the next \0
443        while(*msg++)
444            ;
445    }
446
447    if (LOG_UEVENTS) {
448        LOG(INFO) << "event { '" << uevent->action << "', '" << uevent->path << "', '"
449                  << uevent->subsystem << "', '" << uevent->firmware << "', " << uevent->major
450                  << ", " << uevent->minor << " }";
451    }
452}
453
454std::vector<std::string> get_character_device_symlinks(uevent* uevent) {
455    std::string parent_device;
456    if (!find_platform_device(uevent->path, &parent_device)) return {};
457
458    // skip path to the parent driver
459    std::string path = uevent->path.substr(parent_device.length());
460
461    if (!android::base::StartsWith(path, "/usb")) return {};
462
463    // skip root hub name and device. use device interface
464    // skip 3 slashes, including the first / by starting the search at the 1st character, not 0th.
465    // then extract what comes between the 3rd and 4th slash
466    // e.g. "/usb/usb_device/name/tty2-1:1.0" -> "name"
467
468    std::string::size_type start = 0;
469    start = path.find('/', start + 1);
470    if (start == std::string::npos) return {};
471
472    start = path.find('/', start + 1);
473    if (start == std::string::npos) return {};
474
475    auto end = path.find('/', start + 1);
476    if (end == std::string::npos) return {};
477
478    start++;  // Skip the first '/'
479
480    auto length = end - start;
481    if (length == 0) return {};
482
483    auto name_string = path.substr(start, length);
484
485    std::vector<std::string> links;
486    links.emplace_back("/dev/usb/" + uevent->subsystem + name_string);
487
488    mkdir("/dev/usb", 0755);
489
490    return links;
491}
492
493// replaces any unacceptable characters with '_', the
494// length of the resulting string is equal to the input string
495void sanitize_partition_name(std::string* string) {
496    const char* accept =
497        "abcdefghijklmnopqrstuvwxyz"
498        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
499        "0123456789"
500        "_-.";
501
502    if (!string) return;
503
504    std::string::size_type pos = 0;
505    while ((pos = string->find_first_not_of(accept, pos)) != std::string::npos) {
506        (*string)[pos] = '_';
507    }
508}
509
510std::vector<std::string> get_block_device_symlinks(uevent* uevent) {
511    std::string device;
512    std::string type;
513
514    if (find_platform_device(uevent->path, &device)) {
515        // Skip /devices/platform or /devices/ if present
516        static const std::string devices_platform_prefix = "/devices/platform/";
517        static const std::string devices_prefix = "/devices/";
518
519        if (android::base::StartsWith(device, devices_platform_prefix.c_str())) {
520            device = device.substr(devices_platform_prefix.length());
521        } else if (android::base::StartsWith(device, devices_prefix.c_str())) {
522            device = device.substr(devices_prefix.length());
523        }
524
525        type = "platform";
526    } else if (find_pci_device_prefix(uevent->path, &device)) {
527        type = "pci";
528    } else if (find_vbd_device_prefix(uevent->path, &device)) {
529        type = "vbd";
530    } else {
531        return {};
532    }
533
534    std::vector<std::string> links;
535
536    LOG(VERBOSE) << "found " << type << " device " << device;
537
538    auto link_path = "/dev/block/" + type + "/" + device;
539
540    if (!uevent->partition_name.empty()) {
541        std::string partition_name_sanitized(uevent->partition_name);
542        sanitize_partition_name(&partition_name_sanitized);
543        if (partition_name_sanitized != uevent->partition_name) {
544            LOG(VERBOSE) << "Linking partition '" << uevent->partition_name << "' as '"
545                         << partition_name_sanitized << "'";
546        }
547        links.emplace_back(link_path + "/by-name/" + partition_name_sanitized);
548    }
549
550    if (uevent->partition_num >= 0) {
551        links.emplace_back(link_path + "/by-num/p" + std::to_string(uevent->partition_num));
552    }
553
554    auto last_slash = uevent->path.rfind('/');
555    links.emplace_back(link_path + "/" + uevent->path.substr(last_slash + 1));
556
557    return links;
558}
559
560static void make_link_init(const std::string& oldpath, const std::string& newpath) {
561    if (mkdir_recursive(dirname(newpath.c_str()), 0755, sehandle)) {
562        PLOG(ERROR) << "Failed to create directory " << dirname(newpath.c_str());
563    }
564
565    if (symlink(oldpath.c_str(), newpath.c_str()) && errno != EEXIST) {
566        PLOG(ERROR) << "Failed to symlink " << oldpath << " to " << newpath;
567    }
568}
569
570static void remove_link(const std::string& oldpath, const std::string& newpath) {
571    std::string path;
572    if (android::base::Readlink(newpath, &path) && path == oldpath) unlink(newpath.c_str());
573}
574
575static void handle_device(const std::string& action, const std::string& devpath, int block,
576                          int major, int minor, const std::vector<std::string>& links) {
577    if (action == "add") {
578        make_device(devpath, block, major, minor, links);
579        for (const auto& link : links) {
580            make_link_init(devpath, link);
581        }
582    }
583
584    if (action == "remove") {
585        for (const auto& link : links) {
586            remove_link(devpath, link);
587        }
588        unlink(devpath.c_str());
589    }
590}
591
592void handle_platform_device_event(uevent* uevent) {
593    if (uevent->action == "add") {
594        platform_devices.emplace_back(uevent->path);
595    } else if (uevent->action == "remove") {
596        auto it = std::find(platform_devices.begin(), platform_devices.end(), uevent->path);
597        if (it != platform_devices.end()) platform_devices.erase(it);
598    }
599}
600
601static void handle_block_device_event(uevent* uevent) {
602    // if it's not a /dev device, nothing to do
603    if (uevent->major < 0 || uevent->minor < 0) return;
604
605    const char* base = "/dev/block/";
606    make_dir(base, 0755, sehandle);
607
608    std::string name = android::base::Basename(uevent->path);
609    std::string devpath = base + name;
610
611    std::vector<std::string> links;
612    if (android::base::StartsWith(uevent->path, "/devices")) {
613        links = get_block_device_symlinks(uevent);
614    }
615
616    handle_device(uevent->action, devpath, 1, uevent->major, uevent->minor, links);
617}
618
619static void handle_generic_device_event(uevent* uevent) {
620    // if it's not a /dev device, nothing to do
621    if (uevent->major < 0 || uevent->minor < 0) return;
622
623    std::string devpath;
624
625    if (android::base::StartsWith(uevent->subsystem, "usb")) {
626        if (uevent->subsystem == "usb") {
627            if (!uevent->device_name.empty()) {
628                devpath = "/dev/" + uevent->device_name;
629            } else {
630                // This imitates the file system that would be created
631                // if we were using devfs instead.
632                // Minors are broken up into groups of 128, starting at "001"
633                int bus_id = uevent->minor / 128 + 1;
634                int device_id = uevent->minor % 128 + 1;
635                devpath = android::base::StringPrintf("/dev/bus/usb/%03d/%03d", bus_id, device_id);
636            }
637        } else {
638            // ignore other USB events
639            return;
640        }
641    } else if (auto subsystem = std::find(subsystems.begin(), subsystems.end(), uevent->subsystem);
642               subsystem != subsystems.end()) {
643        devpath = subsystem->ParseDevPath(uevent);
644    } else {
645        devpath = "/dev/" + android::base::Basename(uevent->path);
646    }
647
648    mkdir_recursive(android::base::Dirname(devpath), 0755, sehandle);
649
650    auto links = get_character_device_symlinks(uevent);
651
652    handle_device(uevent->action, devpath, 0, uevent->major, uevent->minor, links);
653}
654
655static void handle_device_event(struct uevent *uevent)
656{
657    if (uevent->action == "add" || uevent->action == "change" || uevent->action == "online") {
658        fixup_sys_permissions(uevent->path, uevent->subsystem);
659    }
660
661    if (uevent->subsystem == "block") {
662        handle_block_device_event(uevent);
663    } else if (uevent->subsystem == "platform") {
664        handle_platform_device_event(uevent);
665    } else {
666        handle_generic_device_event(uevent);
667    }
668}
669
670static void load_firmware(uevent* uevent, const std::string& root,
671                          int fw_fd, size_t fw_size,
672                          int loading_fd, int data_fd) {
673    // Start transfer.
674    android::base::WriteFully(loading_fd, "1", 1);
675
676    // Copy the firmware.
677    int rc = sendfile(data_fd, fw_fd, nullptr, fw_size);
678    if (rc == -1) {
679        PLOG(ERROR) << "firmware: sendfile failed { '" << root << "', '" << uevent->firmware << "' }";
680    }
681
682    // Tell the firmware whether to abort or commit.
683    const char* response = (rc != -1) ? "0" : "-1";
684    android::base::WriteFully(loading_fd, response, strlen(response));
685}
686
687static int is_booting() {
688    return access("/dev/.booting", F_OK) == 0;
689}
690
691static void process_firmware_event(uevent* uevent) {
692    int booting = is_booting();
693
694    LOG(INFO) << "firmware: loading '" << uevent->firmware << "' for '" << uevent->path << "'";
695
696    std::string root = "/sys" + uevent->path;
697    std::string loading = root + "/loading";
698    std::string data = root + "/data";
699
700    android::base::unique_fd loading_fd(open(loading.c_str(), O_WRONLY|O_CLOEXEC));
701    if (loading_fd == -1) {
702        PLOG(ERROR) << "couldn't open firmware loading fd for " << uevent->firmware;
703        return;
704    }
705
706    android::base::unique_fd data_fd(open(data.c_str(), O_WRONLY|O_CLOEXEC));
707    if (data_fd == -1) {
708        PLOG(ERROR) << "couldn't open firmware data fd for " << uevent->firmware;
709        return;
710    }
711
712    static const char* firmware_dirs[] = {"/etc/firmware/", "/vendor/firmware/",
713                                          "/firmware/image/"};
714
715try_loading_again:
716    for (size_t i = 0; i < arraysize(firmware_dirs); i++) {
717        std::string file = firmware_dirs[i] + uevent->firmware;
718        android::base::unique_fd fw_fd(open(file.c_str(), O_RDONLY|O_CLOEXEC));
719        struct stat sb;
720        if (fw_fd != -1 && fstat(fw_fd, &sb) != -1) {
721            load_firmware(uevent, root, fw_fd, sb.st_size, loading_fd, data_fd);
722            return;
723        }
724    }
725
726    if (booting) {
727        // If we're not fully booted, we may be missing
728        // filesystems needed for firmware, wait and retry.
729        std::this_thread::sleep_for(100ms);
730        booting = is_booting();
731        goto try_loading_again;
732    }
733
734    LOG(ERROR) << "firmware: could not find firmware for " << uevent->firmware;
735
736    // Write "-1" as our response to the kernel's firmware request, since we have nothing for it.
737    write(loading_fd, "-1", 2);
738}
739
740static void handle_firmware_event(uevent* uevent) {
741    if (uevent->subsystem != "firmware" || uevent->action != "add") return;
742
743    // Loading the firmware in a child means we can do that in parallel...
744    // (We ignore SIGCHLD rather than wait for our children.)
745    pid_t pid = fork();
746    if (pid == 0) {
747        Timer t;
748        process_firmware_event(uevent);
749        LOG(INFO) << "loading " << uevent->path << " took " << t;
750        _exit(EXIT_SUCCESS);
751    } else if (pid == -1) {
752        PLOG(ERROR) << "could not fork to process firmware event for " << uevent->firmware;
753    }
754}
755
756static bool inline should_stop_coldboot(coldboot_action_t act)
757{
758    return (act == COLDBOOT_STOP || act == COLDBOOT_FINISH);
759}
760
761#define UEVENT_MSG_LEN  2048
762
763static inline coldboot_action_t handle_device_fd_with(
764        std::function<coldboot_action_t(uevent* uevent)> handle_uevent)
765{
766    char msg[UEVENT_MSG_LEN+2];
767    int n;
768    while ((n = uevent_kernel_multicast_recv(device_fd, msg, UEVENT_MSG_LEN)) > 0) {
769        if(n >= UEVENT_MSG_LEN)   /* overflow -- discard */
770            continue;
771
772        msg[n] = '\0';
773        msg[n+1] = '\0';
774
775        uevent uevent;
776        parse_event(msg, &uevent);
777        coldboot_action_t act = handle_uevent(&uevent);
778        if (should_stop_coldboot(act))
779            return act;
780    }
781
782    return COLDBOOT_CONTINUE;
783}
784
785coldboot_action_t handle_device_fd(coldboot_callback fn)
786{
787    coldboot_action_t ret = handle_device_fd_with(
788        [&](uevent* uevent) -> coldboot_action_t {
789            // default is to always create the devices
790            coldboot_action_t act = COLDBOOT_CREATE;
791            if (fn) {
792                act = fn(uevent);
793            }
794
795            if (act == COLDBOOT_CREATE || act == COLDBOOT_STOP) {
796                handle_device_event(uevent);
797                handle_firmware_event(uevent);
798            }
799
800            return act;
801        });
802
803    return ret;
804}
805
806/* Coldboot walks parts of the /sys tree and pokes the uevent files
807** to cause the kernel to regenerate device add events that happened
808** before init's device manager was started
809**
810** We drain any pending events from the netlink socket every time
811** we poke another uevent file to make sure we don't overrun the
812** socket's buffer.
813*/
814
815static coldboot_action_t do_coldboot(DIR *d, coldboot_callback fn)
816{
817    struct dirent *de;
818    int dfd, fd;
819    coldboot_action_t act = COLDBOOT_CONTINUE;
820
821    dfd = dirfd(d);
822
823    fd = openat(dfd, "uevent", O_WRONLY);
824    if (fd >= 0) {
825        write(fd, "add\n", 4);
826        close(fd);
827        act = handle_device_fd(fn);
828        if (should_stop_coldboot(act))
829            return act;
830    }
831
832    while (!should_stop_coldboot(act) && (de = readdir(d))) {
833        DIR *d2;
834
835        if(de->d_type != DT_DIR || de->d_name[0] == '.')
836            continue;
837
838        fd = openat(dfd, de->d_name, O_RDONLY | O_DIRECTORY);
839        if(fd < 0)
840            continue;
841
842        d2 = fdopendir(fd);
843        if(d2 == 0)
844            close(fd);
845        else {
846            act = do_coldboot(d2, fn);
847            closedir(d2);
848        }
849    }
850
851    // default is always to continue looking for uevents
852    return act;
853}
854
855static coldboot_action_t coldboot(const char *path, coldboot_callback fn)
856{
857    std::unique_ptr<DIR, decltype(&closedir)> d(opendir(path), closedir);
858    if (d) {
859        return do_coldboot(d.get(), fn);
860    }
861
862    return COLDBOOT_CONTINUE;
863}
864
865void device_init(const char* path, coldboot_callback fn) {
866    if (!sehandle) {
867        sehandle = selinux_android_file_context_handle();
868    }
869    // open uevent socket and selinux status only if it hasn't been
870    // done before
871    if (device_fd == -1) {
872        /* is 256K enough? udev uses 16MB! */
873        device_fd.reset(uevent_open_socket(256 * 1024, true));
874        if (device_fd == -1) {
875            return;
876        }
877        fcntl(device_fd, F_SETFL, O_NONBLOCK);
878    }
879
880    if (access(COLDBOOT_DONE, F_OK) == 0) {
881        LOG(VERBOSE) << "Skipping coldboot, already done!";
882        return;
883    }
884
885    Timer t;
886    coldboot_action_t act;
887    if (!path) {
888        act = coldboot("/sys/class", fn);
889        if (!should_stop_coldboot(act)) {
890            act = coldboot("/sys/block", fn);
891            if (!should_stop_coldboot(act)) {
892                act = coldboot("/sys/devices", fn);
893            }
894        }
895    } else {
896        act = coldboot(path, fn);
897    }
898
899    // If we have a callback, then do as it says. If no, then the default is
900    // to always create COLDBOOT_DONE file.
901    if (!fn || (act == COLDBOOT_FINISH)) {
902        close(open(COLDBOOT_DONE, O_WRONLY|O_CREAT|O_CLOEXEC, 0000));
903    }
904
905    LOG(INFO) << "Coldboot took " << t;
906}
907
908void device_close() {
909    platform_devices.clear();
910    device_fd.reset();
911}
912
913int get_device_fd() {
914    return device_fd;
915}
916