xref: /linux/include/drm/ttm/ttm_bo.h (revision 33b4e4fcd2980ee5fd754731ca9b0325f0344f04)
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 
36 #include <linux/kref.h>
37 #include <linux/list.h>
38 
39 #include "ttm_device.h"
40 
41 /* Default number of pre-faulted pages in the TTM fault handler */
42 #define TTM_BO_VM_NUM_PREFAULT 16
43 
44 struct iosys_map;
45 
46 struct ttm_global;
47 struct ttm_device;
48 struct ttm_placement;
49 struct ttm_place;
50 struct ttm_resource;
51 struct ttm_resource_manager;
52 struct ttm_tt;
53 
54 /**
55  * enum ttm_bo_type
56  *
57  * @ttm_bo_type_device:	These are 'normal' buffers that can
58  * be mmapped by user space. Each of these bos occupy a slot in the
59  * device address space, that can be used for normal vm operations.
60  *
61  * @ttm_bo_type_kernel: These buffers are like ttm_bo_type_device buffers,
62  * but they cannot be accessed from user-space. For kernel-only use.
63  *
64  * @ttm_bo_type_sg: Buffer made from dmabuf sg table shared with another
65  * driver.
66  */
67 enum ttm_bo_type {
68 	ttm_bo_type_device,
69 	ttm_bo_type_kernel,
70 	ttm_bo_type_sg
71 };
72 
73 /**
74  * struct ttm_buffer_object
75  *
76  * @base: drm_gem_object superclass data.
77  * @bdev: Pointer to the buffer object device structure.
78  * @type: The bo type.
79  * @page_alignment: Page alignment.
80  * @destroy: Destruction function. If NULL, kfree is used.
81  * @kref: Reference count of this buffer object. When this refcount reaches
82  * zero, the object is destroyed or put on the delayed delete list.
83  * @resource: structure describing current placement.
84  * @ttm: TTM structure holding system pages.
85  * @deleted: True if the object is only a zombie and already deleted.
86  * @bulk_move: The bulk move object.
87  * @priority: Priority for LRU, BOs with lower priority are evicted first.
88  * @pin_count: Pin count.
89  *
90  * Base class for TTM buffer object, that deals with data placement and CPU
91  * mappings. GPU mappings are really up to the driver, but for simpler GPUs
92  * the driver can usually use the placement offset @offset directly as the
93  * GPU virtual address. For drivers implementing multiple
94  * GPU memory manager contexts, the driver should manage the address space
95  * in these contexts separately and use these objects to get the correct
96  * placement and caching for these GPU maps. This makes it possible to use
97  * these objects for even quite elaborate memory management schemes.
98  * The destroy member, the API visibility of this object makes it possible
99  * to derive driver specific types.
100  */
101 struct ttm_buffer_object {
102 	struct drm_gem_object base;
103 
104 	/*
105 	 * Members constant at init.
106 	 */
107 	struct ttm_device *bdev;
108 	enum ttm_bo_type type;
109 	uint32_t page_alignment;
110 	void (*destroy) (struct ttm_buffer_object *);
111 
112 	/*
113 	* Members not needing protection.
114 	*/
115 	struct kref kref;
116 
117 	/*
118 	 * Members protected by the bo::resv::reserved lock.
119 	 */
120 	struct ttm_resource *resource;
121 	struct ttm_tt *ttm;
122 	bool deleted;
123 	struct ttm_lru_bulk_move *bulk_move;
124 	unsigned priority;
125 	unsigned pin_count;
126 
127 	/**
128 	 * @delayed_delete: Work item used when we can't delete the BO
129 	 * immediately
130 	 */
131 	struct work_struct delayed_delete;
132 
133 	/**
134 	 * @sg: external source of pages and DMA addresses, protected by the
135 	 * reservation lock.
136 	 */
137 	struct sg_table *sg;
138 };
139 
140 #define TTM_BO_MAP_IOMEM_MASK 0x80
141 
142 /**
143  * struct ttm_bo_kmap_obj
144  *
145  * @virtual: The current kernel virtual address.
146  * @page: The page when kmap'ing a single page.
147  * @bo_kmap_type: Type of bo_kmap.
148  * @bo: The TTM BO.
149  *
150  * Object describing a kernel mapping. Since a TTM bo may be located
151  * in various memory types with various caching policies, the
152  * mapping can either be an ioremap, a vmap, a kmap or part of a
153  * premapped region.
154  */
155 struct ttm_bo_kmap_obj {
156 	void *virtual;
157 	struct page *page;
158 	enum {
159 		ttm_bo_map_iomap        = 1 | TTM_BO_MAP_IOMEM_MASK,
160 		ttm_bo_map_vmap         = 2,
161 		ttm_bo_map_kmap         = 3,
162 		ttm_bo_map_premapped    = 4 | TTM_BO_MAP_IOMEM_MASK,
163 	} bo_kmap_type;
164 	struct ttm_buffer_object *bo;
165 };
166 
167 /**
168  * struct ttm_operation_ctx
169  *
170  * @interruptible: Sleep interruptible if sleeping.
171  * @no_wait_gpu: Return immediately if the GPU is busy.
172  * @gfp_retry_mayfail: Set the __GFP_RETRY_MAYFAIL when allocation pages.
173  * @allow_res_evict: Allow eviction of reserved BOs. Can be used when multiple
174  * BOs share the same reservation object.
175  * faults. Should only be used by TTM internally.
176  * @resv: Reservation object to allow reserved evictions with.
177  * @bytes_moved: Statistics on how many bytes have been moved.
178  *
179  * Context for TTM operations like changing buffer placement or general memory
180  * allocation.
181  */
182 struct ttm_operation_ctx {
183 	bool interruptible;
184 	bool no_wait_gpu;
185 	bool gfp_retry_mayfail;
186 	bool allow_res_evict;
187 	struct dma_resv *resv;
188 	uint64_t bytes_moved;
189 };
190 
191 struct ttm_lru_walk;
192 
193 /** struct ttm_lru_walk_ops - Operations for a LRU walk. */
194 struct ttm_lru_walk_ops {
195 	/**
196 	 * process_bo - Process this bo.
197 	 * @walk: struct ttm_lru_walk describing the walk.
198 	 * @bo: A locked and referenced buffer object.
199 	 *
200 	 * Return: Negative error code on error, User-defined positive value
201 	 * (typically, but not always, size of the processed bo) on success.
202 	 * On success, the returned values are summed by the walk and the
203 	 * walk exits when its target is met.
204 	 * 0 also indicates success, -EBUSY means this bo was skipped.
205 	 */
206 	s64 (*process_bo)(struct ttm_lru_walk *walk, struct ttm_buffer_object *bo);
207 };
208 
209 /**
210  * struct ttm_lru_walk - Structure describing a LRU walk.
211  */
212 struct ttm_lru_walk {
213 	/** @ops: Pointer to the ops structure. */
214 	const struct ttm_lru_walk_ops *ops;
215 	/** @ctx: Pointer to the struct ttm_operation_ctx. */
216 	struct ttm_operation_ctx *ctx;
217 	/** @ticket: The struct ww_acquire_ctx if any. */
218 	struct ww_acquire_ctx *ticket;
219 	/** @trylock_only: Only use trylock for locking. */
220 	bool trylock_only;
221 };
222 
223 s64 ttm_lru_walk_for_evict(struct ttm_lru_walk *walk, struct ttm_device *bdev,
224 			   struct ttm_resource_manager *man, s64 target);
225 
226 /**
227  * struct ttm_bo_shrink_flags - flags to govern the bo shrinking behaviour
228  * @purge: Purge the content rather than backing it up.
229  * @writeback: Attempt to immediately write content to swap space.
230  * @allow_move: Allow moving to system before shrinking. This is typically
231  * not desired for zombie- or ghost objects (with zombie object meaning
232  * objects with a zero gem object refcount)
233  */
234 struct ttm_bo_shrink_flags {
235 	u32 purge : 1;
236 	u32 writeback : 1;
237 	u32 allow_move : 1;
238 };
239 
240 long ttm_bo_shrink(struct ttm_operation_ctx *ctx, struct ttm_buffer_object *bo,
241 		   const struct ttm_bo_shrink_flags flags);
242 
243 bool ttm_bo_shrink_suitable(struct ttm_buffer_object *bo, struct ttm_operation_ctx *ctx);
244 
245 bool ttm_bo_shrink_avoid_wait(void);
246 
247 /**
248  * ttm_bo_reserve:
249  *
250  * @bo: A pointer to a struct ttm_buffer_object.
251  * @interruptible: Sleep interruptible if waiting.
252  * @no_wait: Don't sleep while trying to reserve, rather return -EBUSY.
253  * @ticket: ticket used to acquire the ww_mutex.
254  *
255  * Locks a buffer object for validation. (Or prevents other processes from
256  * locking it for validation), while taking a number of measures to prevent
257  * deadlocks.
258  *
259  * Returns:
260  * -EDEADLK: The reservation may cause a deadlock.
261  * Release all buffer reservations, wait for @bo to become unreserved and
262  * try again.
263  * -ERESTARTSYS: A wait for the buffer to become unreserved was interrupted by
264  * a signal. Release all buffer reservations and return to user-space.
265  * -EBUSY: The function needed to sleep, but @no_wait was true
266  * -EALREADY: Bo already reserved using @ticket. This error code will only
267  * be returned if @use_ticket is set to true.
268  */
269 static inline int ttm_bo_reserve(struct ttm_buffer_object *bo,
270 				 bool interruptible, bool no_wait,
271 				 struct ww_acquire_ctx *ticket)
272 {
273 	int ret = 0;
274 
275 	if (no_wait) {
276 		bool success;
277 
278 		if (WARN_ON(ticket))
279 			return -EBUSY;
280 
281 		success = dma_resv_trylock(bo->base.resv);
282 		return success ? 0 : -EBUSY;
283 	}
284 
285 	if (interruptible)
286 		ret = dma_resv_lock_interruptible(bo->base.resv, ticket);
287 	else
288 		ret = dma_resv_lock(bo->base.resv, ticket);
289 	if (ret == -EINTR)
290 		return -ERESTARTSYS;
291 	return ret;
292 }
293 
294 /**
295  * ttm_bo_reserve_slowpath:
296  * @bo: A pointer to a struct ttm_buffer_object.
297  * @interruptible: Sleep interruptible if waiting.
298  * @ticket: Ticket used to acquire the ww_mutex.
299  *
300  * This is called after ttm_bo_reserve returns -EAGAIN and we backed off
301  * from all our other reservations. Because there are no other reservations
302  * held by us, this function cannot deadlock any more.
303  */
304 static inline int ttm_bo_reserve_slowpath(struct ttm_buffer_object *bo,
305 					  bool interruptible,
306 					  struct ww_acquire_ctx *ticket)
307 {
308 	if (interruptible) {
309 		int ret = dma_resv_lock_slow_interruptible(bo->base.resv,
310 							   ticket);
311 		if (ret == -EINTR)
312 			ret = -ERESTARTSYS;
313 		return ret;
314 	}
315 	dma_resv_lock_slow(bo->base.resv, ticket);
316 	return 0;
317 }
318 
319 void ttm_bo_move_to_lru_tail(struct ttm_buffer_object *bo);
320 
321 static inline void
322 ttm_bo_move_to_lru_tail_unlocked(struct ttm_buffer_object *bo)
323 {
324 	spin_lock(&bo->bdev->lru_lock);
325 	ttm_bo_move_to_lru_tail(bo);
326 	spin_unlock(&bo->bdev->lru_lock);
327 }
328 
329 static inline void ttm_bo_assign_mem(struct ttm_buffer_object *bo,
330 				     struct ttm_resource *new_mem)
331 {
332 	WARN_ON(bo->resource);
333 	bo->resource = new_mem;
334 }
335 
336 /**
337  * ttm_bo_move_null - assign memory for a buffer object.
338  * @bo: The bo to assign the memory to
339  * @new_mem: The memory to be assigned.
340  *
341  * Assign the memory from new_mem to the memory of the buffer object bo.
342  */
343 static inline void ttm_bo_move_null(struct ttm_buffer_object *bo,
344 				    struct ttm_resource *new_mem)
345 {
346 	ttm_resource_free(bo, &bo->resource);
347 	ttm_bo_assign_mem(bo, new_mem);
348 }
349 
350 /**
351  * ttm_bo_unreserve
352  *
353  * @bo: A pointer to a struct ttm_buffer_object.
354  *
355  * Unreserve a previous reservation of @bo.
356  */
357 static inline void ttm_bo_unreserve(struct ttm_buffer_object *bo)
358 {
359 	ttm_bo_move_to_lru_tail_unlocked(bo);
360 	dma_resv_unlock(bo->base.resv);
361 }
362 
363 /**
364  * ttm_kmap_obj_virtual
365  *
366  * @map: A struct ttm_bo_kmap_obj returned from ttm_bo_kmap.
367  * @is_iomem: Pointer to an integer that on return indicates 1 if the
368  * virtual map is io memory, 0 if normal memory.
369  *
370  * Returns the virtual address of a buffer object area mapped by ttm_bo_kmap.
371  * If *is_iomem is 1 on return, the virtual address points to an io memory area,
372  * that should strictly be accessed by the iowriteXX() and similar functions.
373  */
374 static inline void *ttm_kmap_obj_virtual(struct ttm_bo_kmap_obj *map,
375 					 bool *is_iomem)
376 {
377 	*is_iomem = !!(map->bo_kmap_type & TTM_BO_MAP_IOMEM_MASK);
378 	return map->virtual;
379 }
380 
381 int ttm_bo_wait_ctx(struct ttm_buffer_object *bo,
382 		    struct ttm_operation_ctx *ctx);
383 int ttm_bo_validate(struct ttm_buffer_object *bo,
384 		    struct ttm_placement *placement,
385 		    struct ttm_operation_ctx *ctx);
386 void ttm_bo_put(struct ttm_buffer_object *bo);
387 void ttm_bo_set_bulk_move(struct ttm_buffer_object *bo,
388 			  struct ttm_lru_bulk_move *bulk);
389 bool ttm_bo_eviction_valuable(struct ttm_buffer_object *bo,
390 			      const struct ttm_place *place);
391 int ttm_bo_init_reserved(struct ttm_device *bdev, struct ttm_buffer_object *bo,
392 			 enum ttm_bo_type type, struct ttm_placement *placement,
393 			 uint32_t alignment, struct ttm_operation_ctx *ctx,
394 			 struct sg_table *sg, struct dma_resv *resv,
395 			 void (*destroy)(struct ttm_buffer_object *));
396 int ttm_bo_init_validate(struct ttm_device *bdev, struct ttm_buffer_object *bo,
397 			 enum ttm_bo_type type, struct ttm_placement *placement,
398 			 uint32_t alignment, bool interruptible,
399 			 struct sg_table *sg, struct dma_resv *resv,
400 			 void (*destroy)(struct ttm_buffer_object *));
401 int ttm_bo_kmap(struct ttm_buffer_object *bo, unsigned long start_page,
402 		unsigned long num_pages, struct ttm_bo_kmap_obj *map);
403 void ttm_bo_kunmap(struct ttm_bo_kmap_obj *map);
404 int ttm_bo_vmap(struct ttm_buffer_object *bo, struct iosys_map *map);
405 void ttm_bo_vunmap(struct ttm_buffer_object *bo, struct iosys_map *map);
406 int ttm_bo_mmap_obj(struct vm_area_struct *vma, struct ttm_buffer_object *bo);
407 s64 ttm_bo_swapout(struct ttm_device *bdev, struct ttm_operation_ctx *ctx,
408 		   struct ttm_resource_manager *man, gfp_t gfp_flags,
409 		   s64 target);
410 void ttm_bo_pin(struct ttm_buffer_object *bo);
411 void ttm_bo_unpin(struct ttm_buffer_object *bo);
412 int ttm_bo_evict_first(struct ttm_device *bdev,
413 		       struct ttm_resource_manager *man,
414 		       struct ttm_operation_ctx *ctx);
415 int ttm_bo_access(struct ttm_buffer_object *bo, unsigned long offset,
416 		  void *buf, int len, int write);
417 vm_fault_t ttm_bo_vm_reserve(struct ttm_buffer_object *bo,
418 			     struct vm_fault *vmf);
419 vm_fault_t ttm_bo_vm_fault_reserved(struct vm_fault *vmf,
420 				    pgprot_t prot,
421 				    pgoff_t num_prefault);
422 vm_fault_t ttm_bo_vm_fault(struct vm_fault *vmf);
423 void ttm_bo_vm_open(struct vm_area_struct *vma);
424 void ttm_bo_vm_close(struct vm_area_struct *vma);
425 int ttm_bo_vm_access(struct vm_area_struct *vma, unsigned long addr,
426 		     void *buf, int len, int write);
427 vm_fault_t ttm_bo_vm_dummy_page(struct vm_fault *vmf, pgprot_t prot);
428 
429 int ttm_bo_mem_space(struct ttm_buffer_object *bo,
430 		     struct ttm_placement *placement,
431 		     struct ttm_resource **mem,
432 		     struct ttm_operation_ctx *ctx);
433 
434 void ttm_bo_unmap_virtual(struct ttm_buffer_object *bo);
435 /*
436  * ttm_bo_util.c
437  */
438 int ttm_mem_io_reserve(struct ttm_device *bdev,
439 		       struct ttm_resource *mem);
440 void ttm_mem_io_free(struct ttm_device *bdev,
441 		     struct ttm_resource *mem);
442 void ttm_move_memcpy(bool clear, u32 num_pages,
443 		     struct ttm_kmap_iter *dst_iter,
444 		     struct ttm_kmap_iter *src_iter);
445 int ttm_bo_move_memcpy(struct ttm_buffer_object *bo,
446 		       struct ttm_operation_ctx *ctx,
447 		       struct ttm_resource *new_mem);
448 int ttm_bo_move_accel_cleanup(struct ttm_buffer_object *bo,
449 			      struct dma_fence *fence, bool evict,
450 			      bool pipeline,
451 			      struct ttm_resource *new_mem);
452 void ttm_bo_move_sync_cleanup(struct ttm_buffer_object *bo,
453 			      struct ttm_resource *new_mem);
454 int ttm_bo_pipeline_gutting(struct ttm_buffer_object *bo);
455 pgprot_t ttm_io_prot(struct ttm_buffer_object *bo, struct ttm_resource *res,
456 		     pgprot_t tmp);
457 void ttm_bo_tt_destroy(struct ttm_buffer_object *bo);
458 int ttm_bo_populate(struct ttm_buffer_object *bo,
459 		    struct ttm_operation_ctx *ctx);
460 
461 /* Driver LRU walk helpers initially targeted for shrinking. */
462 
463 /**
464  * struct ttm_bo_lru_cursor - Iterator cursor for TTM LRU list looping
465  */
466 struct ttm_bo_lru_cursor {
467 	/** @res_curs: Embedded struct ttm_resource_cursor. */
468 	struct ttm_resource_cursor res_curs;
469 	/**
470 	 * @ctx: The struct ttm_operation_ctx used while looping.
471 	 * governs the locking mode.
472 	 */
473 	struct ttm_operation_ctx *ctx;
474 	/**
475 	 * @bo: Buffer object pointer if a buffer object is refcounted,
476 	 * NULL otherwise.
477 	 */
478 	struct ttm_buffer_object *bo;
479 	/**
480 	 * @needs_unlock: Valid iff @bo != NULL. The bo resv needs
481 	 * unlock before the next iteration or after loop exit.
482 	 */
483 	bool needs_unlock;
484 };
485 
486 void ttm_bo_lru_cursor_fini(struct ttm_bo_lru_cursor *curs);
487 
488 struct ttm_bo_lru_cursor *
489 ttm_bo_lru_cursor_init(struct ttm_bo_lru_cursor *curs,
490 		       struct ttm_resource_manager *man,
491 		       struct ttm_operation_ctx *ctx);
492 
493 struct ttm_buffer_object *ttm_bo_lru_cursor_first(struct ttm_bo_lru_cursor *curs);
494 
495 struct ttm_buffer_object *ttm_bo_lru_cursor_next(struct ttm_bo_lru_cursor *curs);
496 
497 /*
498  * Defines needed to use autocleanup (linux/cleanup.h) with struct ttm_bo_lru_cursor.
499  */
500 DEFINE_CLASS(ttm_bo_lru_cursor, struct ttm_bo_lru_cursor *,
501 	     if (_T) {ttm_bo_lru_cursor_fini(_T); },
502 	     ttm_bo_lru_cursor_init(curs, man, ctx),
503 	     struct ttm_bo_lru_cursor *curs, struct ttm_resource_manager *man,
504 	     struct ttm_operation_ctx *ctx);
505 static inline void *
506 class_ttm_bo_lru_cursor_lock_ptr(class_ttm_bo_lru_cursor_t *_T)
507 { return *_T; }
508 #define class_ttm_bo_lru_cursor_is_conditional false
509 
510 /**
511  * ttm_bo_lru_for_each_reserved_guarded() - Iterate over buffer objects owning
512  * resources on LRU lists.
513  * @_cursor: struct ttm_bo_lru_cursor to use for the iteration.
514  * @_man: The resource manager whose LRU lists to iterate over.
515  * @_ctx: The struct ttm_operation_context to govern the @_bo locking.
516  * @_bo: The struct ttm_buffer_object pointer pointing to the buffer object
517  * for the current iteration.
518  *
519  * Iterate over all resources of @_man and for each resource, attempt to
520  * reference and lock (using the locking mode detailed in @_ctx) the buffer
521  * object it points to. If successful, assign @_bo to the address of the
522  * buffer object and update @_cursor. The iteration is guarded in the
523  * sense that @_cursor will be initialized before looping start and cleaned
524  * up at looping termination, even if terminated prematurely by, for
525  * example a return or break statement. Exiting the loop will also unlock
526  * (if needed) and unreference @_bo.
527  */
528 #define ttm_bo_lru_for_each_reserved_guarded(_cursor, _man, _ctx, _bo)	\
529 	scoped_guard(ttm_bo_lru_cursor, _cursor, _man, _ctx)		\
530 		for ((_bo) = ttm_bo_lru_cursor_first(_cursor); (_bo);	\
531 		     (_bo) = ttm_bo_lru_cursor_next(_cursor))
532 
533 #endif
534