devices.c revision 60a4cd5e348ae263d209a7f64510826825848208
1/*
2 * Copyright (C) 2007 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 <stdio.h>
19#include <stdlib.h>
20#include <sys/stat.h>
21#include <sys/types.h>
22
23#include <fcntl.h>
24#include <dirent.h>
25#include <unistd.h>
26#include <string.h>
27
28#include <sys/socket.h>
29#include <sys/un.h>
30#include <linux/netlink.h>
31#include <private/android_filesystem_config.h>
32#include <sys/time.h>
33#include <asm/page.h>
34
35#include "init.h"
36#include "devices.h"
37
38#define CMDLINE_PREFIX  "/dev"
39#define SYSFS_PREFIX    "/sys"
40#define FIRMWARE_DIR    "/etc/firmware"
41#define MAX_QEMU_PERM 6
42
43struct uevent {
44    const char *action;
45    const char *path;
46    const char *subsystem;
47    const char *firmware;
48    int major;
49    int minor;
50};
51
52static int open_uevent_socket(void)
53{
54    struct sockaddr_nl addr;
55    int sz = 64*1024; // XXX larger? udev uses 16MB!
56    int s;
57
58    memset(&addr, 0, sizeof(addr));
59    addr.nl_family = AF_NETLINK;
60    addr.nl_pid = getpid();
61    addr.nl_groups = 0xffffffff;
62
63    s = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
64    if(s < 0)
65        return -1;
66
67    setsockopt(s, SOL_SOCKET, SO_RCVBUFFORCE, &sz, sizeof(sz));
68
69    if(bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
70        close(s);
71        return -1;
72    }
73
74    return s;
75}
76
77struct perms_ {
78    char *name;
79    mode_t perm;
80    unsigned int uid;
81    unsigned int gid;
82    unsigned short prefix;
83};
84static struct perms_ devperms[] = {
85    { "/dev/null",          0666,   AID_ROOT,       AID_ROOT,       0 },
86    { "/dev/zero",          0666,   AID_ROOT,       AID_ROOT,       0 },
87    { "/dev/full",          0666,   AID_ROOT,       AID_ROOT,       0 },
88    { "/dev/ptmx",          0666,   AID_ROOT,       AID_ROOT,       0 },
89    { "/dev/tty",           0666,   AID_ROOT,       AID_ROOT,       0 },
90    { "/dev/random",        0666,   AID_ROOT,       AID_ROOT,       0 },
91    { "/dev/urandom",       0666,   AID_ROOT,       AID_ROOT,       0 },
92    { "/dev/ashmem",        0666,   AID_ROOT,       AID_ROOT,       0 },
93    { "/dev/binder",        0666,   AID_ROOT,       AID_ROOT,       0 },
94
95	    /* logger should be world writable (for logging) but not readable */
96    { "/dev/log/",          0662,   AID_ROOT,       AID_LOG,        1 },
97
98        /* these should not be world writable */
99    { "/dev/android_adb",   0660,   AID_ADB,        AID_ADB,        0 },
100    { "/dev/android_adb_enable",   0660,   AID_ADB,        AID_ADB,        0 },
101    { "/dev/ttyMSM0",       0600,   AID_BLUETOOTH,  AID_BLUETOOTH,  0 },
102    { "/dev/ttyHS0",        0600,   AID_BLUETOOTH,  AID_BLUETOOTH,  0 },
103    { "/dev/uinput",        0600,   AID_BLUETOOTH,  AID_BLUETOOTH,  0 },
104    { "/dev/alarm",         0664,   AID_SYSTEM,     AID_RADIO,      0 },
105    { "/dev/tty0",          0660,   AID_ROOT,       AID_SYSTEM,     0 },
106    { "/dev/graphics/",     0660,   AID_ROOT,       AID_GRAPHICS,   1 },
107    { "/dev/hw3d",          0660,   AID_SYSTEM,     AID_GRAPHICS,   0 },
108    { "/dev/input/",        0660,   AID_ROOT,       AID_INPUT,      1 },
109    { "/dev/eac",           0660,   AID_ROOT,       AID_AUDIO,      0 },
110    { "/dev/cam",           0660,   AID_ROOT,       AID_CAMERA,     0 },
111    { "/dev/pmem",          0660,   AID_SYSTEM,     AID_GRAPHICS,   0 },
112    { "/dev/pmem_gpu",      0660,   AID_SYSTEM,     AID_GRAPHICS,   1 },
113    { "/dev/pmem_adsp",     0660,   AID_SYSTEM,     AID_AUDIO,      1 },
114    { "/dev/pmem_camera",   0660,   AID_SYSTEM,     AID_CAMERA,     1 },
115    { "/dev/oncrpc/",       0660,   AID_ROOT,       AID_SYSTEM,     1 },
116    { "/dev/adsp/",         0660,   AID_SYSTEM,     AID_AUDIO,      1 },
117    { "/dev/mt9t013",       0660,   AID_SYSTEM,     AID_SYSTEM,     0 },
118    { "/dev/msm_camera/",   0660,   AID_SYSTEM,     AID_SYSTEM,     1 },
119    { "/dev/akm8976_daemon",0640,   AID_COMPASS,    AID_SYSTEM,     0 },
120    { "/dev/akm8976_aot",   0640,   AID_COMPASS,    AID_SYSTEM,     0 },
121    { "/dev/akm8973_daemon",0640,   AID_COMPASS,    AID_SYSTEM,     0 },
122    { "/dev/akm8973_aot",   0640,   AID_COMPASS,    AID_SYSTEM,     0 },
123    { "/dev/bma150",        0640,   AID_COMPASS,    AID_SYSTEM,     0 },
124    { "/dev/akm8976_pffd",  0640,   AID_COMPASS,    AID_SYSTEM,     0 },
125    { "/dev/msm_pcm_out",   0660,   AID_SYSTEM,     AID_AUDIO,      1 },
126    { "/dev/msm_pcm_in",    0660,   AID_SYSTEM,     AID_AUDIO,      1 },
127    { "/dev/msm_pcm_ctl",   0660,   AID_SYSTEM,     AID_AUDIO,      1 },
128    { "/dev/msm_snd",       0660,   AID_SYSTEM,     AID_AUDIO,      1 },
129    { "/dev/msm_mp3",       0660,   AID_SYSTEM,     AID_AUDIO,      1 },
130    { "/dev/msm_audpre",    0660,   AID_SYSTEM,     AID_AUDIO,      0 },
131    { "/dev/htc-acoustic",  0660,   AID_SYSTEM,     AID_AUDIO,      0 },
132    { "/dev/snd/dsp",       0660,   AID_SYSTEM,     AID_AUDIO,      0 },
133    { "/dev/snd/dsp1",      0660,   AID_SYSTEM,     AID_AUDIO,      0 },
134    { "/dev/snd/mixer",     0660,   AID_SYSTEM,     AID_AUDIO,      0 },
135    { "/dev/smd0",          0640,   AID_RADIO,      AID_RADIO,      0 },
136    { "/dev/qemu_trace",    0666,   AID_SYSTEM,     AID_SYSTEM,     0 },
137    { "/dev/qmi",           0640,   AID_RADIO,      AID_RADIO,      0 },
138    { "/dev/qmi0",          0640,   AID_RADIO,      AID_RADIO,      0 },
139    { "/dev/qmi1",          0640,   AID_RADIO,      AID_RADIO,      0 },
140    { "/dev/qmi2",          0640,   AID_RADIO,      AID_RADIO,      0 },
141        /* CDMA radio interface MUX */
142    { "/dev/ts0710mux",     0640,   AID_RADIO,      AID_RADIO,      1 },
143    { "/dev/ppp",           0660,   AID_RADIO,      AID_VPN,        0 },
144    { "/dev/tun",           0640,   AID_VPN,        AID_VPN,        0 },
145    { NULL, 0, 0, 0, 0 },
146};
147
148/* devperms_partners list and perm_node are for hardware specific /dev entries */
149struct perm_node {
150    struct perms_ dp;
151    struct listnode plist;
152};
153list_declare(devperms_partners);
154
155/*
156 * Permission override when in emulator mode, must be parsed before
157 * system properties is initalized.
158 */
159static int qemu_perm_count;
160static struct perms_ qemu_perms[MAX_QEMU_PERM + 1];
161
162int add_devperms_partners(const char *name, mode_t perm, unsigned int uid,
163                        unsigned int gid, unsigned short prefix) {
164    int size;
165    struct perm_node *node = malloc(sizeof (struct perm_node));
166    if (!node)
167        return -ENOMEM;
168
169    size = strlen(name) + 1;
170    if ((node->dp.name = malloc(size)) == NULL)
171        return -ENOMEM;
172
173    memcpy(node->dp.name, name, size);
174    node->dp.perm = perm;
175    node->dp.uid = uid;
176    node->dp.gid = gid;
177    node->dp.prefix = prefix;
178
179    list_add_tail(&devperms_partners, &node->plist);
180    return 0;
181}
182
183void qemu_init(void) {
184    qemu_perm_count = 0;
185    memset(&qemu_perms, 0, sizeof(qemu_perms));
186}
187
188static int qemu_perm(const char* name, mode_t perm, unsigned int uid,
189                         unsigned int gid, unsigned short prefix)
190{
191    char *buf;
192    if (qemu_perm_count == MAX_QEMU_PERM)
193        return -ENOSPC;
194
195    buf = malloc(strlen(name) + 1);
196    if (!buf)
197        return -errno;
198
199    strlcpy(buf, name, strlen(name) + 1);
200    qemu_perms[qemu_perm_count].name = buf;
201    qemu_perms[qemu_perm_count].perm = perm;
202    qemu_perms[qemu_perm_count].uid = uid;
203    qemu_perms[qemu_perm_count].gid = gid;
204    qemu_perms[qemu_perm_count].prefix = prefix;
205
206    qemu_perm_count++;
207    return 0;
208}
209
210/* Permission overrides for emulator that are parsed from /proc/cmdline. */
211void qemu_cmdline(const char* name, const char *value)
212{
213    char *buf;
214    if (!strcmp(name, "android.ril")) {
215        /* cmd line params currently assume /dev/ prefix */
216        if (asprintf(&buf, CMDLINE_PREFIX"/%s", value) == -1) {
217            return;
218        }
219        INFO("nani- buf:: %s\n", buf);
220        qemu_perm(buf, 0660, AID_RADIO, AID_ROOT, 0);
221    }
222}
223
224static int get_device_perm_inner(struct perms_ *perms, const char *path,
225                                    unsigned *uid, unsigned *gid, mode_t *perm)
226{
227    int i;
228    for(i = 0; perms[i].name; i++) {
229
230        if(perms[i].prefix) {
231            if(strncmp(path, perms[i].name, strlen(perms[i].name)))
232                continue;
233        } else {
234            if(strcmp(path, perms[i].name))
235                continue;
236        }
237        *uid = perms[i].uid;
238        *gid = perms[i].gid;
239        *perm = perms[i].perm;
240        return 0;
241    }
242    return -1;
243}
244
245/* First checks for emulator specific permissions specified in /proc/cmdline. */
246static mode_t get_device_perm(const char *path, unsigned *uid, unsigned *gid)
247{
248    mode_t perm;
249
250    if (get_device_perm_inner(qemu_perms, path, uid, gid, &perm) == 0) {
251        return perm;
252    } else if (get_device_perm_inner(devperms, path, uid, gid, &perm) == 0) {
253        return perm;
254    } else {
255        struct listnode *node;
256        struct perm_node *perm_node;
257        struct perms_ *dp;
258
259        /* Check partners list. */
260        list_for_each(node, &devperms_partners) {
261            perm_node = node_to_item(node, struct perm_node, plist);
262            dp = &perm_node->dp;
263
264            if (dp->prefix) {
265                if (strncmp(path, dp->name, strlen(dp->name)))
266                    continue;
267            } else {
268                if (strcmp(path, dp->name))
269                    continue;
270            }
271            /* Found perm in partner list. */
272            *uid = dp->uid;
273            *gid = dp->gid;
274            return dp->perm;
275        }
276        /* Default if nothing found. */
277        *uid = 0;
278        *gid = 0;
279        return 0600;
280    }
281}
282
283static void make_device(const char *path, int block, int major, int minor)
284{
285    unsigned uid;
286    unsigned gid;
287    mode_t mode;
288    dev_t dev;
289
290    if(major > 255 || minor > 255)
291        return;
292
293    mode = get_device_perm(path, &uid, &gid) | (block ? S_IFBLK : S_IFCHR);
294    dev = (major << 8) | minor;
295    mknod(path, mode, dev);
296    chown(path, uid, gid);
297}
298
299#ifdef LOG_UEVENTS
300
301static inline suseconds_t get_usecs(void)
302{
303    struct timeval tv;
304    gettimeofday(&tv, 0);
305    return tv.tv_sec * (suseconds_t) 1000000 + tv.tv_usec;
306}
307
308#define log_event_print(x...) INFO(x)
309
310#else
311
312#define log_event_print(fmt, args...)   do { } while (0)
313#define get_usecs()                     0
314
315#endif
316
317static void parse_event(const char *msg, struct uevent *uevent)
318{
319    uevent->action = "";
320    uevent->path = "";
321    uevent->subsystem = "";
322    uevent->firmware = "";
323    uevent->major = -1;
324    uevent->minor = -1;
325
326        /* currently ignoring SEQNUM */
327    while(*msg) {
328        if(!strncmp(msg, "ACTION=", 7)) {
329            msg += 7;
330            uevent->action = msg;
331        } else if(!strncmp(msg, "DEVPATH=", 8)) {
332            msg += 8;
333            uevent->path = msg;
334        } else if(!strncmp(msg, "SUBSYSTEM=", 10)) {
335            msg += 10;
336            uevent->subsystem = msg;
337        } else if(!strncmp(msg, "FIRMWARE=", 9)) {
338            msg += 9;
339            uevent->firmware = msg;
340        } else if(!strncmp(msg, "MAJOR=", 6)) {
341            msg += 6;
342            uevent->major = atoi(msg);
343        } else if(!strncmp(msg, "MINOR=", 6)) {
344            msg += 6;
345            uevent->minor = atoi(msg);
346        }
347
348            /* advance to after the next \0 */
349        while(*msg++)
350            ;
351    }
352
353    log_event_print("event { '%s', '%s', '%s', '%s', %d, %d }\n",
354                    uevent->action, uevent->path, uevent->subsystem,
355                    uevent->firmware, uevent->major, uevent->minor);
356}
357
358static void handle_device_event(struct uevent *uevent)
359{
360    char devpath[96];
361    char *base, *name;
362    int block;
363
364        /* if it's not a /dev device, nothing to do */
365    if((uevent->major < 0) || (uevent->minor < 0))
366        return;
367
368        /* do we have a name? */
369    name = strrchr(uevent->path, '/');
370    if(!name)
371        return;
372    name++;
373
374        /* too-long names would overrun our buffer */
375    if(strlen(name) > 64)
376        return;
377
378        /* are we block or char? where should we live? */
379    if(!strncmp(uevent->subsystem, "block", 5)) {
380        block = 1;
381        base = "/dev/block/";
382        mkdir(base, 0755);
383    } else {
384        block = 0;
385            /* this should probably be configurable somehow */
386        if(!strncmp(uevent->subsystem, "graphics", 8)) {
387            base = "/dev/graphics/";
388            mkdir(base, 0755);
389        } else if (!strncmp(uevent->subsystem, "oncrpc", 6)) {
390            base = "/dev/oncrpc/";
391            mkdir(base, 0755);
392        } else if (!strncmp(uevent->subsystem, "adsp", 4)) {
393            base = "/dev/adsp/";
394            mkdir(base, 0755);
395        } else if (!strncmp(uevent->subsystem, "msm_camera", 10)) {
396            base = "/dev/msm_camera/";
397            mkdir(base, 0755);
398        } else if(!strncmp(uevent->subsystem, "input", 5)) {
399            base = "/dev/input/";
400            mkdir(base, 0755);
401        } else if(!strncmp(uevent->subsystem, "mtd", 3)) {
402            base = "/dev/mtd/";
403            mkdir(base, 0755);
404        } else if(!strncmp(uevent->subsystem, "sound", 5)) {
405            base = "/dev/snd/";
406            mkdir(base, 0755);
407        } else if(!strncmp(uevent->subsystem, "misc", 4) &&
408                    !strncmp(name, "log_", 4)) {
409            base = "/dev/log/";
410            mkdir(base, 0755);
411            name += 4;
412        } else
413            base = "/dev/";
414    }
415
416    snprintf(devpath, sizeof(devpath), "%s%s", base, name);
417
418    if(!strcmp(uevent->action, "add")) {
419        make_device(devpath, block, uevent->major, uevent->minor);
420        return;
421    }
422
423    if(!strcmp(uevent->action, "remove")) {
424        unlink(devpath);
425        return;
426    }
427}
428
429static int load_firmware(int fw_fd, int loading_fd, int data_fd)
430{
431    struct stat st;
432    long len_to_copy;
433    int ret = 0;
434
435    if(fstat(fw_fd, &st) < 0)
436        return -1;
437    len_to_copy = st.st_size;
438
439    write(loading_fd, "1", 1);  /* start transfer */
440
441    while (len_to_copy > 0) {
442        char buf[PAGE_SIZE];
443        ssize_t nr;
444
445        nr = read(fw_fd, buf, sizeof(buf));
446        if(!nr)
447            break;
448        if(nr < 0) {
449            ret = -1;
450            break;
451        }
452
453        len_to_copy -= nr;
454        while (nr > 0) {
455            ssize_t nw = 0;
456
457            nw = write(data_fd, buf + nw, nr);
458            if(nw <= 0) {
459                ret = -1;
460                goto out;
461            }
462            nr -= nw;
463        }
464    }
465
466out:
467    if(!ret)
468        write(loading_fd, "0", 1);  /* successful end of transfer */
469    else
470        write(loading_fd, "-1", 2); /* abort transfer */
471
472    return ret;
473}
474
475static void process_firmware_event(struct uevent *uevent)
476{
477    char *root, *loading, *data, *file;
478    int l, loading_fd, data_fd, fw_fd;
479
480    log_event_print("firmware event { '%s', '%s' }\n",
481                    uevent->path, uevent->firmware);
482
483    l = asprintf(&root, SYSFS_PREFIX"%s/", uevent->path);
484    if (l == -1)
485        return;
486
487    l = asprintf(&loading, "%sloading", root);
488    if (l == -1)
489        goto root_free_out;
490
491    l = asprintf(&data, "%sdata", root);
492    if (l == -1)
493        goto loading_free_out;
494
495    l = asprintf(&file, FIRMWARE_DIR"/%s", uevent->firmware);
496    if (l == -1)
497        goto data_free_out;
498
499    loading_fd = open(loading, O_WRONLY);
500    if(loading_fd < 0)
501        goto file_free_out;
502
503    data_fd = open(data, O_WRONLY);
504    if(data_fd < 0)
505        goto loading_close_out;
506
507    fw_fd = open(file, O_RDONLY);
508    if(fw_fd < 0)
509        goto data_close_out;
510
511    if(!load_firmware(fw_fd, loading_fd, data_fd))
512        log_event_print("firmware copy success { '%s', '%s' }\n", root, file);
513    else
514        log_event_print("firmware copy failure { '%s', '%s' }\n", root, file);
515
516    close(fw_fd);
517data_close_out:
518    close(data_fd);
519loading_close_out:
520    close(loading_fd);
521file_free_out:
522    free(file);
523data_free_out:
524    free(data);
525loading_free_out:
526    free(loading);
527root_free_out:
528    free(root);
529}
530
531static void handle_firmware_event(struct uevent *uevent)
532{
533    pid_t pid;
534
535    if(strcmp(uevent->subsystem, "firmware"))
536        return;
537
538    if(strcmp(uevent->action, "add"))
539        return;
540
541    /* we fork, to avoid making large memory allocations in init proper */
542    pid = fork();
543    if (!pid) {
544        process_firmware_event(uevent);
545        exit(EXIT_SUCCESS);
546    }
547}
548
549#define UEVENT_MSG_LEN  1024
550void handle_device_fd(int fd)
551{
552    char msg[UEVENT_MSG_LEN+2];
553    int n;
554
555    while((n = recv(fd, msg, UEVENT_MSG_LEN, 0)) > 0) {
556        struct uevent uevent;
557
558        if(n == UEVENT_MSG_LEN)   /* overflow -- discard */
559            continue;
560
561        msg[n] = '\0';
562        msg[n+1] = '\0';
563
564        parse_event(msg, &uevent);
565
566        handle_device_event(&uevent);
567        handle_firmware_event(&uevent);
568    }
569}
570
571/* Coldboot walks parts of the /sys tree and pokes the uevent files
572** to cause the kernel to regenerate device add events that happened
573** before init's device manager was started
574**
575** We drain any pending events from the netlink socket every time
576** we poke another uevent file to make sure we don't overrun the
577** socket's buffer.
578*/
579
580static void do_coldboot(int event_fd, DIR *d)
581{
582    struct dirent *de;
583    int dfd, fd;
584
585    dfd = dirfd(d);
586
587    fd = openat(dfd, "uevent", O_WRONLY);
588    if(fd >= 0) {
589        write(fd, "add\n", 4);
590        close(fd);
591        handle_device_fd(event_fd);
592    }
593
594    while((de = readdir(d))) {
595        DIR *d2;
596
597        if(de->d_type != DT_DIR || de->d_name[0] == '.')
598            continue;
599
600        fd = openat(dfd, de->d_name, O_RDONLY | O_DIRECTORY);
601        if(fd < 0)
602            continue;
603
604        d2 = fdopendir(fd);
605        if(d2 == 0)
606            close(fd);
607        else {
608            do_coldboot(event_fd, d2);
609            closedir(d2);
610        }
611    }
612}
613
614static void coldboot(int event_fd, const char *path)
615{
616    DIR *d = opendir(path);
617    if(d) {
618        do_coldboot(event_fd, d);
619        closedir(d);
620    }
621}
622
623int device_init(void)
624{
625    suseconds_t t0, t1;
626    int fd;
627
628    fd = open_uevent_socket();
629    if(fd < 0)
630        return -1;
631
632    fcntl(fd, F_SETFD, FD_CLOEXEC);
633    fcntl(fd, F_SETFL, O_NONBLOCK);
634
635    t0 = get_usecs();
636    coldboot(fd, "/sys/class");
637    coldboot(fd, "/sys/block");
638    coldboot(fd, "/sys/devices");
639    t1 = get_usecs();
640
641    log_event_print("coldboot %ld uS\n", ((long) (t1 - t0)));
642
643    return fd;
644}
645