summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/include/memrange.h15
-rw-r--r--src/lib/memrange.c55
2 files changed, 70 insertions, 0 deletions
diff --git a/src/include/memrange.h b/src/include/memrange.h
index 0d20236d61..f8fa033cee 100644
--- a/src/include/memrange.h
+++ b/src/include/memrange.h
@@ -16,6 +16,7 @@
#define MEMRANGE_H_
#include <device/resource.h>
+#include <stdbool.h>
/* A memranges structure consists of a list of range_entry(s). The structure
* is exposed so that a memranges can be used on the stack if needed. */
@@ -166,4 +167,18 @@ void memranges_update_tag(struct memranges *ranges, unsigned long old_tag,
/* Returns next entry after the provided entry. NULL if r is last. */
struct range_entry *memranges_next_entry(struct memranges *ranges,
const struct range_entry *r);
+
+/* Steals memory from the available list in given ranges as per the constraints:
+ * limit = Upper bound for the memory range to steal.
+ * size = Requested size for the stolen memory.
+ * align = Alignment requirements for the starting address of the stolen memory.
+ * (Alignment must be a power of 2).
+ * tag = Use a range that matches the given tag.
+ *
+ * If the constraints can be satisfied, this function creates a hole in the memrange,
+ * writes the base address of that hole to stolen_base and returns true. Otherwise it returns
+ * false. */
+bool memranges_steal(struct memranges *ranges, resource_t limit, resource_t size, size_t align,
+ unsigned long tag, resource_t *stolen_base);
+
#endif /* MEMRANGE_H_ */
diff --git a/src/lib/memrange.c b/src/lib/memrange.c
index 21fff003a1..b9c09e8782 100644
--- a/src/lib/memrange.c
+++ b/src/lib/memrange.c
@@ -391,3 +391,58 @@ struct range_entry *memranges_next_entry(struct memranges *ranges,
{
return r->next;
}
+
+/* Find a range entry that satisfies the given constraints to fit a hole that matches the
+ * required alignment, is big enough, does not exceed the limit and has a matching tag. */
+static const struct range_entry *memranges_find_entry(struct memranges *ranges,
+ resource_t limit, resource_t size,
+ size_t align, unsigned long tag)
+{
+ const struct range_entry *r;
+ resource_t base, end;
+
+ if (size == 0)
+ return NULL;
+
+ if (!IS_POWER_OF_2(align))
+ return NULL;
+
+ if (!IS_ALIGNED(align, ranges->align))
+ return NULL;
+
+ memranges_each_entry(r, ranges) {
+
+ if (r->tag != tag)
+ continue;
+
+ base = ALIGN_UP(r->begin, align);
+ end = base + size - 1;
+
+ if (end > r->end)
+ continue;
+
+ if (end > limit)
+ continue;
+
+ return r;
+ }
+
+ return NULL;
+}
+
+bool memranges_steal(struct memranges *ranges, resource_t limit, resource_t size, size_t align,
+ unsigned long tag, resource_t *stolen_base)
+{
+ resource_t base;
+ const struct range_entry *r = memranges_find_entry(ranges, limit, size, align, tag);
+
+ if (r == NULL)
+ return false;
+
+ base = ALIGN_UP(r->begin, align);
+
+ memranges_create_hole(ranges, base, size);
+ *stolen_base = base;
+
+ return true;
+}