qemu/softmmu/device_tree.c
<<
>>
Prefs
   1/*
   2 * Functions to help device tree manipulation using libfdt.
   3 * It also provides functions to read entries from device tree proc
   4 * interface.
   5 *
   6 * Copyright 2008 IBM Corporation.
   7 * Authors: Jerone Young <jyoung5@us.ibm.com>
   8 *          Hollis Blanchard <hollisb@us.ibm.com>
   9 *
  10 * This work is licensed under the GNU GPL license version 2 or later.
  11 *
  12 */
  13
  14#include "qemu/osdep.h"
  15
  16#ifdef CONFIG_LINUX
  17#include <dirent.h>
  18#endif
  19
  20#include "qapi/error.h"
  21#include "qemu/error-report.h"
  22#include "qemu/option.h"
  23#include "qemu/bswap.h"
  24#include "qemu/cutils.h"
  25#include "sysemu/device_tree.h"
  26#include "hw/loader.h"
  27#include "hw/boards.h"
  28#include "qemu/config-file.h"
  29
  30#include <libfdt.h>
  31
  32#define FDT_MAX_SIZE  0x100000
  33
  34void *create_device_tree(int *sizep)
  35{
  36    void *fdt;
  37    int ret;
  38
  39    *sizep = FDT_MAX_SIZE;
  40    fdt = g_malloc0(FDT_MAX_SIZE);
  41    ret = fdt_create(fdt, FDT_MAX_SIZE);
  42    if (ret < 0) {
  43        goto fail;
  44    }
  45    ret = fdt_finish_reservemap(fdt);
  46    if (ret < 0) {
  47        goto fail;
  48    }
  49    ret = fdt_begin_node(fdt, "");
  50    if (ret < 0) {
  51        goto fail;
  52    }
  53    ret = fdt_end_node(fdt);
  54    if (ret < 0) {
  55        goto fail;
  56    }
  57    ret = fdt_finish(fdt);
  58    if (ret < 0) {
  59        goto fail;
  60    }
  61    ret = fdt_open_into(fdt, fdt, *sizep);
  62    if (ret) {
  63        error_report("%s: Unable to copy device tree into memory: %s",
  64                     __func__, fdt_strerror(ret));
  65        exit(1);
  66    }
  67
  68    return fdt;
  69fail:
  70    error_report("%s Couldn't create dt: %s", __func__, fdt_strerror(ret));
  71    exit(1);
  72}
  73
  74void *load_device_tree(const char *filename_path, int *sizep)
  75{
  76    int dt_size;
  77    int dt_file_load_size;
  78    int ret;
  79    void *fdt = NULL;
  80
  81    *sizep = 0;
  82    dt_size = get_image_size(filename_path);
  83    if (dt_size < 0) {
  84        error_report("Unable to get size of device tree file '%s'",
  85                     filename_path);
  86        goto fail;
  87    }
  88    if (dt_size > INT_MAX / 2 - 10000) {
  89        error_report("Device tree file '%s' is too large", filename_path);
  90        goto fail;
  91    }
  92
  93    /* Expand to 2x size to give enough room for manipulation.  */
  94    dt_size += 10000;
  95    dt_size *= 2;
  96    /* First allocate space in qemu for device tree */
  97    fdt = g_malloc0(dt_size);
  98
  99    dt_file_load_size = load_image_size(filename_path, fdt, dt_size);
 100    if (dt_file_load_size < 0) {
 101        error_report("Unable to open device tree file '%s'",
 102                     filename_path);
 103        goto fail;
 104    }
 105
 106    ret = fdt_open_into(fdt, fdt, dt_size);
 107    if (ret) {
 108        error_report("%s: Unable to copy device tree into memory: %s",
 109                     __func__, fdt_strerror(ret));
 110        goto fail;
 111    }
 112
 113    /* Check sanity of device tree */
 114    if (fdt_check_header(fdt)) {
 115        error_report("Device tree file loaded into memory is invalid: %s",
 116                     filename_path);
 117        goto fail;
 118    }
 119    *sizep = dt_size;
 120    return fdt;
 121
 122fail:
 123    g_free(fdt);
 124    return NULL;
 125}
 126
 127#ifdef CONFIG_LINUX
 128
 129#define SYSFS_DT_BASEDIR "/proc/device-tree"
 130
 131/**
 132 * read_fstree: this function is inspired from dtc read_fstree
 133 * @fdt: preallocated fdt blob buffer, to be populated
 134 * @dirname: directory to scan under SYSFS_DT_BASEDIR
 135 * the search is recursive and the tree is searched down to the
 136 * leaves (property files).
 137 *
 138 * the function asserts in case of error
 139 */
 140static void read_fstree(void *fdt, const char *dirname)
 141{
 142    DIR *d;
 143    struct dirent *de;
 144    struct stat st;
 145    const char *root_dir = SYSFS_DT_BASEDIR;
 146    const char *parent_node;
 147
 148    if (strstr(dirname, root_dir) != dirname) {
 149        error_report("%s: %s must be searched within %s",
 150                     __func__, dirname, root_dir);
 151        exit(1);
 152    }
 153    parent_node = &dirname[strlen(SYSFS_DT_BASEDIR)];
 154
 155    d = opendir(dirname);
 156    if (!d) {
 157        error_report("%s cannot open %s", __func__, dirname);
 158        exit(1);
 159    }
 160
 161    while ((de = readdir(d)) != NULL) {
 162        char *tmpnam;
 163
 164        if (!g_strcmp0(de->d_name, ".")
 165            || !g_strcmp0(de->d_name, "..")) {
 166            continue;
 167        }
 168
 169        tmpnam = g_strdup_printf("%s/%s", dirname, de->d_name);
 170
 171        if (lstat(tmpnam, &st) < 0) {
 172            error_report("%s cannot lstat %s", __func__, tmpnam);
 173            exit(1);
 174        }
 175
 176        if (S_ISREG(st.st_mode)) {
 177            gchar *val;
 178            gsize len;
 179
 180            if (!g_file_get_contents(tmpnam, &val, &len, NULL)) {
 181                error_report("%s not able to extract info from %s",
 182                             __func__, tmpnam);
 183                exit(1);
 184            }
 185
 186            if (strlen(parent_node) > 0) {
 187                qemu_fdt_setprop(fdt, parent_node,
 188                                 de->d_name, val, len);
 189            } else {
 190                qemu_fdt_setprop(fdt, "/", de->d_name, val, len);
 191            }
 192            g_free(val);
 193        } else if (S_ISDIR(st.st_mode)) {
 194            char *node_name;
 195
 196            node_name = g_strdup_printf("%s/%s",
 197                                        parent_node, de->d_name);
 198            qemu_fdt_add_subnode(fdt, node_name);
 199            g_free(node_name);
 200            read_fstree(fdt, tmpnam);
 201        }
 202
 203        g_free(tmpnam);
 204    }
 205
 206    closedir(d);
 207}
 208
 209/* load_device_tree_from_sysfs: extract the dt blob from host sysfs */
 210void *load_device_tree_from_sysfs(void)
 211{
 212    void *host_fdt;
 213    int host_fdt_size;
 214
 215    host_fdt = create_device_tree(&host_fdt_size);
 216    read_fstree(host_fdt, SYSFS_DT_BASEDIR);
 217    if (fdt_check_header(host_fdt)) {
 218        error_report("%s host device tree extracted into memory is invalid",
 219                     __func__);
 220        exit(1);
 221    }
 222    return host_fdt;
 223}
 224
 225#endif /* CONFIG_LINUX */
 226
 227static int findnode_nofail(void *fdt, const char *node_path)
 228{
 229    int offset;
 230
 231    offset = fdt_path_offset(fdt, node_path);
 232    if (offset < 0) {
 233        error_report("%s Couldn't find node %s: %s", __func__, node_path,
 234                     fdt_strerror(offset));
 235        exit(1);
 236    }
 237
 238    return offset;
 239}
 240
 241char **qemu_fdt_node_unit_path(void *fdt, const char *name, Error **errp)
 242{
 243    char *prefix =  g_strdup_printf("%s@", name);
 244    unsigned int path_len = 16, n = 0;
 245    GSList *path_list = NULL, *iter;
 246    const char *iter_name;
 247    int offset, len, ret;
 248    char **path_array;
 249
 250    offset = fdt_next_node(fdt, -1, NULL);
 251
 252    while (offset >= 0) {
 253        iter_name = fdt_get_name(fdt, offset, &len);
 254        if (!iter_name) {
 255            offset = len;
 256            break;
 257        }
 258        if (!strcmp(iter_name, name) || g_str_has_prefix(iter_name, prefix)) {
 259            char *path;
 260
 261            path = g_malloc(path_len);
 262            while ((ret = fdt_get_path(fdt, offset, path, path_len))
 263                  == -FDT_ERR_NOSPACE) {
 264                path_len += 16;
 265                path = g_realloc(path, path_len);
 266            }
 267            path_list = g_slist_prepend(path_list, path);
 268            n++;
 269        }
 270        offset = fdt_next_node(fdt, offset, NULL);
 271    }
 272    g_free(prefix);
 273
 274    if (offset < 0 && offset != -FDT_ERR_NOTFOUND) {
 275        error_setg(errp, "%s: abort parsing dt for %s node units: %s",
 276                   __func__, name, fdt_strerror(offset));
 277        for (iter = path_list; iter; iter = iter->next) {
 278            g_free(iter->data);
 279        }
 280        g_slist_free(path_list);
 281        return NULL;
 282    }
 283
 284    path_array = g_new(char *, n + 1);
 285    path_array[n--] = NULL;
 286
 287    for (iter = path_list; iter; iter = iter->next) {
 288        path_array[n--] = iter->data;
 289    }
 290
 291    g_slist_free(path_list);
 292
 293    return path_array;
 294}
 295
 296char **qemu_fdt_node_path(void *fdt, const char *name, const char *compat,
 297                          Error **errp)
 298{
 299    int offset, len, ret;
 300    const char *iter_name;
 301    unsigned int path_len = 16, n = 0;
 302    GSList *path_list = NULL, *iter;
 303    char **path_array;
 304
 305    offset = fdt_node_offset_by_compatible(fdt, -1, compat);
 306
 307    while (offset >= 0) {
 308        iter_name = fdt_get_name(fdt, offset, &len);
 309        if (!iter_name) {
 310            offset = len;
 311            break;
 312        }
 313        if (!name || !strcmp(iter_name, name)) {
 314            char *path;
 315
 316            path = g_malloc(path_len);
 317            while ((ret = fdt_get_path(fdt, offset, path, path_len))
 318                  == -FDT_ERR_NOSPACE) {
 319                path_len += 16;
 320                path = g_realloc(path, path_len);
 321            }
 322            path_list = g_slist_prepend(path_list, path);
 323            n++;
 324        }
 325        offset = fdt_node_offset_by_compatible(fdt, offset, compat);
 326    }
 327
 328    if (offset < 0 && offset != -FDT_ERR_NOTFOUND) {
 329        error_setg(errp, "%s: abort parsing dt for %s/%s: %s",
 330                   __func__, name, compat, fdt_strerror(offset));
 331        for (iter = path_list; iter; iter = iter->next) {
 332            g_free(iter->data);
 333        }
 334        g_slist_free(path_list);
 335        return NULL;
 336    }
 337
 338    path_array = g_new(char *, n + 1);
 339    path_array[n--] = NULL;
 340
 341    for (iter = path_list; iter; iter = iter->next) {
 342        path_array[n--] = iter->data;
 343    }
 344
 345    g_slist_free(path_list);
 346
 347    return path_array;
 348}
 349
 350int qemu_fdt_setprop(void *fdt, const char *node_path,
 351                     const char *property, const void *val, int size)
 352{
 353    int r;
 354
 355    r = fdt_setprop(fdt, findnode_nofail(fdt, node_path), property, val, size);
 356    if (r < 0) {
 357        error_report("%s: Couldn't set %s/%s: %s", __func__, node_path,
 358                     property, fdt_strerror(r));
 359        exit(1);
 360    }
 361
 362    return r;
 363}
 364
 365int qemu_fdt_setprop_cell(void *fdt, const char *node_path,
 366                          const char *property, uint32_t val)
 367{
 368    int r;
 369
 370    r = fdt_setprop_cell(fdt, findnode_nofail(fdt, node_path), property, val);
 371    if (r < 0) {
 372        error_report("%s: Couldn't set %s/%s = %#08x: %s", __func__,
 373                     node_path, property, val, fdt_strerror(r));
 374        exit(1);
 375    }
 376
 377    return r;
 378}
 379
 380int qemu_fdt_setprop_u64(void *fdt, const char *node_path,
 381                         const char *property, uint64_t val)
 382{
 383    val = cpu_to_be64(val);
 384    return qemu_fdt_setprop(fdt, node_path, property, &val, sizeof(val));
 385}
 386
 387int qemu_fdt_setprop_string(void *fdt, const char *node_path,
 388                            const char *property, const char *string)
 389{
 390    int r;
 391
 392    r = fdt_setprop_string(fdt, findnode_nofail(fdt, node_path), property, string);
 393    if (r < 0) {
 394        error_report("%s: Couldn't set %s/%s = %s: %s", __func__,
 395                     node_path, property, string, fdt_strerror(r));
 396        exit(1);
 397    }
 398
 399    return r;
 400}
 401
 402/*
 403 * libfdt doesn't allow us to add string arrays directly but they are
 404 * test a series of null terminated strings with a length. We build
 405 * the string up here so we can calculate the final length.
 406 */
 407int qemu_fdt_setprop_string_array(void *fdt, const char *node_path,
 408                                  const char *prop, char **array, int len)
 409{
 410    int ret, i, total_len = 0;
 411    char *str, *p;
 412    for (i = 0; i < len; i++) {
 413        total_len += strlen(array[i]) + 1;
 414    }
 415    p = str = g_malloc0(total_len);
 416    for (i = 0; i < len; i++) {
 417        int len = strlen(array[i]) + 1;
 418        pstrcpy(p, len, array[i]);
 419        p += len;
 420    }
 421
 422    ret = qemu_fdt_setprop(fdt, node_path, prop, str, total_len);
 423    g_free(str);
 424    return ret;
 425}
 426
 427const void *qemu_fdt_getprop(void *fdt, const char *node_path,
 428                             const char *property, int *lenp, Error **errp)
 429{
 430    int len;
 431    const void *r;
 432
 433    if (!lenp) {
 434        lenp = &len;
 435    }
 436    r = fdt_getprop(fdt, findnode_nofail(fdt, node_path), property, lenp);
 437    if (!r) {
 438        error_setg(errp, "%s: Couldn't get %s/%s: %s", __func__,
 439                  node_path, property, fdt_strerror(*lenp));
 440    }
 441    return r;
 442}
 443
 444uint32_t qemu_fdt_getprop_cell(void *fdt, const char *node_path,
 445                               const char *property, int *lenp, Error **errp)
 446{
 447    int len;
 448    const uint32_t *p;
 449
 450    if (!lenp) {
 451        lenp = &len;
 452    }
 453    p = qemu_fdt_getprop(fdt, node_path, property, lenp, errp);
 454    if (!p) {
 455        return 0;
 456    } else if (*lenp != 4) {
 457        error_setg(errp, "%s: %s/%s not 4 bytes long (not a cell?)",
 458                   __func__, node_path, property);
 459        *lenp = -EINVAL;
 460        return 0;
 461    }
 462    return be32_to_cpu(*p);
 463}
 464
 465uint32_t qemu_fdt_get_phandle(void *fdt, const char *path)
 466{
 467    uint32_t r;
 468
 469    r = fdt_get_phandle(fdt, findnode_nofail(fdt, path));
 470    if (r == 0) {
 471        error_report("%s: Couldn't get phandle for %s: %s", __func__,
 472                     path, fdt_strerror(r));
 473        exit(1);
 474    }
 475
 476    return r;
 477}
 478
 479int qemu_fdt_setprop_phandle(void *fdt, const char *node_path,
 480                             const char *property,
 481                             const char *target_node_path)
 482{
 483    uint32_t phandle = qemu_fdt_get_phandle(fdt, target_node_path);
 484    return qemu_fdt_setprop_cell(fdt, node_path, property, phandle);
 485}
 486
 487uint32_t qemu_fdt_alloc_phandle(void *fdt)
 488{
 489    static int phandle = 0x0;
 490
 491    /*
 492     * We need to find out if the user gave us special instruction at
 493     * which phandle id to start allocating phandles.
 494     */
 495    if (!phandle) {
 496        phandle = machine_phandle_start(current_machine);
 497    }
 498
 499    if (!phandle) {
 500        /*
 501         * None or invalid phandle given on the command line, so fall back to
 502         * default starting point.
 503         */
 504        phandle = 0x8000;
 505    }
 506
 507    return phandle++;
 508}
 509
 510int qemu_fdt_nop_node(void *fdt, const char *node_path)
 511{
 512    int r;
 513
 514    r = fdt_nop_node(fdt, findnode_nofail(fdt, node_path));
 515    if (r < 0) {
 516        error_report("%s: Couldn't nop node %s: %s", __func__, node_path,
 517                     fdt_strerror(r));
 518        exit(1);
 519    }
 520
 521    return r;
 522}
 523
 524int qemu_fdt_add_subnode(void *fdt, const char *name)
 525{
 526    char *dupname = g_strdup(name);
 527    char *basename = strrchr(dupname, '/');
 528    int retval;
 529    int parent = 0;
 530
 531    if (!basename) {
 532        g_free(dupname);
 533        return -1;
 534    }
 535
 536    basename[0] = '\0';
 537    basename++;
 538
 539    if (dupname[0]) {
 540        parent = findnode_nofail(fdt, dupname);
 541    }
 542
 543    retval = fdt_add_subnode(fdt, parent, basename);
 544    if (retval < 0) {
 545        error_report("%s: Failed to create subnode %s: %s",
 546                     __func__, name, fdt_strerror(retval));
 547        exit(1);
 548    }
 549
 550    g_free(dupname);
 551    return retval;
 552}
 553
 554/*
 555 * qemu_fdt_add_path: Like qemu_fdt_add_subnode(), but will add
 556 * all missing subnodes from the given path.
 557 */
 558int qemu_fdt_add_path(void *fdt, const char *path)
 559{
 560    const char *name;
 561    int namelen, retval;
 562    int parent = 0;
 563
 564    if (path[0] != '/') {
 565        return -1;
 566    }
 567
 568    do {
 569        name = path + 1;
 570        path = strchr(name, '/');
 571        namelen = path != NULL ? path - name : strlen(name);
 572
 573        retval = fdt_subnode_offset_namelen(fdt, parent, name, namelen);
 574        if (retval < 0 && retval != -FDT_ERR_NOTFOUND) {
 575            error_report("%s: Unexpected error in finding subnode %.*s: %s",
 576                         __func__, namelen, name, fdt_strerror(retval));
 577            exit(1);
 578        } else if (retval == -FDT_ERR_NOTFOUND) {
 579            retval = fdt_add_subnode_namelen(fdt, parent, name, namelen);
 580            if (retval < 0) {
 581                error_report("%s: Failed to create subnode %.*s: %s",
 582                             __func__, namelen, name, fdt_strerror(retval));
 583                exit(1);
 584            }
 585        }
 586
 587        parent = retval;
 588    } while (path);
 589
 590    return retval;
 591}
 592
 593void qemu_fdt_dumpdtb(void *fdt, int size)
 594{
 595    const char *dumpdtb = current_machine->dumpdtb;
 596
 597    if (dumpdtb) {
 598        /* Dump the dtb to a file and quit */
 599        if (g_file_set_contents(dumpdtb, fdt, size, NULL)) {
 600            info_report("dtb dumped to %s. Exiting.", dumpdtb);
 601            exit(0);
 602        }
 603        error_report("%s: Failed dumping dtb to %s", __func__, dumpdtb);
 604        exit(1);
 605    }
 606}
 607
 608int qemu_fdt_setprop_sized_cells_from_array(void *fdt,
 609                                            const char *node_path,
 610                                            const char *property,
 611                                            int numvalues,
 612                                            uint64_t *values)
 613{
 614    uint32_t *propcells;
 615    uint64_t value;
 616    int cellnum, vnum, ncells;
 617    uint32_t hival;
 618    int ret;
 619
 620    propcells = g_new0(uint32_t, numvalues * 2);
 621
 622    cellnum = 0;
 623    for (vnum = 0; vnum < numvalues; vnum++) {
 624        ncells = values[vnum * 2];
 625        if (ncells != 1 && ncells != 2) {
 626            ret = -1;
 627            goto out;
 628        }
 629        value = values[vnum * 2 + 1];
 630        hival = cpu_to_be32(value >> 32);
 631        if (ncells > 1) {
 632            propcells[cellnum++] = hival;
 633        } else if (hival != 0) {
 634            ret = -1;
 635            goto out;
 636        }
 637        propcells[cellnum++] = cpu_to_be32(value);
 638    }
 639
 640    ret = qemu_fdt_setprop(fdt, node_path, property, propcells,
 641                           cellnum * sizeof(uint32_t));
 642out:
 643    g_free(propcells);
 644    return ret;
 645}
 646