2 * IOVA tree implementation based on GTree.
4 * Copyright 2018 Red Hat, Inc.
7 * Peter Xu <peterx@redhat.com>
9 * This work is licensed under the terms of the GNU GPL, version 2 or later.
12 #include "qemu/osdep.h"
13 #include "qemu/iova-tree.h"
19 static int iova_tree_compare(gconstpointer a
, gconstpointer b
, gpointer data
)
21 const DMAMap
*m1
= a
, *m2
= b
;
23 if (m1
->iova
> m2
->iova
+ m2
->size
) {
27 if (m1
->iova
+ m1
->size
< m2
->iova
) {
35 IOVATree
*iova_tree_new(void)
37 IOVATree
*iova_tree
= g_new0(IOVATree
, 1);
39 /* We don't have values actually, no need to free */
40 iova_tree
->tree
= g_tree_new_full(iova_tree_compare
, NULL
, g_free
, NULL
);
45 DMAMap
*iova_tree_find(IOVATree
*tree
, DMAMap
*map
)
47 return g_tree_lookup(tree
->tree
, map
);
50 DMAMap
*iova_tree_find_address(IOVATree
*tree
, hwaddr iova
)
52 DMAMap map
= { .iova
= iova
, .size
= 0 };
54 return iova_tree_find(tree
, &map
);
57 static inline void iova_tree_insert_internal(GTree
*gtree
, DMAMap
*range
)
59 /* Key and value are sharing the same range data */
60 g_tree_insert(gtree
, range
, range
);
63 int iova_tree_insert(IOVATree
*tree
, DMAMap
*map
)
67 if (map
->iova
+ map
->size
< map
->iova
|| map
->perm
== IOMMU_NONE
) {
68 return IOVA_ERR_INVALID
;
71 /* We don't allow to insert range that overlaps with existings */
72 if (iova_tree_find(tree
, map
)) {
73 return IOVA_ERR_OVERLAP
;
76 new = g_new0(DMAMap
, 1);
77 memcpy(new, map
, sizeof(*new));
78 iova_tree_insert_internal(tree
->tree
, new);
83 static gboolean
iova_tree_traverse(gpointer key
, gpointer value
,
86 iova_tree_iterator iterator
= data
;
89 g_assert(key
== value
);
94 void iova_tree_foreach(IOVATree
*tree
, iova_tree_iterator iterator
)
96 g_tree_foreach(tree
->tree
, iova_tree_traverse
, iterator
);
99 int iova_tree_remove(IOVATree
*tree
, DMAMap
*map
)
103 while ((overlap
= iova_tree_find(tree
, map
))) {
104 g_tree_remove(tree
->tree
, overlap
);
110 void iova_tree_destroy(IOVATree
*tree
)
112 g_tree_destroy(tree
->tree
);