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