1 /**************************************************************************
2  *
3  * Copyright (c) 2006-2009 VMware, Inc., Palo Alto, CA., USA
4  * All Rights Reserved.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the
8  * "Software"), to deal in the Software without restriction, including
9  * without limitation the rights to use, copy, modify, merge, publish,
10  * distribute, sub license, and/or sell copies of the Software, and to
11  * permit persons to whom the Software is furnished to do so, subject to
12  * the following conditions:
13  *
14  * The above copyright notice and this permission notice (including the
15  * next paragraph) shall be included in all copies or substantial portions
16  * of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20  * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
21  * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
22  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
23  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
24  * USE OR OTHER DEALINGS IN THE SOFTWARE.
25  *
26  **************************************************************************/
27 /*
28  * Authors: Thomas Hellstrom <thellstrom-at-vmware-dot-com>
29  */
30 
31 #ifndef _TTM_BO_API_H_
32 #define _TTM_BO_API_H_
33 
34 #include <drm/drm_gem.h>
35 #include <drm/drm_hashtab.h>
36 #include <drm/drm_vma_manager.h>
37 #include <linux/kref.h>
38 #include <linux/list.h>
39 #include <linux/wait.h>
40 #include <linux/mutex.h>
41 #include <linux/mm.h>
42 #include <linux/bitmap.h>
43 #include <linux/dma-resv.h>
44 
45 #include "ttm_resource.h"
46 
47 struct ttm_global;
48 
49 struct ttm_device;
50 
51 struct dma_buf_map;
52 
53 struct drm_mm_node;
54 
55 struct ttm_placement;
56 
57 struct ttm_place;
58 
59 struct ttm_lru_bulk_move;
60 
61 /**
62  * enum ttm_bo_type
63  *
64  * @ttm_bo_type_device:	These are 'normal' buffers that can
65  * be mmapped by user space. Each of these bos occupy a slot in the
66  * device address space, that can be used for normal vm operations.
67  *
68  * @ttm_bo_type_kernel: These buffers are like ttm_bo_type_device buffers,
69  * but they cannot be accessed from user-space. For kernel-only use.
70  *
71  * @ttm_bo_type_sg: Buffer made from dmabuf sg table shared with another
72  * driver.
73  */
74 
75 enum ttm_bo_type {
76 	ttm_bo_type_device,
77 	ttm_bo_type_kernel,
78 	ttm_bo_type_sg
79 };
80 
81 struct ttm_tt;
82 
83 /**
84  * struct ttm_buffer_object
85  *
86  * @base: drm_gem_object superclass data.
87  * @bdev: Pointer to the buffer object device structure.
88  * @type: The bo type.
89  * @page_alignment: Page alignment.
90  * @destroy: Destruction function. If NULL, kfree is used.
91  * @num_pages: Actual number of pages.
92  * @kref: Reference count of this buffer object. When this refcount reaches
93  * zero, the object is destroyed or put on the delayed delete list.
94  * @mem: structure describing current placement.
95  * @ttm: TTM structure holding system pages.
96  * @evicted: Whether the object was evicted without user-space knowing.
97  * @deleted: True if the object is only a zombie and already deleted.
98  * @lru: List head for the lru list.
99  * @ddestroy: List head for the delayed destroy list.
100  * @swap: List head for swap LRU list.
101  * @moving: Fence set when BO is moving
102  * @offset: The current GPU offset, which can have different meanings
103  * depending on the memory type. For SYSTEM type memory, it should be 0.
104  * @cur_placement: Hint of current placement.
105  *
106  * Base class for TTM buffer object, that deals with data placement and CPU
107  * mappings. GPU mappings are really up to the driver, but for simpler GPUs
108  * the driver can usually use the placement offset @offset directly as the
109  * GPU virtual address. For drivers implementing multiple
110  * GPU memory manager contexts, the driver should manage the address space
111  * in these contexts separately and use these objects to get the correct
112  * placement and caching for these GPU maps. This makes it possible to use
113  * these objects for even quite elaborate memory management schemes.
114  * The destroy member, the API visibility of this object makes it possible
115  * to derive driver specific types.
116  */
117 
118 struct ttm_buffer_object {
119 	struct drm_gem_object base;
120 
121 	/**
122 	 * Members constant at init.
123 	 */
124 
125 	struct ttm_device *bdev;
126 	enum ttm_bo_type type;
127 	uint32_t page_alignment;
128 	void (*destroy) (struct ttm_buffer_object *);
129 
130 	/**
131 	* Members not needing protection.
132 	*/
133 	struct kref kref;
134 
135 	/**
136 	 * Members protected by the bo::resv::reserved lock.
137 	 */
138 
139 	struct ttm_resource *resource;
140 	struct ttm_tt *ttm;
141 	bool deleted;
142 
143 	/**
144 	 * Members protected by the bdev::lru_lock.
145 	 */
146 
147 	struct list_head lru;
148 	struct list_head ddestroy;
149 
150 	/**
151 	 * Members protected by a bo reservation.
152 	 */
153 
154 	struct dma_fence *moving;
155 	unsigned priority;
156 	unsigned pin_count;
157 
158 	/**
159 	 * Special members that are protected by the reserve lock
160 	 * and the bo::lock when written to. Can be read with
161 	 * either of these locks held.
162 	 */
163 
164 	struct sg_table *sg;
165 };
166 
167 /**
168  * struct ttm_bo_kmap_obj
169  *
170  * @virtual: The current kernel virtual address.
171  * @page: The page when kmap'ing a single page.
172  * @bo_kmap_type: Type of bo_kmap.
173  *
174  * Object describing a kernel mapping. Since a TTM bo may be located
175  * in various memory types with various caching policies, the
176  * mapping can either be an ioremap, a vmap, a kmap or part of a
177  * premapped region.
178  */
179 
180 #define TTM_BO_MAP_IOMEM_MASK 0x80
181 struct ttm_bo_kmap_obj {
182 	void *virtual;
183 	struct page *page;
184 	enum {
185 		ttm_bo_map_iomap        = 1 | TTM_BO_MAP_IOMEM_MASK,
186 		ttm_bo_map_vmap         = 2,
187 		ttm_bo_map_kmap         = 3,
188 		ttm_bo_map_premapped    = 4 | TTM_BO_MAP_IOMEM_MASK,
189 	} bo_kmap_type;
190 	struct ttm_buffer_object *bo;
191 };
192 
193 /**
194  * struct ttm_operation_ctx
195  *
196  * @interruptible: Sleep interruptible if sleeping.
197  * @no_wait_gpu: Return immediately if the GPU is busy.
198  * @gfp_retry_mayfail: Set the __GFP_RETRY_MAYFAIL when allocation pages.
199  * @allow_res_evict: Allow eviction of reserved BOs. Can be used when multiple
200  * BOs share the same reservation object.
201  * @force_alloc: Don't check the memory account during suspend or CPU page
202  * faults. Should only be used by TTM internally.
203  * @resv: Reservation object to allow reserved evictions with.
204  *
205  * Context for TTM operations like changing buffer placement or general memory
206  * allocation.
207  */
208 struct ttm_operation_ctx {
209 	bool interruptible;
210 	bool no_wait_gpu;
211 	bool gfp_retry_mayfail;
212 	bool allow_res_evict;
213 	bool force_alloc;
214 	struct dma_resv *resv;
215 	uint64_t bytes_moved;
216 };
217 
218 /**
219  * ttm_bo_get - reference a struct ttm_buffer_object
220  *
221  * @bo: The buffer object.
222  */
ttm_bo_get(struct ttm_buffer_object * bo)223 static inline void ttm_bo_get(struct ttm_buffer_object *bo)
224 {
225 	kref_get(&bo->kref);
226 }
227 
228 /**
229  * ttm_bo_get_unless_zero - reference a struct ttm_buffer_object unless
230  * its refcount has already reached zero.
231  * @bo: The buffer object.
232  *
233  * Used to reference a TTM buffer object in lookups where the object is removed
234  * from the lookup structure during the destructor and for RCU lookups.
235  *
236  * Returns: @bo if the referencing was successful, NULL otherwise.
237  */
238 static inline __must_check struct ttm_buffer_object *
ttm_bo_get_unless_zero(struct ttm_buffer_object * bo)239 ttm_bo_get_unless_zero(struct ttm_buffer_object *bo)
240 {
241 	if (!kref_get_unless_zero(&bo->kref))
242 		return NULL;
243 	return bo;
244 }
245 
246 /**
247  * ttm_bo_wait - wait for buffer idle.
248  *
249  * @bo:  The buffer object.
250  * @interruptible:  Use interruptible wait.
251  * @no_wait:  Return immediately if buffer is busy.
252  *
253  * This function must be called with the bo::mutex held, and makes
254  * sure any previous rendering to the buffer is completed.
255  * Note: It might be necessary to block validations before the
256  * wait by reserving the buffer.
257  * Returns -EBUSY if no_wait is true and the buffer is busy.
258  * Returns -ERESTARTSYS if interrupted by a signal.
259  */
260 int ttm_bo_wait(struct ttm_buffer_object *bo, bool interruptible, bool no_wait);
261 
ttm_bo_wait_ctx(struct ttm_buffer_object * bo,struct ttm_operation_ctx * ctx)262 static inline int ttm_bo_wait_ctx(struct ttm_buffer_object *bo, struct ttm_operation_ctx *ctx)
263 {
264 	return ttm_bo_wait(bo, ctx->interruptible, ctx->no_wait_gpu);
265 }
266 
267 /**
268  * ttm_bo_validate
269  *
270  * @bo: The buffer object.
271  * @placement: Proposed placement for the buffer object.
272  * @ctx: validation parameters.
273  *
274  * Changes placement and caching policy of the buffer object
275  * according proposed placement.
276  * Returns
277  * -EINVAL on invalid proposed placement.
278  * -ENOMEM on out-of-memory condition.
279  * -EBUSY if no_wait is true and buffer busy.
280  * -ERESTARTSYS if interrupted by a signal.
281  */
282 int ttm_bo_validate(struct ttm_buffer_object *bo,
283 		    struct ttm_placement *placement,
284 		    struct ttm_operation_ctx *ctx);
285 
286 /**
287  * ttm_bo_put
288  *
289  * @bo: The buffer object.
290  *
291  * Unreference a buffer object.
292  */
293 void ttm_bo_put(struct ttm_buffer_object *bo);
294 
295 /**
296  * ttm_bo_move_to_lru_tail
297  *
298  * @bo: The buffer object.
299  * @mem: Resource object.
300  * @bulk: optional bulk move structure to remember BO positions
301  *
302  * Move this BO to the tail of all lru lists used to lookup and reserve an
303  * object. This function must be called with struct ttm_global::lru_lock
304  * held, and is used to make a BO less likely to be considered for eviction.
305  */
306 void ttm_bo_move_to_lru_tail(struct ttm_buffer_object *bo,
307 			     struct ttm_resource *mem,
308 			     struct ttm_lru_bulk_move *bulk);
309 
310 /**
311  * ttm_bo_bulk_move_lru_tail
312  *
313  * @bulk: bulk move structure
314  *
315  * Bulk move BOs to the LRU tail, only valid to use when driver makes sure that
316  * BO order never changes. Should be called with ttm_global::lru_lock held.
317  */
318 void ttm_bo_bulk_move_lru_tail(struct ttm_lru_bulk_move *bulk);
319 
320 /**
321  * ttm_bo_lock_delayed_workqueue
322  *
323  * Prevent the delayed workqueue from running.
324  * Returns
325  * True if the workqueue was queued at the time
326  */
327 int ttm_bo_lock_delayed_workqueue(struct ttm_device *bdev);
328 
329 /**
330  * ttm_bo_unlock_delayed_workqueue
331  *
332  * Allows the delayed workqueue to run.
333  */
334 void ttm_bo_unlock_delayed_workqueue(struct ttm_device *bdev, int resched);
335 
336 /**
337  * ttm_bo_eviction_valuable
338  *
339  * @bo: The buffer object to evict
340  * @place: the placement we need to make room for
341  *
342  * Check if it is valuable to evict the BO to make room for the given placement.
343  */
344 bool ttm_bo_eviction_valuable(struct ttm_buffer_object *bo,
345 			      const struct ttm_place *place);
346 
347 /**
348  * ttm_bo_init_reserved
349  *
350  * @bdev: Pointer to a ttm_device struct.
351  * @bo: Pointer to a ttm_buffer_object to be initialized.
352  * @size: Requested size of buffer object.
353  * @type: Requested type of buffer object.
354  * @placement: Initial placement for buffer object.
355  * @page_alignment: Data alignment in pages.
356  * @ctx: TTM operation context for memory allocation.
357  * @sg: Scatter-gather table.
358  * @resv: Pointer to a dma_resv, or NULL to let ttm allocate one.
359  * @destroy: Destroy function. Use NULL for kfree().
360  *
361  * This function initializes a pre-allocated struct ttm_buffer_object.
362  * As this object may be part of a larger structure, this function,
363  * together with the @destroy function,
364  * enables driver-specific objects derived from a ttm_buffer_object.
365  *
366  * On successful return, the caller owns an object kref to @bo. The kref and
367  * list_kref are usually set to 1, but note that in some situations, other
368  * tasks may already be holding references to @bo as well.
369  * Furthermore, if resv == NULL, the buffer's reservation lock will be held,
370  * and it is the caller's responsibility to call ttm_bo_unreserve.
371  *
372  * If a failure occurs, the function will call the @destroy function, or
373  * kfree() if @destroy is NULL. Thus, after a failure, dereferencing @bo is
374  * illegal and will likely cause memory corruption.
375  *
376  * Returns
377  * -ENOMEM: Out of memory.
378  * -EINVAL: Invalid placement flags.
379  * -ERESTARTSYS: Interrupted by signal while sleeping waiting for resources.
380  */
381 
382 int ttm_bo_init_reserved(struct ttm_device *bdev,
383 			 struct ttm_buffer_object *bo,
384 			 size_t size, enum ttm_bo_type type,
385 			 struct ttm_placement *placement,
386 			 uint32_t page_alignment,
387 			 struct ttm_operation_ctx *ctx,
388 			 struct sg_table *sg, struct dma_resv *resv,
389 			 void (*destroy) (struct ttm_buffer_object *));
390 
391 /**
392  * ttm_bo_init
393  *
394  * @bdev: Pointer to a ttm_device struct.
395  * @bo: Pointer to a ttm_buffer_object to be initialized.
396  * @size: Requested size of buffer object.
397  * @type: Requested type of buffer object.
398  * @placement: Initial placement for buffer object.
399  * @page_alignment: Data alignment in pages.
400  * @interruptible: If needing to sleep to wait for GPU resources,
401  * sleep interruptible.
402  * pinned in physical memory. If this behaviour is not desired, this member
403  * holds a pointer to a persistent shmem object. Typically, this would
404  * point to the shmem object backing a GEM object if TTM is used to back a
405  * GEM user interface.
406  * @sg: Scatter-gather table.
407  * @resv: Pointer to a dma_resv, or NULL to let ttm allocate one.
408  * @destroy: Destroy function. Use NULL for kfree().
409  *
410  * This function initializes a pre-allocated struct ttm_buffer_object.
411  * As this object may be part of a larger structure, this function,
412  * together with the @destroy function,
413  * enables driver-specific objects derived from a ttm_buffer_object.
414  *
415  * On successful return, the caller owns an object kref to @bo. The kref and
416  * list_kref are usually set to 1, but note that in some situations, other
417  * tasks may already be holding references to @bo as well.
418  *
419  * If a failure occurs, the function will call the @destroy function, or
420  * kfree() if @destroy is NULL. Thus, after a failure, dereferencing @bo is
421  * illegal and will likely cause memory corruption.
422  *
423  * Returns
424  * -ENOMEM: Out of memory.
425  * -EINVAL: Invalid placement flags.
426  * -ERESTARTSYS: Interrupted by signal while sleeping waiting for resources.
427  */
428 int ttm_bo_init(struct ttm_device *bdev, struct ttm_buffer_object *bo,
429 		size_t size, enum ttm_bo_type type,
430 		struct ttm_placement *placement,
431 		uint32_t page_alignment, bool interrubtible,
432 		struct sg_table *sg, struct dma_resv *resv,
433 		void (*destroy) (struct ttm_buffer_object *));
434 
435 /**
436  * ttm_kmap_obj_virtual
437  *
438  * @map: A struct ttm_bo_kmap_obj returned from ttm_bo_kmap.
439  * @is_iomem: Pointer to an integer that on return indicates 1 if the
440  * virtual map is io memory, 0 if normal memory.
441  *
442  * Returns the virtual address of a buffer object area mapped by ttm_bo_kmap.
443  * If *is_iomem is 1 on return, the virtual address points to an io memory area,
444  * that should strictly be accessed by the iowriteXX() and similar functions.
445  */
ttm_kmap_obj_virtual(struct ttm_bo_kmap_obj * map,bool * is_iomem)446 static inline void *ttm_kmap_obj_virtual(struct ttm_bo_kmap_obj *map,
447 					 bool *is_iomem)
448 {
449 	*is_iomem = !!(map->bo_kmap_type & TTM_BO_MAP_IOMEM_MASK);
450 	return map->virtual;
451 }
452 
453 /**
454  * ttm_bo_kmap
455  *
456  * @bo: The buffer object.
457  * @start_page: The first page to map.
458  * @num_pages: Number of pages to map.
459  * @map: pointer to a struct ttm_bo_kmap_obj representing the map.
460  *
461  * Sets up a kernel virtual mapping, using ioremap, vmap or kmap to the
462  * data in the buffer object. The ttm_kmap_obj_virtual function can then be
463  * used to obtain a virtual address to the data.
464  *
465  * Returns
466  * -ENOMEM: Out of memory.
467  * -EINVAL: Invalid range.
468  */
469 int ttm_bo_kmap(struct ttm_buffer_object *bo, unsigned long start_page,
470 		unsigned long num_pages, struct ttm_bo_kmap_obj *map);
471 
472 /**
473  * ttm_bo_kunmap
474  *
475  * @map: Object describing the map to unmap.
476  *
477  * Unmaps a kernel map set up by ttm_bo_kmap.
478  */
479 void ttm_bo_kunmap(struct ttm_bo_kmap_obj *map);
480 
481 /**
482  * ttm_bo_vmap
483  *
484  * @bo: The buffer object.
485  * @map: pointer to a struct dma_buf_map representing the map.
486  *
487  * Sets up a kernel virtual mapping, using ioremap or vmap to the
488  * data in the buffer object. The parameter @map returns the virtual
489  * address as struct dma_buf_map. Unmap the buffer with ttm_bo_vunmap().
490  *
491  * Returns
492  * -ENOMEM: Out of memory.
493  * -EINVAL: Invalid range.
494  */
495 int ttm_bo_vmap(struct ttm_buffer_object *bo, struct dma_buf_map *map);
496 
497 /**
498  * ttm_bo_vunmap
499  *
500  * @bo: The buffer object.
501  * @map: Object describing the map to unmap.
502  *
503  * Unmaps a kernel map set up by ttm_bo_vmap().
504  */
505 void ttm_bo_vunmap(struct ttm_buffer_object *bo, struct dma_buf_map *map);
506 
507 /**
508  * ttm_bo_mmap_obj - mmap memory backed by a ttm buffer object.
509  *
510  * @vma:       vma as input from the fbdev mmap method.
511  * @bo:        The bo backing the address space.
512  *
513  * Maps a buffer object.
514  */
515 int ttm_bo_mmap_obj(struct vm_area_struct *vma, struct ttm_buffer_object *bo);
516 
517 /**
518  * ttm_bo_io
519  *
520  * @bdev:      Pointer to the struct ttm_device.
521  * @filp:      Pointer to the struct file attempting to read / write.
522  * @wbuf:      User-space pointer to address of buffer to write. NULL on read.
523  * @rbuf:      User-space pointer to address of buffer to read into.
524  * Null on write.
525  * @count:     Number of bytes to read / write.
526  * @f_pos:     Pointer to current file position.
527  * @write:     1 for read, 0 for write.
528  *
529  * This function implements read / write into ttm buffer objects, and is
530  * intended to
531  * be called from the fops::read and fops::write method.
532  * Returns:
533  * See man (2) write, man(2) read. In particular,
534  * the function may return -ERESTARTSYS if
535  * interrupted by a signal.
536  */
537 ssize_t ttm_bo_io(struct ttm_device *bdev, struct file *filp,
538 		  const char __user *wbuf, char __user *rbuf,
539 		  size_t count, loff_t *f_pos, bool write);
540 
541 int ttm_bo_swapout(struct ttm_buffer_object *bo, struct ttm_operation_ctx *ctx,
542 		   gfp_t gfp_flags);
543 
544 /**
545  * ttm_bo_pin - Pin the buffer object.
546  * @bo: The buffer object to pin
547  *
548  * Make sure the buffer is not evicted any more during memory pressure.
549  */
ttm_bo_pin(struct ttm_buffer_object * bo)550 static inline void ttm_bo_pin(struct ttm_buffer_object *bo)
551 {
552 	dma_resv_assert_held(bo->base.resv);
553 	WARN_ON_ONCE(!kref_read(&bo->kref));
554 	++bo->pin_count;
555 }
556 
557 /**
558  * ttm_bo_unpin - Unpin the buffer object.
559  * @bo: The buffer object to unpin
560  *
561  * Allows the buffer object to be evicted again during memory pressure.
562  */
ttm_bo_unpin(struct ttm_buffer_object * bo)563 static inline void ttm_bo_unpin(struct ttm_buffer_object *bo)
564 {
565 	dma_resv_assert_held(bo->base.resv);
566 	WARN_ON_ONCE(!kref_read(&bo->kref));
567 	if (bo->pin_count)
568 		--bo->pin_count;
569 	else
570 		WARN_ON_ONCE(true);
571 }
572 
573 int ttm_mem_evict_first(struct ttm_device *bdev,
574 			struct ttm_resource_manager *man,
575 			const struct ttm_place *place,
576 			struct ttm_operation_ctx *ctx,
577 			struct ww_acquire_ctx *ticket);
578 
579 /* Default number of pre-faulted pages in the TTM fault handler */
580 #define TTM_BO_VM_NUM_PREFAULT 16
581 
582 vm_fault_t ttm_bo_vm_reserve(struct ttm_buffer_object *bo,
583 			     struct vm_fault *vmf);
584 
585 vm_fault_t ttm_bo_vm_fault_reserved(struct vm_fault *vmf,
586 				    pgprot_t prot,
587 				    pgoff_t num_prefault);
588 
589 vm_fault_t ttm_bo_vm_fault(struct vm_fault *vmf);
590 
591 void ttm_bo_vm_open(struct vm_area_struct *vma);
592 
593 void ttm_bo_vm_close(struct vm_area_struct *vma);
594 
595 int ttm_bo_vm_access(struct vm_area_struct *vma, unsigned long addr,
596 		     void *buf, int len, int write);
597 bool ttm_bo_delayed_delete(struct ttm_device *bdev, bool remove_all);
598 
599 vm_fault_t ttm_bo_vm_dummy_page(struct vm_fault *vmf, pgprot_t prot);
600 
601 #endif
602