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