1 /*
2  * SPDX-License-Identifier: MIT
3  *
4  * Copyright © 2014-2016 Intel Corporation
5  */
6 
7 #include "i915_drv.h"
8 #include "i915_gem_object.h"
9 #include "i915_scatterlist.h"
10 #include "i915_gem_lmem.h"
11 #include "i915_gem_mman.h"
12 
13 void __i915_gem_object_set_pages(struct drm_i915_gem_object *obj,
14 				 struct sg_table *pages,
15 				 unsigned int sg_page_sizes)
16 {
17 	struct drm_i915_private *i915 = to_i915(obj->base.dev);
18 	unsigned long supported = INTEL_INFO(i915)->page_sizes;
19 	int i;
20 
21 	lockdep_assert_held(&obj->mm.lock);
22 
23 	if (i915_gem_object_is_volatile(obj))
24 		obj->mm.madv = I915_MADV_DONTNEED;
25 
26 	/* Make the pages coherent with the GPU (flushing any swapin). */
27 	if (obj->cache_dirty) {
28 		obj->write_domain = 0;
29 		if (i915_gem_object_has_struct_page(obj))
30 			drm_clflush_sg(pages);
31 		obj->cache_dirty = false;
32 	}
33 
34 	obj->mm.get_page.sg_pos = pages->sgl;
35 	obj->mm.get_page.sg_idx = 0;
36 
37 	obj->mm.pages = pages;
38 
39 	if (i915_gem_object_is_tiled(obj) &&
40 	    i915->quirks & QUIRK_PIN_SWIZZLED_PAGES) {
41 		GEM_BUG_ON(obj->mm.quirked);
42 		__i915_gem_object_pin_pages(obj);
43 		obj->mm.quirked = true;
44 	}
45 
46 	GEM_BUG_ON(!sg_page_sizes);
47 	obj->mm.page_sizes.phys = sg_page_sizes;
48 
49 	/*
50 	 * Calculate the supported page-sizes which fit into the given
51 	 * sg_page_sizes. This will give us the page-sizes which we may be able
52 	 * to use opportunistically when later inserting into the GTT. For
53 	 * example if phys=2G, then in theory we should be able to use 1G, 2M,
54 	 * 64K or 4K pages, although in practice this will depend on a number of
55 	 * other factors.
56 	 */
57 	obj->mm.page_sizes.sg = 0;
58 	for_each_set_bit(i, &supported, ilog2(I915_GTT_MAX_PAGE_SIZE) + 1) {
59 		if (obj->mm.page_sizes.phys & ~0u << i)
60 			obj->mm.page_sizes.sg |= BIT(i);
61 	}
62 	GEM_BUG_ON(!HAS_PAGE_SIZES(i915, obj->mm.page_sizes.sg));
63 
64 	if (i915_gem_object_is_shrinkable(obj)) {
65 		struct list_head *list;
66 		unsigned long flags;
67 
68 		spin_lock_irqsave(&i915->mm.obj_lock, flags);
69 
70 		i915->mm.shrink_count++;
71 		i915->mm.shrink_memory += obj->base.size;
72 
73 		if (obj->mm.madv != I915_MADV_WILLNEED)
74 			list = &i915->mm.purge_list;
75 		else
76 			list = &i915->mm.shrink_list;
77 		list_add_tail(&obj->mm.link, list);
78 
79 		atomic_set(&obj->mm.shrink_pin, 0);
80 		spin_unlock_irqrestore(&i915->mm.obj_lock, flags);
81 	}
82 }
83 
84 int ____i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
85 {
86 	struct drm_i915_private *i915 = to_i915(obj->base.dev);
87 	int err;
88 
89 	if (unlikely(obj->mm.madv != I915_MADV_WILLNEED)) {
90 		drm_dbg(&i915->drm,
91 			"Attempting to obtain a purgeable object\n");
92 		return -EFAULT;
93 	}
94 
95 	err = obj->ops->get_pages(obj);
96 	GEM_BUG_ON(!err && !i915_gem_object_has_pages(obj));
97 
98 	return err;
99 }
100 
101 /* Ensure that the associated pages are gathered from the backing storage
102  * and pinned into our object. i915_gem_object_pin_pages() may be called
103  * multiple times before they are released by a single call to
104  * i915_gem_object_unpin_pages() - once the pages are no longer referenced
105  * either as a result of memory pressure (reaping pages under the shrinker)
106  * or as the object is itself released.
107  */
108 int __i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
109 {
110 	int err;
111 
112 	err = mutex_lock_interruptible_nested(&obj->mm.lock, I915_MM_GET_PAGES);
113 	if (err)
114 		return err;
115 
116 	if (unlikely(!i915_gem_object_has_pages(obj))) {
117 		GEM_BUG_ON(i915_gem_object_has_pinned_pages(obj));
118 
119 		err = ____i915_gem_object_get_pages(obj);
120 		if (err)
121 			goto unlock;
122 
123 		smp_mb__before_atomic();
124 	}
125 	atomic_inc(&obj->mm.pages_pin_count);
126 
127 unlock:
128 	mutex_unlock(&obj->mm.lock);
129 	return err;
130 }
131 
132 /* Immediately discard the backing storage */
133 void i915_gem_object_truncate(struct drm_i915_gem_object *obj)
134 {
135 	drm_gem_free_mmap_offset(&obj->base);
136 	if (obj->ops->truncate)
137 		obj->ops->truncate(obj);
138 }
139 
140 /* Try to discard unwanted pages */
141 void i915_gem_object_writeback(struct drm_i915_gem_object *obj)
142 {
143 	lockdep_assert_held(&obj->mm.lock);
144 	GEM_BUG_ON(i915_gem_object_has_pages(obj));
145 
146 	if (obj->ops->writeback)
147 		obj->ops->writeback(obj);
148 }
149 
150 static void __i915_gem_object_reset_page_iter(struct drm_i915_gem_object *obj)
151 {
152 	struct radix_tree_iter iter;
153 	void __rcu **slot;
154 
155 	rcu_read_lock();
156 	radix_tree_for_each_slot(slot, &obj->mm.get_page.radix, &iter, 0)
157 		radix_tree_delete(&obj->mm.get_page.radix, iter.index);
158 	rcu_read_unlock();
159 }
160 
161 static void unmap_object(struct drm_i915_gem_object *obj, void *ptr)
162 {
163 	if (is_vmalloc_addr(ptr))
164 		vunmap(ptr);
165 	else
166 		kunmap(kmap_to_page(ptr));
167 }
168 
169 struct sg_table *
170 __i915_gem_object_unset_pages(struct drm_i915_gem_object *obj)
171 {
172 	struct sg_table *pages;
173 
174 	pages = fetch_and_zero(&obj->mm.pages);
175 	if (IS_ERR_OR_NULL(pages))
176 		return pages;
177 
178 	if (i915_gem_object_is_volatile(obj))
179 		obj->mm.madv = I915_MADV_WILLNEED;
180 
181 	i915_gem_object_make_unshrinkable(obj);
182 
183 	if (obj->mm.mapping) {
184 		unmap_object(obj, page_mask_bits(obj->mm.mapping));
185 		obj->mm.mapping = NULL;
186 	}
187 
188 	__i915_gem_object_reset_page_iter(obj);
189 	obj->mm.page_sizes.phys = obj->mm.page_sizes.sg = 0;
190 
191 	return pages;
192 }
193 
194 int __i915_gem_object_put_pages(struct drm_i915_gem_object *obj)
195 {
196 	struct sg_table *pages;
197 	int err;
198 
199 	if (i915_gem_object_has_pinned_pages(obj))
200 		return -EBUSY;
201 
202 	/* May be called by shrinker from within get_pages() (on another bo) */
203 	mutex_lock(&obj->mm.lock);
204 	if (unlikely(atomic_read(&obj->mm.pages_pin_count))) {
205 		err = -EBUSY;
206 		goto unlock;
207 	}
208 
209 	i915_gem_object_release_mmap_offset(obj);
210 
211 	/*
212 	 * ->put_pages might need to allocate memory for the bit17 swizzle
213 	 * array, hence protect them from being reaped by removing them from gtt
214 	 * lists early.
215 	 */
216 	pages = __i915_gem_object_unset_pages(obj);
217 
218 	/*
219 	 * XXX Temporary hijinx to avoid updating all backends to handle
220 	 * NULL pages. In the future, when we have more asynchronous
221 	 * get_pages backends we should be better able to handle the
222 	 * cancellation of the async task in a more uniform manner.
223 	 */
224 	if (!pages && !i915_gem_object_needs_async_cancel(obj))
225 		pages = ERR_PTR(-EINVAL);
226 
227 	if (!IS_ERR(pages))
228 		obj->ops->put_pages(obj, pages);
229 
230 	err = 0;
231 unlock:
232 	mutex_unlock(&obj->mm.lock);
233 
234 	return err;
235 }
236 
237 static inline pte_t iomap_pte(resource_size_t base,
238 			      dma_addr_t offset,
239 			      pgprot_t prot)
240 {
241 	return pte_mkspecial(pfn_pte((base + offset) >> PAGE_SHIFT, prot));
242 }
243 
244 /* The 'mapping' part of i915_gem_object_pin_map() below */
245 static void *i915_gem_object_map(struct drm_i915_gem_object *obj,
246 				 enum i915_map_type type)
247 {
248 	unsigned long n_pte = obj->base.size >> PAGE_SHIFT;
249 	struct sg_table *sgt = obj->mm.pages;
250 	pte_t *stack[32], **mem;
251 	struct vm_struct *area;
252 	pgprot_t pgprot;
253 
254 	if (!i915_gem_object_has_struct_page(obj) && type != I915_MAP_WC)
255 		return NULL;
256 
257 	if (GEM_WARN_ON(type == I915_MAP_WC &&
258 			!static_cpu_has(X86_FEATURE_PAT)))
259 		return NULL;
260 
261 	/* A single page can always be kmapped */
262 	if (n_pte == 1 && type == I915_MAP_WB) {
263 		struct page *page = sg_page(sgt->sgl);
264 
265 		/*
266 		 * On 32b, highmem using a finite set of indirect PTE (i.e.
267 		 * vmap) to provide virtual mappings of the high pages.
268 		 * As these are finite, map_new_virtual() must wait for some
269 		 * other kmap() to finish when it runs out. If we map a large
270 		 * number of objects, there is no method for it to tell us
271 		 * to release the mappings, and we deadlock.
272 		 *
273 		 * However, if we make an explicit vmap of the page, that
274 		 * uses a larger vmalloc arena, and also has the ability
275 		 * to tell us to release unwanted mappings. Most importantly,
276 		 * it will fail and propagate an error instead of waiting
277 		 * forever.
278 		 *
279 		 * So if the page is beyond the 32b boundary, make an explicit
280 		 * vmap. On 64b, this check will be optimised away as we can
281 		 * directly kmap any page on the system.
282 		 */
283 		if (!PageHighMem(page))
284 			return kmap(page);
285 	}
286 
287 	mem = stack;
288 	if (n_pte > ARRAY_SIZE(stack)) {
289 		/* Too big for stack -- allocate temporary array instead */
290 		mem = kvmalloc_array(n_pte, sizeof(*mem), GFP_KERNEL);
291 		if (!mem)
292 			return NULL;
293 	}
294 
295 	area = alloc_vm_area(obj->base.size, mem);
296 	if (!area) {
297 		if (mem != stack)
298 			kvfree(mem);
299 		return NULL;
300 	}
301 
302 	switch (type) {
303 	default:
304 		MISSING_CASE(type);
305 		fallthrough;	/* to use PAGE_KERNEL anyway */
306 	case I915_MAP_WB:
307 		pgprot = PAGE_KERNEL;
308 		break;
309 	case I915_MAP_WC:
310 		pgprot = pgprot_writecombine(PAGE_KERNEL_IO);
311 		break;
312 	}
313 
314 	if (i915_gem_object_has_struct_page(obj)) {
315 		struct sgt_iter iter;
316 		struct page *page;
317 		pte_t **ptes = mem;
318 
319 		for_each_sgt_page(page, iter, sgt)
320 			**ptes++ = mk_pte(page, pgprot);
321 	} else {
322 		resource_size_t iomap;
323 		struct sgt_iter iter;
324 		pte_t **ptes = mem;
325 		dma_addr_t addr;
326 
327 		iomap = obj->mm.region->iomap.base;
328 		iomap -= obj->mm.region->region.start;
329 
330 		for_each_sgt_daddr(addr, iter, sgt)
331 			**ptes++ = iomap_pte(iomap, addr, pgprot);
332 	}
333 
334 	if (mem != stack)
335 		kvfree(mem);
336 
337 	return area->addr;
338 }
339 
340 /* get, pin, and map the pages of the object into kernel space */
341 void *i915_gem_object_pin_map(struct drm_i915_gem_object *obj,
342 			      enum i915_map_type type)
343 {
344 	enum i915_map_type has_type;
345 	unsigned int flags;
346 	bool pinned;
347 	void *ptr;
348 	int err;
349 
350 	flags = I915_GEM_OBJECT_HAS_STRUCT_PAGE | I915_GEM_OBJECT_HAS_IOMEM;
351 	if (!i915_gem_object_type_has(obj, flags))
352 		return ERR_PTR(-ENXIO);
353 
354 	err = mutex_lock_interruptible_nested(&obj->mm.lock, I915_MM_GET_PAGES);
355 	if (err)
356 		return ERR_PTR(err);
357 
358 	pinned = !(type & I915_MAP_OVERRIDE);
359 	type &= ~I915_MAP_OVERRIDE;
360 
361 	if (!atomic_inc_not_zero(&obj->mm.pages_pin_count)) {
362 		if (unlikely(!i915_gem_object_has_pages(obj))) {
363 			GEM_BUG_ON(i915_gem_object_has_pinned_pages(obj));
364 
365 			err = ____i915_gem_object_get_pages(obj);
366 			if (err)
367 				goto err_unlock;
368 
369 			smp_mb__before_atomic();
370 		}
371 		atomic_inc(&obj->mm.pages_pin_count);
372 		pinned = false;
373 	}
374 	GEM_BUG_ON(!i915_gem_object_has_pages(obj));
375 
376 	ptr = page_unpack_bits(obj->mm.mapping, &has_type);
377 	if (ptr && has_type != type) {
378 		if (pinned) {
379 			err = -EBUSY;
380 			goto err_unpin;
381 		}
382 
383 		unmap_object(obj, ptr);
384 
385 		ptr = obj->mm.mapping = NULL;
386 	}
387 
388 	if (!ptr) {
389 		ptr = i915_gem_object_map(obj, type);
390 		if (!ptr) {
391 			err = -ENOMEM;
392 			goto err_unpin;
393 		}
394 
395 		obj->mm.mapping = page_pack_bits(ptr, type);
396 	}
397 
398 out_unlock:
399 	mutex_unlock(&obj->mm.lock);
400 	return ptr;
401 
402 err_unpin:
403 	atomic_dec(&obj->mm.pages_pin_count);
404 err_unlock:
405 	ptr = ERR_PTR(err);
406 	goto out_unlock;
407 }
408 
409 void __i915_gem_object_flush_map(struct drm_i915_gem_object *obj,
410 				 unsigned long offset,
411 				 unsigned long size)
412 {
413 	enum i915_map_type has_type;
414 	void *ptr;
415 
416 	GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
417 	GEM_BUG_ON(range_overflows_t(typeof(obj->base.size),
418 				     offset, size, obj->base.size));
419 
420 	wmb(); /* let all previous writes be visible to coherent partners */
421 	obj->mm.dirty = true;
422 
423 	if (obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_WRITE)
424 		return;
425 
426 	ptr = page_unpack_bits(obj->mm.mapping, &has_type);
427 	if (has_type == I915_MAP_WC)
428 		return;
429 
430 	drm_clflush_virt_range(ptr + offset, size);
431 	if (size == obj->base.size) {
432 		obj->write_domain &= ~I915_GEM_DOMAIN_CPU;
433 		obj->cache_dirty = false;
434 	}
435 }
436 
437 void __i915_gem_object_release_map(struct drm_i915_gem_object *obj)
438 {
439 	GEM_BUG_ON(!obj->mm.mapping);
440 
441 	/*
442 	 * We allow removing the mapping from underneath pinned pages!
443 	 *
444 	 * Furthermore, since this is an unsafe operation reserved only
445 	 * for construction time manipulation, we ignore locking prudence.
446 	 */
447 	unmap_object(obj, page_mask_bits(fetch_and_zero(&obj->mm.mapping)));
448 
449 	i915_gem_object_unpin_map(obj);
450 }
451 
452 struct scatterlist *
453 i915_gem_object_get_sg(struct drm_i915_gem_object *obj,
454 		       unsigned int n,
455 		       unsigned int *offset)
456 {
457 	struct i915_gem_object_page_iter *iter = &obj->mm.get_page;
458 	struct scatterlist *sg;
459 	unsigned int idx, count;
460 
461 	might_sleep();
462 	GEM_BUG_ON(n >= obj->base.size >> PAGE_SHIFT);
463 	GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
464 
465 	/* As we iterate forward through the sg, we record each entry in a
466 	 * radixtree for quick repeated (backwards) lookups. If we have seen
467 	 * this index previously, we will have an entry for it.
468 	 *
469 	 * Initial lookup is O(N), but this is amortized to O(1) for
470 	 * sequential page access (where each new request is consecutive
471 	 * to the previous one). Repeated lookups are O(lg(obj->base.size)),
472 	 * i.e. O(1) with a large constant!
473 	 */
474 	if (n < READ_ONCE(iter->sg_idx))
475 		goto lookup;
476 
477 	mutex_lock(&iter->lock);
478 
479 	/* We prefer to reuse the last sg so that repeated lookup of this
480 	 * (or the subsequent) sg are fast - comparing against the last
481 	 * sg is faster than going through the radixtree.
482 	 */
483 
484 	sg = iter->sg_pos;
485 	idx = iter->sg_idx;
486 	count = __sg_page_count(sg);
487 
488 	while (idx + count <= n) {
489 		void *entry;
490 		unsigned long i;
491 		int ret;
492 
493 		/* If we cannot allocate and insert this entry, or the
494 		 * individual pages from this range, cancel updating the
495 		 * sg_idx so that on this lookup we are forced to linearly
496 		 * scan onwards, but on future lookups we will try the
497 		 * insertion again (in which case we need to be careful of
498 		 * the error return reporting that we have already inserted
499 		 * this index).
500 		 */
501 		ret = radix_tree_insert(&iter->radix, idx, sg);
502 		if (ret && ret != -EEXIST)
503 			goto scan;
504 
505 		entry = xa_mk_value(idx);
506 		for (i = 1; i < count; i++) {
507 			ret = radix_tree_insert(&iter->radix, idx + i, entry);
508 			if (ret && ret != -EEXIST)
509 				goto scan;
510 		}
511 
512 		idx += count;
513 		sg = ____sg_next(sg);
514 		count = __sg_page_count(sg);
515 	}
516 
517 scan:
518 	iter->sg_pos = sg;
519 	iter->sg_idx = idx;
520 
521 	mutex_unlock(&iter->lock);
522 
523 	if (unlikely(n < idx)) /* insertion completed by another thread */
524 		goto lookup;
525 
526 	/* In case we failed to insert the entry into the radixtree, we need
527 	 * to look beyond the current sg.
528 	 */
529 	while (idx + count <= n) {
530 		idx += count;
531 		sg = ____sg_next(sg);
532 		count = __sg_page_count(sg);
533 	}
534 
535 	*offset = n - idx;
536 	return sg;
537 
538 lookup:
539 	rcu_read_lock();
540 
541 	sg = radix_tree_lookup(&iter->radix, n);
542 	GEM_BUG_ON(!sg);
543 
544 	/* If this index is in the middle of multi-page sg entry,
545 	 * the radix tree will contain a value entry that points
546 	 * to the start of that range. We will return the pointer to
547 	 * the base page and the offset of this page within the
548 	 * sg entry's range.
549 	 */
550 	*offset = 0;
551 	if (unlikely(xa_is_value(sg))) {
552 		unsigned long base = xa_to_value(sg);
553 
554 		sg = radix_tree_lookup(&iter->radix, base);
555 		GEM_BUG_ON(!sg);
556 
557 		*offset = n - base;
558 	}
559 
560 	rcu_read_unlock();
561 
562 	return sg;
563 }
564 
565 struct page *
566 i915_gem_object_get_page(struct drm_i915_gem_object *obj, unsigned int n)
567 {
568 	struct scatterlist *sg;
569 	unsigned int offset;
570 
571 	GEM_BUG_ON(!i915_gem_object_has_struct_page(obj));
572 
573 	sg = i915_gem_object_get_sg(obj, n, &offset);
574 	return nth_page(sg_page(sg), offset);
575 }
576 
577 /* Like i915_gem_object_get_page(), but mark the returned page dirty */
578 struct page *
579 i915_gem_object_get_dirty_page(struct drm_i915_gem_object *obj,
580 			       unsigned int n)
581 {
582 	struct page *page;
583 
584 	page = i915_gem_object_get_page(obj, n);
585 	if (!obj->mm.dirty)
586 		set_page_dirty(page);
587 
588 	return page;
589 }
590 
591 dma_addr_t
592 i915_gem_object_get_dma_address_len(struct drm_i915_gem_object *obj,
593 				    unsigned long n,
594 				    unsigned int *len)
595 {
596 	struct scatterlist *sg;
597 	unsigned int offset;
598 
599 	sg = i915_gem_object_get_sg(obj, n, &offset);
600 
601 	if (len)
602 		*len = sg_dma_len(sg) - (offset << PAGE_SHIFT);
603 
604 	return sg_dma_address(sg) + (offset << PAGE_SHIFT);
605 }
606 
607 dma_addr_t
608 i915_gem_object_get_dma_address(struct drm_i915_gem_object *obj,
609 				unsigned long n)
610 {
611 	return i915_gem_object_get_dma_address_len(obj, n, NULL);
612 }
613