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