1 /*
2  * SPDX-License-Identifier: MIT
3  *
4  * Copyright © 2014-2016 Intel Corporation
5  */
6 
7 #include <linux/pagevec.h>
8 #include <linux/swap.h>
9 
10 #include "gem/i915_gem_region.h"
11 #include "i915_drv.h"
12 #include "i915_gemfs.h"
13 #include "i915_gem_object.h"
14 #include "i915_scatterlist.h"
15 #include "i915_trace.h"
16 
17 /*
18  * Move pages to appropriate lru and release the pagevec, decrementing the
19  * ref count of those pages.
20  */
21 static void check_release_pagevec(struct pagevec *pvec)
22 {
23 	check_move_unevictable_pages(pvec);
24 	__pagevec_release(pvec);
25 	cond_resched();
26 }
27 
28 static int shmem_get_pages(struct drm_i915_gem_object *obj)
29 {
30 	struct drm_i915_private *i915 = to_i915(obj->base.dev);
31 	struct intel_memory_region *mem = obj->mm.region;
32 	const unsigned long page_count = obj->base.size / PAGE_SIZE;
33 	unsigned long i;
34 	struct address_space *mapping;
35 	struct sg_table *st;
36 	struct scatterlist *sg;
37 	struct sgt_iter sgt_iter;
38 	struct page *page;
39 	unsigned long last_pfn = 0;	/* suppress gcc warning */
40 	unsigned int max_segment = i915_sg_segment_size();
41 	unsigned int sg_page_sizes;
42 	gfp_t noreclaim;
43 	int ret;
44 
45 	/*
46 	 * Assert that the object is not currently in any GPU domain. As it
47 	 * wasn't in the GTT, there shouldn't be any way it could have been in
48 	 * a GPU cache
49 	 */
50 	GEM_BUG_ON(obj->read_domains & I915_GEM_GPU_DOMAINS);
51 	GEM_BUG_ON(obj->write_domain & I915_GEM_GPU_DOMAINS);
52 
53 	/*
54 	 * If there's no chance of allocating enough pages for the whole
55 	 * object, bail early.
56 	 */
57 	if (obj->base.size > resource_size(&mem->region))
58 		return -ENOMEM;
59 
60 	st = kmalloc(sizeof(*st), GFP_KERNEL);
61 	if (!st)
62 		return -ENOMEM;
63 
64 rebuild_st:
65 	if (sg_alloc_table(st, page_count, GFP_KERNEL)) {
66 		kfree(st);
67 		return -ENOMEM;
68 	}
69 
70 	/*
71 	 * Get the list of pages out of our struct file.  They'll be pinned
72 	 * at this point until we release them.
73 	 *
74 	 * Fail silently without starting the shrinker
75 	 */
76 	mapping = obj->base.filp->f_mapping;
77 	mapping_set_unevictable(mapping);
78 	noreclaim = mapping_gfp_constraint(mapping, ~__GFP_RECLAIM);
79 	noreclaim |= __GFP_NORETRY | __GFP_NOWARN;
80 
81 	sg = st->sgl;
82 	st->nents = 0;
83 	sg_page_sizes = 0;
84 	for (i = 0; i < page_count; i++) {
85 		const unsigned int shrink[] = {
86 			I915_SHRINK_BOUND | I915_SHRINK_UNBOUND,
87 			0,
88 		}, *s = shrink;
89 		gfp_t gfp = noreclaim;
90 
91 		do {
92 			cond_resched();
93 			page = shmem_read_mapping_page_gfp(mapping, i, gfp);
94 			if (!IS_ERR(page))
95 				break;
96 
97 			if (!*s) {
98 				ret = PTR_ERR(page);
99 				goto err_sg;
100 			}
101 
102 			i915_gem_shrink(NULL, i915, 2 * page_count, NULL, *s++);
103 
104 			/*
105 			 * We've tried hard to allocate the memory by reaping
106 			 * our own buffer, now let the real VM do its job and
107 			 * go down in flames if truly OOM.
108 			 *
109 			 * However, since graphics tend to be disposable,
110 			 * defer the oom here by reporting the ENOMEM back
111 			 * to userspace.
112 			 */
113 			if (!*s) {
114 				/* reclaim and warn, but no oom */
115 				gfp = mapping_gfp_mask(mapping);
116 
117 				/*
118 				 * Our bo are always dirty and so we require
119 				 * kswapd to reclaim our pages (direct reclaim
120 				 * does not effectively begin pageout of our
121 				 * buffers on its own). However, direct reclaim
122 				 * only waits for kswapd when under allocation
123 				 * congestion. So as a result __GFP_RECLAIM is
124 				 * unreliable and fails to actually reclaim our
125 				 * dirty pages -- unless you try over and over
126 				 * again with !__GFP_NORETRY. However, we still
127 				 * want to fail this allocation rather than
128 				 * trigger the out-of-memory killer and for
129 				 * this we want __GFP_RETRY_MAYFAIL.
130 				 */
131 				gfp |= __GFP_RETRY_MAYFAIL;
132 			}
133 		} while (1);
134 
135 		if (!i ||
136 		    sg->length >= max_segment ||
137 		    page_to_pfn(page) != last_pfn + 1) {
138 			if (i) {
139 				sg_page_sizes |= sg->length;
140 				sg = sg_next(sg);
141 			}
142 			st->nents++;
143 			sg_set_page(sg, page, PAGE_SIZE, 0);
144 		} else {
145 			sg->length += PAGE_SIZE;
146 		}
147 		last_pfn = page_to_pfn(page);
148 
149 		/* Check that the i965g/gm workaround works. */
150 		GEM_BUG_ON(gfp & __GFP_DMA32 && last_pfn >= 0x00100000UL);
151 	}
152 	if (sg) { /* loop terminated early; short sg table */
153 		sg_page_sizes |= sg->length;
154 		sg_mark_end(sg);
155 	}
156 
157 	/* Trim unused sg entries to avoid wasting memory. */
158 	i915_sg_trim(st);
159 
160 	ret = i915_gem_gtt_prepare_pages(obj, st);
161 	if (ret) {
162 		/*
163 		 * DMA remapping failed? One possible cause is that
164 		 * it could not reserve enough large entries, asking
165 		 * for PAGE_SIZE chunks instead may be helpful.
166 		 */
167 		if (max_segment > PAGE_SIZE) {
168 			for_each_sgt_page(page, sgt_iter, st)
169 				put_page(page);
170 			sg_free_table(st);
171 
172 			max_segment = PAGE_SIZE;
173 			goto rebuild_st;
174 		} else {
175 			dev_warn(i915->drm.dev,
176 				 "Failed to DMA remap %lu pages\n",
177 				 page_count);
178 			goto err_pages;
179 		}
180 	}
181 
182 	if (i915_gem_object_needs_bit17_swizzle(obj))
183 		i915_gem_object_do_bit_17_swizzle(obj, st);
184 
185 	/*
186 	 * EHL and JSL add the 'Bypass LLC' MOCS entry, which should make it
187 	 * possible for userspace to bypass the GTT caching bits set by the
188 	 * kernel, as per the given object cache_level. This is troublesome
189 	 * since the heavy flush we apply when first gathering the pages is
190 	 * skipped if the kernel thinks the object is coherent with the GPU. As
191 	 * a result it might be possible to bypass the cache and read the
192 	 * contents of the page directly, which could be stale data. If it's
193 	 * just a case of userspace shooting themselves in the foot then so be
194 	 * it, but since i915 takes the stance of always zeroing memory before
195 	 * handing it to userspace, we need to prevent this.
196 	 *
197 	 * By setting cache_dirty here we make the clflush in set_pages
198 	 * unconditional on such platforms.
199 	 */
200 	if (IS_JSL_EHL(i915) && obj->flags & I915_BO_ALLOC_USER)
201 		obj->cache_dirty = true;
202 
203 	__i915_gem_object_set_pages(obj, st, sg_page_sizes);
204 
205 	return 0;
206 
207 err_sg:
208 	sg_mark_end(sg);
209 err_pages:
210 	mapping_clear_unevictable(mapping);
211 	if (sg != st->sgl) {
212 		struct pagevec pvec;
213 
214 		pagevec_init(&pvec);
215 		for_each_sgt_page(page, sgt_iter, st) {
216 			if (!pagevec_add(&pvec, page))
217 				check_release_pagevec(&pvec);
218 		}
219 		if (pagevec_count(&pvec))
220 			check_release_pagevec(&pvec);
221 	}
222 	sg_free_table(st);
223 	kfree(st);
224 
225 	/*
226 	 * shmemfs first checks if there is enough memory to allocate the page
227 	 * and reports ENOSPC should there be insufficient, along with the usual
228 	 * ENOMEM for a genuine allocation failure.
229 	 *
230 	 * We use ENOSPC in our driver to mean that we have run out of aperture
231 	 * space and so want to translate the error from shmemfs back to our
232 	 * usual understanding of ENOMEM.
233 	 */
234 	if (ret == -ENOSPC)
235 		ret = -ENOMEM;
236 
237 	return ret;
238 }
239 
240 static void
241 shmem_truncate(struct drm_i915_gem_object *obj)
242 {
243 	/*
244 	 * Our goal here is to return as much of the memory as
245 	 * is possible back to the system as we are called from OOM.
246 	 * To do this we must instruct the shmfs to drop all of its
247 	 * backing pages, *now*.
248 	 */
249 	shmem_truncate_range(file_inode(obj->base.filp), 0, (loff_t)-1);
250 	obj->mm.madv = __I915_MADV_PURGED;
251 	obj->mm.pages = ERR_PTR(-EFAULT);
252 }
253 
254 static void
255 shmem_writeback(struct drm_i915_gem_object *obj)
256 {
257 	struct address_space *mapping;
258 	struct writeback_control wbc = {
259 		.sync_mode = WB_SYNC_NONE,
260 		.nr_to_write = SWAP_CLUSTER_MAX,
261 		.range_start = 0,
262 		.range_end = LLONG_MAX,
263 		.for_reclaim = 1,
264 	};
265 	unsigned long i;
266 
267 	/*
268 	 * Leave mmapings intact (GTT will have been revoked on unbinding,
269 	 * leaving only CPU mmapings around) and add those pages to the LRU
270 	 * instead of invoking writeback so they are aged and paged out
271 	 * as normal.
272 	 */
273 	mapping = obj->base.filp->f_mapping;
274 
275 	/* Begin writeback on each dirty page */
276 	for (i = 0; i < obj->base.size >> PAGE_SHIFT; i++) {
277 		struct page *page;
278 
279 		page = find_lock_page(mapping, i);
280 		if (!page)
281 			continue;
282 
283 		if (!page_mapped(page) && clear_page_dirty_for_io(page)) {
284 			int ret;
285 
286 			SetPageReclaim(page);
287 			ret = mapping->a_ops->writepage(page, &wbc);
288 			if (!PageWriteback(page))
289 				ClearPageReclaim(page);
290 			if (!ret)
291 				goto put;
292 		}
293 		unlock_page(page);
294 put:
295 		put_page(page);
296 	}
297 }
298 
299 void
300 __i915_gem_object_release_shmem(struct drm_i915_gem_object *obj,
301 				struct sg_table *pages,
302 				bool needs_clflush)
303 {
304 	GEM_BUG_ON(obj->mm.madv == __I915_MADV_PURGED);
305 
306 	if (obj->mm.madv == I915_MADV_DONTNEED)
307 		obj->mm.dirty = false;
308 
309 	if (needs_clflush &&
310 	    (obj->read_domains & I915_GEM_DOMAIN_CPU) == 0 &&
311 	    !(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ))
312 		drm_clflush_sg(pages);
313 
314 	__start_cpu_write(obj);
315 }
316 
317 void i915_gem_object_put_pages_shmem(struct drm_i915_gem_object *obj, struct sg_table *pages)
318 {
319 	struct sgt_iter sgt_iter;
320 	struct pagevec pvec;
321 	struct page *page;
322 
323 	GEM_WARN_ON(IS_DGFX(to_i915(obj->base.dev)));
324 	__i915_gem_object_release_shmem(obj, pages, true);
325 
326 	i915_gem_gtt_finish_pages(obj, pages);
327 
328 	if (i915_gem_object_needs_bit17_swizzle(obj))
329 		i915_gem_object_save_bit_17_swizzle(obj, pages);
330 
331 	mapping_clear_unevictable(file_inode(obj->base.filp)->i_mapping);
332 
333 	pagevec_init(&pvec);
334 	for_each_sgt_page(page, sgt_iter, pages) {
335 		if (obj->mm.dirty)
336 			set_page_dirty(page);
337 
338 		if (obj->mm.madv == I915_MADV_WILLNEED)
339 			mark_page_accessed(page);
340 
341 		if (!pagevec_add(&pvec, page))
342 			check_release_pagevec(&pvec);
343 	}
344 	if (pagevec_count(&pvec))
345 		check_release_pagevec(&pvec);
346 	obj->mm.dirty = false;
347 
348 	sg_free_table(pages);
349 	kfree(pages);
350 }
351 
352 static void
353 shmem_put_pages(struct drm_i915_gem_object *obj, struct sg_table *pages)
354 {
355 	if (likely(i915_gem_object_has_struct_page(obj)))
356 		i915_gem_object_put_pages_shmem(obj, pages);
357 	else
358 		i915_gem_object_put_pages_phys(obj, pages);
359 }
360 
361 static int
362 shmem_pwrite(struct drm_i915_gem_object *obj,
363 	     const struct drm_i915_gem_pwrite *arg)
364 {
365 	struct address_space *mapping = obj->base.filp->f_mapping;
366 	char __user *user_data = u64_to_user_ptr(arg->data_ptr);
367 	u64 remain, offset;
368 	unsigned int pg;
369 
370 	/* Caller already validated user args */
371 	GEM_BUG_ON(!access_ok(user_data, arg->size));
372 
373 	if (!i915_gem_object_has_struct_page(obj))
374 		return i915_gem_object_pwrite_phys(obj, arg);
375 
376 	/*
377 	 * Before we instantiate/pin the backing store for our use, we
378 	 * can prepopulate the shmemfs filp efficiently using a write into
379 	 * the pagecache. We avoid the penalty of instantiating all the
380 	 * pages, important if the user is just writing to a few and never
381 	 * uses the object on the GPU, and using a direct write into shmemfs
382 	 * allows it to avoid the cost of retrieving a page (either swapin
383 	 * or clearing-before-use) before it is overwritten.
384 	 */
385 	if (i915_gem_object_has_pages(obj))
386 		return -ENODEV;
387 
388 	if (obj->mm.madv != I915_MADV_WILLNEED)
389 		return -EFAULT;
390 
391 	/*
392 	 * Before the pages are instantiated the object is treated as being
393 	 * in the CPU domain. The pages will be clflushed as required before
394 	 * use, and we can freely write into the pages directly. If userspace
395 	 * races pwrite with any other operation; corruption will ensue -
396 	 * that is userspace's prerogative!
397 	 */
398 
399 	remain = arg->size;
400 	offset = arg->offset;
401 	pg = offset_in_page(offset);
402 
403 	do {
404 		unsigned int len, unwritten;
405 		struct page *page;
406 		void *data, *vaddr;
407 		int err;
408 		char c;
409 
410 		len = PAGE_SIZE - pg;
411 		if (len > remain)
412 			len = remain;
413 
414 		/* Prefault the user page to reduce potential recursion */
415 		err = __get_user(c, user_data);
416 		if (err)
417 			return err;
418 
419 		err = __get_user(c, user_data + len - 1);
420 		if (err)
421 			return err;
422 
423 		err = pagecache_write_begin(obj->base.filp, mapping,
424 					    offset, len, 0,
425 					    &page, &data);
426 		if (err < 0)
427 			return err;
428 
429 		vaddr = kmap_atomic(page);
430 		unwritten = __copy_from_user_inatomic(vaddr + pg,
431 						      user_data,
432 						      len);
433 		kunmap_atomic(vaddr);
434 
435 		err = pagecache_write_end(obj->base.filp, mapping,
436 					  offset, len, len - unwritten,
437 					  page, data);
438 		if (err < 0)
439 			return err;
440 
441 		/* We don't handle -EFAULT, leave it to the caller to check */
442 		if (unwritten)
443 			return -ENODEV;
444 
445 		remain -= len;
446 		user_data += len;
447 		offset += len;
448 		pg = 0;
449 	} while (remain);
450 
451 	return 0;
452 }
453 
454 static int
455 shmem_pread(struct drm_i915_gem_object *obj,
456 	    const struct drm_i915_gem_pread *arg)
457 {
458 	if (!i915_gem_object_has_struct_page(obj))
459 		return i915_gem_object_pread_phys(obj, arg);
460 
461 	return -ENODEV;
462 }
463 
464 static void shmem_release(struct drm_i915_gem_object *obj)
465 {
466 	if (i915_gem_object_has_struct_page(obj))
467 		i915_gem_object_release_memory_region(obj);
468 
469 	fput(obj->base.filp);
470 }
471 
472 const struct drm_i915_gem_object_ops i915_gem_shmem_ops = {
473 	.name = "i915_gem_object_shmem",
474 	.flags = I915_GEM_OBJECT_IS_SHRINKABLE,
475 
476 	.get_pages = shmem_get_pages,
477 	.put_pages = shmem_put_pages,
478 	.truncate = shmem_truncate,
479 	.writeback = shmem_writeback,
480 
481 	.pwrite = shmem_pwrite,
482 	.pread = shmem_pread,
483 
484 	.release = shmem_release,
485 };
486 
487 static int __create_shmem(struct drm_i915_private *i915,
488 			  struct drm_gem_object *obj,
489 			  resource_size_t size)
490 {
491 	unsigned long flags = VM_NORESERVE;
492 	struct file *filp;
493 
494 	drm_gem_private_object_init(&i915->drm, obj, size);
495 
496 	if (i915->mm.gemfs)
497 		filp = shmem_file_setup_with_mnt(i915->mm.gemfs, "i915", size,
498 						 flags);
499 	else
500 		filp = shmem_file_setup("i915", size, flags);
501 	if (IS_ERR(filp))
502 		return PTR_ERR(filp);
503 
504 	obj->filp = filp;
505 	return 0;
506 }
507 
508 static int shmem_object_init(struct intel_memory_region *mem,
509 			     struct drm_i915_gem_object *obj,
510 			     resource_size_t size,
511 			     resource_size_t page_size,
512 			     unsigned int flags)
513 {
514 	static struct lock_class_key lock_class;
515 	struct drm_i915_private *i915 = mem->i915;
516 	struct address_space *mapping;
517 	unsigned int cache_level;
518 	gfp_t mask;
519 	int ret;
520 
521 	ret = __create_shmem(i915, &obj->base, size);
522 	if (ret)
523 		return ret;
524 
525 	mask = GFP_HIGHUSER | __GFP_RECLAIMABLE;
526 	if (IS_I965GM(i915) || IS_I965G(i915)) {
527 		/* 965gm cannot relocate objects above 4GiB. */
528 		mask &= ~__GFP_HIGHMEM;
529 		mask |= __GFP_DMA32;
530 	}
531 
532 	mapping = obj->base.filp->f_mapping;
533 	mapping_set_gfp_mask(mapping, mask);
534 	GEM_BUG_ON(!(mapping_gfp_mask(mapping) & __GFP_RECLAIM));
535 
536 	i915_gem_object_init(obj, &i915_gem_shmem_ops, &lock_class, 0);
537 	obj->mem_flags |= I915_BO_FLAG_STRUCT_PAGE;
538 	obj->write_domain = I915_GEM_DOMAIN_CPU;
539 	obj->read_domains = I915_GEM_DOMAIN_CPU;
540 
541 	if (HAS_LLC(i915))
542 		/* On some devices, we can have the GPU use the LLC (the CPU
543 		 * cache) for about a 10% performance improvement
544 		 * compared to uncached.  Graphics requests other than
545 		 * display scanout are coherent with the CPU in
546 		 * accessing this cache.  This means in this mode we
547 		 * don't need to clflush on the CPU side, and on the
548 		 * GPU side we only need to flush internal caches to
549 		 * get data visible to the CPU.
550 		 *
551 		 * However, we maintain the display planes as UC, and so
552 		 * need to rebind when first used as such.
553 		 */
554 		cache_level = I915_CACHE_LLC;
555 	else
556 		cache_level = I915_CACHE_NONE;
557 
558 	i915_gem_object_set_cache_coherency(obj, cache_level);
559 
560 	i915_gem_object_init_memory_region(obj, mem);
561 
562 	return 0;
563 }
564 
565 struct drm_i915_gem_object *
566 i915_gem_object_create_shmem(struct drm_i915_private *i915,
567 			     resource_size_t size)
568 {
569 	return i915_gem_object_create_region(i915->mm.regions[INTEL_REGION_SMEM],
570 					     size, 0, 0);
571 }
572 
573 /* Allocate a new GEM object and fill it with the supplied data */
574 struct drm_i915_gem_object *
575 i915_gem_object_create_shmem_from_data(struct drm_i915_private *dev_priv,
576 				       const void *data, resource_size_t size)
577 {
578 	struct drm_i915_gem_object *obj;
579 	struct file *file;
580 	resource_size_t offset;
581 	int err;
582 
583 	GEM_WARN_ON(IS_DGFX(dev_priv));
584 	obj = i915_gem_object_create_shmem(dev_priv, round_up(size, PAGE_SIZE));
585 	if (IS_ERR(obj))
586 		return obj;
587 
588 	GEM_BUG_ON(obj->write_domain != I915_GEM_DOMAIN_CPU);
589 
590 	file = obj->base.filp;
591 	offset = 0;
592 	do {
593 		unsigned int len = min_t(typeof(size), size, PAGE_SIZE);
594 		struct page *page;
595 		void *pgdata, *vaddr;
596 
597 		err = pagecache_write_begin(file, file->f_mapping,
598 					    offset, len, 0,
599 					    &page, &pgdata);
600 		if (err < 0)
601 			goto fail;
602 
603 		vaddr = kmap(page);
604 		memcpy(vaddr, data, len);
605 		kunmap(page);
606 
607 		err = pagecache_write_end(file, file->f_mapping,
608 					  offset, len, len,
609 					  page, pgdata);
610 		if (err < 0)
611 			goto fail;
612 
613 		size -= len;
614 		data += len;
615 		offset += len;
616 	} while (size);
617 
618 	return obj;
619 
620 fail:
621 	i915_gem_object_put(obj);
622 	return ERR_PTR(err);
623 }
624 
625 static int init_shmem(struct intel_memory_region *mem)
626 {
627 	int err;
628 
629 	err = i915_gemfs_init(mem->i915);
630 	if (err) {
631 		DRM_NOTE("Unable to create a private tmpfs mount, hugepage support will be disabled(%d).\n",
632 			 err);
633 	}
634 
635 	intel_memory_region_set_name(mem, "system");
636 
637 	return 0; /* Don't error, we can simply fallback to the kernel mnt */
638 }
639 
640 static void release_shmem(struct intel_memory_region *mem)
641 {
642 	i915_gemfs_fini(mem->i915);
643 }
644 
645 static const struct intel_memory_region_ops shmem_region_ops = {
646 	.init = init_shmem,
647 	.release = release_shmem,
648 	.init_object = shmem_object_init,
649 };
650 
651 struct intel_memory_region *i915_gem_shmem_setup(struct drm_i915_private *i915,
652 						 u16 type, u16 instance)
653 {
654 	return intel_memory_region_create(i915, 0,
655 					  totalram_pages() << PAGE_SHIFT,
656 					  PAGE_SIZE, 0,
657 					  type, instance,
658 					  &shmem_region_ops);
659 }
660 
661 bool i915_gem_object_is_shmem(const struct drm_i915_gem_object *obj)
662 {
663 	return obj->ops == &i915_gem_shmem_ops;
664 }
665