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