Coverage Report

Created: 2026-11-20 08:13

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