1/*
2 * Copyright 2019, Data61, CSIRO (ABN 41 687 119 230)
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7#include <stdlib.h>
8#include <string.h>
9
10#include <sel4vm/guest_vm.h>
11#include <sel4vmmplatsupport/device.h>
12
13int device_list_init(device_list_t *list)
14{
15    list->num_devices = 0;
16    list->devices = NULL;
17    return 0;
18}
19
20static int dev_cmp(const void *a, const void *b)
21{
22    return ((const struct device *)a)->pstart - ((const struct device *)b)->pstart;
23}
24
25int add_device(device_list_t *list, const struct device *d)
26{
27    if (!list || !d) {
28        return -1;
29    }
30
31    struct device *updated_devices = realloc(list->devices, sizeof(struct device) * (list->num_devices + 1));
32    if (!updated_devices) {
33        return -1;
34    }
35    list->devices = updated_devices;
36    memcpy(&list->devices[list->num_devices++], d, sizeof(struct device));
37    qsort(list->devices, list->num_devices, sizeof(struct device), dev_cmp);
38    return 0;
39}
40
41struct device *
42find_device_by_pa(device_list_t *dev_list, uintptr_t addr)
43{
44    struct device *dev = NULL;
45    for (int i = 0; i < dev_list->num_devices; i++) {
46        struct device *curr_dev = &dev_list->devices[i];
47        if (addr < curr_dev->pstart) {
48            break;
49        }
50
51        if (addr < curr_dev->pstart + curr_dev->size) {
52            /* Found a match */
53            dev = curr_dev;
54            break;
55        }
56    }
57    return dev;
58}
59