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