xref: /netbsd-src/sys/external/bsd/drm2/dist/drm/drm_vma_manager.c (revision 122b5006ee1bd67145794b4cde92f4fe4781a5ec)
1 /*	$NetBSD: drm_vma_manager.c,v 1.2 2018/08/27 04:58:19 riastradh Exp $	*/
2 
3 /*
4  * Copyright (c) 2006-2009 VMware, Inc., Palo Alto, CA., USA
5  * Copyright (c) 2012 David Airlie <airlied@linux.ie>
6  * Copyright (c) 2013 David Herrmann <dh.herrmann@gmail.com>
7  *
8  * Permission is hereby granted, free of charge, to any person obtaining a
9  * copy of this software and associated documentation files (the "Software"),
10  * to deal in the Software without restriction, including without limitation
11  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12  * and/or sell copies of the Software, and to permit persons to whom the
13  * Software is furnished to do so, subject to the following conditions:
14  *
15  * The above copyright notice and this permission notice shall be included in
16  * all copies or substantial portions of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
21  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
22  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
23  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
24  * OTHER DEALINGS IN THE SOFTWARE.
25  */
26 
27 #include <sys/cdefs.h>
28 __KERNEL_RCSID(0, "$NetBSD: drm_vma_manager.c,v 1.2 2018/08/27 04:58:19 riastradh Exp $");
29 
30 #include <drm/drmP.h>
31 #include <drm/drm_mm.h>
32 #include <drm/drm_vma_manager.h>
33 #include <linux/fs.h>
34 #include <linux/mm.h>
35 #include <linux/module.h>
36 #include <linux/rbtree.h>
37 #include <linux/slab.h>
38 #include <linux/spinlock.h>
39 #include <linux/types.h>
40 
41 /**
42  * DOC: vma offset manager
43  *
44  * The vma-manager is responsible to map arbitrary driver-dependent memory
45  * regions into the linear user address-space. It provides offsets to the
46  * caller which can then be used on the address_space of the drm-device. It
47  * takes care to not overlap regions, size them appropriately and to not
48  * confuse mm-core by inconsistent fake vm_pgoff fields.
49  * Drivers shouldn't use this for object placement in VMEM. This manager should
50  * only be used to manage mappings into linear user-space VMs.
51  *
52  * We use drm_mm as backend to manage object allocations. But it is highly
53  * optimized for alloc/free calls, not lookups. Hence, we use an rb-tree to
54  * speed up offset lookups.
55  *
56  * You must not use multiple offset managers on a single address_space.
57  * Otherwise, mm-core will be unable to tear down memory mappings as the VM will
58  * no longer be linear.
59  *
60  * This offset manager works on page-based addresses. That is, every argument
61  * and return code (with the exception of drm_vma_node_offset_addr()) is given
62  * in number of pages, not number of bytes. That means, object sizes and offsets
63  * must always be page-aligned (as usual).
64  * If you want to get a valid byte-based user-space address for a given offset,
65  * please see drm_vma_node_offset_addr().
66  *
67  * Additionally to offset management, the vma offset manager also handles access
68  * management. For every open-file context that is allowed to access a given
69  * node, you must call drm_vma_node_allow(). Otherwise, an mmap() call on this
70  * open-file with the offset of the node will fail with -EACCES. To revoke
71  * access again, use drm_vma_node_revoke(). However, the caller is responsible
72  * for destroying already existing mappings, if required.
73  */
74 
75 /**
76  * drm_vma_offset_manager_init - Initialize new offset-manager
77  * @mgr: Manager object
78  * @page_offset: Offset of available memory area (page-based)
79  * @size: Size of available address space range (page-based)
80  *
81  * Initialize a new offset-manager. The offset and area size available for the
82  * manager are given as @page_offset and @size. Both are interpreted as
83  * page-numbers, not bytes.
84  *
85  * Adding/removing nodes from the manager is locked internally and protected
86  * against concurrent access. However, node allocation and destruction is left
87  * for the caller. While calling into the vma-manager, a given node must
88  * always be guaranteed to be referenced.
89  */
90 void drm_vma_offset_manager_init(struct drm_vma_offset_manager *mgr,
91 				 unsigned long page_offset, unsigned long size)
92 {
93 	rwlock_init(&mgr->vm_lock);
94 	mgr->vm_addr_space_rb = RB_ROOT;
95 	drm_mm_init(&mgr->vm_addr_space_mm, page_offset, size);
96 }
97 EXPORT_SYMBOL(drm_vma_offset_manager_init);
98 
99 /**
100  * drm_vma_offset_manager_destroy() - Destroy offset manager
101  * @mgr: Manager object
102  *
103  * Destroy an object manager which was previously created via
104  * drm_vma_offset_manager_init(). The caller must remove all allocated nodes
105  * before destroying the manager. Otherwise, drm_mm will refuse to free the
106  * requested resources.
107  *
108  * The manager must not be accessed after this function is called.
109  */
110 void drm_vma_offset_manager_destroy(struct drm_vma_offset_manager *mgr)
111 {
112 	/* take the lock to protect against buggy drivers */
113 	write_lock(&mgr->vm_lock);
114 	drm_mm_takedown(&mgr->vm_addr_space_mm);
115 	write_unlock(&mgr->vm_lock);
116 }
117 EXPORT_SYMBOL(drm_vma_offset_manager_destroy);
118 
119 /**
120  * drm_vma_offset_lookup_locked() - Find node in offset space
121  * @mgr: Manager object
122  * @start: Start address for object (page-based)
123  * @pages: Size of object (page-based)
124  *
125  * Find a node given a start address and object size. This returns the _best_
126  * match for the given node. That is, @start may point somewhere into a valid
127  * region and the given node will be returned, as long as the node spans the
128  * whole requested area (given the size in number of pages as @pages).
129  *
130  * Note that before lookup the vma offset manager lookup lock must be acquired
131  * with drm_vma_offset_lock_lookup(). See there for an example. This can then be
132  * used to implement weakly referenced lookups using kref_get_unless_zero().
133  *
134  * Example:
135  *     drm_vma_offset_lock_lookup(mgr);
136  *     node = drm_vma_offset_lookup_locked(mgr);
137  *     if (node)
138  *         kref_get_unless_zero(container_of(node, sth, entr));
139  *     drm_vma_offset_unlock_lookup(mgr);
140  *
141  * RETURNS:
142  * Returns NULL if no suitable node can be found. Otherwise, the best match
143  * is returned. It's the caller's responsibility to make sure the node doesn't
144  * get destroyed before the caller can access it.
145  */
146 struct drm_vma_offset_node *drm_vma_offset_lookup_locked(struct drm_vma_offset_manager *mgr,
147 							 unsigned long start,
148 							 unsigned long pages)
149 {
150 	struct drm_vma_offset_node *node, *best;
151 	struct rb_node *iter;
152 	unsigned long offset;
153 
154 	iter = mgr->vm_addr_space_rb.rb_node;
155 	best = NULL;
156 
157 	while (likely(iter)) {
158 		node = rb_entry(iter, struct drm_vma_offset_node, vm_rb);
159 		offset = node->vm_node.start;
160 		if (start >= offset) {
161 			iter = iter->rb_right;
162 			best = node;
163 			if (start == offset)
164 				break;
165 		} else {
166 			iter = iter->rb_left;
167 		}
168 	}
169 
170 	/* verify that the node spans the requested area */
171 	if (best) {
172 		offset = best->vm_node.start + best->vm_node.size;
173 		if (offset < start + pages)
174 			best = NULL;
175 	}
176 
177 	return best;
178 }
179 EXPORT_SYMBOL(drm_vma_offset_lookup_locked);
180 
181 /* internal helper to link @node into the rb-tree */
182 static void _drm_vma_offset_add_rb(struct drm_vma_offset_manager *mgr,
183 				   struct drm_vma_offset_node *node)
184 {
185 	struct rb_node **iter = &mgr->vm_addr_space_rb.rb_node;
186 	struct rb_node *parent = NULL;
187 	struct drm_vma_offset_node *iter_node;
188 
189 	while (likely(*iter)) {
190 		parent = *iter;
191 		iter_node = rb_entry(*iter, struct drm_vma_offset_node, vm_rb);
192 
193 		if (node->vm_node.start < iter_node->vm_node.start)
194 			iter = &(*iter)->rb_left;
195 		else if (node->vm_node.start > iter_node->vm_node.start)
196 			iter = &(*iter)->rb_right;
197 		else
198 			BUG();
199 	}
200 
201 	rb_link_node(&node->vm_rb, parent, iter);
202 	rb_insert_color(&node->vm_rb, &mgr->vm_addr_space_rb);
203 }
204 
205 /**
206  * drm_vma_offset_add() - Add offset node to manager
207  * @mgr: Manager object
208  * @node: Node to be added
209  * @pages: Allocation size visible to user-space (in number of pages)
210  *
211  * Add a node to the offset-manager. If the node was already added, this does
212  * nothing and return 0. @pages is the size of the object given in number of
213  * pages.
214  * After this call succeeds, you can access the offset of the node until it
215  * is removed again.
216  *
217  * If this call fails, it is safe to retry the operation or call
218  * drm_vma_offset_remove(), anyway. However, no cleanup is required in that
219  * case.
220  *
221  * @pages is not required to be the same size as the underlying memory object
222  * that you want to map. It only limits the size that user-space can map into
223  * their address space.
224  *
225  * RETURNS:
226  * 0 on success, negative error code on failure.
227  */
228 int drm_vma_offset_add(struct drm_vma_offset_manager *mgr,
229 		       struct drm_vma_offset_node *node, unsigned long pages)
230 {
231 	int ret;
232 
233 	write_lock(&mgr->vm_lock);
234 
235 	if (drm_mm_node_allocated(&node->vm_node)) {
236 		ret = 0;
237 		goto out_unlock;
238 	}
239 
240 	ret = drm_mm_insert_node(&mgr->vm_addr_space_mm, &node->vm_node,
241 				 pages, 0, DRM_MM_SEARCH_DEFAULT);
242 	if (ret)
243 		goto out_unlock;
244 
245 	_drm_vma_offset_add_rb(mgr, node);
246 
247 out_unlock:
248 	write_unlock(&mgr->vm_lock);
249 	return ret;
250 }
251 EXPORT_SYMBOL(drm_vma_offset_add);
252 
253 /**
254  * drm_vma_offset_remove() - Remove offset node from manager
255  * @mgr: Manager object
256  * @node: Node to be removed
257  *
258  * Remove a node from the offset manager. If the node wasn't added before, this
259  * does nothing. After this call returns, the offset and size will be 0 until a
260  * new offset is allocated via drm_vma_offset_add() again. Helper functions like
261  * drm_vma_node_start() and drm_vma_node_offset_addr() will return 0 if no
262  * offset is allocated.
263  */
264 void drm_vma_offset_remove(struct drm_vma_offset_manager *mgr,
265 			   struct drm_vma_offset_node *node)
266 {
267 	write_lock(&mgr->vm_lock);
268 
269 	if (drm_mm_node_allocated(&node->vm_node)) {
270 		rb_erase(&node->vm_rb, &mgr->vm_addr_space_rb);
271 		drm_mm_remove_node(&node->vm_node);
272 		memset(&node->vm_node, 0, sizeof(node->vm_node));
273 	}
274 
275 	write_unlock(&mgr->vm_lock);
276 }
277 EXPORT_SYMBOL(drm_vma_offset_remove);
278 
279 /**
280  * drm_vma_node_allow - Add open-file to list of allowed users
281  * @node: Node to modify
282  * @filp: Open file to add
283  *
284  * Add @filp to the list of allowed open-files for this node. If @filp is
285  * already on this list, the ref-count is incremented.
286  *
287  * The list of allowed-users is preserved across drm_vma_offset_add() and
288  * drm_vma_offset_remove() calls. You may even call it if the node is currently
289  * not added to any offset-manager.
290  *
291  * You must remove all open-files the same number of times as you added them
292  * before destroying the node. Otherwise, you will leak memory.
293  *
294  * This is locked against concurrent access internally.
295  *
296  * RETURNS:
297  * 0 on success, negative error code on internal failure (out-of-mem)
298  */
299 int drm_vma_node_allow(struct drm_vma_offset_node *node, struct file *filp)
300 {
301 	struct rb_node **iter;
302 	struct rb_node *parent = NULL;
303 	struct drm_vma_offset_file *new, *entry;
304 	int ret = 0;
305 
306 	/* Preallocate entry to avoid atomic allocations below. It is quite
307 	 * unlikely that an open-file is added twice to a single node so we
308 	 * don't optimize for this case. OOM is checked below only if the entry
309 	 * is actually used. */
310 	new = kmalloc(sizeof(*entry), GFP_KERNEL);
311 
312 	write_lock(&node->vm_lock);
313 
314 	iter = &node->vm_files.rb_node;
315 
316 	while (likely(*iter)) {
317 		parent = *iter;
318 		entry = rb_entry(*iter, struct drm_vma_offset_file, vm_rb);
319 
320 		if (filp == entry->vm_filp) {
321 			entry->vm_count++;
322 			goto unlock;
323 		} else if (filp > entry->vm_filp) {
324 			iter = &(*iter)->rb_right;
325 		} else {
326 			iter = &(*iter)->rb_left;
327 		}
328 	}
329 
330 	if (!new) {
331 		ret = -ENOMEM;
332 		goto unlock;
333 	}
334 
335 	new->vm_filp = filp;
336 	new->vm_count = 1;
337 	rb_link_node(&new->vm_rb, parent, iter);
338 	rb_insert_color(&new->vm_rb, &node->vm_files);
339 	new = NULL;
340 
341 unlock:
342 	write_unlock(&node->vm_lock);
343 	kfree(new);
344 	return ret;
345 }
346 EXPORT_SYMBOL(drm_vma_node_allow);
347 
348 /**
349  * drm_vma_node_revoke - Remove open-file from list of allowed users
350  * @node: Node to modify
351  * @filp: Open file to remove
352  *
353  * Decrement the ref-count of @filp in the list of allowed open-files on @node.
354  * If the ref-count drops to zero, remove @filp from the list. You must call
355  * this once for every drm_vma_node_allow() on @filp.
356  *
357  * This is locked against concurrent access internally.
358  *
359  * If @filp is not on the list, nothing is done.
360  */
361 void drm_vma_node_revoke(struct drm_vma_offset_node *node, struct file *filp)
362 {
363 	struct drm_vma_offset_file *entry;
364 	struct rb_node *iter;
365 
366 	write_lock(&node->vm_lock);
367 
368 	iter = node->vm_files.rb_node;
369 	while (likely(iter)) {
370 		entry = rb_entry(iter, struct drm_vma_offset_file, vm_rb);
371 		if (filp == entry->vm_filp) {
372 			if (!--entry->vm_count) {
373 				rb_erase(&entry->vm_rb, &node->vm_files);
374 				kfree(entry);
375 			}
376 			break;
377 		} else if (filp > entry->vm_filp) {
378 			iter = iter->rb_right;
379 		} else {
380 			iter = iter->rb_left;
381 		}
382 	}
383 
384 	write_unlock(&node->vm_lock);
385 }
386 EXPORT_SYMBOL(drm_vma_node_revoke);
387 
388 /**
389  * drm_vma_node_is_allowed - Check whether an open-file is granted access
390  * @node: Node to check
391  * @filp: Open-file to check for
392  *
393  * Search the list in @node whether @filp is currently on the list of allowed
394  * open-files (see drm_vma_node_allow()).
395  *
396  * This is locked against concurrent access internally.
397  *
398  * RETURNS:
399  * true iff @filp is on the list
400  */
401 bool drm_vma_node_is_allowed(struct drm_vma_offset_node *node,
402 			     struct file *filp)
403 {
404 	struct drm_vma_offset_file *entry;
405 	struct rb_node *iter;
406 
407 	read_lock(&node->vm_lock);
408 
409 	iter = node->vm_files.rb_node;
410 	while (likely(iter)) {
411 		entry = rb_entry(iter, struct drm_vma_offset_file, vm_rb);
412 		if (filp == entry->vm_filp)
413 			break;
414 		else if (filp > entry->vm_filp)
415 			iter = iter->rb_right;
416 		else
417 			iter = iter->rb_left;
418 	}
419 
420 	read_unlock(&node->vm_lock);
421 
422 	return iter;
423 }
424 EXPORT_SYMBOL(drm_vma_node_is_allowed);
425