Home | History | Annotate | Line # | Download | only in drm
drm_mm.c revision 1.8
      1 /*	$NetBSD: drm_mm.c,v 1.8 2021/12/19 01:51:27 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.8 2021/12/19 01:51:27 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 [%08llx + %08llx]: 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 [%08llx + %08llx]: 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 INTERVAL_TREE_DEFINE(struct drm_mm_node, rb,
    161 		     u64, __subtree_last,
    162 		     START, LAST, static inline, drm_mm_interval_tree)
    163 
    164 struct drm_mm_node *
    165 __drm_mm_interval_first(const struct drm_mm *mm, u64 start, u64 last)
    166 {
    167 	return drm_mm_interval_tree_iter_first((struct rb_root_cached *)&mm->interval_tree,
    168 					       start, last) ?: (struct drm_mm_node *)&mm->head_node;
    169 }
    170 EXPORT_SYMBOL(__drm_mm_interval_first);
    171 
    172 static void drm_mm_interval_tree_add_node(struct drm_mm_node *hole_node,
    173 					  struct drm_mm_node *node)
    174 {
    175 	struct drm_mm *mm = hole_node->mm;
    176 	struct rb_node **link, *rb;
    177 	struct drm_mm_node *parent;
    178 	bool leftmost;
    179 
    180 	node->__subtree_last = LAST(node);
    181 
    182 	if (drm_mm_node_allocated(hole_node)) {
    183 		rb = &hole_node->rb;
    184 		while (rb) {
    185 			parent = rb_entry(rb, struct drm_mm_node, rb);
    186 			if (parent->__subtree_last >= node->__subtree_last)
    187 				break;
    188 
    189 			parent->__subtree_last = node->__subtree_last;
    190 			rb = rb_parent(rb);
    191 		}
    192 
    193 		rb = &hole_node->rb;
    194 		link = &hole_node->rb.rb_right;
    195 		leftmost = false;
    196 	} else {
    197 		rb = NULL;
    198 		link = &mm->interval_tree.rb_root.rb_node;
    199 		leftmost = true;
    200 	}
    201 
    202 	while (*link) {
    203 		rb = *link;
    204 		parent = rb_entry(rb, struct drm_mm_node, rb);
    205 		if (parent->__subtree_last < node->__subtree_last)
    206 			parent->__subtree_last = node->__subtree_last;
    207 		if (node->start < parent->start) {
    208 			link = &parent->rb.rb_left;
    209 		} else {
    210 			link = &parent->rb.rb_right;
    211 			leftmost = false;
    212 		}
    213 	}
    214 
    215 	rb_link_node(&node->rb, rb, link);
    216 	rb_insert_augmented_cached(&node->rb, &mm->interval_tree, leftmost,
    217 				   &drm_mm_interval_tree_augment);
    218 }
    219 
    220 #ifndef __NetBSD__
    221 #define RB_INSERT(root, member, expr) do { \
    222 	struct rb_node **link = &root.rb_node, *rb = NULL; \
    223 	u64 x = expr(node); \
    224 	while (*link) { \
    225 		rb = *link; \
    226 		if (x < expr(rb_entry(rb, struct drm_mm_node, member))) \
    227 			link = &rb->rb_left; \
    228 		else \
    229 			link = &rb->rb_right; \
    230 	} \
    231 	rb_link_node(&node->member, rb, link); \
    232 	rb_insert_color(&node->member, &root); \
    233 } while (0)
    234 #endif
    235 
    236 #define HOLE_SIZE(NODE) ((NODE)->hole_size)
    237 #define HOLE_ADDR(NODE) (__drm_mm_hole_node_start(NODE))
    238 
    239 static u64 rb_to_hole_size(struct rb_node *rb)
    240 {
    241 	return rb_entry(rb, struct drm_mm_node, rb_hole_size)->hole_size;
    242 }
    243 
    244 static void insert_hole_size(struct rb_root_cached *root,
    245 			     struct drm_mm_node *node)
    246 {
    247 	struct rb_node **link = &root->rb_root.rb_node, *rb = NULL;
    248 	u64 x = node->hole_size;
    249 	bool first = true;
    250 
    251 	while (*link) {
    252 		rb = *link;
    253 		if (x > rb_to_hole_size(rb)) {
    254 			link = &rb->rb_left;
    255 		} else {
    256 			link = &rb->rb_right;
    257 			first = false;
    258 		}
    259 	}
    260 
    261 	rb_link_node(&node->rb_hole_size, rb, link);
    262 	rb_insert_color_cached(&node->rb_hole_size, root, first);
    263 }
    264 
    265 static void add_hole(struct drm_mm_node *node)
    266 {
    267 	struct drm_mm *mm = node->mm;
    268 
    269 	node->hole_size =
    270 		__drm_mm_hole_node_end(node) - __drm_mm_hole_node_start(node);
    271 	DRM_MM_BUG_ON(!drm_mm_hole_follows(node));
    272 
    273 	insert_hole_size(&mm->holes_size, node);
    274 #ifdef __NetBSD__
    275 	struct rb_node *collision __diagused;
    276 	collision = rb_tree_insert_node(&mm->holes_addr
    277 #else
    278 	RB_INSERT(mm->holes_addr, rb_hole_addr, HOLE_ADDR);
    279 #endif
    280 
    281 	list_add(&node->hole_stack, &mm->hole_stack);
    282 }
    283 
    284 static void rm_hole(struct drm_mm_node *node)
    285 {
    286 	DRM_MM_BUG_ON(!drm_mm_hole_follows(node));
    287 
    288 	list_del(&node->hole_stack);
    289 	rb_erase_cached(&node->rb_hole_size, &node->mm->holes_size);
    290 	rb_erase(&node->rb_hole_addr, &node->mm->holes_addr);
    291 	node->hole_size = 0;
    292 
    293 	DRM_MM_BUG_ON(drm_mm_hole_follows(node));
    294 }
    295 
    296 static inline struct drm_mm_node *rb_hole_size_to_node(struct rb_node *rb)
    297 {
    298 	return rb_entry_safe(rb, struct drm_mm_node, rb_hole_size);
    299 }
    300 
    301 static inline struct drm_mm_node *rb_hole_addr_to_node(struct rb_node *rb)
    302 {
    303 	return rb_entry_safe(rb, struct drm_mm_node, rb_hole_addr);
    304 }
    305 
    306 static inline u64 rb_hole_size(struct rb_node *rb)
    307 {
    308 	return rb_entry(rb, struct drm_mm_node, rb_hole_size)->hole_size;
    309 }
    310 
    311 static struct drm_mm_node *best_hole(struct drm_mm *mm, u64 size)
    312 {
    313 	struct rb_node *rb = mm->holes_size.rb_root.rb_node;
    314 	struct drm_mm_node *best = NULL;
    315 
    316 	do {
    317 		struct drm_mm_node *node =
    318 			rb_entry(rb, struct drm_mm_node, rb_hole_size);
    319 
    320 		if (size <= node->hole_size) {
    321 			best = node;
    322 			rb = rb->rb_right;
    323 		} else {
    324 			rb = rb->rb_left;
    325 		}
    326 	} while (rb);
    327 
    328 	return best;
    329 }
    330 
    331 static struct drm_mm_node *find_hole(struct drm_mm *mm, u64 addr)
    332 {
    333 	struct rb_node *rb = mm->holes_addr.rb_node;
    334 	struct drm_mm_node *node = NULL;
    335 
    336 	while (rb) {
    337 		u64 hole_start;
    338 
    339 		node = rb_hole_addr_to_node(rb);
    340 		hole_start = __drm_mm_hole_node_start(node);
    341 
    342 		if (addr < hole_start)
    343 			rb = node->rb_hole_addr.rb_left;
    344 		else if (addr > hole_start + node->hole_size)
    345 			rb = node->rb_hole_addr.rb_right;
    346 		else
    347 			break;
    348 	}
    349 
    350 	return node;
    351 }
    352 
    353 static struct drm_mm_node *
    354 first_hole(struct drm_mm *mm,
    355 	   u64 start, u64 end, u64 size,
    356 	   enum drm_mm_insert_mode mode)
    357 {
    358 	switch (mode) {
    359 	default:
    360 	case DRM_MM_INSERT_BEST:
    361 		return best_hole(mm, size);
    362 
    363 	case DRM_MM_INSERT_LOW:
    364 		return find_hole(mm, start);
    365 
    366 	case DRM_MM_INSERT_HIGH:
    367 		return find_hole(mm, end);
    368 
    369 	case DRM_MM_INSERT_EVICT:
    370 		return list_first_entry_or_null(&mm->hole_stack,
    371 						struct drm_mm_node,
    372 						hole_stack);
    373 	}
    374 }
    375 
    376 static struct drm_mm_node *
    377 next_hole(struct drm_mm *mm,
    378 	  struct drm_mm_node *node,
    379 	  enum drm_mm_insert_mode mode)
    380 {
    381 	switch (mode) {
    382 	default:
    383 	case DRM_MM_INSERT_BEST:
    384 		return rb_hole_size_to_node(rb_prev(&node->rb_hole_size));
    385 
    386 	case DRM_MM_INSERT_LOW:
    387 		return rb_hole_addr_to_node(rb_next(&node->rb_hole_addr));
    388 
    389 	case DRM_MM_INSERT_HIGH:
    390 		return rb_hole_addr_to_node(rb_prev(&node->rb_hole_addr));
    391 
    392 	case DRM_MM_INSERT_EVICT:
    393 		node = list_next_entry(node, hole_stack);
    394 		return &node->hole_stack == &mm->hole_stack ? NULL : node;
    395 	}
    396 }
    397 
    398 /**
    399  * drm_mm_reserve_node - insert an pre-initialized node
    400  * @mm: drm_mm allocator to insert @node into
    401  * @node: drm_mm_node to insert
    402  *
    403  * This functions inserts an already set-up &drm_mm_node into the allocator,
    404  * meaning that start, size and color must be set by the caller. All other
    405  * fields must be cleared to 0. This is useful to initialize the allocator with
    406  * preallocated objects which must be set-up before the range allocator can be
    407  * set-up, e.g. when taking over a firmware framebuffer.
    408  *
    409  * Returns:
    410  * 0 on success, -ENOSPC if there's no hole where @node is.
    411  */
    412 int drm_mm_reserve_node(struct drm_mm *mm, struct drm_mm_node *node)
    413 {
    414 	u64 end = node->start + node->size;
    415 	struct drm_mm_node *hole;
    416 	u64 hole_start, hole_end;
    417 	u64 adj_start, adj_end;
    418 
    419 	end = node->start + node->size;
    420 	if (unlikely(end <= node->start))
    421 		return -ENOSPC;
    422 
    423 	/* Find the relevant hole to add our node to */
    424 	hole = find_hole(mm, node->start);
    425 	if (!hole)
    426 		return -ENOSPC;
    427 
    428 	adj_start = hole_start = __drm_mm_hole_node_start(hole);
    429 	adj_end = hole_end = hole_start + hole->hole_size;
    430 
    431 	if (mm->color_adjust)
    432 		mm->color_adjust(hole, node->color, &adj_start, &adj_end);
    433 
    434 	if (adj_start > node->start || adj_end < end)
    435 		return -ENOSPC;
    436 
    437 	node->mm = mm;
    438 
    439 	__set_bit(DRM_MM_NODE_ALLOCATED_BIT, &node->flags);
    440 	list_add(&node->node_list, &hole->node_list);
    441 	drm_mm_interval_tree_add_node(hole, node);
    442 	node->hole_size = 0;
    443 
    444 	rm_hole(hole);
    445 	if (node->start > hole_start)
    446 		add_hole(hole);
    447 	if (end < hole_end)
    448 		add_hole(node);
    449 
    450 	save_stack(node);
    451 	return 0;
    452 }
    453 EXPORT_SYMBOL(drm_mm_reserve_node);
    454 
    455 static u64 rb_to_hole_size_or_zero(struct rb_node *rb)
    456 {
    457 	return rb ? rb_to_hole_size(rb) : 0;
    458 }
    459 
    460 /**
    461  * drm_mm_insert_node_in_range - ranged search for space and insert @node
    462  * @mm: drm_mm to allocate from
    463  * @node: preallocate node to insert
    464  * @size: size of the allocation
    465  * @alignment: alignment of the allocation
    466  * @color: opaque tag value to use for this node
    467  * @range_start: start of the allowed range for this node
    468  * @range_end: end of the allowed range for this node
    469  * @mode: fine-tune the allocation search and placement
    470  *
    471  * The preallocated @node must be cleared to 0.
    472  *
    473  * Returns:
    474  * 0 on success, -ENOSPC if there's no suitable hole.
    475  */
    476 int drm_mm_insert_node_in_range(struct drm_mm * const mm,
    477 				struct drm_mm_node * const node,
    478 				u64 size, u64 alignment,
    479 				unsigned long color,
    480 				u64 range_start, u64 range_end,
    481 				enum drm_mm_insert_mode mode)
    482 {
    483 	struct drm_mm_node *hole;
    484 	u64 remainder_mask;
    485 	bool once;
    486 
    487 	DRM_MM_BUG_ON(range_start > range_end);
    488 
    489 	if (unlikely(size == 0 || range_end - range_start < size))
    490 		return -ENOSPC;
    491 
    492 	if (rb_to_hole_size_or_zero(rb_first_cached(&mm->holes_size)) < size)
    493 		return -ENOSPC;
    494 
    495 	if (alignment <= 1)
    496 		alignment = 0;
    497 
    498 	once = mode & DRM_MM_INSERT_ONCE;
    499 	mode &= ~DRM_MM_INSERT_ONCE;
    500 
    501 	remainder_mask = is_power_of_2(alignment) ? alignment - 1 : 0;
    502 	for (hole = first_hole(mm, range_start, range_end, size, mode);
    503 	     hole;
    504 	     hole = once ? NULL : next_hole(mm, hole, mode)) {
    505 		u64 hole_start = __drm_mm_hole_node_start(hole);
    506 		u64 hole_end = hole_start + hole->hole_size;
    507 		u64 adj_start, adj_end;
    508 		u64 col_start, col_end;
    509 
    510 		if (mode == DRM_MM_INSERT_LOW && hole_start >= range_end)
    511 			break;
    512 
    513 		if (mode == DRM_MM_INSERT_HIGH && hole_end <= range_start)
    514 			break;
    515 
    516 		col_start = hole_start;
    517 		col_end = hole_end;
    518 		if (mm->color_adjust)
    519 			mm->color_adjust(hole, color, &col_start, &col_end);
    520 
    521 		adj_start = max(col_start, range_start);
    522 		adj_end = min(col_end, range_end);
    523 
    524 		if (adj_end <= adj_start || adj_end - adj_start < size)
    525 			continue;
    526 
    527 		if (mode == DRM_MM_INSERT_HIGH)
    528 			adj_start = adj_end - size;
    529 
    530 		if (alignment) {
    531 			u64 rem;
    532 
    533 			if (likely(remainder_mask))
    534 				rem = adj_start & remainder_mask;
    535 			else
    536 				div64_u64_rem(adj_start, alignment, &rem);
    537 			if (rem) {
    538 				adj_start -= rem;
    539 				if (mode != DRM_MM_INSERT_HIGH)
    540 					adj_start += alignment;
    541 
    542 				if (adj_start < max(col_start, range_start) ||
    543 				    min(col_end, range_end) - adj_start < size)
    544 					continue;
    545 
    546 				if (adj_end <= adj_start ||
    547 				    adj_end - adj_start < size)
    548 					continue;
    549 			}
    550 		}
    551 
    552 		node->mm = mm;
    553 		node->size = size;
    554 		node->start = adj_start;
    555 		node->color = color;
    556 		node->hole_size = 0;
    557 
    558 		__set_bit(DRM_MM_NODE_ALLOCATED_BIT, &node->flags);
    559 		list_add(&node->node_list, &hole->node_list);
    560 		drm_mm_interval_tree_add_node(hole, node);
    561 
    562 		rm_hole(hole);
    563 		if (adj_start > hole_start)
    564 			add_hole(hole);
    565 		if (adj_start + size < hole_end)
    566 			add_hole(node);
    567 
    568 		save_stack(node);
    569 		return 0;
    570 	}
    571 
    572 	return -ENOSPC;
    573 }
    574 EXPORT_SYMBOL(drm_mm_insert_node_in_range);
    575 
    576 static inline bool drm_mm_node_scanned_block(const struct drm_mm_node *node)
    577 {
    578 	return test_bit(DRM_MM_NODE_SCANNED_BIT, &node->flags);
    579 }
    580 
    581 /**
    582  * drm_mm_remove_node - Remove a memory node from the allocator.
    583  * @node: drm_mm_node to remove
    584  *
    585  * This just removes a node from its drm_mm allocator. The node does not need to
    586  * be cleared again before it can be re-inserted into this or any other drm_mm
    587  * allocator. It is a bug to call this function on a unallocated node.
    588  */
    589 void drm_mm_remove_node(struct drm_mm_node *node)
    590 {
    591 	struct drm_mm *mm = node->mm;
    592 	struct drm_mm_node *prev_node;
    593 
    594 	DRM_MM_BUG_ON(!drm_mm_node_allocated(node));
    595 	DRM_MM_BUG_ON(drm_mm_node_scanned_block(node));
    596 
    597 	prev_node = list_prev_entry(node, node_list);
    598 
    599 	if (drm_mm_hole_follows(node))
    600 		rm_hole(node);
    601 
    602 	drm_mm_interval_tree_remove(node, &mm->interval_tree);
    603 	list_del(&node->node_list);
    604 
    605 	if (drm_mm_hole_follows(prev_node))
    606 		rm_hole(prev_node);
    607 	add_hole(prev_node);
    608 
    609 	clear_bit_unlock(DRM_MM_NODE_ALLOCATED_BIT, &node->flags);
    610 }
    611 EXPORT_SYMBOL(drm_mm_remove_node);
    612 
    613 /**
    614  * drm_mm_replace_node - move an allocation from @old to @new
    615  * @old: drm_mm_node to remove from the allocator
    616  * @new: drm_mm_node which should inherit @old's allocation
    617  *
    618  * This is useful for when drivers embed the drm_mm_node structure and hence
    619  * can't move allocations by reassigning pointers. It's a combination of remove
    620  * and insert with the guarantee that the allocation start will match.
    621  */
    622 void drm_mm_replace_node(struct drm_mm_node *old, struct drm_mm_node *new)
    623 {
    624 	struct drm_mm *mm = old->mm;
    625 
    626 	DRM_MM_BUG_ON(!drm_mm_node_allocated(old));
    627 
    628 	*new = *old;
    629 
    630 	__set_bit(DRM_MM_NODE_ALLOCATED_BIT, &new->flags);
    631 	list_replace(&old->node_list, &new->node_list);
    632 	rb_replace_node_cached(&old->rb, &new->rb, &mm->interval_tree);
    633 
    634 	if (drm_mm_hole_follows(old)) {
    635 		list_replace(&old->hole_stack, &new->hole_stack);
    636 		rb_replace_node_cached(&old->rb_hole_size,
    637 				       &new->rb_hole_size,
    638 				       &mm->holes_size);
    639 		rb_replace_node(&old->rb_hole_addr,
    640 				&new->rb_hole_addr,
    641 				&mm->holes_addr);
    642 	}
    643 
    644 	clear_bit_unlock(DRM_MM_NODE_ALLOCATED_BIT, &old->flags);
    645 }
    646 EXPORT_SYMBOL(drm_mm_replace_node);
    647 
    648 /**
    649  * DOC: lru scan roster
    650  *
    651  * Very often GPUs need to have continuous allocations for a given object. When
    652  * evicting objects to make space for a new one it is therefore not most
    653  * efficient when we simply start to select all objects from the tail of an LRU
    654  * until there's a suitable hole: Especially for big objects or nodes that
    655  * otherwise have special allocation constraints there's a good chance we evict
    656  * lots of (smaller) objects unnecessarily.
    657  *
    658  * The DRM range allocator supports this use-case through the scanning
    659  * interfaces. First a scan operation needs to be initialized with
    660  * drm_mm_scan_init() or drm_mm_scan_init_with_range(). The driver adds
    661  * objects to the roster, probably by walking an LRU list, but this can be
    662  * freely implemented. Eviction candiates are added using
    663  * drm_mm_scan_add_block() until a suitable hole is found or there are no
    664  * further evictable objects. Eviction roster metadata is tracked in &struct
    665  * drm_mm_scan.
    666  *
    667  * The driver must walk through all objects again in exactly the reverse
    668  * order to restore the allocator state. Note that while the allocator is used
    669  * in the scan mode no other operation is allowed.
    670  *
    671  * Finally the driver evicts all objects selected (drm_mm_scan_remove_block()
    672  * reported true) in the scan, and any overlapping nodes after color adjustment
    673  * (drm_mm_scan_color_evict()). Adding and removing an object is O(1), and
    674  * since freeing a node is also O(1) the overall complexity is
    675  * O(scanned_objects). So like the free stack which needs to be walked before a
    676  * scan operation even begins this is linear in the number of objects. It
    677  * doesn't seem to hurt too badly.
    678  */
    679 
    680 /**
    681  * drm_mm_scan_init_with_range - initialize range-restricted lru scanning
    682  * @scan: scan state
    683  * @mm: drm_mm to scan
    684  * @size: size of the allocation
    685  * @alignment: alignment of the allocation
    686  * @color: opaque tag value to use for the allocation
    687  * @start: start of the allowed range for the allocation
    688  * @end: end of the allowed range for the allocation
    689  * @mode: fine-tune the allocation search and placement
    690  *
    691  * This simply sets up the scanning routines with the parameters for the desired
    692  * hole.
    693  *
    694  * Warning:
    695  * As long as the scan list is non-empty, no other operations than
    696  * adding/removing nodes to/from the scan list are allowed.
    697  */
    698 void drm_mm_scan_init_with_range(struct drm_mm_scan *scan,
    699 				 struct drm_mm *mm,
    700 				 u64 size,
    701 				 u64 alignment,
    702 				 unsigned long color,
    703 				 u64 start,
    704 				 u64 end,
    705 				 enum drm_mm_insert_mode mode)
    706 {
    707 	DRM_MM_BUG_ON(start >= end);
    708 	DRM_MM_BUG_ON(!size || size > end - start);
    709 	DRM_MM_BUG_ON(mm->scan_active);
    710 
    711 	scan->mm = mm;
    712 
    713 	if (alignment <= 1)
    714 		alignment = 0;
    715 
    716 	scan->color = color;
    717 	scan->alignment = alignment;
    718 	scan->remainder_mask = is_power_of_2(alignment) ? alignment - 1 : 0;
    719 	scan->size = size;
    720 	scan->mode = mode;
    721 
    722 	DRM_MM_BUG_ON(end <= start);
    723 	scan->range_start = start;
    724 	scan->range_end = end;
    725 
    726 	scan->hit_start = U64_MAX;
    727 	scan->hit_end = 0;
    728 }
    729 EXPORT_SYMBOL(drm_mm_scan_init_with_range);
    730 
    731 /**
    732  * drm_mm_scan_add_block - add a node to the scan list
    733  * @scan: the active drm_mm scanner
    734  * @node: drm_mm_node to add
    735  *
    736  * Add a node to the scan list that might be freed to make space for the desired
    737  * hole.
    738  *
    739  * Returns:
    740  * True if a hole has been found, false otherwise.
    741  */
    742 bool drm_mm_scan_add_block(struct drm_mm_scan *scan,
    743 			   struct drm_mm_node *node)
    744 {
    745 	struct drm_mm *mm = scan->mm;
    746 	struct drm_mm_node *hole;
    747 	u64 hole_start, hole_end;
    748 	u64 col_start, col_end;
    749 	u64 adj_start, adj_end;
    750 
    751 	DRM_MM_BUG_ON(node->mm != mm);
    752 	DRM_MM_BUG_ON(!drm_mm_node_allocated(node));
    753 	DRM_MM_BUG_ON(drm_mm_node_scanned_block(node));
    754 	__set_bit(DRM_MM_NODE_SCANNED_BIT, &node->flags);
    755 	mm->scan_active++;
    756 
    757 	/* Remove this block from the node_list so that we enlarge the hole
    758 	 * (distance between the end of our previous node and the start of
    759 	 * or next), without poisoning the link so that we can restore it
    760 	 * later in drm_mm_scan_remove_block().
    761 	 */
    762 	hole = list_prev_entry(node, node_list);
    763 	DRM_MM_BUG_ON(list_next_entry(hole, node_list) != node);
    764 	__list_del_entry(&node->node_list);
    765 
    766 	hole_start = __drm_mm_hole_node_start(hole);
    767 	hole_end = __drm_mm_hole_node_end(hole);
    768 
    769 	col_start = hole_start;
    770 	col_end = hole_end;
    771 	if (mm->color_adjust)
    772 		mm->color_adjust(hole, scan->color, &col_start, &col_end);
    773 
    774 	adj_start = max(col_start, scan->range_start);
    775 	adj_end = min(col_end, scan->range_end);
    776 	if (adj_end <= adj_start || adj_end - adj_start < scan->size)
    777 		return false;
    778 
    779 	if (scan->mode == DRM_MM_INSERT_HIGH)
    780 		adj_start = adj_end - scan->size;
    781 
    782 	if (scan->alignment) {
    783 		u64 rem;
    784 
    785 		if (likely(scan->remainder_mask))
    786 			rem = adj_start & scan->remainder_mask;
    787 		else
    788 			div64_u64_rem(adj_start, scan->alignment, &rem);
    789 		if (rem) {
    790 			adj_start -= rem;
    791 			if (scan->mode != DRM_MM_INSERT_HIGH)
    792 				adj_start += scan->alignment;
    793 			if (adj_start < max(col_start, scan->range_start) ||
    794 			    min(col_end, scan->range_end) - adj_start < scan->size)
    795 				return false;
    796 
    797 			if (adj_end <= adj_start ||
    798 			    adj_end - adj_start < scan->size)
    799 				return false;
    800 		}
    801 	}
    802 
    803 	scan->hit_start = adj_start;
    804 	scan->hit_end = adj_start + scan->size;
    805 
    806 	DRM_MM_BUG_ON(scan->hit_start >= scan->hit_end);
    807 	DRM_MM_BUG_ON(scan->hit_start < hole_start);
    808 	DRM_MM_BUG_ON(scan->hit_end > hole_end);
    809 
    810 	return true;
    811 }
    812 EXPORT_SYMBOL(drm_mm_scan_add_block);
    813 
    814 /**
    815  * drm_mm_scan_remove_block - remove a node from the scan list
    816  * @scan: the active drm_mm scanner
    817  * @node: drm_mm_node to remove
    818  *
    819  * Nodes **must** be removed in exactly the reverse order from the scan list as
    820  * they have been added (e.g. using list_add() as they are added and then
    821  * list_for_each() over that eviction list to remove), otherwise the internal
    822  * state of the memory manager will be corrupted.
    823  *
    824  * When the scan list is empty, the selected memory nodes can be freed. An
    825  * immediately following drm_mm_insert_node_in_range_generic() or one of the
    826  * simpler versions of that function with !DRM_MM_SEARCH_BEST will then return
    827  * the just freed block (because it's at the top of the free_stack list).
    828  *
    829  * Returns:
    830  * True if this block should be evicted, false otherwise. Will always
    831  * return false when no hole has been found.
    832  */
    833 bool drm_mm_scan_remove_block(struct drm_mm_scan *scan,
    834 			      struct drm_mm_node *node)
    835 {
    836 	struct drm_mm_node *prev_node;
    837 
    838 	DRM_MM_BUG_ON(node->mm != scan->mm);
    839 	DRM_MM_BUG_ON(!drm_mm_node_scanned_block(node));
    840 	__clear_bit(DRM_MM_NODE_SCANNED_BIT, &node->flags);
    841 
    842 	DRM_MM_BUG_ON(!node->mm->scan_active);
    843 	node->mm->scan_active--;
    844 
    845 	/* During drm_mm_scan_add_block() we decoupled this node leaving
    846 	 * its pointers intact. Now that the caller is walking back along
    847 	 * the eviction list we can restore this block into its rightful
    848 	 * place on the full node_list. To confirm that the caller is walking
    849 	 * backwards correctly we check that prev_node->next == node->next,
    850 	 * i.e. both believe the same node should be on the other side of the
    851 	 * hole.
    852 	 */
    853 	prev_node = list_prev_entry(node, node_list);
    854 	DRM_MM_BUG_ON(list_next_entry(prev_node, node_list) !=
    855 		      list_next_entry(node, node_list));
    856 	list_add(&node->node_list, &prev_node->node_list);
    857 
    858 	return (node->start + node->size > scan->hit_start &&
    859 		node->start < scan->hit_end);
    860 }
    861 EXPORT_SYMBOL(drm_mm_scan_remove_block);
    862 
    863 /**
    864  * drm_mm_scan_color_evict - evict overlapping nodes on either side of hole
    865  * @scan: drm_mm scan with target hole
    866  *
    867  * After completing an eviction scan and removing the selected nodes, we may
    868  * need to remove a few more nodes from either side of the target hole if
    869  * mm.color_adjust is being used.
    870  *
    871  * Returns:
    872  * A node to evict, or NULL if there are no overlapping nodes.
    873  */
    874 struct drm_mm_node *drm_mm_scan_color_evict(struct drm_mm_scan *scan)
    875 {
    876 	struct drm_mm *mm = scan->mm;
    877 	struct drm_mm_node *hole;
    878 	u64 hole_start, hole_end;
    879 
    880 	DRM_MM_BUG_ON(list_empty(&mm->hole_stack));
    881 
    882 	if (!mm->color_adjust)
    883 		return NULL;
    884 
    885 	/*
    886 	 * The hole found during scanning should ideally be the first element
    887 	 * in the hole_stack list, but due to side-effects in the driver it
    888 	 * may not be.
    889 	 */
    890 	list_for_each_entry(hole, &mm->hole_stack, hole_stack) {
    891 		hole_start = __drm_mm_hole_node_start(hole);
    892 		hole_end = hole_start + hole->hole_size;
    893 
    894 		if (hole_start <= scan->hit_start &&
    895 		    hole_end >= scan->hit_end)
    896 			break;
    897 	}
    898 
    899 	/* We should only be called after we found the hole previously */
    900 	DRM_MM_BUG_ON(&hole->hole_stack == &mm->hole_stack);
    901 	if (unlikely(&hole->hole_stack == &mm->hole_stack))
    902 		return NULL;
    903 
    904 	DRM_MM_BUG_ON(hole_start > scan->hit_start);
    905 	DRM_MM_BUG_ON(hole_end < scan->hit_end);
    906 
    907 	mm->color_adjust(hole, scan->color, &hole_start, &hole_end);
    908 	if (hole_start > scan->hit_start)
    909 		return hole;
    910 	if (hole_end < scan->hit_end)
    911 		return list_next_entry(hole, node_list);
    912 
    913 	return NULL;
    914 }
    915 EXPORT_SYMBOL(drm_mm_scan_color_evict);
    916 
    917 /**
    918  * drm_mm_init - initialize a drm-mm allocator
    919  * @mm: the drm_mm structure to initialize
    920  * @start: start of the range managed by @mm
    921  * @size: end of the range managed by @mm
    922  *
    923  * Note that @mm must be cleared to 0 before calling this function.
    924  */
    925 void drm_mm_init(struct drm_mm *mm, u64 start, u64 size)
    926 {
    927 	DRM_MM_BUG_ON(start + size <= start);
    928 
    929 	mm->color_adjust = NULL;
    930 
    931 	INIT_LIST_HEAD(&mm->hole_stack);
    932 	mm->interval_tree = RB_ROOT_CACHED;
    933 	mm->holes_size = RB_ROOT_CACHED;
    934 	mm->holes_addr = RB_ROOT;
    935 
    936 	/* Clever trick to avoid a special case in the free hole tracking. */
    937 	INIT_LIST_HEAD(&mm->head_node.node_list);
    938 	mm->head_node.flags = 0;
    939 	mm->head_node.mm = mm;
    940 	mm->head_node.start = start + size;
    941 	mm->head_node.size = -size;
    942 	add_hole(&mm->head_node);
    943 
    944 	mm->scan_active = 0;
    945 }
    946 EXPORT_SYMBOL(drm_mm_init);
    947 
    948 /**
    949  * drm_mm_takedown - clean up a drm_mm allocator
    950  * @mm: drm_mm allocator to clean up
    951  *
    952  * Note that it is a bug to call this function on an allocator which is not
    953  * clean.
    954  */
    955 void drm_mm_takedown(struct drm_mm *mm)
    956 {
    957 	if (WARN(!drm_mm_clean(mm),
    958 		 "Memory manager not clean during takedown.\n"))
    959 		show_leaks(mm);
    960 }
    961 EXPORT_SYMBOL(drm_mm_takedown);
    962 
    963 static u64 drm_mm_dump_hole(struct drm_printer *p, const struct drm_mm_node *entry)
    964 {
    965 	u64 start, size;
    966 
    967 	size = entry->hole_size;
    968 	if (size) {
    969 		start = drm_mm_hole_node_start(entry);
    970 		drm_printf(p, "%#018"PRIx64"-%#018"PRIx64": %"PRIu64": free\n",
    971 			   start, start + size, size);
    972 	}
    973 
    974 	return size;
    975 }
    976 /**
    977  * drm_mm_print - print allocator state
    978  * @mm: drm_mm allocator to print
    979  * @p: DRM printer to use
    980  */
    981 void drm_mm_print(const struct drm_mm *mm, struct drm_printer *p)
    982 {
    983 	const struct drm_mm_node *entry;
    984 	u64 total_used = 0, total_free = 0, total = 0;
    985 
    986 	total_free += drm_mm_dump_hole(p, &mm->head_node);
    987 
    988 	drm_mm_for_each_node(entry, mm) {
    989 		drm_printf(p, "%#018llx-%#018llx: %llu: used\n", entry->start,
    990 			   entry->start + entry->size, entry->size);
    991 		total_used += entry->size;
    992 		total_free += drm_mm_dump_hole(p, entry);
    993 	}
    994 	total = total_free + total_used;
    995 
    996 	drm_printf(p, "total: %llu, used %llu free %llu\n", total,
    997 		   total_used, total_free);
    998 }
    999 EXPORT_SYMBOL(drm_mm_print);
   1000