Home | History | Annotate | Line # | Download | only in drm
drm_mm.c revision 1.18
      1 /*	$NetBSD: drm_mm.c,v 1.18 2022/02/14 13:22:30 riastradh Exp $	*/
      2 
      3 /**************************************************************************
      4  *
      5  * Copyright 2006 Tungsten Graphics, Inc., Bismarck, ND., USA.
      6  * Copyright 2016 Intel Corporation
      7  * All Rights Reserved.
      8  *
      9  * Permission is hereby granted, free of charge, to any person obtaining a
     10  * copy of this software and associated documentation files (the
     11  * "Software"), to deal in the Software without restriction, including
     12  * without limitation the rights to use, copy, modify, merge, publish,
     13  * distribute, sub license, and/or sell copies of the Software, and to
     14  * permit persons to whom the Software is furnished to do so, subject to
     15  * the following conditions:
     16  *
     17  * The above copyright notice and this permission notice (including the
     18  * next paragraph) shall be included in all copies or substantial portions
     19  * of the Software.
     20  *
     21  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     22  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     23  * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
     24  * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
     25  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
     26  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
     27  * USE OR OTHER DEALINGS IN THE SOFTWARE.
     28  *
     29  *
     30  **************************************************************************/
     31 
     32 /*
     33  * Generic simple memory manager implementation. Intended to be used as a base
     34  * class implementation for more advanced memory managers.
     35  *
     36  * Note that the algorithm used is quite simple and there might be substantial
     37  * performance gains if a smarter free list is implemented. Currently it is
     38  * just an unordered stack of free regions. This could easily be improved if
     39  * an RB-tree is used instead. At least if we expect heavy fragmentation.
     40  *
     41  * Aligned allocations can also see improvement.
     42  *
     43  * Authors:
     44  * Thomas Hellstrm <thomas-at-tungstengraphics-dot-com>
     45  */
     46 
     47 #include <sys/cdefs.h>
     48 __KERNEL_RCSID(0, "$NetBSD: drm_mm.c,v 1.18 2022/02/14 13:22:30 riastradh Exp $");
     49 
     50 #include <linux/export.h>
     51 #include <linux/interval_tree_generic.h>
     52 #include <linux/seq_file.h>
     53 #include <linux/slab.h>
     54 #include <linux/stacktrace.h>
     55 
     56 #include <drm/drm_mm.h>
     57 
     58 /**
     59  * DOC: Overview
     60  *
     61  * drm_mm provides a simple range allocator. The drivers are free to use the
     62  * resource allocator from the linux core if it suits them, the upside of drm_mm
     63  * is that it's in the DRM core. Which means that it's easier to extend for
     64  * some of the crazier special purpose needs of gpus.
     65  *
     66  * The main data struct is &drm_mm, allocations are tracked in &drm_mm_node.
     67  * Drivers are free to embed either of them into their own suitable
     68  * datastructures. drm_mm itself will not do any memory allocations of its own,
     69  * so if drivers choose not to embed nodes they need to still allocate them
     70  * themselves.
     71  *
     72  * The range allocator also supports reservation of preallocated blocks. This is
     73  * useful for taking over initial mode setting configurations from the firmware,
     74  * where an object needs to be created which exactly matches the firmware's
     75  * scanout target. As long as the range is still free it can be inserted anytime
     76  * after the allocator is initialized, which helps with avoiding looped
     77  * dependencies in the driver load sequence.
     78  *
     79  * drm_mm maintains a stack of most recently freed holes, which of all
     80  * simplistic datastructures seems to be a fairly decent approach to clustering
     81  * allocations and avoiding too much fragmentation. This means free space
     82  * searches are O(num_holes). Given that all the fancy features drm_mm supports
     83  * something better would be fairly complex and since gfx thrashing is a fairly
     84  * steep cliff not a real concern. Removing a node again is O(1).
     85  *
     86  * drm_mm supports a few features: Alignment and range restrictions can be
     87  * supplied. Furthermore every &drm_mm_node has a color value (which is just an
     88  * opaque unsigned long) which in conjunction with a driver callback can be used
     89  * to implement sophisticated placement restrictions. The i915 DRM driver uses
     90  * this to implement guard pages between incompatible caching domains in the
     91  * graphics TT.
     92  *
     93  * Two behaviors are supported for searching and allocating: bottom-up and
     94  * top-down. The default is bottom-up. Top-down allocation can be used if the
     95  * memory area has different restrictions, or just to reduce fragmentation.
     96  *
     97  * Finally iteration helpers to walk all nodes and all holes are provided as are
     98  * some basic allocator dumpers for debugging.
     99  *
    100  * Note that this range allocator is not thread-safe, drivers need to protect
    101  * modifications with their own locking. The idea behind this is that for a full
    102  * memory manager additional data needs to be protected anyway, hence internal
    103  * locking would be fully redundant.
    104  */
    105 
    106 #ifdef CONFIG_DRM_DEBUG_MM
    107 #include <linux/stackdepot.h>
    108 
    109 #define STACKDEPTH 32
    110 #define BUFSZ 4096
    111 
    112 static noinline void save_stack(struct drm_mm_node *node)
    113 {
    114 	unsigned long entries[STACKDEPTH];
    115 	unsigned int n;
    116 
    117 	n = stack_trace_save(entries, ARRAY_SIZE(entries), 1);
    118 
    119 	/* May be called under spinlock, so avoid sleeping */
    120 	node->stack = stack_depot_save(entries, n, GFP_NOWAIT);
    121 }
    122 
    123 static void show_leaks(struct drm_mm *mm)
    124 {
    125 	struct drm_mm_node *node;
    126 	unsigned long *entries;
    127 	unsigned int nr_entries;
    128 	char *buf;
    129 
    130 	buf = kmalloc(BUFSZ, GFP_KERNEL);
    131 	if (!buf)
    132 		return;
    133 
    134 	list_for_each_entry(node, drm_mm_nodes(mm), node_list) {
    135 		if (!node->stack) {
    136 			DRM_ERROR("node [%08"PRIx64" + %08"PRIx64"]: unknown owner\n",
    137 				  node->start, node->size);
    138 			continue;
    139 		}
    140 
    141 		nr_entries = stack_depot_fetch(node->stack, &entries);
    142 		stack_trace_snprint(buf, BUFSZ, entries, nr_entries, 0);
    143 		DRM_ERROR("node [%08"PRIx64" + %08"PRIx64"]: inserted at\n%s",
    144 			  node->start, node->size, buf);
    145 	}
    146 
    147 	kfree(buf);
    148 }
    149 
    150 #undef STACKDEPTH
    151 #undef BUFSZ
    152 #else
    153 static void save_stack(struct drm_mm_node *node) { }
    154 static void show_leaks(struct drm_mm *mm) { }
    155 #endif
    156 
    157 #define START(node) ((node)->start)
    158 #define LAST(node)  ((node)->start + (node)->size - 1)
    159 
    160 #ifndef __NetBSD__
    161 INTERVAL_TREE_DEFINE(struct drm_mm_node, rb,
    162 		     u64, __subtree_last,
    163 		     START, LAST, static inline, drm_mm_interval_tree)
    164 #endif
    165 
    166 struct drm_mm_node *
    167 __drm_mm_interval_first(const struct drm_mm *mm_const, u64 start, u64 last)
    168 {
    169 	struct drm_mm *mm = __UNCONST(mm_const);
    170 #ifdef __NetBSD__
    171 	struct drm_mm_node *node;
    172 	list_for_each_entry(node, &mm->head_node.node_list, node_list) {
    173 		if (node->start <= start)
    174 			return node;
    175 	}
    176 	return NULL;
    177 #else
    178 	return drm_mm_interval_tree_iter_first((struct rb_root_cached *)&mm->interval_tree,
    179 					       start, last) ?: (struct drm_mm_node *)&mm->head_node;
    180 #endif
    181 }
    182 EXPORT_SYMBOL(__drm_mm_interval_first);
    183 
    184 #ifndef __NetBSD__
    185 static void drm_mm_interval_tree_add_node(struct drm_mm_node *hole_node,
    186 					  struct drm_mm_node *node)
    187 {
    188 	struct drm_mm *mm = hole_node->mm;
    189 	struct rb_node **link, *rb;
    190 	struct drm_mm_node *parent;
    191 	bool leftmost;
    192 
    193 	node->__subtree_last = LAST(node);
    194 
    195 	if (drm_mm_node_allocated(hole_node)) {
    196 		rb = &hole_node->rb;
    197 		while (rb) {
    198 			parent = rb_entry(rb, struct drm_mm_node, rb);
    199 			if (parent->__subtree_last >= node->__subtree_last)
    200 				break;
    201 
    202 			parent->__subtree_last = node->__subtree_last;
    203 			rb = rb_parent(rb);
    204 		}
    205 
    206 		rb = &hole_node->rb;
    207 		link = &hole_node->rb.rb_right;
    208 		leftmost = false;
    209 	} else {
    210 		rb = NULL;
    211 		link = &mm->interval_tree.rb_root.rb_node;
    212 		leftmost = true;
    213 	}
    214 
    215 	while (*link) {
    216 		rb = *link;
    217 		parent = rb_entry(rb, struct drm_mm_node, rb);
    218 		if (parent->__subtree_last < node->__subtree_last)
    219 			parent->__subtree_last = node->__subtree_last;
    220 		if (node->start < parent->start) {
    221 			link = &parent->rb.rb_left;
    222 		} else {
    223 			link = &parent->rb.rb_right;
    224 			leftmost = false;
    225 		}
    226 	}
    227 
    228 	rb_link_node(&node->rb, rb, link);
    229 	rb_insert_augmented_cached(&node->rb, &mm->interval_tree, leftmost,
    230 				   &drm_mm_interval_tree_augment);
    231 }
    232 #endif
    233 
    234 #ifdef __NetBSD__
    235 
    236 static int
    237 compare_hole_addrs(void *cookie, const void *va, const void *vb)
    238 {
    239 	const struct drm_mm_node *a = va, *b = vb;
    240 	const u64 aa = __drm_mm_hole_node_start(a);
    241 	const u64 ba = __drm_mm_hole_node_start(b);
    242 
    243 	KASSERTMSG((aa == ba ||
    244 		aa + a->hole_size <= ba ||
    245 		aa >= ba + b->hole_size),
    246 	    "overlapping holes: [0x%"PRIx64", 0x%"PRIx64"),"
    247 	    " [0x%"PRIx64", 0x%"PRIx64")",
    248 	    aa, aa + a->hole_size,
    249 	    ba, ba + b->hole_size);
    250 	if (aa < ba)
    251 		return -1;
    252 	if (aa > ba)
    253 		return +1;
    254 	return 0;
    255 }
    256 
    257 static int
    258 compare_hole_addr_key(void *cookie, const void *vn, const void *vk)
    259 {
    260 	const struct drm_mm_node *n = vn;
    261 	const u64 a = __drm_mm_hole_node_start(n);
    262 	const u64 *k = vk;
    263 
    264 	if (a < *k)
    265 		return -1;
    266 	if (a + n->hole_size >= *k) /* allows range lookups */
    267 		return +1;
    268 	return 0;
    269 }
    270 
    271 static const rb_tree_ops_t holes_addr_rb_ops = {
    272 	.rbto_compare_nodes = compare_hole_addrs,
    273 	.rbto_compare_key = compare_hole_addr_key,
    274 	.rbto_node_offset = offsetof(struct drm_mm_node, rb_hole_addr),
    275 };
    276 
    277 #else
    278 
    279 #define RB_INSERT(root, member, expr) do { \
    280 	struct rb_node **link = &root.rb_node, *rb = NULL; \
    281 	u64 x = expr(node); \
    282 	while (*link) { \
    283 		rb = *link; \
    284 		if (x < expr(rb_entry(rb, struct drm_mm_node, member))) \
    285 			link = &rb->rb_left; \
    286 		else \
    287 			link = &rb->rb_right; \
    288 	} \
    289 	rb_link_node(&node->member, rb, link); \
    290 	rb_insert_color(&node->member, &root); \
    291 } while (0)
    292 
    293 #endif
    294 
    295 #define HOLE_SIZE(NODE) ((NODE)->hole_size)
    296 #define HOLE_ADDR(NODE) (__drm_mm_hole_node_start(NODE))
    297 
    298 static u64 rb_to_hole_size(struct rb_node *rb)
    299 {
    300 	return rb_entry(rb, struct drm_mm_node, rb_hole_size)->hole_size;
    301 }
    302 
    303 static int
    304 compare_hole_sizes(void *cookie, const void *va, const void *vb)
    305 {
    306 	const struct drm_mm_node *a = va, *b = vb;
    307 
    308 	if (a->hole_size > b->hole_size)
    309 		return -1;
    310 	if (a->hole_size < b->hole_size)
    311 		return +1;
    312 	return (a < b ? -1 : a > b ? +1 : 0);
    313 }
    314 
    315 static int
    316 compare_hole_size_key(void *cookie, const void *vn, const void *vk)
    317 {
    318 	const struct drm_mm_node *n = vn;
    319 	const u64 *k = vk;
    320 
    321 	if (n->hole_size > *k)
    322 		return -1;
    323 	if (n->hole_size < *k)
    324 		return +1;
    325 	return 0;
    326 }
    327 
    328 static const rb_tree_ops_t holes_size_rb_ops = {
    329 	.rbto_compare_nodes = compare_hole_sizes,
    330 	.rbto_compare_key = compare_hole_size_key,
    331 	.rbto_node_offset = offsetof(struct drm_mm_node, rb_hole_size),
    332 };
    333 
    334 static void insert_hole_size(struct rb_root_cached *root,
    335 			     struct drm_mm_node *node)
    336 {
    337 #ifdef __NetBSD__
    338 	struct drm_mm_node *collision __diagused;
    339 	collision = rb_tree_insert_node(&root->rb_root.rbr_tree, node);
    340 	KASSERT(collision == node);
    341 #else
    342 	struct rb_node **link = &root->rb_root.rb_node, *rb = NULL;
    343 	u64 x = node->hole_size;
    344 	bool first = true;
    345 
    346 	while (*link) {
    347 		rb = *link;
    348 		if (x > rb_to_hole_size(rb)) {
    349 			link = &rb->rb_left;
    350 		} else {
    351 			link = &rb->rb_right;
    352 			first = false;
    353 		}
    354 	}
    355 
    356 	rb_link_node(&node->rb_hole_size, rb, link);
    357 	rb_insert_color_cached(&node->rb_hole_size, root, first);
    358 #endif
    359 }
    360 
    361 static void add_hole(struct drm_mm_node *node)
    362 {
    363 	struct drm_mm *mm = node->mm;
    364 
    365 	node->hole_size =
    366 		__drm_mm_hole_node_end(node) - __drm_mm_hole_node_start(node);
    367 	DRM_MM_BUG_ON(!drm_mm_hole_follows(node));
    368 
    369 	insert_hole_size(&mm->holes_size, node);
    370 #ifdef __NetBSD__
    371 	struct drm_mm_node *collision __diagused;
    372 	collision = rb_tree_insert_node(&mm->holes_addr.rbr_tree, node);
    373 	KASSERT(collision == node);
    374 #else
    375 	RB_INSERT(mm->holes_addr, rb_hole_addr, HOLE_ADDR);
    376 #endif
    377 
    378 	list_add(&node->hole_stack, &mm->hole_stack);
    379 }
    380 
    381 static void rm_hole(struct drm_mm_node *node)
    382 {
    383 	DRM_MM_BUG_ON(!drm_mm_hole_follows(node));
    384 
    385 	list_del(&node->hole_stack);
    386 	rb_erase_cached(&node->rb_hole_size, &node->mm->holes_size);
    387 	rb_erase(&node->rb_hole_addr, &node->mm->holes_addr);
    388 	node->hole_size = 0;
    389 
    390 	DRM_MM_BUG_ON(drm_mm_hole_follows(node));
    391 }
    392 
    393 static inline struct drm_mm_node *rb_hole_size_to_node(struct rb_node *rb)
    394 {
    395 	return rb_entry_safe(rb, struct drm_mm_node, rb_hole_size);
    396 }
    397 
    398 static inline struct drm_mm_node *rb_hole_addr_to_node(struct rb_node *rb)
    399 {
    400 	return rb_entry_safe(rb, struct drm_mm_node, rb_hole_addr);
    401 }
    402 
    403 static inline u64 rb_hole_size(struct rb_node *rb)
    404 {
    405 	return rb_entry(rb, struct drm_mm_node, rb_hole_size)->hole_size;
    406 }
    407 
    408 static struct drm_mm_node *best_hole(struct drm_mm *mm, u64 size)
    409 {
    410 #ifdef __NetBSD__
    411 	struct drm_mm_node *best;
    412 
    413 	best = rb_tree_find_node_leq(&mm->holes_size.rb_root.rbr_tree, &size);
    414 	KASSERT(best == NULL || size <= best->hole_size);
    415 
    416 	return best;
    417 #else
    418 	struct rb_node *rb = mm->holes_size.rb_root.rb_node;
    419 	struct drm_mm_node *best = NULL;
    420 
    421 	do {
    422 		struct drm_mm_node *node =
    423 			rb_entry(rb, struct drm_mm_node, rb_hole_size);
    424 
    425 		if (size <= node->hole_size) {
    426 			best = node;
    427 			rb = rb->rb_right;
    428 		} else {
    429 			rb = rb->rb_left;
    430 		}
    431 	} while (rb);
    432 
    433 	return best;
    434 #endif
    435 }
    436 
    437 static struct drm_mm_node *find_hole(struct drm_mm *mm, u64 addr)
    438 {
    439 #ifdef __NetBSD__
    440 	struct drm_mm_node *node;
    441 
    442 	node = rb_tree_find_node(&mm->holes_addr.rbr_tree, &addr);
    443 	KASSERT(node == NULL || __drm_mm_hole_node_start(node) <= addr);
    444 	KASSERT(node == NULL || addr <
    445 	    __drm_mm_hole_node_start(node) + node->hole_size);
    446 
    447 	return node;
    448 #else
    449 	struct rb_node *rb = mm->holes_addr.rb_node;
    450 	struct drm_mm_node *node = NULL;
    451 
    452 	while (rb) {
    453 		u64 hole_start;
    454 
    455 		node = rb_hole_addr_to_node(rb);
    456 		hole_start = __drm_mm_hole_node_start(node);
    457 
    458 		if (addr < hole_start)
    459 			rb = node->rb_hole_addr.rb_left;
    460 		else if (addr > hole_start + node->hole_size)
    461 			rb = node->rb_hole_addr.rb_right;
    462 		else
    463 			break;
    464 	}
    465 
    466 	return node;
    467 #endif
    468 }
    469 
    470 static struct drm_mm_node *
    471 first_hole(struct drm_mm *mm,
    472 	   u64 start, u64 end, u64 size,
    473 	   enum drm_mm_insert_mode mode)
    474 {
    475 	switch (mode) {
    476 	default:
    477 	case DRM_MM_INSERT_BEST:
    478 		return best_hole(mm, size);
    479 
    480 	case DRM_MM_INSERT_LOW:
    481 #ifdef __NetBSD__
    482 		return rb_tree_find_node_geq(&mm->holes_addr.rbr_tree, &start);
    483 #else
    484 		return find_hole(mm, start);
    485 #endif
    486 
    487 	case DRM_MM_INSERT_HIGH:
    488 #ifdef __NetBSD__
    489 		return rb_tree_find_node_leq(&mm->holes_addr.rbr_tree, &end);
    490 #else
    491 		return find_hole(mm, end);
    492 #endif
    493 
    494 	case DRM_MM_INSERT_EVICT:
    495 		return list_first_entry_or_null(&mm->hole_stack,
    496 						struct drm_mm_node,
    497 						hole_stack);
    498 	}
    499 }
    500 
    501 static struct drm_mm_node *
    502 next_hole(struct drm_mm *mm,
    503 	  struct drm_mm_node *node,
    504 	  enum drm_mm_insert_mode mode)
    505 {
    506 	switch (mode) {
    507 	default:
    508 	case DRM_MM_INSERT_BEST:
    509 #ifdef __NetBSD__
    510 		return RB_TREE_PREV(&mm->holes_size.rb_root.rbr_tree, node);
    511 #else
    512 		return rb_hole_size_to_node(rb_prev(&node->rb_hole_size));
    513 #endif
    514 
    515 	case DRM_MM_INSERT_LOW:
    516 #ifdef __NetBSD__
    517 		return RB_TREE_NEXT(&mm->holes_addr.rbr_tree, node);
    518 #else
    519 		return rb_hole_addr_to_node(rb_next(&node->rb_hole_addr));
    520 #endif
    521 
    522 	case DRM_MM_INSERT_HIGH:
    523 #ifdef __NetBSD__
    524 		return RB_TREE_PREV(&mm->holes_addr.rbr_tree, node);
    525 #else
    526 		return rb_hole_addr_to_node(rb_prev(&node->rb_hole_addr));
    527 #endif
    528 
    529 	case DRM_MM_INSERT_EVICT:
    530 		node = list_next_entry(node, hole_stack);
    531 		return &node->hole_stack == &mm->hole_stack ? NULL : node;
    532 	}
    533 }
    534 
    535 /**
    536  * drm_mm_reserve_node - insert an pre-initialized node
    537  * @mm: drm_mm allocator to insert @node into
    538  * @node: drm_mm_node to insert
    539  *
    540  * This functions inserts an already set-up &drm_mm_node into the allocator,
    541  * meaning that start, size and color must be set by the caller. All other
    542  * fields must be cleared to 0. This is useful to initialize the allocator with
    543  * preallocated objects which must be set-up before the range allocator can be
    544  * set-up, e.g. when taking over a firmware framebuffer.
    545  *
    546  * Returns:
    547  * 0 on success, -ENOSPC if there's no hole where @node is.
    548  */
    549 int drm_mm_reserve_node(struct drm_mm *mm, struct drm_mm_node *node)
    550 {
    551 	u64 end = node->start + node->size;
    552 	struct drm_mm_node *hole;
    553 	u64 hole_start, hole_end;
    554 	u64 adj_start, adj_end;
    555 
    556 	end = node->start + node->size;
    557 	if (unlikely(end <= node->start))
    558 		return -ENOSPC;
    559 
    560 	/* Find the relevant hole to add our node to */
    561 	hole = find_hole(mm, node->start);
    562 	if (!hole)
    563 		return -ENOSPC;
    564 
    565 	adj_start = hole_start = __drm_mm_hole_node_start(hole);
    566 	adj_end = hole_end = hole_start + hole->hole_size;
    567 
    568 	if (mm->color_adjust)
    569 		mm->color_adjust(hole, node->color, &adj_start, &adj_end);
    570 
    571 	if (adj_start > node->start || adj_end < end)
    572 		return -ENOSPC;
    573 
    574 	node->mm = mm;
    575 
    576 	__set_bit(DRM_MM_NODE_ALLOCATED_BIT, &node->flags);
    577 	list_add(&node->node_list, &hole->node_list);
    578 #ifndef __NetBSD__
    579 	drm_mm_interval_tree_add_node(hole, node);
    580 #endif
    581 	node->hole_size = 0;
    582 
    583 	rm_hole(hole);
    584 	if (node->start > hole_start)
    585 		add_hole(hole);
    586 	if (end < hole_end)
    587 		add_hole(node);
    588 
    589 	save_stack(node);
    590 	return 0;
    591 }
    592 EXPORT_SYMBOL(drm_mm_reserve_node);
    593 
    594 static u64 rb_to_hole_size_or_zero(struct rb_node *rb)
    595 {
    596 	return rb ? rb_to_hole_size(rb) : 0;
    597 }
    598 
    599 /**
    600  * drm_mm_insert_node_in_range - ranged search for space and insert @node
    601  * @mm: drm_mm to allocate from
    602  * @node: preallocate node to insert
    603  * @size: size of the allocation
    604  * @alignment: alignment of the allocation
    605  * @color: opaque tag value to use for this node
    606  * @range_start: start of the allowed range for this node
    607  * @range_end: end of the allowed range for this node
    608  * @mode: fine-tune the allocation search and placement
    609  *
    610  * The preallocated @node must be cleared to 0.
    611  *
    612  * Returns:
    613  * 0 on success, -ENOSPC if there's no suitable hole.
    614  */
    615 int drm_mm_insert_node_in_range(struct drm_mm * const mm,
    616 				struct drm_mm_node * const node,
    617 				u64 size, u64 alignment,
    618 				unsigned long color,
    619 				u64 range_start, u64 range_end,
    620 				enum drm_mm_insert_mode mode)
    621 {
    622 	struct drm_mm_node *hole;
    623 	u64 remainder_mask;
    624 	bool once;
    625 
    626 	DRM_MM_BUG_ON(range_start > range_end);
    627 
    628 	if (unlikely(size == 0 || range_end - range_start < size))
    629 		return -ENOSPC;
    630 
    631 	if (rb_to_hole_size_or_zero(rb_first_cached(&mm->holes_size)) < size)
    632 		return -ENOSPC;
    633 
    634 	if (alignment <= 1)
    635 		alignment = 0;
    636 
    637 	once = mode & DRM_MM_INSERT_ONCE;
    638 	mode &= ~DRM_MM_INSERT_ONCE;
    639 
    640 	remainder_mask = is_power_of_2(alignment) ? alignment - 1 : 0;
    641 	for (hole = first_hole(mm, range_start, range_end, size, mode);
    642 	     hole;
    643 	     hole = once ? NULL : next_hole(mm, hole, mode)) {
    644 		u64 hole_start = __drm_mm_hole_node_start(hole);
    645 		u64 hole_end = hole_start + hole->hole_size;
    646 		u64 adj_start, adj_end;
    647 		u64 col_start, col_end;
    648 
    649 		if (mode == DRM_MM_INSERT_LOW && hole_start >= range_end)
    650 			break;
    651 
    652 		if (mode == DRM_MM_INSERT_HIGH && hole_end <= range_start)
    653 			break;
    654 
    655 		col_start = hole_start;
    656 		col_end = hole_end;
    657 		if (mm->color_adjust)
    658 			mm->color_adjust(hole, color, &col_start, &col_end);
    659 
    660 		adj_start = max(col_start, range_start);
    661 		adj_end = min(col_end, range_end);
    662 
    663 		if (adj_end <= adj_start || adj_end - adj_start < size)
    664 			continue;
    665 
    666 		if (mode == DRM_MM_INSERT_HIGH)
    667 			adj_start = adj_end - size;
    668 
    669 		if (alignment) {
    670 			u64 rem;
    671 
    672 			if (likely(remainder_mask))
    673 				rem = adj_start & remainder_mask;
    674 			else
    675 				div64_u64_rem(adj_start, alignment, &rem);
    676 			if (rem) {
    677 				adj_start -= rem;
    678 				if (mode != DRM_MM_INSERT_HIGH)
    679 					adj_start += alignment;
    680 
    681 				if (adj_start < max(col_start, range_start) ||
    682 				    min(col_end, range_end) - adj_start < size)
    683 					continue;
    684 
    685 				if (adj_end <= adj_start ||
    686 				    adj_end - adj_start < size)
    687 					continue;
    688 			}
    689 		}
    690 
    691 		node->mm = mm;
    692 		node->size = size;
    693 		node->start = adj_start;
    694 		node->color = color;
    695 		node->hole_size = 0;
    696 
    697 		__set_bit(DRM_MM_NODE_ALLOCATED_BIT, &node->flags);
    698 		list_add(&node->node_list, &hole->node_list);
    699 #ifndef __NetBSD__
    700 		drm_mm_interval_tree_add_node(hole, node);
    701 #endif
    702 
    703 		rm_hole(hole);
    704 		if (adj_start > hole_start)
    705 			add_hole(hole);
    706 		if (adj_start + size < hole_end)
    707 			add_hole(node);
    708 
    709 		save_stack(node);
    710 		return 0;
    711 	}
    712 
    713 	return -ENOSPC;
    714 }
    715 EXPORT_SYMBOL(drm_mm_insert_node_in_range);
    716 
    717 static inline bool drm_mm_node_scanned_block(const struct drm_mm_node *node)
    718 {
    719 	return test_bit(DRM_MM_NODE_SCANNED_BIT, &node->flags);
    720 }
    721 
    722 /**
    723  * drm_mm_remove_node - Remove a memory node from the allocator.
    724  * @node: drm_mm_node to remove
    725  *
    726  * This just removes a node from its drm_mm allocator. The node does not need to
    727  * be cleared again before it can be re-inserted into this or any other drm_mm
    728  * allocator. It is a bug to call this function on a unallocated node.
    729  */
    730 void drm_mm_remove_node(struct drm_mm_node *node)
    731 {
    732 	struct drm_mm *mm = node->mm;
    733 	struct drm_mm_node *prev_node;
    734 
    735 	DRM_MM_BUG_ON(!drm_mm_node_allocated(node));
    736 	DRM_MM_BUG_ON(drm_mm_node_scanned_block(node));
    737 
    738 	prev_node = list_prev_entry(node, node_list);
    739 
    740 	if (drm_mm_hole_follows(node))
    741 		rm_hole(node);
    742 
    743 #ifdef __NetBSD__
    744 	__USE(mm);
    745 #else
    746 	drm_mm_interval_tree_remove(node, &mm->interval_tree);
    747 #endif
    748 	list_del(&node->node_list);
    749 
    750 	if (drm_mm_hole_follows(prev_node))
    751 		rm_hole(prev_node);
    752 	add_hole(prev_node);
    753 
    754 	clear_bit_unlock(DRM_MM_NODE_ALLOCATED_BIT, &node->flags);
    755 }
    756 EXPORT_SYMBOL(drm_mm_remove_node);
    757 
    758 /**
    759  * drm_mm_replace_node - move an allocation from @old to @new
    760  * @old: drm_mm_node to remove from the allocator
    761  * @new: drm_mm_node which should inherit @old's allocation
    762  *
    763  * This is useful for when drivers embed the drm_mm_node structure and hence
    764  * can't move allocations by reassigning pointers. It's a combination of remove
    765  * and insert with the guarantee that the allocation start will match.
    766  */
    767 void drm_mm_replace_node(struct drm_mm_node *old, struct drm_mm_node *new)
    768 {
    769 	struct drm_mm *mm = old->mm;
    770 
    771 	DRM_MM_BUG_ON(!drm_mm_node_allocated(old));
    772 
    773 	*new = *old;
    774 
    775 	__set_bit(DRM_MM_NODE_ALLOCATED_BIT, &new->flags);
    776 	list_replace(&old->node_list, &new->node_list);
    777 #ifndef __NetBSD__
    778 	rb_replace_node_cached(&old->rb, &new->rb, &mm->interval_tree);
    779 #endif
    780 
    781 	if (drm_mm_hole_follows(old)) {
    782 		list_replace(&old->hole_stack, &new->hole_stack);
    783 		rb_replace_node_cached(&old->rb_hole_size,
    784 				       &new->rb_hole_size,
    785 				       &mm->holes_size);
    786 		rb_replace_node(&old->rb_hole_addr,
    787 				&new->rb_hole_addr,
    788 				&mm->holes_addr);
    789 	}
    790 
    791 	clear_bit_unlock(DRM_MM_NODE_ALLOCATED_BIT, &old->flags);
    792 }
    793 EXPORT_SYMBOL(drm_mm_replace_node);
    794 
    795 /**
    796  * DOC: lru scan roster
    797  *
    798  * Very often GPUs need to have continuous allocations for a given object. When
    799  * evicting objects to make space for a new one it is therefore not most
    800  * efficient when we simply start to select all objects from the tail of an LRU
    801  * until there's a suitable hole: Especially for big objects or nodes that
    802  * otherwise have special allocation constraints there's a good chance we evict
    803  * lots of (smaller) objects unnecessarily.
    804  *
    805  * The DRM range allocator supports this use-case through the scanning
    806  * interfaces. First a scan operation needs to be initialized with
    807  * drm_mm_scan_init() or drm_mm_scan_init_with_range(). The driver adds
    808  * objects to the roster, probably by walking an LRU list, but this can be
    809  * freely implemented. Eviction candiates are added using
    810  * drm_mm_scan_add_block() until a suitable hole is found or there are no
    811  * further evictable objects. Eviction roster metadata is tracked in &struct
    812  * drm_mm_scan.
    813  *
    814  * The driver must walk through all objects again in exactly the reverse
    815  * order to restore the allocator state. Note that while the allocator is used
    816  * in the scan mode no other operation is allowed.
    817  *
    818  * Finally the driver evicts all objects selected (drm_mm_scan_remove_block()
    819  * reported true) in the scan, and any overlapping nodes after color adjustment
    820  * (drm_mm_scan_color_evict()). Adding and removing an object is O(1), and
    821  * since freeing a node is also O(1) the overall complexity is
    822  * O(scanned_objects). So like the free stack which needs to be walked before a
    823  * scan operation even begins this is linear in the number of objects. It
    824  * doesn't seem to hurt too badly.
    825  */
    826 
    827 /**
    828  * drm_mm_scan_init_with_range - initialize range-restricted lru scanning
    829  * @scan: scan state
    830  * @mm: drm_mm to scan
    831  * @size: size of the allocation
    832  * @alignment: alignment of the allocation
    833  * @color: opaque tag value to use for the allocation
    834  * @start: start of the allowed range for the allocation
    835  * @end: end of the allowed range for the allocation
    836  * @mode: fine-tune the allocation search and placement
    837  *
    838  * This simply sets up the scanning routines with the parameters for the desired
    839  * hole.
    840  *
    841  * Warning:
    842  * As long as the scan list is non-empty, no other operations than
    843  * adding/removing nodes to/from the scan list are allowed.
    844  */
    845 void drm_mm_scan_init_with_range(struct drm_mm_scan *scan,
    846 				 struct drm_mm *mm,
    847 				 u64 size,
    848 				 u64 alignment,
    849 				 unsigned long color,
    850 				 u64 start,
    851 				 u64 end,
    852 				 enum drm_mm_insert_mode mode)
    853 {
    854 	DRM_MM_BUG_ON(start >= end);
    855 	DRM_MM_BUG_ON(!size || size > end - start);
    856 	DRM_MM_BUG_ON(mm->scan_active);
    857 
    858 	scan->mm = mm;
    859 
    860 	if (alignment <= 1)
    861 		alignment = 0;
    862 
    863 	scan->color = color;
    864 	scan->alignment = alignment;
    865 	scan->remainder_mask = is_power_of_2(alignment) ? alignment - 1 : 0;
    866 	scan->size = size;
    867 	scan->mode = mode;
    868 
    869 	DRM_MM_BUG_ON(end <= start);
    870 	scan->range_start = start;
    871 	scan->range_end = end;
    872 
    873 	scan->hit_start = U64_MAX;
    874 	scan->hit_end = 0;
    875 }
    876 EXPORT_SYMBOL(drm_mm_scan_init_with_range);
    877 
    878 /**
    879  * drm_mm_scan_add_block - add a node to the scan list
    880  * @scan: the active drm_mm scanner
    881  * @node: drm_mm_node to add
    882  *
    883  * Add a node to the scan list that might be freed to make space for the desired
    884  * hole.
    885  *
    886  * Returns:
    887  * True if a hole has been found, false otherwise.
    888  */
    889 bool drm_mm_scan_add_block(struct drm_mm_scan *scan,
    890 			   struct drm_mm_node *node)
    891 {
    892 	struct drm_mm *mm = scan->mm;
    893 	struct drm_mm_node *hole;
    894 	u64 hole_start, hole_end;
    895 	u64 col_start, col_end;
    896 	u64 adj_start, adj_end;
    897 
    898 	DRM_MM_BUG_ON(node->mm != mm);
    899 	DRM_MM_BUG_ON(!drm_mm_node_allocated(node));
    900 	DRM_MM_BUG_ON(drm_mm_node_scanned_block(node));
    901 	__set_bit(DRM_MM_NODE_SCANNED_BIT, &node->flags);
    902 	mm->scan_active++;
    903 
    904 	/* Remove this block from the node_list so that we enlarge the hole
    905 	 * (distance between the end of our previous node and the start of
    906 	 * or next), without poisoning the link so that we can restore it
    907 	 * later in drm_mm_scan_remove_block().
    908 	 */
    909 	hole = list_prev_entry(node, node_list);
    910 	DRM_MM_BUG_ON(list_next_entry(hole, node_list) != node);
    911 	__list_del_entry(&node->node_list);
    912 
    913 	hole_start = __drm_mm_hole_node_start(hole);
    914 	hole_end = __drm_mm_hole_node_end(hole);
    915 
    916 	col_start = hole_start;
    917 	col_end = hole_end;
    918 	if (mm->color_adjust)
    919 		mm->color_adjust(hole, scan->color, &col_start, &col_end);
    920 
    921 	adj_start = max(col_start, scan->range_start);
    922 	adj_end = min(col_end, scan->range_end);
    923 	if (adj_end <= adj_start || adj_end - adj_start < scan->size)
    924 		return false;
    925 
    926 	if (scan->mode == DRM_MM_INSERT_HIGH)
    927 		adj_start = adj_end - scan->size;
    928 
    929 	if (scan->alignment) {
    930 		u64 rem;
    931 
    932 		if (likely(scan->remainder_mask))
    933 			rem = adj_start & scan->remainder_mask;
    934 		else
    935 			div64_u64_rem(adj_start, scan->alignment, &rem);
    936 		if (rem) {
    937 			adj_start -= rem;
    938 			if (scan->mode != DRM_MM_INSERT_HIGH)
    939 				adj_start += scan->alignment;
    940 			if (adj_start < max(col_start, scan->range_start) ||
    941 			    min(col_end, scan->range_end) - adj_start < scan->size)
    942 				return false;
    943 
    944 			if (adj_end <= adj_start ||
    945 			    adj_end - adj_start < scan->size)
    946 				return false;
    947 		}
    948 	}
    949 
    950 	scan->hit_start = adj_start;
    951 	scan->hit_end = adj_start + scan->size;
    952 
    953 	DRM_MM_BUG_ON(scan->hit_start >= scan->hit_end);
    954 	DRM_MM_BUG_ON(scan->hit_start < hole_start);
    955 	DRM_MM_BUG_ON(scan->hit_end > hole_end);
    956 
    957 	return true;
    958 }
    959 EXPORT_SYMBOL(drm_mm_scan_add_block);
    960 
    961 /**
    962  * drm_mm_scan_remove_block - remove a node from the scan list
    963  * @scan: the active drm_mm scanner
    964  * @node: drm_mm_node to remove
    965  *
    966  * Nodes **must** be removed in exactly the reverse order from the scan list as
    967  * they have been added (e.g. using list_add() as they are added and then
    968  * list_for_each() over that eviction list to remove), otherwise the internal
    969  * state of the memory manager will be corrupted.
    970  *
    971  * When the scan list is empty, the selected memory nodes can be freed. An
    972  * immediately following drm_mm_insert_node_in_range_generic() or one of the
    973  * simpler versions of that function with !DRM_MM_SEARCH_BEST will then return
    974  * the just freed block (because it's at the top of the free_stack list).
    975  *
    976  * Returns:
    977  * True if this block should be evicted, false otherwise. Will always
    978  * return false when no hole has been found.
    979  */
    980 bool drm_mm_scan_remove_block(struct drm_mm_scan *scan,
    981 			      struct drm_mm_node *node)
    982 {
    983 	struct drm_mm_node *prev_node;
    984 
    985 	DRM_MM_BUG_ON(node->mm != scan->mm);
    986 	DRM_MM_BUG_ON(!drm_mm_node_scanned_block(node));
    987 	__clear_bit(DRM_MM_NODE_SCANNED_BIT, &node->flags);
    988 
    989 	DRM_MM_BUG_ON(!node->mm->scan_active);
    990 	node->mm->scan_active--;
    991 
    992 	/* During drm_mm_scan_add_block() we decoupled this node leaving
    993 	 * its pointers intact. Now that the caller is walking back along
    994 	 * the eviction list we can restore this block into its rightful
    995 	 * place on the full node_list. To confirm that the caller is walking
    996 	 * backwards correctly we check that prev_node->next == node->next,
    997 	 * i.e. both believe the same node should be on the other side of the
    998 	 * hole.
    999 	 */
   1000 	prev_node = list_prev_entry(node, node_list);
   1001 	DRM_MM_BUG_ON(list_next_entry(prev_node, node_list) !=
   1002 		      list_next_entry(node, node_list));
   1003 	list_add(&node->node_list, &prev_node->node_list);
   1004 
   1005 	return (node->start + node->size > scan->hit_start &&
   1006 		node->start < scan->hit_end);
   1007 }
   1008 EXPORT_SYMBOL(drm_mm_scan_remove_block);
   1009 
   1010 /**
   1011  * drm_mm_scan_color_evict - evict overlapping nodes on either side of hole
   1012  * @scan: drm_mm scan with target hole
   1013  *
   1014  * After completing an eviction scan and removing the selected nodes, we may
   1015  * need to remove a few more nodes from either side of the target hole if
   1016  * mm.color_adjust is being used.
   1017  *
   1018  * Returns:
   1019  * A node to evict, or NULL if there are no overlapping nodes.
   1020  */
   1021 struct drm_mm_node *drm_mm_scan_color_evict(struct drm_mm_scan *scan)
   1022 {
   1023 	struct drm_mm *mm = scan->mm;
   1024 	struct drm_mm_node *hole;
   1025 	u64 hole_start, hole_end;
   1026 
   1027 	DRM_MM_BUG_ON(list_empty(&mm->hole_stack));
   1028 
   1029 	if (!mm->color_adjust)
   1030 		return NULL;
   1031 
   1032 	/*
   1033 	 * The hole found during scanning should ideally be the first element
   1034 	 * in the hole_stack list, but due to side-effects in the driver it
   1035 	 * may not be.
   1036 	 */
   1037 	list_for_each_entry(hole, &mm->hole_stack, hole_stack) {
   1038 		hole_start = __drm_mm_hole_node_start(hole);
   1039 		hole_end = hole_start + hole->hole_size;
   1040 
   1041 		if (hole_start <= scan->hit_start &&
   1042 		    hole_end >= scan->hit_end)
   1043 			break;
   1044 	}
   1045 
   1046 	/* We should only be called after we found the hole previously */
   1047 	DRM_MM_BUG_ON(&hole->hole_stack == &mm->hole_stack);
   1048 	if (unlikely(&hole->hole_stack == &mm->hole_stack))
   1049 		return NULL;
   1050 
   1051 	DRM_MM_BUG_ON(hole_start > scan->hit_start);
   1052 	DRM_MM_BUG_ON(hole_end < scan->hit_end);
   1053 
   1054 	mm->color_adjust(hole, scan->color, &hole_start, &hole_end);
   1055 	if (hole_start > scan->hit_start)
   1056 		return hole;
   1057 	if (hole_end < scan->hit_end)
   1058 		return list_next_entry(hole, node_list);
   1059 
   1060 	return NULL;
   1061 }
   1062 EXPORT_SYMBOL(drm_mm_scan_color_evict);
   1063 
   1064 /**
   1065  * drm_mm_init - initialize a drm-mm allocator
   1066  * @mm: the drm_mm structure to initialize
   1067  * @start: start of the range managed by @mm
   1068  * @size: end of the range managed by @mm
   1069  *
   1070  * Note that @mm must be cleared to 0 before calling this function.
   1071  */
   1072 void drm_mm_init(struct drm_mm *mm, u64 start, u64 size)
   1073 {
   1074 	DRM_MM_BUG_ON(start + size <= start);
   1075 
   1076 	mm->color_adjust = NULL;
   1077 
   1078 	INIT_LIST_HEAD(&mm->hole_stack);
   1079 #ifdef __NetBSD__
   1080 	/* XXX interval tree */
   1081 	rb_tree_init(&mm->holes_size.rb_root.rbr_tree, &holes_size_rb_ops);
   1082 	rb_tree_init(&mm->holes_addr.rbr_tree, &holes_addr_rb_ops);
   1083 #else
   1084 	mm->interval_tree = RB_ROOT_CACHED;
   1085 	mm->holes_size = RB_ROOT_CACHED;
   1086 	mm->holes_addr = RB_ROOT;
   1087 #endif
   1088 
   1089 	/* Clever trick to avoid a special case in the free hole tracking. */
   1090 	INIT_LIST_HEAD(&mm->head_node.node_list);
   1091 	mm->head_node.flags = 0;
   1092 	mm->head_node.mm = mm;
   1093 	mm->head_node.start = start + size;
   1094 	mm->head_node.size = -size;
   1095 	add_hole(&mm->head_node);
   1096 
   1097 	mm->scan_active = 0;
   1098 }
   1099 EXPORT_SYMBOL(drm_mm_init);
   1100 
   1101 /**
   1102  * drm_mm_takedown - clean up a drm_mm allocator
   1103  * @mm: drm_mm allocator to clean up
   1104  *
   1105  * Note that it is a bug to call this function on an allocator which is not
   1106  * clean.
   1107  */
   1108 void drm_mm_takedown(struct drm_mm *mm)
   1109 {
   1110 	if (WARN(!drm_mm_clean(mm),
   1111 		 "Memory manager not clean during takedown.\n"))
   1112 		show_leaks(mm);
   1113 }
   1114 EXPORT_SYMBOL(drm_mm_takedown);
   1115 
   1116 static u64 drm_mm_dump_hole(struct drm_printer *p, const struct drm_mm_node *entry)
   1117 {
   1118 	u64 start, size;
   1119 
   1120 	size = entry->hole_size;
   1121 	if (size) {
   1122 		start = drm_mm_hole_node_start(entry);
   1123 		drm_printf(p, "%#018"PRIx64"-%#018"PRIx64": %"PRIu64": free\n",
   1124 			   start, start + size, size);
   1125 	}
   1126 
   1127 	return size;
   1128 }
   1129 /**
   1130  * drm_mm_print - print allocator state
   1131  * @mm: drm_mm allocator to print
   1132  * @p: DRM printer to use
   1133  */
   1134 void drm_mm_print(const struct drm_mm *mm, struct drm_printer *p)
   1135 {
   1136 	const struct drm_mm_node *entry;
   1137 	u64 total_used = 0, total_free = 0, total = 0;
   1138 
   1139 	total_free += drm_mm_dump_hole(p, &mm->head_node);
   1140 
   1141 	drm_mm_for_each_node(entry, mm) {
   1142 		drm_printf(p, "%#018"PRIx64"-%#018"PRIx64": %"PRIu64": used\n", entry->start,
   1143 			   entry->start + entry->size, entry->size);
   1144 		total_used += entry->size;
   1145 		total_free += drm_mm_dump_hole(p, entry);
   1146 	}
   1147 	total = total_free + total_used;
   1148 
   1149 	drm_printf(p, "total: %"PRIu64", used %"PRIu64" free %"PRIu64"\n", total,
   1150 		   total_used, total_free);
   1151 }
   1152 EXPORT_SYMBOL(drm_mm_print);
   1153