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