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