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