devices.c revision 9a52eda8c5dd9df763a63f9b71cd24847f014737
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/tun",           0640,   AID_VPN  ,      AID_VPN,        0 },
144    { NULL, 0, 0, 0, 0 },
145};
146
147/* devperms_partners list and perm_node are for hardware specific /dev entries */
148struct perm_node {
149    struct perms_ dp;
150    struct listnode plist;
151};
152list_declare(devperms_partners);
153
154/*
155 * Permission override when in emulator mode, must be parsed before
156 * system properties is initalized.
157 */
158static int qemu_perm_count;
159static struct perms_ qemu_perms[MAX_QEMU_PERM + 1];
160
161int add_devperms_partners(const char *name, mode_t perm, unsigned int uid,
162                        unsigned int gid, unsigned short prefix) {
163    int size;
164    struct perm_node *node = malloc(sizeof (struct perm_node));
165    if (!node)
166        return -ENOMEM;
167
168    size = strlen(name) + 1;
169    if ((node->dp.name = malloc(size)) == NULL)
170        return -ENOMEM;
171
172    memcpy(node->dp.name, name, size);
173    node->dp.perm = perm;
174    node->dp.uid = uid;
175    node->dp.gid = gid;
176    node->dp.prefix = prefix;
177
178    list_add_tail(&devperms_partners, &node->plist);
179    return 0;
180}
181
182void qemu_init(void) {
183    qemu_perm_count = 0;
184    memset(&qemu_perms, 0, sizeof(qemu_perms));
185}
186
187static int qemu_perm(const char* name, mode_t perm, unsigned int uid,
188                         unsigned int gid, unsigned short prefix)
189{
190    char *buf;
191    if (qemu_perm_count == MAX_QEMU_PERM)
192        return -ENOSPC;
193
194    buf = malloc(strlen(name) + 1);
195    if (!buf)
196        return -errno;
197
198    strlcpy(buf, name, strlen(name) + 1);
199    qemu_perms[qemu_perm_count].name = buf;
200    qemu_perms[qemu_perm_count].perm = perm;
201    qemu_perms[qemu_perm_count].uid = uid;
202    qemu_perms[qemu_perm_count].gid = gid;
203    qemu_perms[qemu_perm_count].prefix = prefix;
204
205    qemu_perm_count++;
206    return 0;
207}
208
209/* Permission overrides for emulator that are parsed from /proc/cmdline. */
210void qemu_cmdline(const char* name, const char *value)
211{
212    char *buf;
213    if (!strcmp(name, "android.ril")) {
214        /* cmd line params currently assume /dev/ prefix */
215        if (asprintf(&buf, CMDLINE_PREFIX"/%s", value) == -1) {
216            return;
217        }
218        INFO("nani- buf:: %s\n", buf);
219        qemu_perm(buf, 0660, AID_RADIO, AID_ROOT, 0);
220    }
221}
222
223static int get_device_perm_inner(struct perms_ *perms, const char *path,
224                                    unsigned *uid, unsigned *gid, mode_t *perm)
225{
226    int i;
227    for(i = 0; perms[i].name; i++) {
228
229        if(perms[i].prefix) {
230            if(strncmp(path, perms[i].name, strlen(perms[i].name)))
231                continue;
232        } else {
233            if(strcmp(path, perms[i].name))
234                continue;
235        }
236        *uid = perms[i].uid;
237        *gid = perms[i].gid;
238        *perm = perms[i].perm;
239        return 0;
240    }
241    return -1;
242}
243
244/* First checks for emulator specific permissions specified in /proc/cmdline. */
245static mode_t get_device_perm(const char *path, unsigned *uid, unsigned *gid)
246{
247    mode_t perm;
248
249    if (get_device_perm_inner(qemu_perms, path, uid, gid, &perm) == 0) {
250        return perm;
251    } else if (get_device_perm_inner(devperms, path, uid, gid, &perm) == 0) {
252        return perm;
253    } else {
254        struct listnode *node;
255        struct perm_node *perm_node;
256        struct perms_ *dp;
257
258        /* Check partners list. */
259        list_for_each(node, &devperms_partners) {
260            perm_node = node_to_item(node, struct perm_node, plist);
261            dp = &perm_node->dp;
262
263            if (dp->prefix) {
264                if (strncmp(path, dp->name, strlen(dp->name)))
265                    continue;
266            } else {
267                if (strcmp(path, dp->name))
268                    continue;
269            }
270            /* Found perm in partner list. */
271            *uid = dp->uid;
272            *gid = dp->gid;
273            return dp->perm;
274        }
275        /* Default if nothing found. */
276        *uid = 0;
277        *gid = 0;
278        return 0600;
279    }
280}
281
282static void make_device(const char *path, int block, int major, int minor)
283{
284    unsigned uid;
285    unsigned gid;
286    mode_t mode;
287    dev_t dev;
288
289    if(major > 255 || minor > 255)
290        return;
291
292    mode = get_device_perm(path, &uid, &gid) | (block ? S_IFBLK : S_IFCHR);
293    dev = (major << 8) | minor;
294    mknod(path, mode, dev);
295    chown(path, uid, gid);
296}
297
298#ifdef LOG_UEVENTS
299
300static inline suseconds_t get_usecs(void)
301{
302    struct timeval tv;
303    gettimeofday(&tv, 0);
304    return tv.tv_sec * (suseconds_t) 1000000 + tv.tv_usec;
305}
306
307#define log_event_print(x...) INFO(x)
308
309#else
310
311#define log_event_print(fmt, args...)   do { } while (0)
312#define get_usecs()                     0
313
314#endif
315
316static void parse_event(const char *msg, struct uevent *uevent)
317{
318    uevent->action = "";
319    uevent->path = "";
320    uevent->subsystem = "";
321    uevent->firmware = "";
322    uevent->major = -1;
323    uevent->minor = -1;
324
325        /* currently ignoring SEQNUM */
326    while(*msg) {
327        if(!strncmp(msg, "ACTION=", 7)) {
328            msg += 7;
329            uevent->action = msg;
330        } else if(!strncmp(msg, "DEVPATH=", 8)) {
331            msg += 8;
332            uevent->path = msg;
333        } else if(!strncmp(msg, "SUBSYSTEM=", 10)) {
334            msg += 10;
335            uevent->subsystem = msg;
336        } else if(!strncmp(msg, "FIRMWARE=", 9)) {
337            msg += 9;
338            uevent->firmware = msg;
339        } else if(!strncmp(msg, "MAJOR=", 6)) {
340            msg += 6;
341            uevent->major = atoi(msg);
342        } else if(!strncmp(msg, "MINOR=", 6)) {
343            msg += 6;
344            uevent->minor = atoi(msg);
345        }
346
347            /* advance to after the next \0 */
348        while(*msg++)
349            ;
350    }
351
352    log_event_print("event { '%s', '%s', '%s', '%s', %d, %d }\n",
353                    uevent->action, uevent->path, uevent->subsystem,
354                    uevent->firmware, uevent->major, uevent->minor);
355}
356
357static void handle_device_event(struct uevent *uevent)
358{
359    char devpath[96];
360    char *base, *name;
361    int block;
362
363        /* if it's not a /dev device, nothing to do */
364    if((uevent->major < 0) || (uevent->minor < 0))
365        return;
366
367        /* do we have a name? */
368    name = strrchr(uevent->path, '/');
369    if(!name)
370        return;
371    name++;
372
373        /* too-long names would overrun our buffer */
374    if(strlen(name) > 64)
375        return;
376
377        /* are we block or char? where should we live? */
378    if(!strncmp(uevent->subsystem, "block", 5)) {
379        block = 1;
380        base = "/dev/block/";
381        mkdir(base, 0755);
382    } else {
383        block = 0;
384            /* this should probably be configurable somehow */
385        if(!strncmp(uevent->subsystem, "graphics", 8)) {
386            base = "/dev/graphics/";
387            mkdir(base, 0755);
388        } else if (!strncmp(uevent->subsystem, "oncrpc", 6)) {
389            base = "/dev/oncrpc/";
390            mkdir(base, 0755);
391        } else if (!strncmp(uevent->subsystem, "adsp", 4)) {
392            base = "/dev/adsp/";
393            mkdir(base, 0755);
394        } else if (!strncmp(uevent->subsystem, "msm_camera", 10)) {
395            base = "/dev/msm_camera/";
396            mkdir(base, 0755);
397        } else if(!strncmp(uevent->subsystem, "input", 5)) {
398            base = "/dev/input/";
399            mkdir(base, 0755);
400        } else if(!strncmp(uevent->subsystem, "mtd", 3)) {
401            base = "/dev/mtd/";
402            mkdir(base, 0755);
403        } else if(!strncmp(uevent->subsystem, "sound", 5)) {
404            base = "/dev/snd/";
405            mkdir(base, 0755);
406        } else if(!strncmp(uevent->subsystem, "misc", 4) &&
407                    !strncmp(name, "log_", 4)) {
408            base = "/dev/log/";
409            mkdir(base, 0755);
410            name += 4;
411        } else
412            base = "/dev/";
413    }
414
415    snprintf(devpath, sizeof(devpath), "%s%s", base, name);
416
417    if(!strcmp(uevent->action, "add")) {
418        make_device(devpath, block, uevent->major, uevent->minor);
419        return;
420    }
421
422    if(!strcmp(uevent->action, "remove")) {
423        unlink(devpath);
424        return;
425    }
426}
427
428static int load_firmware(int fw_fd, int loading_fd, int data_fd)
429{
430    struct stat st;
431    long len_to_copy;
432    int ret = 0;
433
434    if(fstat(fw_fd, &st) < 0)
435        return -1;
436    len_to_copy = st.st_size;
437
438    write(loading_fd, "1", 1);  /* start transfer */
439
440    while (len_to_copy > 0) {
441        char buf[PAGE_SIZE];
442        ssize_t nr;
443
444        nr = read(fw_fd, buf, sizeof(buf));
445        if(!nr)
446            break;
447        if(nr < 0) {
448            ret = -1;
449            break;
450        }
451
452        len_to_copy -= nr;
453        while (nr > 0) {
454            ssize_t nw = 0;
455
456            nw = write(data_fd, buf + nw, nr);
457            if(nw <= 0) {
458                ret = -1;
459                goto out;
460            }
461            nr -= nw;
462        }
463    }
464
465out:
466    if(!ret)
467        write(loading_fd, "0", 1);  /* successful end of transfer */
468    else
469        write(loading_fd, "-1", 2); /* abort transfer */
470
471    return ret;
472}
473
474static void process_firmware_event(struct uevent *uevent)
475{
476    char *root, *loading, *data, *file;
477    int l, loading_fd, data_fd, fw_fd;
478
479    log_event_print("firmware event { '%s', '%s' }\n",
480                    uevent->path, uevent->firmware);
481
482    l = asprintf(&root, SYSFS_PREFIX"%s/", uevent->path);
483    if (l == -1)
484        return;
485
486    l = asprintf(&loading, "%sloading", root);
487    if (l == -1)
488        goto root_free_out;
489
490    l = asprintf(&data, "%sdata", root);
491    if (l == -1)
492        goto loading_free_out;
493
494    l = asprintf(&file, FIRMWARE_DIR"/%s", uevent->firmware);
495    if (l == -1)
496        goto data_free_out;
497
498    loading_fd = open(loading, O_WRONLY);
499    if(loading_fd < 0)
500        goto file_free_out;
501
502    data_fd = open(data, O_WRONLY);
503    if(data_fd < 0)
504        goto loading_close_out;
505
506    fw_fd = open(file, O_RDONLY);
507    if(fw_fd < 0)
508        goto data_close_out;
509
510    if(!load_firmware(fw_fd, loading_fd, data_fd))
511        log_event_print("firmware copy success { '%s', '%s' }\n", root, file);
512    else
513        log_event_print("firmware copy failure { '%s', '%s' }\n", root, file);
514
515    close(fw_fd);
516data_close_out:
517    close(data_fd);
518loading_close_out:
519    close(loading_fd);
520file_free_out:
521    free(file);
522data_free_out:
523    free(data);
524loading_free_out:
525    free(loading);
526root_free_out:
527    free(root);
528}
529
530static void handle_firmware_event(struct uevent *uevent)
531{
532    pid_t pid;
533
534    if(strcmp(uevent->subsystem, "firmware"))
535        return;
536
537    if(strcmp(uevent->action, "add"))
538        return;
539
540    /* we fork, to avoid making large memory allocations in init proper */
541    pid = fork();
542    if (!pid) {
543        process_firmware_event(uevent);
544        exit(EXIT_SUCCESS);
545    }
546}
547
548#define UEVENT_MSG_LEN  1024
549void handle_device_fd(int fd)
550{
551    char msg[UEVENT_MSG_LEN+2];
552    int n;
553
554    while((n = recv(fd, msg, UEVENT_MSG_LEN, 0)) > 0) {
555        struct uevent uevent;
556
557        if(n == UEVENT_MSG_LEN)   /* overflow -- discard */
558            continue;
559
560        msg[n] = '\0';
561        msg[n+1] = '\0';
562
563        parse_event(msg, &uevent);
564
565        handle_device_event(&uevent);
566        handle_firmware_event(&uevent);
567    }
568}
569
570/* Coldboot walks parts of the /sys tree and pokes the uevent files
571** to cause the kernel to regenerate device add events that happened
572** before init's device manager was started
573**
574** We drain any pending events from the netlink socket every time
575** we poke another uevent file to make sure we don't overrun the
576** socket's buffer.
577*/
578
579static void do_coldboot(int event_fd, DIR *d)
580{
581    struct dirent *de;
582    int dfd, fd;
583
584    dfd = dirfd(d);
585
586    fd = openat(dfd, "uevent", O_WRONLY);
587    if(fd >= 0) {
588        write(fd, "add\n", 4);
589        close(fd);
590        handle_device_fd(event_fd);
591    }
592
593    while((de = readdir(d))) {
594        DIR *d2;
595
596        if(de->d_type != DT_DIR || de->d_name[0] == '.')
597            continue;
598
599        fd = openat(dfd, de->d_name, O_RDONLY | O_DIRECTORY);
600        if(fd < 0)
601            continue;
602
603        d2 = fdopendir(fd);
604        if(d2 == 0)
605            close(fd);
606        else {
607            do_coldboot(event_fd, d2);
608            closedir(d2);
609        }
610    }
611}
612
613static void coldboot(int event_fd, const char *path)
614{
615    DIR *d = opendir(path);
616    if(d) {
617        do_coldboot(event_fd, d);
618        closedir(d);
619    }
620}
621
622int device_init(void)
623{
624    suseconds_t t0, t1;
625    int fd;
626
627    fd = open_uevent_socket();
628    if(fd < 0)
629        return -1;
630
631    fcntl(fd, F_SETFD, FD_CLOEXEC);
632    fcntl(fd, F_SETFL, O_NONBLOCK);
633
634    t0 = get_usecs();
635    coldboot(fd, "/sys/class");
636    coldboot(fd, "/sys/block");
637    coldboot(fd, "/sys/devices");
638    t1 = get_usecs();
639
640    log_event_print("coldboot %ld uS\n", ((long) (t1 - t0)));
641
642    return fd;
643}
644