xref: /linux/drivers/gpu/drm/drm_gpuvm.c (revision f7606400f19ca0291718ce4eed5770798890ea2f)
1 // SPDX-License-Identifier: GPL-2.0-only OR MIT
2 /*
3  * Copyright (c) 2022 Red Hat.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
19  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
20  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21  * OTHER DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *     Danilo Krummrich <dakr@redhat.com>
25  *
26  */
27 
28 #include <drm/drm_gpuvm.h>
29 #include <drm/drm_print.h>
30 
31 #include <linux/export.h>
32 #include <linux/interval_tree_generic.h>
33 #include <linux/mm.h>
34 
35 /**
36  * DOC: Overview
37  *
38  * The DRM GPU VA Manager, represented by struct drm_gpuvm keeps track of a
39  * GPU's virtual address (VA) space and manages the corresponding virtual
40  * mappings represented by &drm_gpuva objects. It also keeps track of the
41  * mapping's backing &drm_gem_object buffers.
42  *
43  * &drm_gem_object buffers maintain a list of &drm_gpuva objects representing
44  * all existing GPU VA mappings using this &drm_gem_object as backing buffer.
45  *
46  * GPU VAs can be flagged as sparse, such that drivers may use GPU VAs to also
47  * keep track of sparse PTEs in order to support Vulkan 'Sparse Resources'.
48  *
49  * The GPU VA manager internally uses a rb-tree to manage the
50  * &drm_gpuva mappings within a GPU's virtual address space.
51  *
52  * The &drm_gpuvm structure contains a special &drm_gpuva representing the
53  * portion of VA space reserved by the kernel. This node is initialized together
54  * with the GPU VA manager instance and removed when the GPU VA manager is
55  * destroyed.
56  *
57  * In a typical application drivers would embed struct drm_gpuvm and
58  * struct drm_gpuva within their own driver specific structures, there won't be
59  * any memory allocations of its own nor memory allocations of &drm_gpuva
60  * entries.
61  *
62  * The data structures needed to store &drm_gpuvas within the &drm_gpuvm are
63  * contained within struct drm_gpuva already. Hence, for inserting &drm_gpuva
64  * entries from within dma-fence signalling critical sections it is enough to
65  * pre-allocate the &drm_gpuva structures.
66  *
67  * &drm_gem_objects which are private to a single VM can share a common
68  * &dma_resv in order to improve locking efficiency (e.g. with &drm_exec).
69  * For this purpose drivers must pass a &drm_gem_object to drm_gpuvm_init(), in
70  * the following called 'resv object', which serves as the container of the
71  * GPUVM's shared &dma_resv. This resv object can be a driver specific
72  * &drm_gem_object, such as the &drm_gem_object containing the root page table,
73  * but it can also be a 'dummy' object, which can be allocated with
74  * drm_gpuvm_resv_object_alloc().
75  *
76  * In order to connect a struct drm_gpuva to its backing &drm_gem_object each
77  * &drm_gem_object maintains a list of &drm_gpuvm_bo structures, and each
78  * &drm_gpuvm_bo contains a list of &drm_gpuva structures.
79  *
80  * A &drm_gpuvm_bo is an abstraction that represents a combination of a
81  * &drm_gpuvm and a &drm_gem_object. Every such combination should be unique.
82  * This is ensured by the API through drm_gpuvm_bo_obtain() and
83  * drm_gpuvm_bo_obtain_prealloc() which first look into the corresponding
84  * &drm_gem_object list of &drm_gpuvm_bos for an existing instance of this
85  * particular combination. If not present, a new instance is created and linked
86  * to the &drm_gem_object.
87  *
88  * &drm_gpuvm_bo structures, since unique for a given &drm_gpuvm, are also used
89  * as entry for the &drm_gpuvm's lists of external and evicted objects. Those
90  * lists are maintained in order to accelerate locking of dma-resv locks and
91  * validation of evicted objects bound in a &drm_gpuvm. For instance, all
92  * &drm_gem_object's &dma_resv of a given &drm_gpuvm can be locked by calling
93  * drm_gpuvm_exec_lock(). Once locked drivers can call drm_gpuvm_validate() in
94  * order to validate all evicted &drm_gem_objects. It is also possible to lock
95  * additional &drm_gem_objects by providing the corresponding parameters to
96  * drm_gpuvm_exec_lock() as well as open code the &drm_exec loop while making
97  * use of helper functions such as drm_gpuvm_prepare_range() or
98  * drm_gpuvm_prepare_objects().
99  *
100  * Every bound &drm_gem_object is treated as external object when its &dma_resv
101  * structure is different than the &drm_gpuvm's common &dma_resv structure.
102  */
103 
104 /**
105  * DOC: Split and Merge
106  *
107  * Besides its capability to manage and represent a GPU VA space, the
108  * GPU VA manager also provides functions to let the &drm_gpuvm calculate a
109  * sequence of operations to satisfy a given map or unmap request.
110  *
111  * Therefore the DRM GPU VA manager provides an algorithm implementing splitting
112  * and merging of existing GPU VA mappings with the ones that are requested to
113  * be mapped or unmapped. This feature is required by the Vulkan API to
114  * implement Vulkan 'Sparse Memory Bindings' - drivers UAPIs often refer to this
115  * as VM BIND.
116  *
117  * Drivers can call drm_gpuvm_sm_map() to receive a sequence of callbacks
118  * containing map, unmap and remap operations for a given newly requested
119  * mapping. The sequence of callbacks represents the set of operations to
120  * execute in order to integrate the new mapping cleanly into the current state
121  * of the GPU VA space.
122  *
123  * Depending on how the new GPU VA mapping intersects with the existing mappings
124  * of the GPU VA space the &drm_gpuvm_ops callbacks contain an arbitrary amount
125  * of unmap operations, a maximum of two remap operations and a single map
126  * operation. The caller might receive no callback at all if no operation is
127  * required, e.g. if the requested mapping already exists in the exact same way.
128  *
129  * The single map operation represents the original map operation requested by
130  * the caller.
131  *
132  * &drm_gpuva_op_unmap contains a 'keep' field, which indicates whether the
133  * &drm_gpuva to unmap is physically contiguous with the original mapping
134  * request. Optionally, if 'keep' is set, drivers may keep the actual page table
135  * entries for this &drm_gpuva, adding the missing page table entries only and
136  * update the &drm_gpuvm's view of things accordingly.
137  *
138  * Drivers may do the same optimization, namely delta page table updates, also
139  * for remap operations. This is possible since &drm_gpuva_op_remap consists of
140  * one unmap operation and one or two map operations, such that drivers can
141  * derive the page table update delta accordingly.
142  *
143  * Note that there can't be more than two existing mappings to split up, one at
144  * the beginning and one at the end of the new mapping, hence there is a
145  * maximum of two remap operations.
146  *
147  * Analogous to drm_gpuvm_sm_map() drm_gpuvm_sm_unmap() uses &drm_gpuvm_ops to
148  * call back into the driver in order to unmap a range of GPU VA space. The
149  * logic behind this function is way simpler though: For all existing mappings
150  * enclosed by the given range unmap operations are created. For mappings which
151  * are only partially located within the given range, remap operations are
152  * created such that those mappings are split up and re-mapped partially.
153  *
154  * As an alternative to drm_gpuvm_sm_map() and drm_gpuvm_sm_unmap(),
155  * drm_gpuvm_sm_map_ops_create() and drm_gpuvm_sm_unmap_ops_create() can be used
156  * to directly obtain an instance of struct drm_gpuva_ops containing a list of
157  * &drm_gpuva_op, which can be iterated with drm_gpuva_for_each_op(). This list
158  * contains the &drm_gpuva_ops analogous to the callbacks one would receive when
159  * calling drm_gpuvm_sm_map() or drm_gpuvm_sm_unmap(). While this way requires
160  * more memory (to allocate the &drm_gpuva_ops), it provides drivers a way to
161  * iterate the &drm_gpuva_op multiple times, e.g. once in a context where memory
162  * allocations are possible (e.g. to allocate GPU page tables) and once in the
163  * dma-fence signalling critical path.
164  *
165  * To update the &drm_gpuvm's view of the GPU VA space drm_gpuva_insert() and
166  * drm_gpuva_remove() may be used. These functions can safely be used from
167  * &drm_gpuvm_ops callbacks originating from drm_gpuvm_sm_map() or
168  * drm_gpuvm_sm_unmap(). However, it might be more convenient to use the
169  * provided helper functions drm_gpuva_map(), drm_gpuva_remap() and
170  * drm_gpuva_unmap() instead.
171  *
172  * The following diagram depicts the basic relationships of existing GPU VA
173  * mappings, a newly requested mapping and the resulting mappings as implemented
174  * by drm_gpuvm_sm_map() - it doesn't cover any arbitrary combinations of these.
175  *
176  * 1) Requested mapping is identical. Replace it, but indicate the backing PTEs
177  *    could be kept.
178  *
179  *    ::
180  *
181  *	     0     a     1
182  *	old: |-----------| (bo_offset=n)
183  *
184  *	     0     a     1
185  *	req: |-----------| (bo_offset=n)
186  *
187  *	     0     a     1
188  *	new: |-----------| (bo_offset=n)
189  *
190  *
191  * 2) Requested mapping is identical, except for the BO offset, hence replace
192  *    the mapping.
193  *
194  *    ::
195  *
196  *	     0     a     1
197  *	old: |-----------| (bo_offset=n)
198  *
199  *	     0     a     1
200  *	req: |-----------| (bo_offset=m)
201  *
202  *	     0     a     1
203  *	new: |-----------| (bo_offset=m)
204  *
205  *
206  * 3) Requested mapping is identical, except for the backing BO, hence replace
207  *    the mapping.
208  *
209  *    ::
210  *
211  *	     0     a     1
212  *	old: |-----------| (bo_offset=n)
213  *
214  *	     0     b     1
215  *	req: |-----------| (bo_offset=n)
216  *
217  *	     0     b     1
218  *	new: |-----------| (bo_offset=n)
219  *
220  *
221  * 4) Existent mapping is a left aligned subset of the requested one, hence
222  *    replace the existing one.
223  *
224  *    ::
225  *
226  *	     0  a  1
227  *	old: |-----|       (bo_offset=n)
228  *
229  *	     0     a     2
230  *	req: |-----------| (bo_offset=n)
231  *
232  *	     0     a     2
233  *	new: |-----------| (bo_offset=n)
234  *
235  *    .. note::
236  *       We expect to see the same result for a request with a different BO
237  *       and/or non-contiguous BO offset.
238  *
239  *
240  * 5) Requested mapping's range is a left aligned subset of the existing one,
241  *    but backed by a different BO. Hence, map the requested mapping and split
242  *    the existing one adjusting its BO offset.
243  *
244  *    ::
245  *
246  *	     0     a     2
247  *	old: |-----------| (bo_offset=n)
248  *
249  *	     0  b  1
250  *	req: |-----|       (bo_offset=n)
251  *
252  *	     0  b  1  a' 2
253  *	new: |-----|-----| (b.bo_offset=n, a.bo_offset=n+1)
254  *
255  *    .. note::
256  *       We expect to see the same result for a request with a different BO
257  *       and/or non-contiguous BO offset.
258  *
259  *
260  * 6) Existent mapping is a superset of the requested mapping. Split it up, but
261  *    indicate that the backing PTEs could be kept.
262  *
263  *    ::
264  *
265  *	     0     a     2
266  *	old: |-----------| (bo_offset=n)
267  *
268  *	     0  a  1
269  *	req: |-----|       (bo_offset=n)
270  *
271  *	     0  a  1  a' 2
272  *	new: |-----|-----| (a.bo_offset=n, a'.bo_offset=n+1)
273  *
274  *
275  * 7) Requested mapping's range is a right aligned subset of the existing one,
276  *    but backed by a different BO. Hence, map the requested mapping and split
277  *    the existing one, without adjusting the BO offset.
278  *
279  *    ::
280  *
281  *	     0     a     2
282  *	old: |-----------| (bo_offset=n)
283  *
284  *	           1  b  2
285  *	req:       |-----| (bo_offset=m)
286  *
287  *	     0  a  1  b  2
288  *	new: |-----|-----| (a.bo_offset=n,b.bo_offset=m)
289  *
290  *
291  * 8) Existent mapping is a superset of the requested mapping. Split it up, but
292  *    indicate that the backing PTEs could be kept.
293  *
294  *    ::
295  *
296  *	      0     a     2
297  *	old: |-----------| (bo_offset=n)
298  *
299  *	           1  a  2
300  *	req:       |-----| (bo_offset=n+1)
301  *
302  *	     0  a' 1  a  2
303  *	new: |-----|-----| (a'.bo_offset=n, a.bo_offset=n+1)
304  *
305  *
306  * 9) Existent mapping is overlapped at the end by the requested mapping backed
307  *    by a different BO. Hence, map the requested mapping and split up the
308  *    existing one, without adjusting the BO offset.
309  *
310  *    ::
311  *
312  *	     0     a     2
313  *	old: |-----------|       (bo_offset=n)
314  *
315  *	           1     b     3
316  *	req:       |-----------| (bo_offset=m)
317  *
318  *	     0  a  1     b     3
319  *	new: |-----|-----------| (a.bo_offset=n,b.bo_offset=m)
320  *
321  *
322  * 10) Existent mapping is overlapped by the requested mapping, both having the
323  *     same backing BO with a contiguous offset. Indicate the backing PTEs of
324  *     the old mapping could be kept.
325  *
326  *     ::
327  *
328  *	      0     a     2
329  *	 old: |-----------|       (bo_offset=n)
330  *
331  *	            1     a     3
332  *	 req:       |-----------| (bo_offset=n+1)
333  *
334  *	      0  a' 1     a     3
335  *	 new: |-----|-----------| (a'.bo_offset=n, a.bo_offset=n+1)
336  *
337  *
338  * 11) Requested mapping's range is a centered subset of the existing one
339  *     having a different backing BO. Hence, map the requested mapping and split
340  *     up the existing one in two mappings, adjusting the BO offset of the right
341  *     one accordingly.
342  *
343  *     ::
344  *
345  *	      0        a        3
346  *	 old: |-----------------| (bo_offset=n)
347  *
348  *	            1  b  2
349  *	 req:       |-----|       (bo_offset=m)
350  *
351  *	      0  a  1  b  2  a' 3
352  *	 new: |-----|-----|-----| (a.bo_offset=n,b.bo_offset=m,a'.bo_offset=n+2)
353  *
354  *
355  * 12) Requested mapping is a contiguous subset of the existing one. Split it
356  *     up, but indicate that the backing PTEs could be kept.
357  *
358  *     ::
359  *
360  *	      0        a        3
361  *	 old: |-----------------| (bo_offset=n)
362  *
363  *	            1  a  2
364  *	 req:       |-----|       (bo_offset=n+1)
365  *
366  *	      0  a' 1  a  2 a'' 3
367  *	 old: |-----|-----|-----| (a'.bo_offset=n, a.bo_offset=n+1, a''.bo_offset=n+2)
368  *
369  *
370  * 13) Existent mapping is a right aligned subset of the requested one, hence
371  *     replace the existing one.
372  *
373  *     ::
374  *
375  *	            1  a  2
376  *	 old:       |-----| (bo_offset=n+1)
377  *
378  *	      0     a     2
379  *	 req: |-----------| (bo_offset=n)
380  *
381  *	      0     a     2
382  *	 new: |-----------| (bo_offset=n)
383  *
384  *     .. note::
385  *        We expect to see the same result for a request with a different bo
386  *        and/or non-contiguous bo_offset.
387  *
388  *
389  * 14) Existent mapping is a centered subset of the requested one, hence
390  *     replace the existing one.
391  *
392  *     ::
393  *
394  *	            1  a  2
395  *	 old:       |-----| (bo_offset=n+1)
396  *
397  *	      0        a       3
398  *	 req: |----------------| (bo_offset=n)
399  *
400  *	      0        a       3
401  *	 new: |----------------| (bo_offset=n)
402  *
403  *     .. note::
404  *        We expect to see the same result for a request with a different bo
405  *        and/or non-contiguous bo_offset.
406  *
407  *
408  * 15) Existent mappings is overlapped at the beginning by the requested mapping
409  *     backed by a different BO. Hence, map the requested mapping and split up
410  *     the existing one, adjusting its BO offset accordingly.
411  *
412  *     ::
413  *
414  *	            1     a     3
415  *	 old:       |-----------| (bo_offset=n)
416  *
417  *	      0     b     2
418  *	 req: |-----------|       (bo_offset=m)
419  *
420  *	      0     b     2  a' 3
421  *	 new: |-----------|-----| (b.bo_offset=m,a.bo_offset=n+2)
422  */
423 
424 /**
425  * DOC: Madvise Logic - Splitting and Traversal
426  *
427  * This logic handles GPU VA range updates by generating remap and map operations
428  * without performing unmaps or merging existing mappings.
429  *
430  * 1) The requested range lies entirely within a single drm_gpuva. The logic splits
431  * the existing mapping at the start and end boundaries and inserts a new map.
432  *
433  * ::
434  *              a      start    end     b
435  *         pre: |-----------------------|
436  *                     drm_gpuva1
437  *
438  *              a      start    end     b
439  *         new: |-----|=========|-------|
440  *               remap   map      remap
441  *
442  * one REMAP and one MAP : Same behaviour as SPLIT and MERGE
443  *
444  * 2) The requested range spans multiple drm_gpuva regions. The logic traverses
445  * across boundaries, remapping the start and end segments, and inserting two
446  * map operations to cover the full range.
447  *
448  * ::           a       start      b              c        end       d
449  *         pre: |------------------|--------------|------------------|
450  *                    drm_gpuva1      drm_gpuva2         drm_gpuva3
451  *
452  *              a       start      b              c        end       d
453  *         new: |-------|==========|--------------|========|---------|
454  *                remap1   map1       drm_gpuva2    map2     remap2
455  *
456  * two REMAPS and two MAPS
457  *
458  * 3) Either start or end lies within a drm_gpuva. A single remap and map operation
459  * are generated to update the affected portion.
460  *
461  *
462  * ::           a/start            b              c        end       d
463  *         pre: |------------------|--------------|------------------|
464  *                    drm_gpuva1      drm_gpuva2         drm_gpuva3
465  *
466  *              a/start            b              c        end       d
467  *         new: |------------------|--------------|========|---------|
468  *                drm_gpuva1         drm_gpuva2     map1     remap1
469  *
470  * ::           a       start      b              c/end              d
471  *         pre: |------------------|--------------|------------------|
472  *                    drm_gpuva1      drm_gpuva2         drm_gpuva3
473  *
474  *              a       start      b              c/end              d
475  *         new: |-------|==========|--------------|------------------|
476  *                remap1   map1       drm_gpuva2        drm_gpuva3
477  *
478  * one REMAP and one MAP
479  *
480  * 4) Both start and end align with existing drm_gpuva boundaries. No operations
481  * are needed as the range is already covered.
482  *
483  * 5) No existing drm_gpuvas. No operations.
484  *
485  * Unlike drm_gpuvm_sm_map_ops_create, this logic avoids unmaps and merging,
486  * focusing solely on remap and map operations for efficient traversal and update.
487  */
488 
489 /**
490  * DOC: Locking
491  *
492  * In terms of managing &drm_gpuva entries DRM GPUVM does not take care of
493  * locking itself, it is the drivers responsibility to take care about locking.
494  * Drivers might want to protect the following operations: inserting, removing
495  * and iterating &drm_gpuva objects as well as generating all kinds of
496  * operations, such as split / merge or prefetch.
497  *
498  * DRM GPUVM also does not take care of the locking of the backing
499  * &drm_gem_object buffers GPU VA lists and &drm_gpuvm_bo abstractions by
500  * itself; drivers are responsible to enforce mutual exclusion using either the
501  * GEMs dma_resv lock or the GEMs gpuva.lock mutex.
502  *
503  * However, DRM GPUVM contains lockdep checks to ensure callers of its API hold
504  * the corresponding lock whenever the &drm_gem_objects GPU VA list is accessed
505  * by functions such as drm_gpuva_link() or drm_gpuva_unlink(), but also
506  * drm_gpuvm_bo_obtain() and drm_gpuvm_bo_put().
507  *
508  * The latter is required since on creation and destruction of a &drm_gpuvm_bo
509  * the &drm_gpuvm_bo is attached / removed from the &drm_gem_objects gpuva list.
510  * Subsequent calls to drm_gpuvm_bo_obtain() for the same &drm_gpuvm and
511  * &drm_gem_object must be able to observe previous creations and destructions
512  * of &drm_gpuvm_bos in order to keep instances unique.
513  *
514  * The &drm_gpuvm's lists for keeping track of external and evicted objects are
515  * protected against concurrent insertion / removal and iteration internally.
516  *
517  * However, drivers still need ensure to protect concurrent calls to functions
518  * iterating those lists, namely drm_gpuvm_prepare_objects() and
519  * drm_gpuvm_validate().
520  *
521  * Alternatively, drivers can set the &DRM_GPUVM_RESV_PROTECTED flag to indicate
522  * that the corresponding &dma_resv locks are held in order to protect the
523  * lists. If &DRM_GPUVM_RESV_PROTECTED is set, internal locking is disabled and
524  * the corresponding lockdep checks are enabled. This is an optimization for
525  * drivers which are capable of taking the corresponding &dma_resv locks and
526  * hence do not require internal locking.
527  */
528 
529 /**
530  * DOC: Examples
531  *
532  * This section gives two examples on how to let the DRM GPUVA Manager generate
533  * &drm_gpuva_op in order to satisfy a given map or unmap request and how to
534  * make use of them.
535  *
536  * The below code is strictly limited to illustrate the generic usage pattern.
537  * To maintain simplicity, it doesn't make use of any abstractions for common
538  * code, different (asynchronous) stages with fence signalling critical paths,
539  * any other helpers or error handling in terms of freeing memory and dropping
540  * previously taken locks.
541  *
542  * 1) Obtain a list of &drm_gpuva_op to create a new mapping::
543  *
544  *	// Allocates a new &drm_gpuva.
545  *	struct drm_gpuva * driver_gpuva_alloc(void);
546  *
547  *	// Typically drivers would embed the &drm_gpuvm and &drm_gpuva
548  *	// structure in individual driver structures and lock the dma-resv with
549  *	// drm_exec or similar helpers.
550  *	int driver_mapping_create(struct drm_gpuvm *gpuvm,
551  *				  u64 addr, u64 range,
552  *				  struct drm_gem_object *obj, u64 offset)
553  *	{
554  *		struct drm_gpuvm_map_req map_req = {
555  *		        .map.va.addr = addr,
556  *	                .map.va.range = range,
557  *	                .map.gem.obj = obj,
558  *	                .map.gem.offset = offset,
559  *	           };
560  *		struct drm_gpuva_ops *ops;
561  *		struct drm_gpuva_op *op
562  *		struct drm_gpuvm_bo *vm_bo;
563  *
564  *		driver_lock_va_space();
565  *		ops = drm_gpuvm_sm_map_ops_create(gpuvm, &map_req);
566  *		if (IS_ERR(ops))
567  *			return PTR_ERR(ops);
568  *
569  *		vm_bo = drm_gpuvm_bo_obtain(gpuvm, obj);
570  *		if (IS_ERR(vm_bo))
571  *			return PTR_ERR(vm_bo);
572  *
573  *		drm_gpuva_for_each_op(op, ops) {
574  *			struct drm_gpuva *va;
575  *
576  *			switch (op->op) {
577  *			case DRM_GPUVA_OP_MAP:
578  *				va = driver_gpuva_alloc();
579  *				if (!va)
580  *					; // unwind previous VA space updates,
581  *					  // free memory and unlock
582  *
583  *				driver_vm_map();
584  *				drm_gpuva_map(gpuvm, va, &op->map);
585  *				drm_gpuva_link(va, vm_bo);
586  *
587  *				break;
588  *			case DRM_GPUVA_OP_REMAP: {
589  *				struct drm_gpuva *prev = NULL, *next = NULL;
590  *
591  *				va = op->remap.unmap->va;
592  *
593  *				if (op->remap.prev) {
594  *					prev = driver_gpuva_alloc();
595  *					if (!prev)
596  *						; // unwind previous VA space
597  *						  // updates, free memory and
598  *						  // unlock
599  *				}
600  *
601  *				if (op->remap.next) {
602  *					next = driver_gpuva_alloc();
603  *					if (!next)
604  *						; // unwind previous VA space
605  *						  // updates, free memory and
606  *						  // unlock
607  *				}
608  *
609  *				driver_vm_remap();
610  *				drm_gpuva_remap(prev, next, &op->remap);
611  *
612  *				if (prev)
613  *					drm_gpuva_link(prev, va->vm_bo);
614  *				if (next)
615  *					drm_gpuva_link(next, va->vm_bo);
616  *				drm_gpuva_unlink(va);
617  *
618  *				break;
619  *			}
620  *			case DRM_GPUVA_OP_UNMAP:
621  *				va = op->unmap->va;
622  *
623  *				driver_vm_unmap();
624  *				drm_gpuva_unlink(va);
625  *				drm_gpuva_unmap(&op->unmap);
626  *
627  *				break;
628  *			default:
629  *				break;
630  *			}
631  *		}
632  *		drm_gpuvm_bo_put(vm_bo);
633  *		driver_unlock_va_space();
634  *
635  *		return 0;
636  *	}
637  *
638  * 2) Receive a callback for each &drm_gpuva_op to create a new mapping::
639  *
640  *	struct driver_context {
641  *		struct drm_gpuvm *gpuvm;
642  *		struct drm_gpuvm_bo *vm_bo;
643  *		struct drm_gpuva *new_va;
644  *		struct drm_gpuva *prev_va;
645  *		struct drm_gpuva *next_va;
646  *	};
647  *
648  *	// ops to pass to drm_gpuvm_init()
649  *	static const struct drm_gpuvm_ops driver_gpuvm_ops = {
650  *		.sm_step_map = driver_gpuva_map,
651  *		.sm_step_remap = driver_gpuva_remap,
652  *		.sm_step_unmap = driver_gpuva_unmap,
653  *	};
654  *
655  *	// Typically drivers would embed the &drm_gpuvm and &drm_gpuva
656  *	// structure in individual driver structures and lock the dma-resv with
657  *	// drm_exec or similar helpers.
658  *	int driver_mapping_create(struct drm_gpuvm *gpuvm,
659  *				  u64 addr, u64 range,
660  *				  struct drm_gem_object *obj, u64 offset)
661  *	{
662  *		struct driver_context ctx;
663  *		struct drm_gpuvm_bo *vm_bo;
664  *		struct drm_gpuva_ops *ops;
665  *		struct drm_gpuva_op *op;
666  *		int ret = 0;
667  *
668  *		ctx.gpuvm = gpuvm;
669  *
670  *		ctx.new_va = kzalloc(sizeof(*ctx.new_va), GFP_KERNEL);
671  *		ctx.prev_va = kzalloc(sizeof(*ctx.prev_va), GFP_KERNEL);
672  *		ctx.next_va = kzalloc(sizeof(*ctx.next_va), GFP_KERNEL);
673  *		ctx.vm_bo = drm_gpuvm_bo_create(gpuvm, obj);
674  *		if (!ctx.new_va || !ctx.prev_va || !ctx.next_va || !vm_bo) {
675  *			ret = -ENOMEM;
676  *			goto out;
677  *		}
678  *
679  *		// Typically protected with a driver specific GEM gpuva lock
680  *		// used in the fence signaling path for drm_gpuva_link() and
681  *		// drm_gpuva_unlink(), hence pre-allocate.
682  *		ctx.vm_bo = drm_gpuvm_bo_obtain_prealloc(ctx.vm_bo);
683  *
684  *		driver_lock_va_space();
685  *		ret = drm_gpuvm_sm_map(gpuvm, &ctx, addr, range, obj, offset);
686  *		driver_unlock_va_space();
687  *
688  *	out:
689  *		drm_gpuvm_bo_put(ctx.vm_bo);
690  *		kfree(ctx.new_va);
691  *		kfree(ctx.prev_va);
692  *		kfree(ctx.next_va);
693  *		return ret;
694  *	}
695  *
696  *	int driver_gpuva_map(struct drm_gpuva_op *op, void *__ctx)
697  *	{
698  *		struct driver_context *ctx = __ctx;
699  *
700  *		drm_gpuva_map(ctx->vm, ctx->new_va, &op->map);
701  *
702  *		drm_gpuva_link(ctx->new_va, ctx->vm_bo);
703  *
704  *		// prevent the new GPUVA from being freed in
705  *		// driver_mapping_create()
706  *		ctx->new_va = NULL;
707  *
708  *		return 0;
709  *	}
710  *
711  *	int driver_gpuva_remap(struct drm_gpuva_op *op, void *__ctx)
712  *	{
713  *		struct driver_context *ctx = __ctx;
714  *		struct drm_gpuva *va = op->remap.unmap->va;
715  *
716  *		drm_gpuva_remap(ctx->prev_va, ctx->next_va, &op->remap);
717  *
718  *		if (op->remap.prev) {
719  *			drm_gpuva_link(ctx->prev_va, va->vm_bo);
720  *			ctx->prev_va = NULL;
721  *		}
722  *
723  *		if (op->remap.next) {
724  *			drm_gpuva_link(ctx->next_va, va->vm_bo);
725  *			ctx->next_va = NULL;
726  *		}
727  *
728  *		drm_gpuva_unlink(va);
729  *		kfree(va);
730  *
731  *		return 0;
732  *	}
733  *
734  *	int driver_gpuva_unmap(struct drm_gpuva_op *op, void *__ctx)
735  *	{
736  *		drm_gpuva_unlink(op->unmap.va);
737  *		drm_gpuva_unmap(&op->unmap);
738  *		kfree(op->unmap.va);
739  *
740  *		return 0;
741  *	}
742  */
743 
744 /**
745  * get_next_vm_bo_from_list() - get the next vm_bo element
746  * @__gpuvm: the &drm_gpuvm
747  * @__list_name: the name of the list we're iterating on
748  * @__local_list: a pointer to the local list used to store already iterated items
749  * @__prev_vm_bo: the previous element we got from get_next_vm_bo_from_list()
750  *
751  * This helper is here to provide lockless list iteration. Lockless as in, the
752  * iterator releases the lock immediately after picking the first element from
753  * the list, so list insertion and deletion can happen concurrently.
754  *
755  * Elements popped from the original list are kept in a local list, so removal
756  * and is_empty checks can still happen while we're iterating the list.
757  */
758 #define get_next_vm_bo_from_list(__gpuvm, __list_name, __local_list, __prev_vm_bo)	\
759 	({										\
760 		struct drm_gpuvm_bo *__vm_bo = NULL;					\
761 											\
762 		drm_gpuvm_bo_put(__prev_vm_bo);						\
763 											\
764 		spin_lock(&(__gpuvm)->__list_name.lock);				\
765 		if (!(__gpuvm)->__list_name.local_list)					\
766 			(__gpuvm)->__list_name.local_list = __local_list;		\
767 		else									\
768 			drm_WARN_ON((__gpuvm)->drm,					\
769 				    (__gpuvm)->__list_name.local_list != __local_list);	\
770 											\
771 		while (!list_empty(&(__gpuvm)->__list_name.list)) {			\
772 			__vm_bo = list_first_entry(&(__gpuvm)->__list_name.list,	\
773 						   struct drm_gpuvm_bo,			\
774 						   list.entry.__list_name);		\
775 			if (kref_get_unless_zero(&__vm_bo->kref)) {			\
776 				list_move_tail(&(__vm_bo)->list.entry.__list_name,	\
777 					       __local_list);				\
778 				break;							\
779 			} else {							\
780 				list_del_init(&(__vm_bo)->list.entry.__list_name);	\
781 				__vm_bo = NULL;						\
782 			}								\
783 		}									\
784 		spin_unlock(&(__gpuvm)->__list_name.lock);				\
785 											\
786 		__vm_bo;								\
787 	})
788 
789 /**
790  * for_each_vm_bo_in_list() - internal vm_bo list iterator
791  * @__gpuvm: the &drm_gpuvm
792  * @__list_name: the name of the list we're iterating on
793  * @__local_list: a pointer to the local list used to store already iterated items
794  * @__vm_bo: the struct drm_gpuvm_bo to assign in each iteration step
795  *
796  * This helper is here to provide lockless list iteration. Lockless as in, the
797  * iterator releases the lock immediately after picking the first element from the
798  * list, hence list insertion and deletion can happen concurrently.
799  *
800  * It is not allowed to re-assign the vm_bo pointer from inside this loop.
801  *
802  * Typical use:
803  *
804  *	struct drm_gpuvm_bo *vm_bo;
805  *	LIST_HEAD(my_local_list);
806  *
807  *	ret = 0;
808  *	for_each_vm_bo_in_list(gpuvm, <list_name>, &my_local_list, vm_bo) {
809  *		ret = do_something_with_vm_bo(..., vm_bo);
810  *		if (ret)
811  *			break;
812  *	}
813  *	// Drop ref in case we break out of the loop.
814  *	drm_gpuvm_bo_put(vm_bo);
815  *	restore_vm_bo_list(gpuvm, <list_name>, &my_local_list);
816  *
817  *
818  * Only used for internal list iterations, not meant to be exposed to the outside
819  * world.
820  */
821 #define for_each_vm_bo_in_list(__gpuvm, __list_name, __local_list, __vm_bo)	\
822 	for (__vm_bo = get_next_vm_bo_from_list(__gpuvm, __list_name,		\
823 						__local_list, NULL);		\
824 	     __vm_bo;								\
825 	     __vm_bo = get_next_vm_bo_from_list(__gpuvm, __list_name,		\
826 						__local_list, __vm_bo))
827 
828 static void
829 __restore_vm_bo_list(struct drm_gpuvm *gpuvm, spinlock_t *lock,
830 		     struct list_head *list, struct list_head **local_list)
831 {
832 	/* Merge back the two lists, moving local list elements to the
833 	 * head to preserve previous ordering, in case it matters.
834 	 */
835 	spin_lock(lock);
836 	if (*local_list) {
837 		list_splice(*local_list, list);
838 		*local_list = NULL;
839 	}
840 	spin_unlock(lock);
841 }
842 
843 /**
844  * restore_vm_bo_list() - move vm_bo elements back to their original list
845  * @__gpuvm: the &drm_gpuvm
846  * @__list_name: the name of the list we're iterating on
847  *
848  * When we're done iterating a vm_bo list, we should call restore_vm_bo_list()
849  * to restore the original state and let new iterations take place.
850  */
851 #define restore_vm_bo_list(__gpuvm, __list_name)			\
852 	__restore_vm_bo_list((__gpuvm), &(__gpuvm)->__list_name.lock,	\
853 			     &(__gpuvm)->__list_name.list,		\
854 			     &(__gpuvm)->__list_name.local_list)
855 
856 static void
857 cond_spin_lock(spinlock_t *lock, bool cond)
858 {
859 	if (cond)
860 		spin_lock(lock);
861 }
862 
863 static void
864 cond_spin_unlock(spinlock_t *lock, bool cond)
865 {
866 	if (cond)
867 		spin_unlock(lock);
868 }
869 
870 static void
871 __drm_gpuvm_bo_list_add(struct drm_gpuvm *gpuvm, spinlock_t *lock,
872 			struct list_head *entry, struct list_head *list)
873 {
874 	cond_spin_lock(lock, !!lock);
875 	if (list_empty(entry))
876 		list_add_tail(entry, list);
877 	cond_spin_unlock(lock, !!lock);
878 }
879 
880 /**
881  * drm_gpuvm_bo_is_zombie() - check whether this vm_bo is scheduled for cleanup
882  * @vm_bo: the &drm_gpuvm_bo
883  *
884  * When a vm_bo is scheduled for cleanup using the bo_defer list, it is not
885  * immediately removed from the evict and extobj lists. Therefore, anyone
886  * iterating these lists should skip entries that are being destroyed.
887  *
888  * Checking the refcount without incrementing it is okay as long as the lock
889  * protecting the evict/extobj list is held for as long as you are using the
890  * vm_bo, because even if the refcount hits zero while you are using it, freeing
891  * the vm_bo requires taking the list's lock.
892  *
893  * Zombie entries can be observed on the evict and extobj lists regardless of
894  * whether DRM_GPUVM_RESV_PROTECTED is used, but they remain on the lists for a
895  * longer time when the resv lock is used because we can't take the resv lock
896  * during run_job() in immediate mode, meaning that they need to remain on the
897  * lists until drm_gpuvm_bo_deferred_cleanup() is called.
898  */
899 static bool
900 drm_gpuvm_bo_is_zombie(struct drm_gpuvm_bo *vm_bo)
901 {
902 	return !kref_read(&vm_bo->kref);
903 }
904 
905 /**
906  * drm_gpuvm_bo_list_add() - insert a vm_bo into the given list
907  * @__vm_bo: the &drm_gpuvm_bo
908  * @__list_name: the name of the list to insert into
909  * @__lock: whether to lock with the internal spinlock
910  *
911  * Inserts the given @__vm_bo into the list specified by @__list_name.
912  */
913 #define drm_gpuvm_bo_list_add(__vm_bo, __list_name, __lock)			\
914 	__drm_gpuvm_bo_list_add((__vm_bo)->vm,					\
915 				__lock ? &(__vm_bo)->vm->__list_name.lock :	\
916 					 NULL,					\
917 				&(__vm_bo)->list.entry.__list_name,		\
918 				&(__vm_bo)->vm->__list_name.list)
919 
920 static void
921 __drm_gpuvm_bo_list_del(struct drm_gpuvm *gpuvm, spinlock_t *lock,
922 			struct list_head *entry, bool init)
923 {
924 	cond_spin_lock(lock, !!lock);
925 	if (init) {
926 		if (!list_empty(entry))
927 			list_del_init(entry);
928 	} else {
929 		list_del(entry);
930 	}
931 	cond_spin_unlock(lock, !!lock);
932 }
933 
934 /**
935  * drm_gpuvm_bo_list_del_init() - remove a vm_bo from the given list
936  * @__vm_bo: the &drm_gpuvm_bo
937  * @__list_name: the name of the list to insert into
938  * @__lock: whether to lock with the internal spinlock
939  *
940  * Removes the given @__vm_bo from the list specified by @__list_name.
941  */
942 #define drm_gpuvm_bo_list_del_init(__vm_bo, __list_name, __lock)		\
943 	__drm_gpuvm_bo_list_del((__vm_bo)->vm,					\
944 				__lock ? &(__vm_bo)->vm->__list_name.lock :	\
945 					 NULL,					\
946 				&(__vm_bo)->list.entry.__list_name,		\
947 				true)
948 
949 /**
950  * drm_gpuvm_bo_list_del() - remove a vm_bo from the given list
951  * @__vm_bo: the &drm_gpuvm_bo
952  * @__list_name: the name of the list to insert into
953  * @__lock: whether to lock with the internal spinlock
954  *
955  * Removes the given @__vm_bo from the list specified by @__list_name.
956  */
957 #define drm_gpuvm_bo_list_del(__vm_bo, __list_name, __lock)			\
958 	__drm_gpuvm_bo_list_del((__vm_bo)->vm,					\
959 				__lock ? &(__vm_bo)->vm->__list_name.lock :	\
960 					 NULL,					\
961 				&(__vm_bo)->list.entry.__list_name,		\
962 				false)
963 
964 #define to_drm_gpuva(__node)	container_of((__node), struct drm_gpuva, rb.node)
965 
966 #define GPUVA_START(node) ((node)->va.addr)
967 #define GPUVA_LAST(node) ((node)->va.addr + (node)->va.range - 1)
968 
969 /* We do not actually use drm_gpuva_it_next(), tell the compiler to not complain
970  * about this.
971  */
972 INTERVAL_TREE_DEFINE(struct drm_gpuva, rb.node, u64, rb.__subtree_last,
973 		     GPUVA_START, GPUVA_LAST, static __maybe_unused,
974 		     drm_gpuva_it)
975 
976 static int __drm_gpuva_insert(struct drm_gpuvm *gpuvm,
977 			      struct drm_gpuva *va);
978 static void __drm_gpuva_remove(struct drm_gpuva *va);
979 
980 static bool
981 drm_gpuvm_check_overflow(u64 addr, u64 range)
982 {
983 	u64 end;
984 
985 	return check_add_overflow(addr, range, &end);
986 }
987 
988 static bool
989 drm_gpuvm_warn_check_overflow(struct drm_gpuvm *gpuvm, u64 addr, u64 range)
990 {
991 	return drm_WARN(gpuvm->drm, drm_gpuvm_check_overflow(addr, range),
992 			"GPUVA address limited to %zu bytes.\n", sizeof(addr));
993 }
994 
995 static bool
996 drm_gpuvm_in_mm_range(struct drm_gpuvm *gpuvm, u64 addr, u64 range)
997 {
998 	u64 end = addr + range;
999 	u64 mm_start = gpuvm->mm_start;
1000 	u64 mm_end = mm_start + gpuvm->mm_range;
1001 
1002 	return addr >= mm_start && end <= mm_end;
1003 }
1004 
1005 static bool
1006 drm_gpuvm_in_kernel_node(struct drm_gpuvm *gpuvm, u64 addr, u64 range)
1007 {
1008 	u64 end = addr + range;
1009 	u64 kstart = gpuvm->kernel_alloc_node.va.addr;
1010 	u64 krange = gpuvm->kernel_alloc_node.va.range;
1011 	u64 kend = kstart + krange;
1012 
1013 	return krange && addr < kend && kstart < end;
1014 }
1015 
1016 /**
1017  * drm_gpuvm_range_valid() - checks whether the given range is valid for the
1018  * given &drm_gpuvm
1019  * @gpuvm: the GPUVM to check the range for
1020  * @addr: the base address
1021  * @range: the range starting from the base address
1022  *
1023  * Checks whether the range is within the GPUVM's managed boundaries.
1024  *
1025  * Returns: true for a valid range, false otherwise
1026  */
1027 bool
1028 drm_gpuvm_range_valid(struct drm_gpuvm *gpuvm,
1029 		      u64 addr, u64 range)
1030 {
1031 	return !drm_gpuvm_check_overflow(addr, range) &&
1032 	       drm_gpuvm_in_mm_range(gpuvm, addr, range) &&
1033 	       !drm_gpuvm_in_kernel_node(gpuvm, addr, range);
1034 }
1035 EXPORT_SYMBOL_GPL(drm_gpuvm_range_valid);
1036 
1037 static void
1038 drm_gpuvm_gem_object_free(struct drm_gem_object *obj)
1039 {
1040 	drm_gem_object_release(obj);
1041 	kfree(obj);
1042 }
1043 
1044 static const struct drm_gem_object_funcs drm_gpuvm_object_funcs = {
1045 	.free = drm_gpuvm_gem_object_free,
1046 };
1047 
1048 /**
1049  * drm_gpuvm_resv_object_alloc() - allocate a dummy &drm_gem_object
1050  * @drm: the drivers &drm_device
1051  *
1052  * Allocates a dummy &drm_gem_object which can be passed to drm_gpuvm_init() in
1053  * order to serve as root GEM object providing the &drm_resv shared across
1054  * &drm_gem_objects local to a single GPUVM.
1055  *
1056  * Returns: the &drm_gem_object on success, NULL on failure
1057  */
1058 struct drm_gem_object *
1059 drm_gpuvm_resv_object_alloc(struct drm_device *drm)
1060 {
1061 	struct drm_gem_object *obj;
1062 
1063 	obj = kzalloc_obj(*obj);
1064 	if (!obj)
1065 		return NULL;
1066 
1067 	obj->funcs = &drm_gpuvm_object_funcs;
1068 	drm_gem_private_object_init(drm, obj, 0);
1069 
1070 	return obj;
1071 }
1072 EXPORT_SYMBOL_GPL(drm_gpuvm_resv_object_alloc);
1073 
1074 /**
1075  * drm_gpuvm_init() - initialize a &drm_gpuvm
1076  * @gpuvm: pointer to the &drm_gpuvm to initialize
1077  * @name: the name of the GPU VA space
1078  * @flags: the &drm_gpuvm_flags for this GPUVM
1079  * @drm: the &drm_device this VM resides in
1080  * @r_obj: the resv &drm_gem_object providing the GPUVM's common &dma_resv
1081  * @start_offset: the start offset of the GPU VA space
1082  * @range: the size of the GPU VA space
1083  * @reserve_offset: the start of the kernel reserved GPU VA area
1084  * @reserve_range: the size of the kernel reserved GPU VA area
1085  * @ops: &drm_gpuvm_ops called on &drm_gpuvm_sm_map / &drm_gpuvm_sm_unmap
1086  *
1087  * The &drm_gpuvm must be initialized with this function before use.
1088  *
1089  * Note that @gpuvm must be cleared to 0 before calling this function. The given
1090  * &name is expected to be managed by the surrounding driver structures.
1091  */
1092 void
1093 drm_gpuvm_init(struct drm_gpuvm *gpuvm, const char *name,
1094 	       enum drm_gpuvm_flags flags,
1095 	       struct drm_device *drm,
1096 	       struct drm_gem_object *r_obj,
1097 	       u64 start_offset, u64 range,
1098 	       u64 reserve_offset, u64 reserve_range,
1099 	       const struct drm_gpuvm_ops *ops)
1100 {
1101 	gpuvm->rb.tree = RB_ROOT_CACHED;
1102 	INIT_LIST_HEAD(&gpuvm->rb.list);
1103 
1104 	INIT_LIST_HEAD(&gpuvm->extobj.list);
1105 	spin_lock_init(&gpuvm->extobj.lock);
1106 
1107 	INIT_LIST_HEAD(&gpuvm->evict.list);
1108 	spin_lock_init(&gpuvm->evict.lock);
1109 
1110 	init_llist_head(&gpuvm->bo_defer);
1111 
1112 	kref_init(&gpuvm->kref);
1113 
1114 	gpuvm->name = name ? name : "unknown";
1115 	gpuvm->flags = flags;
1116 	gpuvm->ops = ops;
1117 	gpuvm->drm = drm;
1118 	gpuvm->r_obj = r_obj;
1119 
1120 	drm_gem_object_get(r_obj);
1121 
1122 	drm_gpuvm_warn_check_overflow(gpuvm, start_offset, range);
1123 	gpuvm->mm_start = start_offset;
1124 	gpuvm->mm_range = range;
1125 
1126 	memset(&gpuvm->kernel_alloc_node, 0, sizeof(struct drm_gpuva));
1127 	if (reserve_range) {
1128 		gpuvm->kernel_alloc_node.va.addr = reserve_offset;
1129 		gpuvm->kernel_alloc_node.va.range = reserve_range;
1130 
1131 		if (likely(!drm_gpuvm_warn_check_overflow(gpuvm, reserve_offset,
1132 							  reserve_range)))
1133 			__drm_gpuva_insert(gpuvm, &gpuvm->kernel_alloc_node);
1134 	}
1135 }
1136 EXPORT_SYMBOL_GPL(drm_gpuvm_init);
1137 
1138 static void
1139 drm_gpuvm_fini(struct drm_gpuvm *gpuvm)
1140 {
1141 	gpuvm->name = NULL;
1142 
1143 	if (gpuvm->kernel_alloc_node.va.range)
1144 		__drm_gpuva_remove(&gpuvm->kernel_alloc_node);
1145 
1146 	drm_WARN(gpuvm->drm, !RB_EMPTY_ROOT(&gpuvm->rb.tree.rb_root),
1147 		 "GPUVA tree is not empty, potentially leaking memory.\n");
1148 
1149 	drm_WARN(gpuvm->drm, !list_empty(&gpuvm->extobj.list),
1150 		 "Extobj list should be empty.\n");
1151 	drm_WARN(gpuvm->drm, !list_empty(&gpuvm->evict.list),
1152 		 "Evict list should be empty.\n");
1153 	drm_WARN(gpuvm->drm, !llist_empty(&gpuvm->bo_defer),
1154 		 "VM BO cleanup list should be empty.\n");
1155 
1156 	drm_gem_object_put(gpuvm->r_obj);
1157 }
1158 
1159 static void
1160 drm_gpuvm_free(struct kref *kref)
1161 {
1162 	struct drm_gpuvm *gpuvm = container_of(kref, struct drm_gpuvm, kref);
1163 
1164 	drm_gpuvm_fini(gpuvm);
1165 
1166 	if (drm_WARN_ON(gpuvm->drm, !gpuvm->ops->vm_free))
1167 		return;
1168 
1169 	gpuvm->ops->vm_free(gpuvm);
1170 }
1171 
1172 /**
1173  * drm_gpuvm_put() - drop a struct drm_gpuvm reference
1174  * @gpuvm: the &drm_gpuvm to release the reference of
1175  *
1176  * This releases a reference to @gpuvm.
1177  *
1178  * This function may be called from atomic context.
1179  */
1180 void
1181 drm_gpuvm_put(struct drm_gpuvm *gpuvm)
1182 {
1183 	if (gpuvm)
1184 		kref_put(&gpuvm->kref, drm_gpuvm_free);
1185 }
1186 EXPORT_SYMBOL_GPL(drm_gpuvm_put);
1187 
1188 static int
1189 exec_prepare_obj(struct drm_exec *exec, struct drm_gem_object *obj,
1190 		 unsigned int num_fences)
1191 {
1192 	return num_fences ? drm_exec_prepare_obj(exec, obj, num_fences) :
1193 			    drm_exec_lock_obj(exec, obj);
1194 }
1195 
1196 /**
1197  * drm_gpuvm_prepare_vm() - prepare the GPUVMs common dma-resv
1198  * @gpuvm: the &drm_gpuvm
1199  * @exec: the &drm_exec context
1200  * @num_fences: the amount of &dma_fences to reserve
1201  *
1202  * Calls drm_exec_prepare_obj() for the GPUVMs dummy &drm_gem_object; if
1203  * @num_fences is zero drm_exec_lock_obj() is called instead.
1204  *
1205  * Using this function directly, it is the drivers responsibility to call
1206  * drm_exec_init() and drm_exec_fini() accordingly.
1207  *
1208  * Returns: 0 on success, negative error code on failure.
1209  */
1210 int
1211 drm_gpuvm_prepare_vm(struct drm_gpuvm *gpuvm,
1212 		     struct drm_exec *exec,
1213 		     unsigned int num_fences)
1214 {
1215 	return exec_prepare_obj(exec, gpuvm->r_obj, num_fences);
1216 }
1217 EXPORT_SYMBOL_GPL(drm_gpuvm_prepare_vm);
1218 
1219 static int
1220 __drm_gpuvm_prepare_objects(struct drm_gpuvm *gpuvm,
1221 			    struct drm_exec *exec,
1222 			    unsigned int num_fences)
1223 {
1224 	struct drm_gpuvm_bo *vm_bo;
1225 	LIST_HEAD(extobjs);
1226 	int ret = 0;
1227 
1228 	for_each_vm_bo_in_list(gpuvm, extobj, &extobjs, vm_bo) {
1229 		ret = exec_prepare_obj(exec, vm_bo->obj, num_fences);
1230 		if (ret)
1231 			break;
1232 	}
1233 	/* Drop ref in case we break out of the loop. */
1234 	drm_gpuvm_bo_put(vm_bo);
1235 	restore_vm_bo_list(gpuvm, extobj);
1236 
1237 	return ret;
1238 }
1239 
1240 static int
1241 drm_gpuvm_prepare_objects_locked(struct drm_gpuvm *gpuvm,
1242 				 struct drm_exec *exec,
1243 				 unsigned int num_fences)
1244 {
1245 	struct drm_gpuvm_bo *vm_bo;
1246 	int ret = 0;
1247 
1248 	drm_gpuvm_resv_assert_held(gpuvm);
1249 	list_for_each_entry(vm_bo, &gpuvm->extobj.list, list.entry.extobj) {
1250 		if (drm_gpuvm_bo_is_zombie(vm_bo))
1251 			continue;
1252 
1253 		ret = exec_prepare_obj(exec, vm_bo->obj, num_fences);
1254 		if (ret)
1255 			break;
1256 
1257 		if (vm_bo->evicted)
1258 			drm_gpuvm_bo_list_add(vm_bo, evict, false);
1259 	}
1260 
1261 	return ret;
1262 }
1263 
1264 /**
1265  * drm_gpuvm_prepare_objects() - prepare all associated BOs
1266  * @gpuvm: the &drm_gpuvm
1267  * @exec: the &drm_exec locking context
1268  * @num_fences: the amount of &dma_fences to reserve
1269  *
1270  * Calls drm_exec_prepare_obj() for all &drm_gem_objects the given
1271  * &drm_gpuvm contains mappings of; if @num_fences is zero drm_exec_lock_obj()
1272  * is called instead.
1273  *
1274  * Using this function directly, it is the drivers responsibility to call
1275  * drm_exec_init() and drm_exec_fini() accordingly.
1276  *
1277  * Note: This function is safe against concurrent insertion and removal of
1278  * external objects, however it is not safe against concurrent usage itself.
1279  *
1280  * Drivers need to make sure to protect this case with either an outer VM lock
1281  * or by calling drm_gpuvm_prepare_vm() before this function within the
1282  * drm_exec_until_all_locked() loop, such that the GPUVM's dma-resv lock ensures
1283  * mutual exclusion.
1284  *
1285  * Returns: 0 on success, negative error code on failure.
1286  */
1287 int
1288 drm_gpuvm_prepare_objects(struct drm_gpuvm *gpuvm,
1289 			  struct drm_exec *exec,
1290 			  unsigned int num_fences)
1291 {
1292 	if (drm_gpuvm_resv_protected(gpuvm))
1293 		return drm_gpuvm_prepare_objects_locked(gpuvm, exec,
1294 							num_fences);
1295 	else
1296 		return __drm_gpuvm_prepare_objects(gpuvm, exec, num_fences);
1297 }
1298 EXPORT_SYMBOL_GPL(drm_gpuvm_prepare_objects);
1299 
1300 /**
1301  * drm_gpuvm_prepare_range() - prepare all BOs mapped within a given range
1302  * @gpuvm: the &drm_gpuvm
1303  * @exec: the &drm_exec locking context
1304  * @addr: the start address within the VA space
1305  * @range: the range to iterate within the VA space
1306  * @num_fences: the amount of &dma_fences to reserve
1307  *
1308  * Calls drm_exec_prepare_obj() for all &drm_gem_objects mapped between @addr
1309  * and @addr + @range; if @num_fences is zero drm_exec_lock_obj() is called
1310  * instead.
1311  *
1312  * Returns: 0 on success, negative error code on failure.
1313  */
1314 int
1315 drm_gpuvm_prepare_range(struct drm_gpuvm *gpuvm, struct drm_exec *exec,
1316 			u64 addr, u64 range, unsigned int num_fences)
1317 {
1318 	struct drm_gpuva *va;
1319 	u64 end = addr + range;
1320 	int ret;
1321 
1322 	drm_gpuvm_for_each_va_range(va, gpuvm, addr, end) {
1323 		struct drm_gem_object *obj = va->gem.obj;
1324 
1325 		if (unlikely(!obj))
1326 			continue;
1327 
1328 		ret = exec_prepare_obj(exec, obj, num_fences);
1329 		if (ret)
1330 			return ret;
1331 	}
1332 
1333 	return 0;
1334 }
1335 EXPORT_SYMBOL_GPL(drm_gpuvm_prepare_range);
1336 
1337 /**
1338  * drm_gpuvm_exec_lock() - lock all dma-resv of all associated BOs
1339  * @vm_exec: the &drm_gpuvm_exec wrapper
1340  *
1341  * Acquires all dma-resv locks of all &drm_gem_objects the given
1342  * &drm_gpuvm contains mappings of.
1343  *
1344  * Additionally, when calling this function with struct drm_gpuvm_exec::extra
1345  * being set the driver receives the given @fn callback to lock additional
1346  * dma-resv in the context of the &drm_gpuvm_exec instance. Typically, drivers
1347  * would call drm_exec_prepare_obj() from within this callback.
1348  *
1349  * Returns: 0 on success, negative error code on failure.
1350  */
1351 int
1352 drm_gpuvm_exec_lock(struct drm_gpuvm_exec *vm_exec)
1353 {
1354 	struct drm_gpuvm *gpuvm = vm_exec->vm;
1355 	struct drm_exec *exec = &vm_exec->exec;
1356 	unsigned int num_fences = vm_exec->num_fences;
1357 	int ret;
1358 
1359 	drm_exec_init(exec, vm_exec->flags, 0);
1360 
1361 	drm_exec_until_all_locked(exec) {
1362 		ret = drm_gpuvm_prepare_vm(gpuvm, exec, num_fences);
1363 		drm_exec_retry_on_contention(exec);
1364 		if (ret)
1365 			goto err;
1366 
1367 		ret = drm_gpuvm_prepare_objects(gpuvm, exec, num_fences);
1368 		drm_exec_retry_on_contention(exec);
1369 		if (ret)
1370 			goto err;
1371 
1372 		if (vm_exec->extra.fn) {
1373 			ret = vm_exec->extra.fn(vm_exec);
1374 			drm_exec_retry_on_contention(exec);
1375 			if (ret)
1376 				goto err;
1377 		}
1378 	}
1379 
1380 	return 0;
1381 
1382 err:
1383 	drm_exec_fini(exec);
1384 	return ret;
1385 }
1386 EXPORT_SYMBOL_GPL(drm_gpuvm_exec_lock);
1387 
1388 static int
1389 fn_lock_array(struct drm_gpuvm_exec *vm_exec)
1390 {
1391 	struct {
1392 		struct drm_gem_object **objs;
1393 		unsigned int num_objs;
1394 	} *args = vm_exec->extra.priv;
1395 
1396 	return drm_exec_prepare_array(&vm_exec->exec, args->objs,
1397 				      args->num_objs, vm_exec->num_fences);
1398 }
1399 
1400 /**
1401  * drm_gpuvm_exec_lock_array() - lock all dma-resv of all associated BOs
1402  * @vm_exec: the &drm_gpuvm_exec wrapper
1403  * @objs: additional &drm_gem_objects to lock
1404  * @num_objs: the number of additional &drm_gem_objects to lock
1405  *
1406  * Acquires all dma-resv locks of all &drm_gem_objects the given &drm_gpuvm
1407  * contains mappings of, plus the ones given through @objs.
1408  *
1409  * Returns: 0 on success, negative error code on failure.
1410  */
1411 int
1412 drm_gpuvm_exec_lock_array(struct drm_gpuvm_exec *vm_exec,
1413 			  struct drm_gem_object **objs,
1414 			  unsigned int num_objs)
1415 {
1416 	struct {
1417 		struct drm_gem_object **objs;
1418 		unsigned int num_objs;
1419 	} args;
1420 
1421 	args.objs = objs;
1422 	args.num_objs = num_objs;
1423 
1424 	vm_exec->extra.fn = fn_lock_array;
1425 	vm_exec->extra.priv = &args;
1426 
1427 	return drm_gpuvm_exec_lock(vm_exec);
1428 }
1429 EXPORT_SYMBOL_GPL(drm_gpuvm_exec_lock_array);
1430 
1431 /**
1432  * drm_gpuvm_exec_lock_range() - prepare all BOs mapped within a given range
1433  * @vm_exec: the &drm_gpuvm_exec wrapper
1434  * @addr: the start address within the VA space
1435  * @range: the range to iterate within the VA space
1436  *
1437  * Acquires all dma-resv locks of all &drm_gem_objects mapped between @addr and
1438  * @addr + @range.
1439  *
1440  * Returns: 0 on success, negative error code on failure.
1441  */
1442 int
1443 drm_gpuvm_exec_lock_range(struct drm_gpuvm_exec *vm_exec,
1444 			  u64 addr, u64 range)
1445 {
1446 	struct drm_gpuvm *gpuvm = vm_exec->vm;
1447 	struct drm_exec *exec = &vm_exec->exec;
1448 	int ret;
1449 
1450 	drm_exec_init(exec, vm_exec->flags, 0);
1451 
1452 	drm_exec_until_all_locked(exec) {
1453 		ret = drm_gpuvm_prepare_range(gpuvm, exec, addr, range,
1454 					      vm_exec->num_fences);
1455 		drm_exec_retry_on_contention(exec);
1456 		if (ret)
1457 			goto err;
1458 	}
1459 
1460 	return ret;
1461 
1462 err:
1463 	drm_exec_fini(exec);
1464 	return ret;
1465 }
1466 EXPORT_SYMBOL_GPL(drm_gpuvm_exec_lock_range);
1467 
1468 static int
1469 __drm_gpuvm_validate(struct drm_gpuvm *gpuvm, struct drm_exec *exec)
1470 {
1471 	const struct drm_gpuvm_ops *ops = gpuvm->ops;
1472 	struct drm_gpuvm_bo *vm_bo;
1473 	LIST_HEAD(evict);
1474 	int ret = 0;
1475 
1476 	for_each_vm_bo_in_list(gpuvm, evict, &evict, vm_bo) {
1477 		ret = ops->vm_bo_validate(vm_bo, exec);
1478 		if (ret)
1479 			break;
1480 	}
1481 	/* Drop ref in case we break out of the loop. */
1482 	drm_gpuvm_bo_put(vm_bo);
1483 	restore_vm_bo_list(gpuvm, evict);
1484 
1485 	return ret;
1486 }
1487 
1488 static int
1489 drm_gpuvm_validate_locked(struct drm_gpuvm *gpuvm, struct drm_exec *exec)
1490 {
1491 	const struct drm_gpuvm_ops *ops = gpuvm->ops;
1492 	struct drm_gpuvm_bo *vm_bo, *next;
1493 	int ret = 0;
1494 
1495 	drm_gpuvm_resv_assert_held(gpuvm);
1496 
1497 	list_for_each_entry_safe(vm_bo, next, &gpuvm->evict.list,
1498 				 list.entry.evict) {
1499 		if (drm_gpuvm_bo_is_zombie(vm_bo))
1500 			continue;
1501 
1502 		ret = ops->vm_bo_validate(vm_bo, exec);
1503 		if (ret)
1504 			break;
1505 
1506 		dma_resv_assert_held(vm_bo->obj->resv);
1507 		if (!vm_bo->evicted)
1508 			drm_gpuvm_bo_list_del_init(vm_bo, evict, false);
1509 	}
1510 
1511 	return ret;
1512 }
1513 
1514 /**
1515  * drm_gpuvm_validate() - validate all BOs marked as evicted
1516  * @gpuvm: the &drm_gpuvm to validate evicted BOs
1517  * @exec: the &drm_exec instance used for locking the GPUVM
1518  *
1519  * Calls the &drm_gpuvm_ops::vm_bo_validate callback for all evicted buffer
1520  * objects being mapped in the given &drm_gpuvm.
1521  *
1522  * Returns: 0 on success, negative error code on failure.
1523  */
1524 int
1525 drm_gpuvm_validate(struct drm_gpuvm *gpuvm, struct drm_exec *exec)
1526 {
1527 	const struct drm_gpuvm_ops *ops = gpuvm->ops;
1528 
1529 	if (unlikely(!ops || !ops->vm_bo_validate))
1530 		return -EOPNOTSUPP;
1531 
1532 	if (drm_gpuvm_resv_protected(gpuvm))
1533 		return drm_gpuvm_validate_locked(gpuvm, exec);
1534 	else
1535 		return __drm_gpuvm_validate(gpuvm, exec);
1536 }
1537 EXPORT_SYMBOL_GPL(drm_gpuvm_validate);
1538 
1539 /**
1540  * drm_gpuvm_resv_add_fence - add fence to private and all extobj
1541  * dma-resv
1542  * @gpuvm: the &drm_gpuvm to add a fence to
1543  * @exec: the &drm_exec locking context
1544  * @fence: fence to add
1545  * @private_usage: private dma-resv usage
1546  * @extobj_usage: extobj dma-resv usage
1547  */
1548 void
1549 drm_gpuvm_resv_add_fence(struct drm_gpuvm *gpuvm,
1550 			 struct drm_exec *exec,
1551 			 struct dma_fence *fence,
1552 			 enum dma_resv_usage private_usage,
1553 			 enum dma_resv_usage extobj_usage)
1554 {
1555 	struct drm_gem_object *obj;
1556 
1557 	drm_exec_for_each_locked_object(exec, obj) {
1558 		dma_resv_assert_held(obj->resv);
1559 		dma_resv_add_fence(obj->resv, fence,
1560 				   drm_gpuvm_is_extobj(gpuvm, obj) ?
1561 				   extobj_usage : private_usage);
1562 	}
1563 }
1564 EXPORT_SYMBOL_GPL(drm_gpuvm_resv_add_fence);
1565 
1566 /**
1567  * drm_gpuvm_bo_create() - create a new instance of struct drm_gpuvm_bo
1568  * @gpuvm: The &drm_gpuvm the @obj is mapped in.
1569  * @obj: The &drm_gem_object being mapped in the @gpuvm.
1570  *
1571  * If provided by the driver, this function uses the &drm_gpuvm_ops
1572  * vm_bo_alloc() callback to allocate.
1573  *
1574  * Returns: a pointer to the &drm_gpuvm_bo on success, NULL on failure
1575  */
1576 struct drm_gpuvm_bo *
1577 drm_gpuvm_bo_create(struct drm_gpuvm *gpuvm,
1578 		    struct drm_gem_object *obj)
1579 {
1580 	const struct drm_gpuvm_ops *ops = gpuvm->ops;
1581 	struct drm_gpuvm_bo *vm_bo;
1582 
1583 	if (ops && ops->vm_bo_alloc)
1584 		vm_bo = ops->vm_bo_alloc();
1585 	else
1586 		vm_bo = kzalloc_obj(*vm_bo);
1587 
1588 	if (unlikely(!vm_bo))
1589 		return NULL;
1590 
1591 	vm_bo->vm = drm_gpuvm_get(gpuvm);
1592 	vm_bo->obj = obj;
1593 	drm_gem_object_get(obj);
1594 
1595 	kref_init(&vm_bo->kref);
1596 	INIT_LIST_HEAD(&vm_bo->list.gpuva);
1597 	INIT_LIST_HEAD(&vm_bo->list.entry.gem);
1598 
1599 	INIT_LIST_HEAD(&vm_bo->list.entry.extobj);
1600 	INIT_LIST_HEAD(&vm_bo->list.entry.evict);
1601 	init_llist_node(&vm_bo->list.entry.bo_defer);
1602 
1603 	return vm_bo;
1604 }
1605 EXPORT_SYMBOL_GPL(drm_gpuvm_bo_create);
1606 
1607 /*
1608  * drm_gpuvm_bo_destroy_not_in_lists() - final part of drm_gpuvm_bo cleanup
1609  * @vm_bo: the &drm_gpuvm_bo to destroy
1610  *
1611  * It is illegal to call this method if the @vm_bo is present in the GEMs gpuva
1612  * list, the extobj list, or the evicted list.
1613  *
1614  * Note that this puts a refcount on the GEM object, which may destroy the GEM
1615  * object if the refcount reaches zero. It's illegal for this to happen if the
1616  * caller holds the GEMs gpuva mutex because it would free the mutex.
1617  */
1618 static void
1619 drm_gpuvm_bo_destroy_not_in_lists(struct drm_gpuvm_bo *vm_bo)
1620 {
1621 	struct drm_gpuvm *gpuvm = vm_bo->vm;
1622 	const struct drm_gpuvm_ops *ops = gpuvm->ops;
1623 	struct drm_gem_object *obj = vm_bo->obj;
1624 
1625 	if (ops && ops->vm_bo_free)
1626 		ops->vm_bo_free(vm_bo);
1627 	else
1628 		kfree(vm_bo);
1629 
1630 	drm_gpuvm_put(gpuvm);
1631 	drm_gem_object_put(obj);
1632 }
1633 
1634 static void
1635 drm_gpuvm_bo_destroy_not_in_lists_kref(struct kref *kref)
1636 {
1637 	struct drm_gpuvm_bo *vm_bo = container_of(kref, struct drm_gpuvm_bo,
1638 						  kref);
1639 
1640 	drm_gpuvm_bo_destroy_not_in_lists(vm_bo);
1641 }
1642 
1643 static void
1644 drm_gpuvm_bo_destroy(struct kref *kref)
1645 {
1646 	struct drm_gpuvm_bo *vm_bo = container_of(kref, struct drm_gpuvm_bo,
1647 						  kref);
1648 	struct drm_gpuvm *gpuvm = vm_bo->vm;
1649 	bool lock = !drm_gpuvm_resv_protected(gpuvm);
1650 
1651 	if (!lock)
1652 		drm_gpuvm_resv_assert_held(gpuvm);
1653 
1654 	drm_gpuvm_bo_list_del(vm_bo, extobj, lock);
1655 	drm_gpuvm_bo_list_del(vm_bo, evict, lock);
1656 
1657 	drm_gem_gpuva_assert_lock_held(gpuvm, vm_bo->obj);
1658 	list_del(&vm_bo->list.entry.gem);
1659 
1660 	drm_gpuvm_bo_destroy_not_in_lists(vm_bo);
1661 }
1662 
1663 /**
1664  * drm_gpuvm_bo_put() - drop a struct drm_gpuvm_bo reference
1665  * @vm_bo: the &drm_gpuvm_bo to release the reference of
1666  *
1667  * This releases a reference to @vm_bo.
1668  *
1669  * If the reference count drops to zero, the &gpuvm_bo is destroyed, which
1670  * includes removing it from the GEMs gpuva list. Hence, if a call to this
1671  * function can potentially let the reference count drop to zero the caller must
1672  * hold the lock that the GEM uses for its gpuva list (either the GEM's
1673  * dma-resv or gpuva.lock mutex).
1674  *
1675  * This function may only be called from non-atomic context.
1676  *
1677  * Returns: true if vm_bo was destroyed, false otherwise.
1678  */
1679 bool
1680 drm_gpuvm_bo_put(struct drm_gpuvm_bo *vm_bo)
1681 {
1682 	might_sleep();
1683 
1684 	if (vm_bo)
1685 		return !!kref_put(&vm_bo->kref, drm_gpuvm_bo_destroy);
1686 
1687 	return false;
1688 }
1689 EXPORT_SYMBOL_GPL(drm_gpuvm_bo_put);
1690 
1691 /*
1692  * drm_gpuvm_bo_into_zombie() - called when the vm_bo becomes a zombie due to
1693  * deferred cleanup
1694  *
1695  * If deferred cleanup is used, then this must be called right after the vm_bo
1696  * refcount drops to zero. Must be called with GEM mutex held. After releasing
1697  * the GEM mutex, drm_gpuvm_bo_defer_zombie_cleanup() must be called.
1698  */
1699 static void
1700 drm_gpuvm_bo_into_zombie(struct kref *kref)
1701 {
1702 	struct drm_gpuvm_bo *vm_bo = container_of(kref, struct drm_gpuvm_bo,
1703 						  kref);
1704 
1705 	if (!drm_gpuvm_resv_protected(vm_bo->vm)) {
1706 		drm_gpuvm_bo_list_del(vm_bo, extobj, true);
1707 		drm_gpuvm_bo_list_del(vm_bo, evict, true);
1708 	}
1709 
1710 	list_del(&vm_bo->list.entry.gem);
1711 }
1712 
1713 /*
1714  * drm_gpuvm_bo_defer_zombie_cleanup() - adds a new zombie vm_bo to the
1715  * bo_defer list
1716  *
1717  * Called after drm_gpuvm_bo_into_zombie(). GEM mutex must not be held.
1718  *
1719  * It's important that the GEM stays alive for the duration in which we hold
1720  * the mutex, but the instant we add the vm_bo to bo_defer, another thread
1721  * might call drm_gpuvm_bo_deferred_cleanup() and put the GEM. Therefore, to
1722  * avoid kfreeing a mutex we are holding, the GEM mutex must be released
1723  * *before* calling this function.
1724  */
1725 static void
1726 drm_gpuvm_bo_defer_zombie_cleanup(struct drm_gpuvm_bo *vm_bo)
1727 {
1728 	llist_add(&vm_bo->list.entry.bo_defer, &vm_bo->vm->bo_defer);
1729 }
1730 
1731 static void
1732 drm_gpuvm_bo_defer_free(struct kref *kref)
1733 {
1734 	struct drm_gpuvm_bo *vm_bo = container_of(kref, struct drm_gpuvm_bo,
1735 						  kref);
1736 
1737 	drm_gpuvm_bo_into_zombie(kref);
1738 	mutex_unlock(&vm_bo->obj->gpuva.lock);
1739 	drm_gpuvm_bo_defer_zombie_cleanup(vm_bo);
1740 }
1741 
1742 /**
1743  * drm_gpuvm_bo_put_deferred() - drop a struct drm_gpuvm_bo reference with
1744  * deferred cleanup
1745  * @vm_bo: the &drm_gpuvm_bo to release the reference of
1746  *
1747  * This releases a reference to @vm_bo.
1748  *
1749  * This might take and release the GEMs GPUVA lock. You should call
1750  * drm_gpuvm_bo_deferred_cleanup() later to complete the cleanup process.
1751  *
1752  * Returns: true if vm_bo is being destroyed, false otherwise.
1753  */
1754 bool
1755 drm_gpuvm_bo_put_deferred(struct drm_gpuvm_bo *vm_bo)
1756 {
1757 	if (!vm_bo)
1758 		return false;
1759 
1760 	drm_WARN_ON(vm_bo->vm->drm, !drm_gpuvm_immediate_mode(vm_bo->vm));
1761 
1762 	return !!kref_put_mutex(&vm_bo->kref,
1763 				drm_gpuvm_bo_defer_free,
1764 				&vm_bo->obj->gpuva.lock);
1765 }
1766 EXPORT_SYMBOL_GPL(drm_gpuvm_bo_put_deferred);
1767 
1768 /**
1769  * drm_gpuvm_bo_deferred_cleanup() - clean up BOs in the deferred list
1770  * deferred cleanup
1771  * @gpuvm: the VM to clean up
1772  *
1773  * Cleans up &drm_gpuvm_bo instances in the deferred cleanup list.
1774  */
1775 void
1776 drm_gpuvm_bo_deferred_cleanup(struct drm_gpuvm *gpuvm)
1777 {
1778 	struct drm_gpuvm_bo *vm_bo;
1779 	struct llist_node *bo_defer;
1780 
1781 	bo_defer = llist_del_all(&gpuvm->bo_defer);
1782 	if (!bo_defer)
1783 		return;
1784 
1785 	if (drm_gpuvm_resv_protected(gpuvm)) {
1786 		dma_resv_lock(drm_gpuvm_resv(gpuvm), NULL);
1787 		llist_for_each_entry(vm_bo, bo_defer, list.entry.bo_defer) {
1788 			drm_gpuvm_bo_list_del(vm_bo, extobj, false);
1789 			drm_gpuvm_bo_list_del(vm_bo, evict, false);
1790 		}
1791 		dma_resv_unlock(drm_gpuvm_resv(gpuvm));
1792 	}
1793 
1794 	while (bo_defer) {
1795 		vm_bo = llist_entry(bo_defer, struct drm_gpuvm_bo, list.entry.bo_defer);
1796 		bo_defer = bo_defer->next;
1797 		drm_gpuvm_bo_destroy_not_in_lists(vm_bo);
1798 	}
1799 }
1800 EXPORT_SYMBOL_GPL(drm_gpuvm_bo_deferred_cleanup);
1801 
1802 static struct drm_gpuvm_bo *
1803 __drm_gpuvm_bo_find(struct drm_gpuvm *gpuvm,
1804 		    struct drm_gem_object *obj)
1805 {
1806 	struct drm_gpuvm_bo *vm_bo;
1807 
1808 	drm_gem_gpuva_assert_lock_held(gpuvm, obj);
1809 	drm_gem_for_each_gpuvm_bo(vm_bo, obj)
1810 		if (vm_bo->vm == gpuvm)
1811 			return vm_bo;
1812 
1813 	return NULL;
1814 }
1815 
1816 /**
1817  * drm_gpuvm_bo_find() - find the &drm_gpuvm_bo for the given
1818  * &drm_gpuvm and &drm_gem_object
1819  * @gpuvm: The &drm_gpuvm the @obj is mapped in.
1820  * @obj: The &drm_gem_object being mapped in the @gpuvm.
1821  *
1822  * Find the &drm_gpuvm_bo representing the combination of the given
1823  * &drm_gpuvm and &drm_gem_object. If found, increases the reference
1824  * count of the &drm_gpuvm_bo accordingly.
1825  *
1826  * Returns: a pointer to the &drm_gpuvm_bo on success, NULL on failure
1827  */
1828 struct drm_gpuvm_bo *
1829 drm_gpuvm_bo_find(struct drm_gpuvm *gpuvm,
1830 		  struct drm_gem_object *obj)
1831 {
1832 	struct drm_gpuvm_bo *vm_bo = __drm_gpuvm_bo_find(gpuvm, obj);
1833 
1834 	return vm_bo ? drm_gpuvm_bo_get(vm_bo) : NULL;
1835 }
1836 EXPORT_SYMBOL_GPL(drm_gpuvm_bo_find);
1837 
1838 /**
1839  * drm_gpuvm_bo_obtain_locked() - obtains an instance of the &drm_gpuvm_bo for
1840  * the given &drm_gpuvm and &drm_gem_object
1841  * @gpuvm: The &drm_gpuvm the @obj is mapped in.
1842  * @obj: The &drm_gem_object being mapped in the @gpuvm.
1843  *
1844  * Find the &drm_gpuvm_bo representing the combination of the given
1845  * &drm_gpuvm and &drm_gem_object. If found, increases the reference
1846  * count of the &drm_gpuvm_bo accordingly. If not found, allocates a new
1847  * &drm_gpuvm_bo.
1848  *
1849  * Requires the lock for the GEMs gpuva list.
1850  *
1851  * A new &drm_gpuvm_bo is added to the GEMs gpuva list.
1852  *
1853  * Returns: a pointer to the &drm_gpuvm_bo on success, an ERR_PTR on failure
1854  */
1855 struct drm_gpuvm_bo *
1856 drm_gpuvm_bo_obtain_locked(struct drm_gpuvm *gpuvm,
1857 			   struct drm_gem_object *obj)
1858 {
1859 	struct drm_gpuvm_bo *vm_bo;
1860 
1861 	/*
1862 	 * In immediate mode this would require the caller to hold the GEMs
1863 	 * gpuva mutex, but it's not okay to allocate while holding that lock,
1864 	 * and this method allocates. Immediate mode drivers should use
1865 	 * drm_gpuvm_bo_obtain_prealloc() instead.
1866 	 */
1867 	drm_WARN_ON(gpuvm->drm, drm_gpuvm_immediate_mode(gpuvm));
1868 
1869 	vm_bo = drm_gpuvm_bo_find(gpuvm, obj);
1870 	if (vm_bo)
1871 		return vm_bo;
1872 
1873 	vm_bo = drm_gpuvm_bo_create(gpuvm, obj);
1874 	if (!vm_bo)
1875 		return ERR_PTR(-ENOMEM);
1876 
1877 	drm_gem_gpuva_assert_lock_held(gpuvm, obj);
1878 	list_add_tail(&vm_bo->list.entry.gem, &obj->gpuva.list);
1879 
1880 	return vm_bo;
1881 }
1882 EXPORT_SYMBOL_GPL(drm_gpuvm_bo_obtain_locked);
1883 
1884 /**
1885  * drm_gpuvm_bo_obtain_prealloc() - obtains an instance of the &drm_gpuvm_bo
1886  * for the given &drm_gpuvm and &drm_gem_object
1887  * @__vm_bo: A pre-allocated struct drm_gpuvm_bo.
1888  *
1889  * Find the &drm_gpuvm_bo representing the combination of the given
1890  * &drm_gpuvm and &drm_gem_object. If found, increases the reference
1891  * count of the found &drm_gpuvm_bo accordingly, while the @__vm_bo reference
1892  * count is decreased. If not found @__vm_bo is returned without further
1893  * increase of the reference count.
1894  *
1895  * The provided @__vm_bo must not already be in the gpuva, evict, or extobj
1896  * lists prior to calling this method.
1897  *
1898  * A new &drm_gpuvm_bo is added to the GEMs gpuva list.
1899  *
1900  * Returns: a pointer to the found &drm_gpuvm_bo or @__vm_bo if no existing
1901  * &drm_gpuvm_bo was found
1902  */
1903 struct drm_gpuvm_bo *
1904 drm_gpuvm_bo_obtain_prealloc(struct drm_gpuvm_bo *__vm_bo)
1905 {
1906 	struct drm_gpuvm *gpuvm = __vm_bo->vm;
1907 	struct drm_gem_object *obj = __vm_bo->obj;
1908 	struct drm_gpuvm_bo *vm_bo;
1909 
1910 	drm_WARN_ON(gpuvm->drm, !drm_gpuvm_immediate_mode(gpuvm));
1911 
1912 	mutex_lock(&obj->gpuva.lock);
1913 	vm_bo = drm_gpuvm_bo_find(gpuvm, obj);
1914 	if (vm_bo) {
1915 		mutex_unlock(&obj->gpuva.lock);
1916 		kref_put(&__vm_bo->kref, drm_gpuvm_bo_destroy_not_in_lists_kref);
1917 		return vm_bo;
1918 	}
1919 
1920 	drm_gem_gpuva_assert_lock_held(gpuvm, obj);
1921 	list_add_tail(&__vm_bo->list.entry.gem, &obj->gpuva.list);
1922 	mutex_unlock(&obj->gpuva.lock);
1923 
1924 	return __vm_bo;
1925 }
1926 EXPORT_SYMBOL_GPL(drm_gpuvm_bo_obtain_prealloc);
1927 
1928 /**
1929  * drm_gpuvm_bo_extobj_add() - adds the &drm_gpuvm_bo to its &drm_gpuvm's
1930  * extobj list
1931  * @vm_bo: The &drm_gpuvm_bo to add to its &drm_gpuvm's the extobj list.
1932  *
1933  * Adds the given @vm_bo to its &drm_gpuvm's extobj list if not on the list
1934  * already and if the corresponding &drm_gem_object is an external object,
1935  * actually.
1936  */
1937 void
1938 drm_gpuvm_bo_extobj_add(struct drm_gpuvm_bo *vm_bo)
1939 {
1940 	struct drm_gpuvm *gpuvm = vm_bo->vm;
1941 	bool lock = !drm_gpuvm_resv_protected(gpuvm);
1942 
1943 	if (!lock)
1944 		drm_gpuvm_resv_assert_held(gpuvm);
1945 
1946 	if (drm_gpuvm_is_extobj(gpuvm, vm_bo->obj))
1947 		drm_gpuvm_bo_list_add(vm_bo, extobj, lock);
1948 }
1949 EXPORT_SYMBOL_GPL(drm_gpuvm_bo_extobj_add);
1950 
1951 /**
1952  * drm_gpuvm_bo_evict() - add / remove a &drm_gpuvm_bo to / from the &drm_gpuvms
1953  * evicted list
1954  * @vm_bo: the &drm_gpuvm_bo to add or remove
1955  * @evict: indicates whether the object is evicted
1956  *
1957  * Adds a &drm_gpuvm_bo to or removes it from the &drm_gpuvm's evicted list.
1958  */
1959 void
1960 drm_gpuvm_bo_evict(struct drm_gpuvm_bo *vm_bo, bool evict)
1961 {
1962 	struct drm_gpuvm *gpuvm = vm_bo->vm;
1963 	struct drm_gem_object *obj = vm_bo->obj;
1964 	bool lock = !drm_gpuvm_resv_protected(gpuvm);
1965 
1966 	dma_resv_assert_held(obj->resv);
1967 	vm_bo->evicted = evict;
1968 
1969 	/* Can't add external objects to the evicted list directly if not using
1970 	 * internal spinlocks, since in this case the evicted list is protected
1971 	 * with the VM's common dma-resv lock.
1972 	 */
1973 	if (drm_gpuvm_is_extobj(gpuvm, obj) && !lock)
1974 		return;
1975 
1976 	if (evict)
1977 		drm_gpuvm_bo_list_add(vm_bo, evict, lock);
1978 	else
1979 		drm_gpuvm_bo_list_del_init(vm_bo, evict, lock);
1980 }
1981 EXPORT_SYMBOL_GPL(drm_gpuvm_bo_evict);
1982 
1983 static int
1984 __drm_gpuva_insert(struct drm_gpuvm *gpuvm,
1985 		   struct drm_gpuva *va)
1986 {
1987 	struct rb_node *node;
1988 	struct list_head *head;
1989 
1990 	if (drm_gpuva_it_iter_first(&gpuvm->rb.tree,
1991 				    GPUVA_START(va),
1992 				    GPUVA_LAST(va)))
1993 		return -EEXIST;
1994 
1995 	va->vm = gpuvm;
1996 
1997 	drm_gpuva_it_insert(va, &gpuvm->rb.tree);
1998 
1999 	node = rb_prev(&va->rb.node);
2000 	if (node)
2001 		head = &(to_drm_gpuva(node))->rb.entry;
2002 	else
2003 		head = &gpuvm->rb.list;
2004 
2005 	list_add(&va->rb.entry, head);
2006 
2007 	return 0;
2008 }
2009 
2010 /**
2011  * drm_gpuva_insert() - insert a &drm_gpuva
2012  * @gpuvm: the &drm_gpuvm to insert the &drm_gpuva in
2013  * @va: the &drm_gpuva to insert
2014  *
2015  * Insert a &drm_gpuva with a given address and range into a
2016  * &drm_gpuvm.
2017  *
2018  * It is safe to use this function using the safe versions of iterating the GPU
2019  * VA space, such as drm_gpuvm_for_each_va_safe() and
2020  * drm_gpuvm_for_each_va_range_safe().
2021  *
2022  * Returns: 0 on success, negative error code on failure.
2023  */
2024 int
2025 drm_gpuva_insert(struct drm_gpuvm *gpuvm,
2026 		 struct drm_gpuva *va)
2027 {
2028 	u64 addr = va->va.addr;
2029 	u64 range = va->va.range;
2030 	int ret;
2031 
2032 	if (unlikely(!drm_gpuvm_range_valid(gpuvm, addr, range)))
2033 		return -EINVAL;
2034 
2035 	ret = __drm_gpuva_insert(gpuvm, va);
2036 	if (likely(!ret))
2037 		/* Take a reference of the GPUVM for the successfully inserted
2038 		 * drm_gpuva. We can't take the reference in
2039 		 * __drm_gpuva_insert() itself, since we don't want to increse
2040 		 * the reference count for the GPUVM's kernel_alloc_node.
2041 		 */
2042 		drm_gpuvm_get(gpuvm);
2043 
2044 	return ret;
2045 }
2046 EXPORT_SYMBOL_GPL(drm_gpuva_insert);
2047 
2048 static void
2049 __drm_gpuva_remove(struct drm_gpuva *va)
2050 {
2051 	drm_gpuva_it_remove(va, &va->vm->rb.tree);
2052 	list_del_init(&va->rb.entry);
2053 }
2054 
2055 /**
2056  * drm_gpuva_remove() - remove a &drm_gpuva
2057  * @va: the &drm_gpuva to remove
2058  *
2059  * This removes the given &va from the underlying tree.
2060  *
2061  * It is safe to use this function using the safe versions of iterating the GPU
2062  * VA space, such as drm_gpuvm_for_each_va_safe() and
2063  * drm_gpuvm_for_each_va_range_safe().
2064  */
2065 void
2066 drm_gpuva_remove(struct drm_gpuva *va)
2067 {
2068 	struct drm_gpuvm *gpuvm = va->vm;
2069 
2070 	if (unlikely(va == &gpuvm->kernel_alloc_node)) {
2071 		drm_WARN(gpuvm->drm, 1,
2072 			 "Can't destroy kernel reserved node.\n");
2073 		return;
2074 	}
2075 
2076 	__drm_gpuva_remove(va);
2077 	drm_gpuvm_put(va->vm);
2078 }
2079 EXPORT_SYMBOL_GPL(drm_gpuva_remove);
2080 
2081 /**
2082  * drm_gpuva_link() - link a &drm_gpuva
2083  * @va: the &drm_gpuva to link
2084  * @vm_bo: the &drm_gpuvm_bo to add the &drm_gpuva to
2085  *
2086  * This adds the given &va to the GPU VA list of the &drm_gpuvm_bo and the
2087  * &drm_gpuvm_bo to the &drm_gem_object it is associated with.
2088  *
2089  * For every &drm_gpuva entry added to the &drm_gpuvm_bo an additional
2090  * reference of the latter is taken.
2091  *
2092  * This function expects the caller to protect the GEM's GPUVA list against
2093  * concurrent access using either the GEM's dma-resv or gpuva.lock mutex.
2094  */
2095 void
2096 drm_gpuva_link(struct drm_gpuva *va, struct drm_gpuvm_bo *vm_bo)
2097 {
2098 	struct drm_gem_object *obj = va->gem.obj;
2099 	struct drm_gpuvm *gpuvm = va->vm;
2100 
2101 	if (unlikely(!obj))
2102 		return;
2103 
2104 	drm_WARN_ON(gpuvm->drm, obj != vm_bo->obj);
2105 
2106 	va->vm_bo = drm_gpuvm_bo_get(vm_bo);
2107 
2108 	drm_gem_gpuva_assert_lock_held(gpuvm, obj);
2109 	list_add_tail(&va->gem.entry, &vm_bo->list.gpuva);
2110 }
2111 EXPORT_SYMBOL_GPL(drm_gpuva_link);
2112 
2113 /**
2114  * drm_gpuva_unlink() - unlink a &drm_gpuva
2115  * @va: the &drm_gpuva to unlink
2116  *
2117  * This removes the given &va from the GPU VA list of the &drm_gem_object it is
2118  * associated with.
2119  *
2120  * This removes the given &va from the GPU VA list of the &drm_gpuvm_bo and
2121  * the &drm_gpuvm_bo from the &drm_gem_object it is associated with in case
2122  * this call unlinks the last &drm_gpuva from the &drm_gpuvm_bo.
2123  *
2124  * For every &drm_gpuva entry removed from the &drm_gpuvm_bo a reference of
2125  * the latter is dropped.
2126  *
2127  * This function expects the caller to protect the GEM's GPUVA list against
2128  * concurrent access using either the GEM's dma-resv or gpuva.lock mutex.
2129  */
2130 void
2131 drm_gpuva_unlink(struct drm_gpuva *va)
2132 {
2133 	struct drm_gem_object *obj = va->gem.obj;
2134 	struct drm_gpuvm_bo *vm_bo = va->vm_bo;
2135 
2136 	if (unlikely(!obj))
2137 		return;
2138 
2139 	drm_gem_gpuva_assert_lock_held(va->vm, obj);
2140 	list_del_init(&va->gem.entry);
2141 
2142 	va->vm_bo = NULL;
2143 	drm_gpuvm_bo_put(vm_bo);
2144 }
2145 EXPORT_SYMBOL_GPL(drm_gpuva_unlink);
2146 
2147 /**
2148  * drm_gpuva_unlink_defer() - unlink a &drm_gpuva with deferred vm_bo cleanup
2149  * @va: the &drm_gpuva to unlink
2150  *
2151  * Similar to drm_gpuva_unlink(), but uses drm_gpuvm_bo_put_deferred() and takes
2152  * the lock for the caller.
2153  */
2154 void
2155 drm_gpuva_unlink_defer(struct drm_gpuva *va)
2156 {
2157 	struct drm_gem_object *obj = va->gem.obj;
2158 	struct drm_gpuvm_bo *vm_bo = va->vm_bo;
2159 	bool should_defer_bo;
2160 
2161 	if (unlikely(!obj))
2162 		return;
2163 
2164 	drm_WARN_ON(vm_bo->vm->drm, !drm_gpuvm_immediate_mode(vm_bo->vm));
2165 
2166 	mutex_lock(&obj->gpuva.lock);
2167 	list_del_init(&va->gem.entry);
2168 
2169 	/*
2170 	 * This is drm_gpuvm_bo_put_deferred() except we already hold the mutex.
2171 	 */
2172 	should_defer_bo = kref_put(&vm_bo->kref, drm_gpuvm_bo_into_zombie);
2173 	mutex_unlock(&obj->gpuva.lock);
2174 	if (should_defer_bo)
2175 		drm_gpuvm_bo_defer_zombie_cleanup(vm_bo);
2176 
2177 	va->vm_bo = NULL;
2178 }
2179 EXPORT_SYMBOL_GPL(drm_gpuva_unlink_defer);
2180 
2181 /**
2182  * drm_gpuva_find_first() - find the first &drm_gpuva in the given range
2183  * @gpuvm: the &drm_gpuvm to search in
2184  * @addr: the &drm_gpuvas address
2185  * @range: the &drm_gpuvas range
2186  *
2187  * Returns: the first &drm_gpuva within the given range
2188  */
2189 struct drm_gpuva *
2190 drm_gpuva_find_first(struct drm_gpuvm *gpuvm,
2191 		     u64 addr, u64 range)
2192 {
2193 	u64 last = addr + range - 1;
2194 
2195 	return drm_gpuva_it_iter_first(&gpuvm->rb.tree, addr, last);
2196 }
2197 EXPORT_SYMBOL_GPL(drm_gpuva_find_first);
2198 
2199 /**
2200  * drm_gpuva_find() - find a &drm_gpuva
2201  * @gpuvm: the &drm_gpuvm to search in
2202  * @addr: the &drm_gpuvas address
2203  * @range: the &drm_gpuvas range
2204  *
2205  * Returns: the &drm_gpuva at a given &addr and with a given &range
2206  */
2207 struct drm_gpuva *
2208 drm_gpuva_find(struct drm_gpuvm *gpuvm,
2209 	       u64 addr, u64 range)
2210 {
2211 	struct drm_gpuva *va;
2212 
2213 	va = drm_gpuva_find_first(gpuvm, addr, range);
2214 	if (!va)
2215 		goto out;
2216 
2217 	if (va->va.addr != addr ||
2218 	    va->va.range != range)
2219 		goto out;
2220 
2221 	return va;
2222 
2223 out:
2224 	return NULL;
2225 }
2226 EXPORT_SYMBOL_GPL(drm_gpuva_find);
2227 
2228 /**
2229  * drm_gpuva_find_prev() - find the &drm_gpuva before the given address
2230  * @gpuvm: the &drm_gpuvm to search in
2231  * @start: the given GPU VA's start address
2232  *
2233  * Find the adjacent &drm_gpuva before the GPU VA with given &start address.
2234  *
2235  * Note that if there is any free space between the GPU VA mappings no mapping
2236  * is returned.
2237  *
2238  * Returns: a pointer to the found &drm_gpuva or NULL if none was found
2239  */
2240 struct drm_gpuva *
2241 drm_gpuva_find_prev(struct drm_gpuvm *gpuvm, u64 start)
2242 {
2243 	if (!drm_gpuvm_range_valid(gpuvm, start - 1, 1))
2244 		return NULL;
2245 
2246 	return drm_gpuva_it_iter_first(&gpuvm->rb.tree, start - 1, start);
2247 }
2248 EXPORT_SYMBOL_GPL(drm_gpuva_find_prev);
2249 
2250 /**
2251  * drm_gpuva_find_next() - find the &drm_gpuva after the given address
2252  * @gpuvm: the &drm_gpuvm to search in
2253  * @end: the given GPU VA's end address
2254  *
2255  * Find the adjacent &drm_gpuva after the GPU VA with given &end address.
2256  *
2257  * Note that if there is any free space between the GPU VA mappings no mapping
2258  * is returned.
2259  *
2260  * Returns: a pointer to the found &drm_gpuva or NULL if none was found
2261  */
2262 struct drm_gpuva *
2263 drm_gpuva_find_next(struct drm_gpuvm *gpuvm, u64 end)
2264 {
2265 	if (!drm_gpuvm_range_valid(gpuvm, end, 1))
2266 		return NULL;
2267 
2268 	return drm_gpuva_it_iter_first(&gpuvm->rb.tree, end, end + 1);
2269 }
2270 EXPORT_SYMBOL_GPL(drm_gpuva_find_next);
2271 
2272 /**
2273  * drm_gpuvm_interval_empty() - indicate whether a given interval of the VA space
2274  * is empty
2275  * @gpuvm: the &drm_gpuvm to check the range for
2276  * @addr: the start address of the range
2277  * @range: the range of the interval
2278  *
2279  * Returns: true if the interval is empty, false otherwise
2280  */
2281 bool
2282 drm_gpuvm_interval_empty(struct drm_gpuvm *gpuvm, u64 addr, u64 range)
2283 {
2284 	return !drm_gpuva_find_first(gpuvm, addr, range);
2285 }
2286 EXPORT_SYMBOL_GPL(drm_gpuvm_interval_empty);
2287 
2288 /**
2289  * drm_gpuva_map() - helper to insert a &drm_gpuva according to a
2290  * &drm_gpuva_op_map
2291  * @gpuvm: the &drm_gpuvm
2292  * @va: the &drm_gpuva to insert
2293  * @op: the &drm_gpuva_op_map to initialize @va with
2294  *
2295  * Initializes the @va from the @op and inserts it into the given @gpuvm.
2296  */
2297 void
2298 drm_gpuva_map(struct drm_gpuvm *gpuvm,
2299 	      struct drm_gpuva *va,
2300 	      const struct drm_gpuva_op_map *op)
2301 {
2302 	drm_gpuva_init_from_op(va, op);
2303 	drm_gpuva_insert(gpuvm, va);
2304 }
2305 EXPORT_SYMBOL_GPL(drm_gpuva_map);
2306 
2307 /**
2308  * drm_gpuva_remap() - helper to remap a &drm_gpuva according to a
2309  * &drm_gpuva_op_remap
2310  * @prev: the &drm_gpuva to remap when keeping the start of a mapping
2311  * @next: the &drm_gpuva to remap when keeping the end of a mapping
2312  * @op: the &drm_gpuva_op_remap to initialize @prev and @next with
2313  *
2314  * Removes the currently mapped &drm_gpuva and remaps it using @prev and/or
2315  * @next.
2316  */
2317 void
2318 drm_gpuva_remap(struct drm_gpuva *prev,
2319 		struct drm_gpuva *next,
2320 		const struct drm_gpuva_op_remap *op)
2321 {
2322 	struct drm_gpuva *va = op->unmap->va;
2323 	struct drm_gpuvm *gpuvm = va->vm;
2324 
2325 	drm_gpuva_remove(va);
2326 
2327 	if (op->prev) {
2328 		drm_gpuva_init_from_op(prev, op->prev);
2329 		drm_gpuva_insert(gpuvm, prev);
2330 	}
2331 
2332 	if (op->next) {
2333 		drm_gpuva_init_from_op(next, op->next);
2334 		drm_gpuva_insert(gpuvm, next);
2335 	}
2336 }
2337 EXPORT_SYMBOL_GPL(drm_gpuva_remap);
2338 
2339 /**
2340  * drm_gpuva_unmap() - helper to remove a &drm_gpuva according to a
2341  * &drm_gpuva_op_unmap
2342  * @op: the &drm_gpuva_op_unmap specifying the &drm_gpuva to remove
2343  *
2344  * Removes the &drm_gpuva associated with the &drm_gpuva_op_unmap.
2345  */
2346 void
2347 drm_gpuva_unmap(const struct drm_gpuva_op_unmap *op)
2348 {
2349 	drm_gpuva_remove(op->va);
2350 }
2351 EXPORT_SYMBOL_GPL(drm_gpuva_unmap);
2352 
2353 static int
2354 op_map_cb(const struct drm_gpuvm_ops *fn, void *priv,
2355 	  const struct drm_gpuvm_map_req *req)
2356 {
2357 	struct drm_gpuva_op op = {};
2358 
2359 	if (!req)
2360 		return 0;
2361 
2362 	op.op = DRM_GPUVA_OP_MAP;
2363 	op.map.va.addr = req->map.va.addr;
2364 	op.map.va.range = req->map.va.range;
2365 	op.map.gem.obj = req->map.gem.obj;
2366 	op.map.gem.offset = req->map.gem.offset;
2367 
2368 	return fn->sm_step_map(&op, priv);
2369 }
2370 
2371 static int
2372 op_remap_cb(const struct drm_gpuvm_ops *fn, void *priv,
2373 	    struct drm_gpuva_op_map *prev,
2374 	    struct drm_gpuva_op_map *next,
2375 	    struct drm_gpuva_op_unmap *unmap)
2376 {
2377 	struct drm_gpuva_op op = {};
2378 	struct drm_gpuva_op_remap *r;
2379 
2380 	op.op = DRM_GPUVA_OP_REMAP;
2381 	r = &op.remap;
2382 	r->prev = prev;
2383 	r->next = next;
2384 	r->unmap = unmap;
2385 
2386 	return fn->sm_step_remap(&op, priv);
2387 }
2388 
2389 static int
2390 op_unmap_cb(const struct drm_gpuvm_ops *fn, void *priv,
2391 	    struct drm_gpuva *va, bool merge, bool madvise)
2392 {
2393 	struct drm_gpuva_op op = {};
2394 
2395 	if (madvise)
2396 		return 0;
2397 
2398 	op.op = DRM_GPUVA_OP_UNMAP;
2399 	op.unmap.va = va;
2400 	op.unmap.keep = merge;
2401 
2402 	return fn->sm_step_unmap(&op, priv);
2403 }
2404 
2405 static int
2406 __drm_gpuvm_sm_map(struct drm_gpuvm *gpuvm,
2407 		   const struct drm_gpuvm_ops *ops, void *priv,
2408 		   const struct drm_gpuvm_map_req *req,
2409 		   bool madvise)
2410 {
2411 	struct drm_gem_object *req_obj = req->map.gem.obj;
2412 	const struct drm_gpuvm_map_req *op_map = madvise ? NULL : req;
2413 	struct drm_gpuva *va, *next;
2414 	u64 req_offset = req->map.gem.offset;
2415 	u64 req_range = req->map.va.range;
2416 	u64 req_addr = req->map.va.addr;
2417 	u64 req_end = req_addr + req_range;
2418 	int ret;
2419 
2420 	if (unlikely(!drm_gpuvm_range_valid(gpuvm, req_addr, req_range)))
2421 		return -EINVAL;
2422 
2423 	drm_gpuvm_for_each_va_range_safe(va, next, gpuvm, req_addr, req_end) {
2424 		struct drm_gem_object *obj = va->gem.obj;
2425 		u64 offset = va->gem.offset;
2426 		u64 addr = va->va.addr;
2427 		u64 range = va->va.range;
2428 		u64 end = addr + range;
2429 		bool merge = !!va->gem.obj;
2430 
2431 		if (madvise && obj)
2432 			continue;
2433 
2434 		if (addr == req_addr) {
2435 			merge &= obj == req_obj &&
2436 				 offset == req_offset;
2437 
2438 			if (end == req_end) {
2439 				ret = op_unmap_cb(ops, priv, va, merge, madvise);
2440 				if (ret)
2441 					return ret;
2442 				break;
2443 			}
2444 
2445 			if (end < req_end) {
2446 				ret = op_unmap_cb(ops, priv, va, merge, madvise);
2447 				if (ret)
2448 					return ret;
2449 				continue;
2450 			}
2451 
2452 			if (end > req_end) {
2453 				struct drm_gpuva_op_map n = {
2454 					.va.addr = req_end,
2455 					.va.range = range - req_range,
2456 					.gem.obj = obj,
2457 					.gem.offset = offset + req_range,
2458 				};
2459 				struct drm_gpuva_op_unmap u = {
2460 					.va = va,
2461 					.keep = merge,
2462 				};
2463 
2464 				ret = op_remap_cb(ops, priv, NULL, &n, &u);
2465 				if (ret)
2466 					return ret;
2467 
2468 				if (madvise)
2469 					op_map = req;
2470 				break;
2471 			}
2472 		} else if (addr < req_addr) {
2473 			u64 ls_range = req_addr - addr;
2474 			struct drm_gpuva_op_map p = {
2475 				.va.addr = addr,
2476 				.va.range = ls_range,
2477 				.gem.obj = obj,
2478 				.gem.offset = offset,
2479 			};
2480 			struct drm_gpuva_op_unmap u = { .va = va };
2481 
2482 			merge &= obj == req_obj &&
2483 				 offset + ls_range == req_offset;
2484 			u.keep = merge;
2485 
2486 			if (end == req_end) {
2487 				ret = op_remap_cb(ops, priv, &p, NULL, &u);
2488 				if (ret)
2489 					return ret;
2490 
2491 				if (madvise)
2492 					op_map = req;
2493 				break;
2494 			}
2495 
2496 			if (end < req_end) {
2497 				ret = op_remap_cb(ops, priv, &p, NULL, &u);
2498 				if (ret)
2499 					return ret;
2500 
2501 				if (madvise) {
2502 					struct drm_gpuvm_map_req map_req = {
2503 						.map.va.addr =  req_addr,
2504 						.map.va.range = end - req_addr,
2505 					};
2506 
2507 					ret = op_map_cb(ops, priv, &map_req);
2508 					if (ret)
2509 						return ret;
2510 				}
2511 
2512 				continue;
2513 			}
2514 
2515 			if (end > req_end) {
2516 				struct drm_gpuva_op_map n = {
2517 					.va.addr = req_end,
2518 					.va.range = end - req_end,
2519 					.gem.obj = obj,
2520 					.gem.offset = offset + ls_range +
2521 						      req_range,
2522 				};
2523 
2524 				ret = op_remap_cb(ops, priv, &p, &n, &u);
2525 				if (ret)
2526 					return ret;
2527 
2528 				if (madvise)
2529 					op_map = req;
2530 				break;
2531 			}
2532 		} else if (addr > req_addr) {
2533 			merge &= obj == req_obj &&
2534 				 offset == req_offset +
2535 					   (addr - req_addr);
2536 
2537 			if (end == req_end) {
2538 				ret = op_unmap_cb(ops, priv, va, merge, madvise);
2539 				if (ret)
2540 					return ret;
2541 
2542 				break;
2543 			}
2544 
2545 			if (end < req_end) {
2546 				ret = op_unmap_cb(ops, priv, va, merge, madvise);
2547 				if (ret)
2548 					return ret;
2549 
2550 				continue;
2551 			}
2552 
2553 			if (end > req_end) {
2554 				struct drm_gpuva_op_map n = {
2555 					.va.addr = req_end,
2556 					.va.range = end - req_end,
2557 					.gem.obj = obj,
2558 					.gem.offset = offset + req_end - addr,
2559 				};
2560 				struct drm_gpuva_op_unmap u = {
2561 					.va = va,
2562 					.keep = merge,
2563 				};
2564 
2565 				ret = op_remap_cb(ops, priv, NULL, &n, &u);
2566 				if (ret)
2567 					return ret;
2568 
2569 				if (madvise) {
2570 					struct drm_gpuvm_map_req map_req = {
2571 						.map.va.addr =  addr,
2572 						.map.va.range = req_end - addr,
2573 					};
2574 
2575 					return op_map_cb(ops, priv, &map_req);
2576 				}
2577 				break;
2578 			}
2579 		}
2580 	}
2581 	return op_map_cb(ops, priv, op_map);
2582 }
2583 
2584 static int
2585 __drm_gpuvm_sm_unmap(struct drm_gpuvm *gpuvm,
2586 		     const struct drm_gpuvm_ops *ops, void *priv,
2587 		     u64 req_addr, u64 req_range)
2588 {
2589 	struct drm_gpuva *va, *next;
2590 	u64 req_end = req_addr + req_range;
2591 	int ret;
2592 
2593 	if (unlikely(!drm_gpuvm_range_valid(gpuvm, req_addr, req_range)))
2594 		return -EINVAL;
2595 
2596 	drm_gpuvm_for_each_va_range_safe(va, next, gpuvm, req_addr, req_end) {
2597 		struct drm_gpuva_op_map prev = {}, next = {};
2598 		bool prev_split = false, next_split = false;
2599 		struct drm_gem_object *obj = va->gem.obj;
2600 		u64 offset = va->gem.offset;
2601 		u64 addr = va->va.addr;
2602 		u64 range = va->va.range;
2603 		u64 end = addr + range;
2604 
2605 		if (addr < req_addr) {
2606 			prev.va.addr = addr;
2607 			prev.va.range = req_addr - addr;
2608 			prev.gem.obj = obj;
2609 			prev.gem.offset = offset;
2610 
2611 			prev_split = true;
2612 		}
2613 
2614 		if (end > req_end) {
2615 			next.va.addr = req_end;
2616 			next.va.range = end - req_end;
2617 			next.gem.obj = obj;
2618 			next.gem.offset = offset + (req_end - addr);
2619 
2620 			next_split = true;
2621 		}
2622 
2623 		if (prev_split || next_split) {
2624 			struct drm_gpuva_op_unmap unmap = { .va = va };
2625 
2626 			ret = op_remap_cb(ops, priv,
2627 					  prev_split ? &prev : NULL,
2628 					  next_split ? &next : NULL,
2629 					  &unmap);
2630 			if (ret)
2631 				return ret;
2632 		} else {
2633 			ret = op_unmap_cb(ops, priv, va, false, false);
2634 			if (ret)
2635 				return ret;
2636 		}
2637 	}
2638 
2639 	return 0;
2640 }
2641 
2642 /**
2643  * drm_gpuvm_sm_map() - calls the &drm_gpuva_op split/merge steps
2644  * @gpuvm: the &drm_gpuvm representing the GPU VA space
2645  * @priv: pointer to a driver private data structure
2646  * @req: ptr to struct drm_gpuvm_map_req
2647  *
2648  * This function iterates the given range of the GPU VA space. It utilizes the
2649  * &drm_gpuvm_ops to call back into the driver providing the split and merge
2650  * steps.
2651  *
2652  * Drivers may use these callbacks to update the GPU VA space right away within
2653  * the callback. In case the driver decides to copy and store the operations for
2654  * later processing neither this function nor &drm_gpuvm_sm_unmap is allowed to
2655  * be called before the &drm_gpuvm's view of the GPU VA space was
2656  * updated with the previous set of operations. To update the
2657  * &drm_gpuvm's view of the GPU VA space drm_gpuva_insert(),
2658  * drm_gpuva_destroy_locked() and/or drm_gpuva_destroy_unlocked() should be
2659  * used.
2660  *
2661  * A sequence of callbacks can contain map, unmap and remap operations, but
2662  * the sequence of callbacks might also be empty if no operation is required,
2663  * e.g. if the requested mapping already exists in the exact same way.
2664  *
2665  * There can be an arbitrary amount of unmap operations, a maximum of two remap
2666  * operations and a single map operation. The latter one represents the original
2667  * map operation requested by the caller.
2668  *
2669  * Returns: 0 on success or a negative error code
2670  */
2671 int
2672 drm_gpuvm_sm_map(struct drm_gpuvm *gpuvm, void *priv,
2673 		 const struct drm_gpuvm_map_req *req)
2674 {
2675 	const struct drm_gpuvm_ops *ops = gpuvm->ops;
2676 
2677 	if (unlikely(!(ops && ops->sm_step_map &&
2678 		       ops->sm_step_remap &&
2679 		       ops->sm_step_unmap)))
2680 		return -EINVAL;
2681 
2682 	return __drm_gpuvm_sm_map(gpuvm, ops, priv, req, false);
2683 }
2684 EXPORT_SYMBOL_GPL(drm_gpuvm_sm_map);
2685 
2686 /**
2687  * drm_gpuvm_sm_unmap() - calls the &drm_gpuva_ops to split on unmap
2688  * @gpuvm: the &drm_gpuvm representing the GPU VA space
2689  * @priv: pointer to a driver private data structure
2690  * @req_addr: the start address of the range to unmap
2691  * @req_range: the range of the mappings to unmap
2692  *
2693  * This function iterates the given range of the GPU VA space. It utilizes the
2694  * &drm_gpuvm_ops to call back into the driver providing the operations to
2695  * unmap and, if required, split existing mappings.
2696  *
2697  * Drivers may use these callbacks to update the GPU VA space right away within
2698  * the callback. In case the driver decides to copy and store the operations for
2699  * later processing neither this function nor &drm_gpuvm_sm_map is allowed to be
2700  * called before the &drm_gpuvm's view of the GPU VA space was updated
2701  * with the previous set of operations. To update the &drm_gpuvm's view
2702  * of the GPU VA space drm_gpuva_insert(), drm_gpuva_destroy_locked() and/or
2703  * drm_gpuva_destroy_unlocked() should be used.
2704  *
2705  * A sequence of callbacks can contain unmap and remap operations, depending on
2706  * whether there are actual overlapping mappings to split.
2707  *
2708  * There can be an arbitrary amount of unmap operations and a maximum of two
2709  * remap operations.
2710  *
2711  * Returns: 0 on success or a negative error code
2712  */
2713 int
2714 drm_gpuvm_sm_unmap(struct drm_gpuvm *gpuvm, void *priv,
2715 		   u64 req_addr, u64 req_range)
2716 {
2717 	const struct drm_gpuvm_ops *ops = gpuvm->ops;
2718 
2719 	if (unlikely(!(ops && ops->sm_step_remap &&
2720 		       ops->sm_step_unmap)))
2721 		return -EINVAL;
2722 
2723 	return __drm_gpuvm_sm_unmap(gpuvm, ops, priv,
2724 				    req_addr, req_range);
2725 }
2726 EXPORT_SYMBOL_GPL(drm_gpuvm_sm_unmap);
2727 
2728 static int
2729 drm_gpuva_sm_step_lock(struct drm_gpuva_op *op, void *priv)
2730 {
2731 	struct drm_exec *exec = priv;
2732 
2733 	switch (op->op) {
2734 	case DRM_GPUVA_OP_REMAP:
2735 		if (op->remap.unmap->va->gem.obj)
2736 			return drm_exec_lock_obj(exec, op->remap.unmap->va->gem.obj);
2737 		return 0;
2738 	case DRM_GPUVA_OP_UNMAP:
2739 		if (op->unmap.va->gem.obj)
2740 			return drm_exec_lock_obj(exec, op->unmap.va->gem.obj);
2741 		return 0;
2742 	default:
2743 		return 0;
2744 	}
2745 }
2746 
2747 static const struct drm_gpuvm_ops lock_ops = {
2748 	.sm_step_map = drm_gpuva_sm_step_lock,
2749 	.sm_step_remap = drm_gpuva_sm_step_lock,
2750 	.sm_step_unmap = drm_gpuva_sm_step_lock,
2751 };
2752 
2753 /**
2754  * drm_gpuvm_sm_map_exec_lock() - locks the objects touched by a drm_gpuvm_sm_map()
2755  * @gpuvm: the &drm_gpuvm representing the GPU VA space
2756  * @exec: the &drm_exec locking context
2757  * @num_fences: for newly mapped objects, the # of fences to reserve
2758  * @req: ptr to drm_gpuvm_map_req struct
2759  *
2760  * This function locks (drm_exec_lock_obj()) objects that will be unmapped/
2761  * remapped, and locks+prepares (drm_exec_prepare_object()) objects that
2762  * will be newly mapped.
2763  *
2764  * The expected usage is::
2765  *
2766  *    vm_bind {
2767  *        struct drm_exec exec;
2768  *
2769  *        // IGNORE_DUPLICATES is required, INTERRUPTIBLE_WAIT is recommended:
2770  *        drm_exec_init(&exec, IGNORE_DUPLICATES | INTERRUPTIBLE_WAIT, 0);
2771  *
2772  *        drm_exec_until_all_locked (&exec) {
2773  *            for_each_vm_bind_operation {
2774  *                switch (op->op) {
2775  *                case DRIVER_OP_UNMAP:
2776  *                    ret = drm_gpuvm_sm_unmap_exec_lock(gpuvm, &exec, op->addr, op->range);
2777  *                    break;
2778  *                case DRIVER_OP_MAP:
2779  *                    ret = drm_gpuvm_sm_map_exec_lock(gpuvm, &exec, num_fences, &req);
2780  *                    break;
2781  *                }
2782  *
2783  *                drm_exec_retry_on_contention(&exec);
2784  *                if (ret)
2785  *                    return ret;
2786  *            }
2787  *        }
2788  *    }
2789  *
2790  * This enables all locking to be performed before the driver begins modifying
2791  * the VM.  This is safe to do in the case of overlapping DRIVER_VM_BIND_OPs,
2792  * where an earlier op can alter the sequence of steps generated for a later
2793  * op, because the later altered step will involve the same GEM object(s)
2794  * already seen in the earlier locking step.  For example:
2795  *
2796  * 1) An earlier driver DRIVER_OP_UNMAP op removes the need for a
2797  *    DRM_GPUVA_OP_REMAP/UNMAP step.  This is safe because we've already
2798  *    locked the GEM object in the earlier DRIVER_OP_UNMAP op.
2799  *
2800  * 2) An earlier DRIVER_OP_MAP op overlaps with a later DRIVER_OP_MAP/UNMAP
2801  *    op, introducing a DRM_GPUVA_OP_REMAP/UNMAP that wouldn't have been
2802  *    required without the earlier DRIVER_OP_MAP.  This is safe because we've
2803  *    already locked the GEM object in the earlier DRIVER_OP_MAP step.
2804  *
2805  * Returns: 0 on success or a negative error code
2806  */
2807 int
2808 drm_gpuvm_sm_map_exec_lock(struct drm_gpuvm *gpuvm,
2809 			   struct drm_exec *exec, unsigned int num_fences,
2810 			   struct drm_gpuvm_map_req *req)
2811 {
2812 	struct drm_gem_object *req_obj = req->map.gem.obj;
2813 
2814 	if (req_obj) {
2815 		int ret = drm_exec_prepare_obj(exec, req_obj, num_fences);
2816 		if (ret)
2817 			return ret;
2818 	}
2819 
2820 	return __drm_gpuvm_sm_map(gpuvm, &lock_ops, exec, req, false);
2821 
2822 }
2823 EXPORT_SYMBOL_GPL(drm_gpuvm_sm_map_exec_lock);
2824 
2825 /**
2826  * drm_gpuvm_sm_unmap_exec_lock() - locks the objects touched by drm_gpuvm_sm_unmap()
2827  * @gpuvm: the &drm_gpuvm representing the GPU VA space
2828  * @exec: the &drm_exec locking context
2829  * @req_addr: the start address of the range to unmap
2830  * @req_range: the range of the mappings to unmap
2831  *
2832  * This function locks (drm_exec_lock_obj()) objects that will be unmapped/
2833  * remapped by drm_gpuvm_sm_unmap().
2834  *
2835  * See drm_gpuvm_sm_map_exec_lock() for expected usage.
2836  *
2837  * Returns: 0 on success or a negative error code
2838  */
2839 int
2840 drm_gpuvm_sm_unmap_exec_lock(struct drm_gpuvm *gpuvm, struct drm_exec *exec,
2841 			     u64 req_addr, u64 req_range)
2842 {
2843 	return __drm_gpuvm_sm_unmap(gpuvm, &lock_ops, exec,
2844 				    req_addr, req_range);
2845 }
2846 EXPORT_SYMBOL_GPL(drm_gpuvm_sm_unmap_exec_lock);
2847 
2848 static struct drm_gpuva_op *
2849 gpuva_op_alloc(struct drm_gpuvm *gpuvm)
2850 {
2851 	const struct drm_gpuvm_ops *fn = gpuvm->ops;
2852 	struct drm_gpuva_op *op;
2853 
2854 	if (fn && fn->op_alloc)
2855 		op = fn->op_alloc();
2856 	else
2857 		op = kzalloc_obj(*op);
2858 
2859 	if (unlikely(!op))
2860 		return NULL;
2861 
2862 	return op;
2863 }
2864 
2865 static void
2866 gpuva_op_free(struct drm_gpuvm *gpuvm,
2867 	      struct drm_gpuva_op *op)
2868 {
2869 	const struct drm_gpuvm_ops *fn = gpuvm->ops;
2870 
2871 	if (fn && fn->op_free)
2872 		fn->op_free(op);
2873 	else
2874 		kfree(op);
2875 }
2876 
2877 static int
2878 drm_gpuva_sm_step(struct drm_gpuva_op *__op,
2879 		  void *priv)
2880 {
2881 	struct {
2882 		struct drm_gpuvm *vm;
2883 		struct drm_gpuva_ops *ops;
2884 	} *args = priv;
2885 	struct drm_gpuvm *gpuvm = args->vm;
2886 	struct drm_gpuva_ops *ops = args->ops;
2887 	struct drm_gpuva_op *op;
2888 
2889 	op = gpuva_op_alloc(gpuvm);
2890 	if (unlikely(!op))
2891 		goto err;
2892 
2893 	memcpy(op, __op, sizeof(*op));
2894 
2895 	if (op->op == DRM_GPUVA_OP_REMAP) {
2896 		struct drm_gpuva_op_remap *__r = &__op->remap;
2897 		struct drm_gpuva_op_remap *r = &op->remap;
2898 
2899 		r->unmap = kmemdup(__r->unmap, sizeof(*r->unmap),
2900 				   GFP_KERNEL);
2901 		if (unlikely(!r->unmap))
2902 			goto err_free_op;
2903 
2904 		if (__r->prev) {
2905 			r->prev = kmemdup(__r->prev, sizeof(*r->prev),
2906 					  GFP_KERNEL);
2907 			if (unlikely(!r->prev))
2908 				goto err_free_unmap;
2909 		}
2910 
2911 		if (__r->next) {
2912 			r->next = kmemdup(__r->next, sizeof(*r->next),
2913 					  GFP_KERNEL);
2914 			if (unlikely(!r->next))
2915 				goto err_free_prev;
2916 		}
2917 	}
2918 
2919 	list_add_tail(&op->entry, &ops->list);
2920 
2921 	return 0;
2922 
2923 err_free_unmap:
2924 	kfree(op->remap.unmap);
2925 err_free_prev:
2926 	kfree(op->remap.prev);
2927 err_free_op:
2928 	gpuva_op_free(gpuvm, op);
2929 err:
2930 	return -ENOMEM;
2931 }
2932 
2933 static const struct drm_gpuvm_ops gpuvm_list_ops = {
2934 	.sm_step_map = drm_gpuva_sm_step,
2935 	.sm_step_remap = drm_gpuva_sm_step,
2936 	.sm_step_unmap = drm_gpuva_sm_step,
2937 };
2938 
2939 static struct drm_gpuva_ops *
2940 __drm_gpuvm_sm_map_ops_create(struct drm_gpuvm *gpuvm,
2941 			      const struct drm_gpuvm_map_req *req,
2942 			      bool madvise)
2943 {
2944 	struct drm_gpuva_ops *ops;
2945 	struct {
2946 		struct drm_gpuvm *vm;
2947 		struct drm_gpuva_ops *ops;
2948 	} args;
2949 	int ret;
2950 
2951 	ops = kzalloc_obj(*ops);
2952 	if (unlikely(!ops))
2953 		return ERR_PTR(-ENOMEM);
2954 
2955 	INIT_LIST_HEAD(&ops->list);
2956 
2957 	args.vm = gpuvm;
2958 	args.ops = ops;
2959 
2960 	ret = __drm_gpuvm_sm_map(gpuvm, &gpuvm_list_ops, &args, req, madvise);
2961 	if (ret)
2962 		goto err_free_ops;
2963 
2964 	return ops;
2965 
2966 err_free_ops:
2967 	drm_gpuva_ops_free(gpuvm, ops);
2968 	return ERR_PTR(ret);
2969 }
2970 
2971 /**
2972  * drm_gpuvm_sm_map_ops_create() - creates the &drm_gpuva_ops to split and merge
2973  * @gpuvm: the &drm_gpuvm representing the GPU VA space
2974  * @req: map request arguments
2975  *
2976  * This function creates a list of operations to perform splitting and merging
2977  * of existing mapping(s) with the newly requested one.
2978  *
2979  * The list can be iterated with &drm_gpuva_for_each_op and must be processed
2980  * in the given order. It can contain map, unmap and remap operations, but it
2981  * also can be empty if no operation is required, e.g. if the requested mapping
2982  * already exists in the exact same way.
2983  *
2984  * There can be an arbitrary amount of unmap operations, a maximum of two remap
2985  * operations and a single map operation. The latter one represents the original
2986  * map operation requested by the caller.
2987  *
2988  * Note that before calling this function again with another mapping request it
2989  * is necessary to update the &drm_gpuvm's view of the GPU VA space. The
2990  * previously obtained operations must be either processed or abandoned. To
2991  * update the &drm_gpuvm's view of the GPU VA space drm_gpuva_insert(),
2992  * drm_gpuva_destroy_locked() and/or drm_gpuva_destroy_unlocked() should be
2993  * used.
2994  *
2995  * After the caller finished processing the returned &drm_gpuva_ops, they must
2996  * be freed with &drm_gpuva_ops_free.
2997  *
2998  * Returns: a pointer to the &drm_gpuva_ops on success, an ERR_PTR on failure
2999  */
3000 struct drm_gpuva_ops *
3001 drm_gpuvm_sm_map_ops_create(struct drm_gpuvm *gpuvm,
3002 			    const struct drm_gpuvm_map_req *req)
3003 {
3004 	return __drm_gpuvm_sm_map_ops_create(gpuvm, req, false);
3005 }
3006 EXPORT_SYMBOL_GPL(drm_gpuvm_sm_map_ops_create);
3007 
3008 /**
3009  * drm_gpuvm_madvise_ops_create() - creates the &drm_gpuva_ops to split
3010  * @gpuvm: the &drm_gpuvm representing the GPU VA space
3011  * @req: map request arguments
3012  *
3013  * This function creates a list of operations to perform splitting
3014  * of existent mapping(s) at start or end, based on the request map.
3015  *
3016  * The list can be iterated with &drm_gpuva_for_each_op and must be processed
3017  * in the given order. It can contain map and remap operations, but it
3018  * also can be empty if no operation is required, e.g. if the requested mapping
3019  * already exists is the exact same way.
3020  *
3021  * There will be no unmap operations, a maximum of two remap operations and two
3022  * map operations. The two map operations correspond to: one from start to the
3023  * end of drm_gpuvaX, and another from the start of drm_gpuvaY to end.
3024  *
3025  * Note that before calling this function again with another mapping request it
3026  * is necessary to update the &drm_gpuvm's view of the GPU VA space. The
3027  * previously obtained operations must be either processed or abandoned. To
3028  * update the &drm_gpuvm's view of the GPU VA space drm_gpuva_insert(),
3029  * drm_gpuva_destroy_locked() and/or drm_gpuva_destroy_unlocked() should be
3030  * used.
3031  *
3032  * After the caller finished processing the returned &drm_gpuva_ops, they must
3033  * be freed with &drm_gpuva_ops_free.
3034  *
3035  * Returns: a pointer to the &drm_gpuva_ops on success, an ERR_PTR on failure
3036  */
3037 struct drm_gpuva_ops *
3038 drm_gpuvm_madvise_ops_create(struct drm_gpuvm *gpuvm,
3039 			     const struct drm_gpuvm_map_req *req)
3040 {
3041 	return __drm_gpuvm_sm_map_ops_create(gpuvm, req, true);
3042 }
3043 EXPORT_SYMBOL_GPL(drm_gpuvm_madvise_ops_create);
3044 
3045 /**
3046  * drm_gpuvm_sm_unmap_ops_create() - creates the &drm_gpuva_ops to split on
3047  * unmap
3048  * @gpuvm: the &drm_gpuvm representing the GPU VA space
3049  * @req_addr: the start address of the range to unmap
3050  * @req_range: the range of the mappings to unmap
3051  *
3052  * This function creates a list of operations to perform unmapping and, if
3053  * required, splitting of the mappings overlapping the unmap range.
3054  *
3055  * The list can be iterated with &drm_gpuva_for_each_op and must be processed
3056  * in the given order. It can contain unmap and remap operations, depending on
3057  * whether there are actual overlapping mappings to split.
3058  *
3059  * There can be an arbitrary amount of unmap operations and a maximum of two
3060  * remap operations.
3061  *
3062  * Note that before calling this function again with another range to unmap it
3063  * is necessary to update the &drm_gpuvm's view of the GPU VA space. The
3064  * previously obtained operations must be processed or abandoned. To update the
3065  * &drm_gpuvm's view of the GPU VA space drm_gpuva_insert(),
3066  * drm_gpuva_destroy_locked() and/or drm_gpuva_destroy_unlocked() should be
3067  * used.
3068  *
3069  * After the caller finished processing the returned &drm_gpuva_ops, they must
3070  * be freed with &drm_gpuva_ops_free.
3071  *
3072  * Returns: a pointer to the &drm_gpuva_ops on success, an ERR_PTR on failure
3073  */
3074 struct drm_gpuva_ops *
3075 drm_gpuvm_sm_unmap_ops_create(struct drm_gpuvm *gpuvm,
3076 			      u64 req_addr, u64 req_range)
3077 {
3078 	struct drm_gpuva_ops *ops;
3079 	struct {
3080 		struct drm_gpuvm *vm;
3081 		struct drm_gpuva_ops *ops;
3082 	} args;
3083 	int ret;
3084 
3085 	ops = kzalloc_obj(*ops);
3086 	if (unlikely(!ops))
3087 		return ERR_PTR(-ENOMEM);
3088 
3089 	INIT_LIST_HEAD(&ops->list);
3090 
3091 	args.vm = gpuvm;
3092 	args.ops = ops;
3093 
3094 	ret = __drm_gpuvm_sm_unmap(gpuvm, &gpuvm_list_ops, &args,
3095 				   req_addr, req_range);
3096 	if (ret)
3097 		goto err_free_ops;
3098 
3099 	return ops;
3100 
3101 err_free_ops:
3102 	drm_gpuva_ops_free(gpuvm, ops);
3103 	return ERR_PTR(ret);
3104 }
3105 EXPORT_SYMBOL_GPL(drm_gpuvm_sm_unmap_ops_create);
3106 
3107 /**
3108  * drm_gpuvm_prefetch_ops_create() - creates the &drm_gpuva_ops to prefetch
3109  * @gpuvm: the &drm_gpuvm representing the GPU VA space
3110  * @addr: the start address of the range to prefetch
3111  * @range: the range of the mappings to prefetch
3112  *
3113  * This function creates a list of operations to perform prefetching.
3114  *
3115  * The list can be iterated with &drm_gpuva_for_each_op and must be processed
3116  * in the given order. It can contain prefetch operations.
3117  *
3118  * There can be an arbitrary amount of prefetch operations.
3119  *
3120  * After the caller finished processing the returned &drm_gpuva_ops, they must
3121  * be freed with &drm_gpuva_ops_free.
3122  *
3123  * Returns: a pointer to the &drm_gpuva_ops on success, an ERR_PTR on failure
3124  */
3125 struct drm_gpuva_ops *
3126 drm_gpuvm_prefetch_ops_create(struct drm_gpuvm *gpuvm,
3127 			      u64 addr, u64 range)
3128 {
3129 	struct drm_gpuva_ops *ops;
3130 	struct drm_gpuva_op *op;
3131 	struct drm_gpuva *va;
3132 	u64 end = addr + range;
3133 	int ret;
3134 
3135 	ops = kzalloc_obj(*ops);
3136 	if (!ops)
3137 		return ERR_PTR(-ENOMEM);
3138 
3139 	INIT_LIST_HEAD(&ops->list);
3140 
3141 	drm_gpuvm_for_each_va_range(va, gpuvm, addr, end) {
3142 		op = gpuva_op_alloc(gpuvm);
3143 		if (!op) {
3144 			ret = -ENOMEM;
3145 			goto err_free_ops;
3146 		}
3147 
3148 		op->op = DRM_GPUVA_OP_PREFETCH;
3149 		op->prefetch.va = va;
3150 		list_add_tail(&op->entry, &ops->list);
3151 	}
3152 
3153 	return ops;
3154 
3155 err_free_ops:
3156 	drm_gpuva_ops_free(gpuvm, ops);
3157 	return ERR_PTR(ret);
3158 }
3159 EXPORT_SYMBOL_GPL(drm_gpuvm_prefetch_ops_create);
3160 
3161 /**
3162  * drm_gpuvm_bo_unmap_ops_create() - creates the &drm_gpuva_ops to unmap a GEM
3163  * @vm_bo: the &drm_gpuvm_bo abstraction
3164  *
3165  * This function creates a list of operations to perform unmapping for every
3166  * GPUVA attached to a GEM.
3167  *
3168  * The list can be iterated with &drm_gpuva_for_each_op and consists out of an
3169  * arbitrary amount of unmap operations.
3170  *
3171  * After the caller finished processing the returned &drm_gpuva_ops, they must
3172  * be freed with &drm_gpuva_ops_free.
3173  *
3174  * This function expects the caller to protect the GEM's GPUVA list against
3175  * concurrent access using either the GEM's dma-resv or gpuva.lock mutex.
3176  *
3177  * Returns: a pointer to the &drm_gpuva_ops on success, an ERR_PTR on failure
3178  */
3179 struct drm_gpuva_ops *
3180 drm_gpuvm_bo_unmap_ops_create(struct drm_gpuvm_bo *vm_bo)
3181 {
3182 	struct drm_gpuva_ops *ops;
3183 	struct drm_gpuva_op *op;
3184 	struct drm_gpuva *va;
3185 	int ret;
3186 
3187 	drm_gem_gpuva_assert_lock_held(vm_bo->vm, vm_bo->obj);
3188 
3189 	ops = kzalloc_obj(*ops);
3190 	if (!ops)
3191 		return ERR_PTR(-ENOMEM);
3192 
3193 	INIT_LIST_HEAD(&ops->list);
3194 
3195 	drm_gpuvm_bo_for_each_va(va, vm_bo) {
3196 		op = gpuva_op_alloc(vm_bo->vm);
3197 		if (!op) {
3198 			ret = -ENOMEM;
3199 			goto err_free_ops;
3200 		}
3201 
3202 		op->op = DRM_GPUVA_OP_UNMAP;
3203 		op->unmap.va = va;
3204 		list_add_tail(&op->entry, &ops->list);
3205 	}
3206 
3207 	return ops;
3208 
3209 err_free_ops:
3210 	drm_gpuva_ops_free(vm_bo->vm, ops);
3211 	return ERR_PTR(ret);
3212 }
3213 EXPORT_SYMBOL_GPL(drm_gpuvm_bo_unmap_ops_create);
3214 
3215 /**
3216  * drm_gpuva_ops_free() - free the given &drm_gpuva_ops
3217  * @gpuvm: the &drm_gpuvm the ops were created for
3218  * @ops: the &drm_gpuva_ops to free
3219  *
3220  * Frees the given &drm_gpuva_ops structure including all the ops associated
3221  * with it.
3222  */
3223 void
3224 drm_gpuva_ops_free(struct drm_gpuvm *gpuvm,
3225 		   struct drm_gpuva_ops *ops)
3226 {
3227 	struct drm_gpuva_op *op, *next;
3228 
3229 	drm_gpuva_for_each_op_safe(op, next, ops) {
3230 		list_del(&op->entry);
3231 
3232 		if (op->op == DRM_GPUVA_OP_REMAP) {
3233 			kfree(op->remap.prev);
3234 			kfree(op->remap.next);
3235 			kfree(op->remap.unmap);
3236 		}
3237 
3238 		gpuva_op_free(gpuvm, op);
3239 	}
3240 
3241 	kfree(ops);
3242 }
3243 EXPORT_SYMBOL_GPL(drm_gpuva_ops_free);
3244 
3245 MODULE_DESCRIPTION("DRM GPUVM");
3246 MODULE_LICENSE("GPL");
3247