2 * Copyright © 2008-2015 Intel Corporation
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
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 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
24 * Eric Anholt <eric@anholt.net>
29 #include <drm/drm_vma_manager.h>
30 #include <drm/i915_drm.h>
32 #include "i915_gem_clflush.h"
33 #include "i915_vgpu.h"
34 #include "i915_trace.h"
35 #include "intel_drv.h"
36 #include "intel_frontbuffer.h"
37 #include "intel_mocs.h"
38 #include "i915_gemfs.h"
39 #include <linux/dma-fence-array.h>
40 #include <linux/kthread.h>
41 #include <linux/reservation.h>
42 #include <linux/shmem_fs.h>
43 #include <linux/slab.h>
44 #include <linux/stop_machine.h>
45 #include <linux/swap.h>
46 #include <linux/pci.h>
47 #include <linux/dma-buf.h>
49 static void i915_gem_flush_free_objects(struct drm_i915_private *i915);
51 static bool cpu_write_needs_clflush(struct drm_i915_gem_object *obj)
56 if (!(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_WRITE))
59 return obj->pin_global; /* currently in use by HW, keep flushed */
63 insert_mappable_node(struct i915_ggtt *ggtt,
64 struct drm_mm_node *node, u32 size)
66 memset(node, 0, sizeof(*node));
67 return drm_mm_insert_node_in_range(&ggtt->base.mm, node,
68 size, 0, I915_COLOR_UNEVICTABLE,
69 0, ggtt->mappable_end,
74 remove_mappable_node(struct drm_mm_node *node)
76 drm_mm_remove_node(node);
79 /* some bookkeeping */
80 static void i915_gem_info_add_obj(struct drm_i915_private *dev_priv,
83 spin_lock(&dev_priv->mm.object_stat_lock);
84 dev_priv->mm.object_count++;
85 dev_priv->mm.object_memory += size;
86 spin_unlock(&dev_priv->mm.object_stat_lock);
89 static void i915_gem_info_remove_obj(struct drm_i915_private *dev_priv,
92 spin_lock(&dev_priv->mm.object_stat_lock);
93 dev_priv->mm.object_count--;
94 dev_priv->mm.object_memory -= size;
95 spin_unlock(&dev_priv->mm.object_stat_lock);
99 i915_gem_wait_for_error(struct i915_gpu_error *error)
106 * Only wait 10 seconds for the gpu reset to complete to avoid hanging
107 * userspace. If it takes that long something really bad is going on and
108 * we should simply try to bail out and fail as gracefully as possible.
110 ret = wait_event_interruptible_timeout(error->reset_queue,
111 !i915_reset_backoff(error),
114 DRM_ERROR("Timed out waiting for the gpu reset to complete\n");
116 } else if (ret < 0) {
123 int i915_mutex_lock_interruptible(struct drm_device *dev)
125 struct drm_i915_private *dev_priv = to_i915(dev);
128 ret = i915_gem_wait_for_error(&dev_priv->gpu_error);
132 ret = mutex_lock_interruptible(&dev->struct_mutex);
140 i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
141 struct drm_file *file)
143 struct drm_i915_private *dev_priv = to_i915(dev);
144 struct i915_ggtt *ggtt = &dev_priv->ggtt;
145 struct drm_i915_gem_get_aperture *args = data;
146 struct i915_vma *vma;
149 pinned = ggtt->base.reserved;
150 mutex_lock(&dev->struct_mutex);
151 list_for_each_entry(vma, &ggtt->base.active_list, vm_link)
152 if (i915_vma_is_pinned(vma))
153 pinned += vma->node.size;
154 list_for_each_entry(vma, &ggtt->base.inactive_list, vm_link)
155 if (i915_vma_is_pinned(vma))
156 pinned += vma->node.size;
157 mutex_unlock(&dev->struct_mutex);
159 args->aper_size = ggtt->base.total;
160 args->aper_available_size = args->aper_size - pinned;
165 static int i915_gem_object_get_pages_phys(struct drm_i915_gem_object *obj)
167 struct address_space *mapping = obj->base.filp->f_mapping;
168 drm_dma_handle_t *phys;
170 struct scatterlist *sg;
175 if (WARN_ON(i915_gem_object_needs_bit17_swizzle(obj)))
178 /* Always aligning to the object size, allows a single allocation
179 * to handle all possible callers, and given typical object sizes,
180 * the alignment of the buddy allocation will naturally match.
182 phys = drm_pci_alloc(obj->base.dev,
183 roundup_pow_of_two(obj->base.size),
184 roundup_pow_of_two(obj->base.size));
189 for (i = 0; i < obj->base.size / PAGE_SIZE; i++) {
193 page = shmem_read_mapping_page(mapping, i);
199 src = kmap_atomic(page);
200 memcpy(vaddr, src, PAGE_SIZE);
201 drm_clflush_virt_range(vaddr, PAGE_SIZE);
208 i915_gem_chipset_flush(to_i915(obj->base.dev));
210 st = kmalloc(sizeof(*st), GFP_KERNEL);
216 if (sg_alloc_table(st, 1, GFP_KERNEL)) {
224 sg->length = obj->base.size;
226 sg_dma_address(sg) = phys->busaddr;
227 sg_dma_len(sg) = obj->base.size;
229 obj->phys_handle = phys;
231 __i915_gem_object_set_pages(obj, st, sg->length);
236 drm_pci_free(obj->base.dev, phys);
241 static void __start_cpu_write(struct drm_i915_gem_object *obj)
243 obj->base.read_domains = I915_GEM_DOMAIN_CPU;
244 obj->base.write_domain = I915_GEM_DOMAIN_CPU;
245 if (cpu_write_needs_clflush(obj))
246 obj->cache_dirty = true;
250 __i915_gem_object_release_shmem(struct drm_i915_gem_object *obj,
251 struct sg_table *pages,
254 GEM_BUG_ON(obj->mm.madv == __I915_MADV_PURGED);
256 if (obj->mm.madv == I915_MADV_DONTNEED)
257 obj->mm.dirty = false;
260 (obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0 &&
261 !(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ))
262 drm_clflush_sg(pages);
264 __start_cpu_write(obj);
268 i915_gem_object_put_pages_phys(struct drm_i915_gem_object *obj,
269 struct sg_table *pages)
271 __i915_gem_object_release_shmem(obj, pages, false);
274 struct address_space *mapping = obj->base.filp->f_mapping;
275 char *vaddr = obj->phys_handle->vaddr;
278 for (i = 0; i < obj->base.size / PAGE_SIZE; i++) {
282 page = shmem_read_mapping_page(mapping, i);
286 dst = kmap_atomic(page);
287 drm_clflush_virt_range(vaddr, PAGE_SIZE);
288 memcpy(dst, vaddr, PAGE_SIZE);
291 set_page_dirty(page);
292 if (obj->mm.madv == I915_MADV_WILLNEED)
293 mark_page_accessed(page);
297 obj->mm.dirty = false;
300 sg_free_table(pages);
303 drm_pci_free(obj->base.dev, obj->phys_handle);
307 i915_gem_object_release_phys(struct drm_i915_gem_object *obj)
309 i915_gem_object_unpin_pages(obj);
312 static const struct drm_i915_gem_object_ops i915_gem_phys_ops = {
313 .get_pages = i915_gem_object_get_pages_phys,
314 .put_pages = i915_gem_object_put_pages_phys,
315 .release = i915_gem_object_release_phys,
318 static const struct drm_i915_gem_object_ops i915_gem_object_ops;
320 int i915_gem_object_unbind(struct drm_i915_gem_object *obj)
322 struct i915_vma *vma;
323 LIST_HEAD(still_in_list);
326 lockdep_assert_held(&obj->base.dev->struct_mutex);
328 /* Closed vma are removed from the obj->vma_list - but they may
329 * still have an active binding on the object. To remove those we
330 * must wait for all rendering to complete to the object (as unbinding
331 * must anyway), and retire the requests.
333 ret = i915_gem_object_wait(obj,
334 I915_WAIT_INTERRUPTIBLE |
337 MAX_SCHEDULE_TIMEOUT,
342 i915_gem_retire_requests(to_i915(obj->base.dev));
344 while ((vma = list_first_entry_or_null(&obj->vma_list,
347 list_move_tail(&vma->obj_link, &still_in_list);
348 ret = i915_vma_unbind(vma);
352 list_splice(&still_in_list, &obj->vma_list);
358 i915_gem_object_wait_fence(struct dma_fence *fence,
361 struct intel_rps_client *rps_client)
363 struct drm_i915_gem_request *rq;
365 BUILD_BUG_ON(I915_WAIT_INTERRUPTIBLE != 0x1);
367 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
370 if (!dma_fence_is_i915(fence))
371 return dma_fence_wait_timeout(fence,
372 flags & I915_WAIT_INTERRUPTIBLE,
375 rq = to_request(fence);
376 if (i915_gem_request_completed(rq))
379 /* This client is about to stall waiting for the GPU. In many cases
380 * this is undesirable and limits the throughput of the system, as
381 * many clients cannot continue processing user input/output whilst
382 * blocked. RPS autotuning may take tens of milliseconds to respond
383 * to the GPU load and thus incurs additional latency for the client.
384 * We can circumvent that by promoting the GPU frequency to maximum
385 * before we wait. This makes the GPU throttle up much more quickly
386 * (good for benchmarks and user experience, e.g. window animations),
387 * but at a cost of spending more power processing the workload
388 * (bad for battery). Not all clients even want their results
389 * immediately and for them we should just let the GPU select its own
390 * frequency to maximise efficiency. To prevent a single client from
391 * forcing the clocks too high for the whole system, we only allow
392 * each client to waitboost once in a busy period.
395 if (INTEL_GEN(rq->i915) >= 6)
396 gen6_rps_boost(rq, rps_client);
401 timeout = i915_wait_request(rq, flags, timeout);
404 if (flags & I915_WAIT_LOCKED && i915_gem_request_completed(rq))
405 i915_gem_request_retire_upto(rq);
411 i915_gem_object_wait_reservation(struct reservation_object *resv,
414 struct intel_rps_client *rps_client)
416 unsigned int seq = __read_seqcount_begin(&resv->seq);
417 struct dma_fence *excl;
418 bool prune_fences = false;
420 if (flags & I915_WAIT_ALL) {
421 struct dma_fence **shared;
422 unsigned int count, i;
425 ret = reservation_object_get_fences_rcu(resv,
426 &excl, &count, &shared);
430 for (i = 0; i < count; i++) {
431 timeout = i915_gem_object_wait_fence(shared[i],
437 dma_fence_put(shared[i]);
440 for (; i < count; i++)
441 dma_fence_put(shared[i]);
444 prune_fences = count && timeout >= 0;
446 excl = reservation_object_get_excl_rcu(resv);
449 if (excl && timeout >= 0) {
450 timeout = i915_gem_object_wait_fence(excl, flags, timeout,
452 prune_fences = timeout >= 0;
457 /* Oportunistically prune the fences iff we know they have *all* been
458 * signaled and that the reservation object has not been changed (i.e.
459 * no new fences have been added).
461 if (prune_fences && !__read_seqcount_retry(&resv->seq, seq)) {
462 if (reservation_object_trylock(resv)) {
463 if (!__read_seqcount_retry(&resv->seq, seq))
464 reservation_object_add_excl_fence(resv, NULL);
465 reservation_object_unlock(resv);
472 static void __fence_set_priority(struct dma_fence *fence, int prio)
474 struct drm_i915_gem_request *rq;
475 struct intel_engine_cs *engine;
477 if (!dma_fence_is_i915(fence))
480 rq = to_request(fence);
482 if (!engine->schedule)
485 engine->schedule(rq, prio);
488 static void fence_set_priority(struct dma_fence *fence, int prio)
490 /* Recurse once into a fence-array */
491 if (dma_fence_is_array(fence)) {
492 struct dma_fence_array *array = to_dma_fence_array(fence);
495 for (i = 0; i < array->num_fences; i++)
496 __fence_set_priority(array->fences[i], prio);
498 __fence_set_priority(fence, prio);
503 i915_gem_object_wait_priority(struct drm_i915_gem_object *obj,
507 struct dma_fence *excl;
509 if (flags & I915_WAIT_ALL) {
510 struct dma_fence **shared;
511 unsigned int count, i;
514 ret = reservation_object_get_fences_rcu(obj->resv,
515 &excl, &count, &shared);
519 for (i = 0; i < count; i++) {
520 fence_set_priority(shared[i], prio);
521 dma_fence_put(shared[i]);
526 excl = reservation_object_get_excl_rcu(obj->resv);
530 fence_set_priority(excl, prio);
537 * Waits for rendering to the object to be completed
538 * @obj: i915 gem object
539 * @flags: how to wait (under a lock, for all rendering or just for writes etc)
540 * @timeout: how long to wait
541 * @rps: client (user process) to charge for any waitboosting
544 i915_gem_object_wait(struct drm_i915_gem_object *obj,
547 struct intel_rps_client *rps_client)
550 #if IS_ENABLED(CONFIG_LOCKDEP)
551 GEM_BUG_ON(debug_locks &&
552 !!lockdep_is_held(&obj->base.dev->struct_mutex) !=
553 !!(flags & I915_WAIT_LOCKED));
555 GEM_BUG_ON(timeout < 0);
557 timeout = i915_gem_object_wait_reservation(obj->resv,
560 return timeout < 0 ? timeout : 0;
563 static struct intel_rps_client *to_rps_client(struct drm_file *file)
565 struct drm_i915_file_private *fpriv = file->driver_priv;
567 return &fpriv->rps_client;
571 i915_gem_phys_pwrite(struct drm_i915_gem_object *obj,
572 struct drm_i915_gem_pwrite *args,
573 struct drm_file *file)
575 void *vaddr = obj->phys_handle->vaddr + args->offset;
576 char __user *user_data = u64_to_user_ptr(args->data_ptr);
578 /* We manually control the domain here and pretend that it
579 * remains coherent i.e. in the GTT domain, like shmem_pwrite.
581 intel_fb_obj_invalidate(obj, ORIGIN_CPU);
582 if (copy_from_user(vaddr, user_data, args->size))
585 drm_clflush_virt_range(vaddr, args->size);
586 i915_gem_chipset_flush(to_i915(obj->base.dev));
588 intel_fb_obj_flush(obj, ORIGIN_CPU);
592 void *i915_gem_object_alloc(struct drm_i915_private *dev_priv)
594 return kmem_cache_zalloc(dev_priv->objects, GFP_KERNEL);
597 void i915_gem_object_free(struct drm_i915_gem_object *obj)
599 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
600 kmem_cache_free(dev_priv->objects, obj);
604 i915_gem_create(struct drm_file *file,
605 struct drm_i915_private *dev_priv,
609 struct drm_i915_gem_object *obj;
613 size = roundup(size, PAGE_SIZE);
617 /* Allocate the new object */
618 obj = i915_gem_object_create(dev_priv, size);
622 ret = drm_gem_handle_create(file, &obj->base, &handle);
623 /* drop reference from allocate - handle holds it now */
624 i915_gem_object_put(obj);
633 i915_gem_dumb_create(struct drm_file *file,
634 struct drm_device *dev,
635 struct drm_mode_create_dumb *args)
637 /* have to work out size/pitch and return them */
638 args->pitch = ALIGN(args->width * DIV_ROUND_UP(args->bpp, 8), 64);
639 args->size = args->pitch * args->height;
640 return i915_gem_create(file, to_i915(dev),
641 args->size, &args->handle);
644 static bool gpu_write_needs_clflush(struct drm_i915_gem_object *obj)
646 return !(obj->cache_level == I915_CACHE_NONE ||
647 obj->cache_level == I915_CACHE_WT);
651 * Creates a new mm object and returns a handle to it.
652 * @dev: drm device pointer
653 * @data: ioctl data blob
654 * @file: drm file pointer
657 i915_gem_create_ioctl(struct drm_device *dev, void *data,
658 struct drm_file *file)
660 struct drm_i915_private *dev_priv = to_i915(dev);
661 struct drm_i915_gem_create *args = data;
663 i915_gem_flush_free_objects(dev_priv);
665 return i915_gem_create(file, dev_priv,
666 args->size, &args->handle);
669 static inline enum fb_op_origin
670 fb_write_origin(struct drm_i915_gem_object *obj, unsigned int domain)
672 return (domain == I915_GEM_DOMAIN_GTT ?
673 obj->frontbuffer_ggtt_origin : ORIGIN_CPU);
677 flush_write_domain(struct drm_i915_gem_object *obj, unsigned int flush_domains)
679 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
681 if (!(obj->base.write_domain & flush_domains))
684 /* No actual flushing is required for the GTT write domain. Writes
685 * to it "immediately" go to main memory as far as we know, so there's
686 * no chipset flush. It also doesn't land in render cache.
688 * However, we do have to enforce the order so that all writes through
689 * the GTT land before any writes to the device, such as updates to
692 * We also have to wait a bit for the writes to land from the GTT.
693 * An uncached read (i.e. mmio) seems to be ideal for the round-trip
694 * timing. This issue has only been observed when switching quickly
695 * between GTT writes and CPU reads from inside the kernel on recent hw,
696 * and it appears to only affect discrete GTT blocks (i.e. on LLC
697 * system agents we cannot reproduce this behaviour).
701 switch (obj->base.write_domain) {
702 case I915_GEM_DOMAIN_GTT:
703 if (!HAS_LLC(dev_priv)) {
704 intel_runtime_pm_get(dev_priv);
705 spin_lock_irq(&dev_priv->uncore.lock);
706 POSTING_READ_FW(RING_HEAD(dev_priv->engine[RCS]->mmio_base));
707 spin_unlock_irq(&dev_priv->uncore.lock);
708 intel_runtime_pm_put(dev_priv);
711 intel_fb_obj_flush(obj,
712 fb_write_origin(obj, I915_GEM_DOMAIN_GTT));
715 case I915_GEM_DOMAIN_CPU:
716 i915_gem_clflush_object(obj, I915_CLFLUSH_SYNC);
719 case I915_GEM_DOMAIN_RENDER:
720 if (gpu_write_needs_clflush(obj))
721 obj->cache_dirty = true;
725 obj->base.write_domain = 0;
729 __copy_to_user_swizzled(char __user *cpu_vaddr,
730 const char *gpu_vaddr, int gpu_offset,
733 int ret, cpu_offset = 0;
736 int cacheline_end = ALIGN(gpu_offset + 1, 64);
737 int this_length = min(cacheline_end - gpu_offset, length);
738 int swizzled_gpu_offset = gpu_offset ^ 64;
740 ret = __copy_to_user(cpu_vaddr + cpu_offset,
741 gpu_vaddr + swizzled_gpu_offset,
746 cpu_offset += this_length;
747 gpu_offset += this_length;
748 length -= this_length;
755 __copy_from_user_swizzled(char *gpu_vaddr, int gpu_offset,
756 const char __user *cpu_vaddr,
759 int ret, cpu_offset = 0;
762 int cacheline_end = ALIGN(gpu_offset + 1, 64);
763 int this_length = min(cacheline_end - gpu_offset, length);
764 int swizzled_gpu_offset = gpu_offset ^ 64;
766 ret = __copy_from_user(gpu_vaddr + swizzled_gpu_offset,
767 cpu_vaddr + cpu_offset,
772 cpu_offset += this_length;
773 gpu_offset += this_length;
774 length -= this_length;
781 * Pins the specified object's pages and synchronizes the object with
782 * GPU accesses. Sets needs_clflush to non-zero if the caller should
783 * flush the object from the CPU cache.
785 int i915_gem_obj_prepare_shmem_read(struct drm_i915_gem_object *obj,
786 unsigned int *needs_clflush)
790 lockdep_assert_held(&obj->base.dev->struct_mutex);
793 if (!i915_gem_object_has_struct_page(obj))
796 ret = i915_gem_object_wait(obj,
797 I915_WAIT_INTERRUPTIBLE |
799 MAX_SCHEDULE_TIMEOUT,
804 ret = i915_gem_object_pin_pages(obj);
808 if (obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ ||
809 !static_cpu_has(X86_FEATURE_CLFLUSH)) {
810 ret = i915_gem_object_set_to_cpu_domain(obj, false);
817 flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
819 /* If we're not in the cpu read domain, set ourself into the gtt
820 * read domain and manually flush cachelines (if required). This
821 * optimizes for the case when the gpu will dirty the data
822 * anyway again before the next pread happens.
824 if (!obj->cache_dirty &&
825 !(obj->base.read_domains & I915_GEM_DOMAIN_CPU))
826 *needs_clflush = CLFLUSH_BEFORE;
829 /* return with the pages pinned */
833 i915_gem_object_unpin_pages(obj);
837 int i915_gem_obj_prepare_shmem_write(struct drm_i915_gem_object *obj,
838 unsigned int *needs_clflush)
842 lockdep_assert_held(&obj->base.dev->struct_mutex);
845 if (!i915_gem_object_has_struct_page(obj))
848 ret = i915_gem_object_wait(obj,
849 I915_WAIT_INTERRUPTIBLE |
852 MAX_SCHEDULE_TIMEOUT,
857 ret = i915_gem_object_pin_pages(obj);
861 if (obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_WRITE ||
862 !static_cpu_has(X86_FEATURE_CLFLUSH)) {
863 ret = i915_gem_object_set_to_cpu_domain(obj, true);
870 flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
872 /* If we're not in the cpu write domain, set ourself into the
873 * gtt write domain and manually flush cachelines (as required).
874 * This optimizes for the case when the gpu will use the data
875 * right away and we therefore have to clflush anyway.
877 if (!obj->cache_dirty) {
878 *needs_clflush |= CLFLUSH_AFTER;
881 * Same trick applies to invalidate partially written
882 * cachelines read before writing.
884 if (!(obj->base.read_domains & I915_GEM_DOMAIN_CPU))
885 *needs_clflush |= CLFLUSH_BEFORE;
889 intel_fb_obj_invalidate(obj, ORIGIN_CPU);
890 obj->mm.dirty = true;
891 /* return with the pages pinned */
895 i915_gem_object_unpin_pages(obj);
900 shmem_clflush_swizzled_range(char *addr, unsigned long length,
903 if (unlikely(swizzled)) {
904 unsigned long start = (unsigned long) addr;
905 unsigned long end = (unsigned long) addr + length;
907 /* For swizzling simply ensure that we always flush both
908 * channels. Lame, but simple and it works. Swizzled
909 * pwrite/pread is far from a hotpath - current userspace
910 * doesn't use it at all. */
911 start = round_down(start, 128);
912 end = round_up(end, 128);
914 drm_clflush_virt_range((void *)start, end - start);
916 drm_clflush_virt_range(addr, length);
921 /* Only difference to the fast-path function is that this can handle bit17
922 * and uses non-atomic copy and kmap functions. */
924 shmem_pread_slow(struct page *page, int offset, int length,
925 char __user *user_data,
926 bool page_do_bit17_swizzling, bool needs_clflush)
933 shmem_clflush_swizzled_range(vaddr + offset, length,
934 page_do_bit17_swizzling);
936 if (page_do_bit17_swizzling)
937 ret = __copy_to_user_swizzled(user_data, vaddr, offset, length);
939 ret = __copy_to_user(user_data, vaddr + offset, length);
942 return ret ? - EFAULT : 0;
946 shmem_pread(struct page *page, int offset, int length, char __user *user_data,
947 bool page_do_bit17_swizzling, bool needs_clflush)
952 if (!page_do_bit17_swizzling) {
953 char *vaddr = kmap_atomic(page);
956 drm_clflush_virt_range(vaddr + offset, length);
957 ret = __copy_to_user_inatomic(user_data, vaddr + offset, length);
958 kunmap_atomic(vaddr);
963 return shmem_pread_slow(page, offset, length, user_data,
964 page_do_bit17_swizzling, needs_clflush);
968 i915_gem_shmem_pread(struct drm_i915_gem_object *obj,
969 struct drm_i915_gem_pread *args)
971 char __user *user_data;
973 unsigned int obj_do_bit17_swizzling;
974 unsigned int needs_clflush;
975 unsigned int idx, offset;
978 obj_do_bit17_swizzling = 0;
979 if (i915_gem_object_needs_bit17_swizzle(obj))
980 obj_do_bit17_swizzling = BIT(17);
982 ret = mutex_lock_interruptible(&obj->base.dev->struct_mutex);
986 ret = i915_gem_obj_prepare_shmem_read(obj, &needs_clflush);
987 mutex_unlock(&obj->base.dev->struct_mutex);
992 user_data = u64_to_user_ptr(args->data_ptr);
993 offset = offset_in_page(args->offset);
994 for (idx = args->offset >> PAGE_SHIFT; remain; idx++) {
995 struct page *page = i915_gem_object_get_page(obj, idx);
999 if (offset + length > PAGE_SIZE)
1000 length = PAGE_SIZE - offset;
1002 ret = shmem_pread(page, offset, length, user_data,
1003 page_to_phys(page) & obj_do_bit17_swizzling,
1009 user_data += length;
1013 i915_gem_obj_finish_shmem_access(obj);
1018 gtt_user_read(struct io_mapping *mapping,
1019 loff_t base, int offset,
1020 char __user *user_data, int length)
1022 void __iomem *vaddr;
1023 unsigned long unwritten;
1025 /* We can use the cpu mem copy function because this is X86. */
1026 vaddr = io_mapping_map_atomic_wc(mapping, base);
1027 unwritten = __copy_to_user_inatomic(user_data,
1028 (void __force *)vaddr + offset,
1030 io_mapping_unmap_atomic(vaddr);
1032 vaddr = io_mapping_map_wc(mapping, base, PAGE_SIZE);
1033 unwritten = copy_to_user(user_data,
1034 (void __force *)vaddr + offset,
1036 io_mapping_unmap(vaddr);
1042 i915_gem_gtt_pread(struct drm_i915_gem_object *obj,
1043 const struct drm_i915_gem_pread *args)
1045 struct drm_i915_private *i915 = to_i915(obj->base.dev);
1046 struct i915_ggtt *ggtt = &i915->ggtt;
1047 struct drm_mm_node node;
1048 struct i915_vma *vma;
1049 void __user *user_data;
1053 ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
1057 intel_runtime_pm_get(i915);
1058 vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
1063 node.start = i915_ggtt_offset(vma);
1064 node.allocated = false;
1065 ret = i915_vma_put_fence(vma);
1067 i915_vma_unpin(vma);
1072 ret = insert_mappable_node(ggtt, &node, PAGE_SIZE);
1075 GEM_BUG_ON(!node.allocated);
1078 ret = i915_gem_object_set_to_gtt_domain(obj, false);
1082 mutex_unlock(&i915->drm.struct_mutex);
1084 user_data = u64_to_user_ptr(args->data_ptr);
1085 remain = args->size;
1086 offset = args->offset;
1088 while (remain > 0) {
1089 /* Operation in this page
1091 * page_base = page offset within aperture
1092 * page_offset = offset within page
1093 * page_length = bytes to copy for this page
1095 u32 page_base = node.start;
1096 unsigned page_offset = offset_in_page(offset);
1097 unsigned page_length = PAGE_SIZE - page_offset;
1098 page_length = remain < page_length ? remain : page_length;
1099 if (node.allocated) {
1101 ggtt->base.insert_page(&ggtt->base,
1102 i915_gem_object_get_dma_address(obj, offset >> PAGE_SHIFT),
1103 node.start, I915_CACHE_NONE, 0);
1106 page_base += offset & PAGE_MASK;
1109 if (gtt_user_read(&ggtt->mappable, page_base, page_offset,
1110 user_data, page_length)) {
1115 remain -= page_length;
1116 user_data += page_length;
1117 offset += page_length;
1120 mutex_lock(&i915->drm.struct_mutex);
1122 if (node.allocated) {
1124 ggtt->base.clear_range(&ggtt->base,
1125 node.start, node.size);
1126 remove_mappable_node(&node);
1128 i915_vma_unpin(vma);
1131 intel_runtime_pm_put(i915);
1132 mutex_unlock(&i915->drm.struct_mutex);
1138 * Reads data from the object referenced by handle.
1139 * @dev: drm device pointer
1140 * @data: ioctl data blob
1141 * @file: drm file pointer
1143 * On error, the contents of *data are undefined.
1146 i915_gem_pread_ioctl(struct drm_device *dev, void *data,
1147 struct drm_file *file)
1149 struct drm_i915_gem_pread *args = data;
1150 struct drm_i915_gem_object *obj;
1153 if (args->size == 0)
1156 if (!access_ok(VERIFY_WRITE,
1157 u64_to_user_ptr(args->data_ptr),
1161 obj = i915_gem_object_lookup(file, args->handle);
1165 /* Bounds check source. */
1166 if (range_overflows_t(u64, args->offset, args->size, obj->base.size)) {
1171 trace_i915_gem_object_pread(obj, args->offset, args->size);
1173 ret = i915_gem_object_wait(obj,
1174 I915_WAIT_INTERRUPTIBLE,
1175 MAX_SCHEDULE_TIMEOUT,
1176 to_rps_client(file));
1180 ret = i915_gem_object_pin_pages(obj);
1184 ret = i915_gem_shmem_pread(obj, args);
1185 if (ret == -EFAULT || ret == -ENODEV)
1186 ret = i915_gem_gtt_pread(obj, args);
1188 i915_gem_object_unpin_pages(obj);
1190 i915_gem_object_put(obj);
1194 /* This is the fast write path which cannot handle
1195 * page faults in the source data
1199 ggtt_write(struct io_mapping *mapping,
1200 loff_t base, int offset,
1201 char __user *user_data, int length)
1203 void __iomem *vaddr;
1204 unsigned long unwritten;
1206 /* We can use the cpu mem copy function because this is X86. */
1207 vaddr = io_mapping_map_atomic_wc(mapping, base);
1208 unwritten = __copy_from_user_inatomic_nocache((void __force *)vaddr + offset,
1210 io_mapping_unmap_atomic(vaddr);
1212 vaddr = io_mapping_map_wc(mapping, base, PAGE_SIZE);
1213 unwritten = copy_from_user((void __force *)vaddr + offset,
1215 io_mapping_unmap(vaddr);
1222 * This is the fast pwrite path, where we copy the data directly from the
1223 * user into the GTT, uncached.
1224 * @obj: i915 GEM object
1225 * @args: pwrite arguments structure
1228 i915_gem_gtt_pwrite_fast(struct drm_i915_gem_object *obj,
1229 const struct drm_i915_gem_pwrite *args)
1231 struct drm_i915_private *i915 = to_i915(obj->base.dev);
1232 struct i915_ggtt *ggtt = &i915->ggtt;
1233 struct drm_mm_node node;
1234 struct i915_vma *vma;
1236 void __user *user_data;
1239 ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
1243 if (i915_gem_object_has_struct_page(obj)) {
1245 * Avoid waking the device up if we can fallback, as
1246 * waking/resuming is very slow (worst-case 10-100 ms
1247 * depending on PCI sleeps and our own resume time).
1248 * This easily dwarfs any performance advantage from
1249 * using the cache bypass of indirect GGTT access.
1251 if (!intel_runtime_pm_get_if_in_use(i915)) {
1256 /* No backing pages, no fallback, we must force GGTT access */
1257 intel_runtime_pm_get(i915);
1260 vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
1265 node.start = i915_ggtt_offset(vma);
1266 node.allocated = false;
1267 ret = i915_vma_put_fence(vma);
1269 i915_vma_unpin(vma);
1274 ret = insert_mappable_node(ggtt, &node, PAGE_SIZE);
1277 GEM_BUG_ON(!node.allocated);
1280 ret = i915_gem_object_set_to_gtt_domain(obj, true);
1284 mutex_unlock(&i915->drm.struct_mutex);
1286 intel_fb_obj_invalidate(obj, ORIGIN_CPU);
1288 user_data = u64_to_user_ptr(args->data_ptr);
1289 offset = args->offset;
1290 remain = args->size;
1292 /* Operation in this page
1294 * page_base = page offset within aperture
1295 * page_offset = offset within page
1296 * page_length = bytes to copy for this page
1298 u32 page_base = node.start;
1299 unsigned int page_offset = offset_in_page(offset);
1300 unsigned int page_length = PAGE_SIZE - page_offset;
1301 page_length = remain < page_length ? remain : page_length;
1302 if (node.allocated) {
1303 wmb(); /* flush the write before we modify the GGTT */
1304 ggtt->base.insert_page(&ggtt->base,
1305 i915_gem_object_get_dma_address(obj, offset >> PAGE_SHIFT),
1306 node.start, I915_CACHE_NONE, 0);
1307 wmb(); /* flush modifications to the GGTT (insert_page) */
1309 page_base += offset & PAGE_MASK;
1311 /* If we get a fault while copying data, then (presumably) our
1312 * source page isn't available. Return the error and we'll
1313 * retry in the slow path.
1314 * If the object is non-shmem backed, we retry again with the
1315 * path that handles page fault.
1317 if (ggtt_write(&ggtt->mappable, page_base, page_offset,
1318 user_data, page_length)) {
1323 remain -= page_length;
1324 user_data += page_length;
1325 offset += page_length;
1327 intel_fb_obj_flush(obj, ORIGIN_CPU);
1329 mutex_lock(&i915->drm.struct_mutex);
1331 if (node.allocated) {
1333 ggtt->base.clear_range(&ggtt->base,
1334 node.start, node.size);
1335 remove_mappable_node(&node);
1337 i915_vma_unpin(vma);
1340 intel_runtime_pm_put(i915);
1342 mutex_unlock(&i915->drm.struct_mutex);
1347 shmem_pwrite_slow(struct page *page, int offset, int length,
1348 char __user *user_data,
1349 bool page_do_bit17_swizzling,
1350 bool needs_clflush_before,
1351 bool needs_clflush_after)
1357 if (unlikely(needs_clflush_before || page_do_bit17_swizzling))
1358 shmem_clflush_swizzled_range(vaddr + offset, length,
1359 page_do_bit17_swizzling);
1360 if (page_do_bit17_swizzling)
1361 ret = __copy_from_user_swizzled(vaddr, offset, user_data,
1364 ret = __copy_from_user(vaddr + offset, user_data, length);
1365 if (needs_clflush_after)
1366 shmem_clflush_swizzled_range(vaddr + offset, length,
1367 page_do_bit17_swizzling);
1370 return ret ? -EFAULT : 0;
1373 /* Per-page copy function for the shmem pwrite fastpath.
1374 * Flushes invalid cachelines before writing to the target if
1375 * needs_clflush_before is set and flushes out any written cachelines after
1376 * writing if needs_clflush is set.
1379 shmem_pwrite(struct page *page, int offset, int len, char __user *user_data,
1380 bool page_do_bit17_swizzling,
1381 bool needs_clflush_before,
1382 bool needs_clflush_after)
1387 if (!page_do_bit17_swizzling) {
1388 char *vaddr = kmap_atomic(page);
1390 if (needs_clflush_before)
1391 drm_clflush_virt_range(vaddr + offset, len);
1392 ret = __copy_from_user_inatomic(vaddr + offset, user_data, len);
1393 if (needs_clflush_after)
1394 drm_clflush_virt_range(vaddr + offset, len);
1396 kunmap_atomic(vaddr);
1401 return shmem_pwrite_slow(page, offset, len, user_data,
1402 page_do_bit17_swizzling,
1403 needs_clflush_before,
1404 needs_clflush_after);
1408 i915_gem_shmem_pwrite(struct drm_i915_gem_object *obj,
1409 const struct drm_i915_gem_pwrite *args)
1411 struct drm_i915_private *i915 = to_i915(obj->base.dev);
1412 void __user *user_data;
1414 unsigned int obj_do_bit17_swizzling;
1415 unsigned int partial_cacheline_write;
1416 unsigned int needs_clflush;
1417 unsigned int offset, idx;
1420 ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
1424 ret = i915_gem_obj_prepare_shmem_write(obj, &needs_clflush);
1425 mutex_unlock(&i915->drm.struct_mutex);
1429 obj_do_bit17_swizzling = 0;
1430 if (i915_gem_object_needs_bit17_swizzle(obj))
1431 obj_do_bit17_swizzling = BIT(17);
1433 /* If we don't overwrite a cacheline completely we need to be
1434 * careful to have up-to-date data by first clflushing. Don't
1435 * overcomplicate things and flush the entire patch.
1437 partial_cacheline_write = 0;
1438 if (needs_clflush & CLFLUSH_BEFORE)
1439 partial_cacheline_write = boot_cpu_data.x86_clflush_size - 1;
1441 user_data = u64_to_user_ptr(args->data_ptr);
1442 remain = args->size;
1443 offset = offset_in_page(args->offset);
1444 for (idx = args->offset >> PAGE_SHIFT; remain; idx++) {
1445 struct page *page = i915_gem_object_get_page(obj, idx);
1449 if (offset + length > PAGE_SIZE)
1450 length = PAGE_SIZE - offset;
1452 ret = shmem_pwrite(page, offset, length, user_data,
1453 page_to_phys(page) & obj_do_bit17_swizzling,
1454 (offset | length) & partial_cacheline_write,
1455 needs_clflush & CLFLUSH_AFTER);
1460 user_data += length;
1464 intel_fb_obj_flush(obj, ORIGIN_CPU);
1465 i915_gem_obj_finish_shmem_access(obj);
1470 * Writes data to the object referenced by handle.
1472 * @data: ioctl data blob
1475 * On error, the contents of the buffer that were to be modified are undefined.
1478 i915_gem_pwrite_ioctl(struct drm_device *dev, void *data,
1479 struct drm_file *file)
1481 struct drm_i915_gem_pwrite *args = data;
1482 struct drm_i915_gem_object *obj;
1485 if (args->size == 0)
1488 if (!access_ok(VERIFY_READ,
1489 u64_to_user_ptr(args->data_ptr),
1493 obj = i915_gem_object_lookup(file, args->handle);
1497 /* Bounds check destination. */
1498 if (range_overflows_t(u64, args->offset, args->size, obj->base.size)) {
1503 trace_i915_gem_object_pwrite(obj, args->offset, args->size);
1506 if (obj->ops->pwrite)
1507 ret = obj->ops->pwrite(obj, args);
1511 ret = i915_gem_object_wait(obj,
1512 I915_WAIT_INTERRUPTIBLE |
1514 MAX_SCHEDULE_TIMEOUT,
1515 to_rps_client(file));
1519 ret = i915_gem_object_pin_pages(obj);
1524 /* We can only do the GTT pwrite on untiled buffers, as otherwise
1525 * it would end up going through the fenced access, and we'll get
1526 * different detiling behavior between reading and writing.
1527 * pread/pwrite currently are reading and writing from the CPU
1528 * perspective, requiring manual detiling by the client.
1530 if (!i915_gem_object_has_struct_page(obj) ||
1531 cpu_write_needs_clflush(obj))
1532 /* Note that the gtt paths might fail with non-page-backed user
1533 * pointers (e.g. gtt mappings when moving data between
1534 * textures). Fallback to the shmem path in that case.
1536 ret = i915_gem_gtt_pwrite_fast(obj, args);
1538 if (ret == -EFAULT || ret == -ENOSPC) {
1539 if (obj->phys_handle)
1540 ret = i915_gem_phys_pwrite(obj, args, file);
1542 ret = i915_gem_shmem_pwrite(obj, args);
1545 i915_gem_object_unpin_pages(obj);
1547 i915_gem_object_put(obj);
1551 static void i915_gem_object_bump_inactive_ggtt(struct drm_i915_gem_object *obj)
1553 struct drm_i915_private *i915;
1554 struct list_head *list;
1555 struct i915_vma *vma;
1557 GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
1559 list_for_each_entry(vma, &obj->vma_list, obj_link) {
1560 if (!i915_vma_is_ggtt(vma))
1563 if (i915_vma_is_active(vma))
1566 if (!drm_mm_node_allocated(&vma->node))
1569 list_move_tail(&vma->vm_link, &vma->vm->inactive_list);
1572 i915 = to_i915(obj->base.dev);
1573 spin_lock(&i915->mm.obj_lock);
1574 list = obj->bind_count ? &i915->mm.bound_list : &i915->mm.unbound_list;
1575 list_move_tail(&obj->mm.link, list);
1576 spin_unlock(&i915->mm.obj_lock);
1580 * Called when user space prepares to use an object with the CPU, either
1581 * through the mmap ioctl's mapping or a GTT mapping.
1583 * @data: ioctl data blob
1587 i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
1588 struct drm_file *file)
1590 struct drm_i915_gem_set_domain *args = data;
1591 struct drm_i915_gem_object *obj;
1592 uint32_t read_domains = args->read_domains;
1593 uint32_t write_domain = args->write_domain;
1596 /* Only handle setting domains to types used by the CPU. */
1597 if ((write_domain | read_domains) & I915_GEM_GPU_DOMAINS)
1600 /* Having something in the write domain implies it's in the read
1601 * domain, and only that read domain. Enforce that in the request.
1603 if (write_domain != 0 && read_domains != write_domain)
1606 obj = i915_gem_object_lookup(file, args->handle);
1610 /* Try to flush the object off the GPU without holding the lock.
1611 * We will repeat the flush holding the lock in the normal manner
1612 * to catch cases where we are gazumped.
1614 err = i915_gem_object_wait(obj,
1615 I915_WAIT_INTERRUPTIBLE |
1616 (write_domain ? I915_WAIT_ALL : 0),
1617 MAX_SCHEDULE_TIMEOUT,
1618 to_rps_client(file));
1622 /* Flush and acquire obj->pages so that we are coherent through
1623 * direct access in memory with previous cached writes through
1624 * shmemfs and that our cache domain tracking remains valid.
1625 * For example, if the obj->filp was moved to swap without us
1626 * being notified and releasing the pages, we would mistakenly
1627 * continue to assume that the obj remained out of the CPU cached
1630 err = i915_gem_object_pin_pages(obj);
1634 err = i915_mutex_lock_interruptible(dev);
1638 if (read_domains & I915_GEM_DOMAIN_WC)
1639 err = i915_gem_object_set_to_wc_domain(obj, write_domain);
1640 else if (read_domains & I915_GEM_DOMAIN_GTT)
1641 err = i915_gem_object_set_to_gtt_domain(obj, write_domain);
1643 err = i915_gem_object_set_to_cpu_domain(obj, write_domain);
1645 /* And bump the LRU for this access */
1646 i915_gem_object_bump_inactive_ggtt(obj);
1648 mutex_unlock(&dev->struct_mutex);
1650 if (write_domain != 0)
1651 intel_fb_obj_invalidate(obj,
1652 fb_write_origin(obj, write_domain));
1655 i915_gem_object_unpin_pages(obj);
1657 i915_gem_object_put(obj);
1662 * Called when user space has done writes to this buffer
1664 * @data: ioctl data blob
1668 i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
1669 struct drm_file *file)
1671 struct drm_i915_gem_sw_finish *args = data;
1672 struct drm_i915_gem_object *obj;
1674 obj = i915_gem_object_lookup(file, args->handle);
1678 /* Pinned buffers may be scanout, so flush the cache */
1679 i915_gem_object_flush_if_display(obj);
1680 i915_gem_object_put(obj);
1686 * i915_gem_mmap_ioctl - Maps the contents of an object, returning the address
1689 * @data: ioctl data blob
1692 * While the mapping holds a reference on the contents of the object, it doesn't
1693 * imply a ref on the object itself.
1697 * DRM driver writers who look a this function as an example for how to do GEM
1698 * mmap support, please don't implement mmap support like here. The modern way
1699 * to implement DRM mmap support is with an mmap offset ioctl (like
1700 * i915_gem_mmap_gtt) and then using the mmap syscall on the DRM fd directly.
1701 * That way debug tooling like valgrind will understand what's going on, hiding
1702 * the mmap call in a driver private ioctl will break that. The i915 driver only
1703 * does cpu mmaps this way because we didn't know better.
1706 i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
1707 struct drm_file *file)
1709 struct drm_i915_gem_mmap *args = data;
1710 struct drm_i915_gem_object *obj;
1713 if (args->flags & ~(I915_MMAP_WC))
1716 if (args->flags & I915_MMAP_WC && !boot_cpu_has(X86_FEATURE_PAT))
1719 obj = i915_gem_object_lookup(file, args->handle);
1723 /* prime objects have no backing filp to GEM mmap
1726 if (!obj->base.filp) {
1727 i915_gem_object_put(obj);
1731 addr = vm_mmap(obj->base.filp, 0, args->size,
1732 PROT_READ | PROT_WRITE, MAP_SHARED,
1734 if (args->flags & I915_MMAP_WC) {
1735 struct mm_struct *mm = current->mm;
1736 struct vm_area_struct *vma;
1738 if (down_write_killable(&mm->mmap_sem)) {
1739 i915_gem_object_put(obj);
1742 vma = find_vma(mm, addr);
1745 pgprot_writecombine(vm_get_page_prot(vma->vm_flags));
1748 up_write(&mm->mmap_sem);
1750 /* This may race, but that's ok, it only gets set */
1751 WRITE_ONCE(obj->frontbuffer_ggtt_origin, ORIGIN_CPU);
1753 i915_gem_object_put(obj);
1754 if (IS_ERR((void *)addr))
1757 args->addr_ptr = (uint64_t) addr;
1762 static unsigned int tile_row_pages(struct drm_i915_gem_object *obj)
1764 return i915_gem_object_get_tile_row_size(obj) >> PAGE_SHIFT;
1768 * i915_gem_mmap_gtt_version - report the current feature set for GTT mmaps
1770 * A history of the GTT mmap interface:
1772 * 0 - Everything had to fit into the GTT. Both parties of a memcpy had to
1773 * aligned and suitable for fencing, and still fit into the available
1774 * mappable space left by the pinned display objects. A classic problem
1775 * we called the page-fault-of-doom where we would ping-pong between
1776 * two objects that could not fit inside the GTT and so the memcpy
1777 * would page one object in at the expense of the other between every
1780 * 1 - Objects can be any size, and have any compatible fencing (X Y, or none
1781 * as set via i915_gem_set_tiling() [DRM_I915_GEM_SET_TILING]). If the
1782 * object is too large for the available space (or simply too large
1783 * for the mappable aperture!), a view is created instead and faulted
1784 * into userspace. (This view is aligned and sized appropriately for
1787 * 2 - Recognise WC as a separate cache domain so that we can flush the
1788 * delayed writes via GTT before performing direct access via WC.
1792 * * snoopable objects cannot be accessed via the GTT. It can cause machine
1793 * hangs on some architectures, corruption on others. An attempt to service
1794 * a GTT page fault from a snoopable object will generate a SIGBUS.
1796 * * the object must be able to fit into RAM (physical memory, though no
1797 * limited to the mappable aperture).
1802 * * a new GTT page fault will synchronize rendering from the GPU and flush
1803 * all data to system memory. Subsequent access will not be synchronized.
1805 * * all mappings are revoked on runtime device suspend.
1807 * * there are only 8, 16 or 32 fence registers to share between all users
1808 * (older machines require fence register for display and blitter access
1809 * as well). Contention of the fence registers will cause the previous users
1810 * to be unmapped and any new access will generate new page faults.
1812 * * running out of memory while servicing a fault may generate a SIGBUS,
1813 * rather than the expected SIGSEGV.
1815 int i915_gem_mmap_gtt_version(void)
1820 static inline struct i915_ggtt_view
1821 compute_partial_view(struct drm_i915_gem_object *obj,
1822 pgoff_t page_offset,
1825 struct i915_ggtt_view view;
1827 if (i915_gem_object_is_tiled(obj))
1828 chunk = roundup(chunk, tile_row_pages(obj));
1830 view.type = I915_GGTT_VIEW_PARTIAL;
1831 view.partial.offset = rounddown(page_offset, chunk);
1833 min_t(unsigned int, chunk,
1834 (obj->base.size >> PAGE_SHIFT) - view.partial.offset);
1836 /* If the partial covers the entire object, just create a normal VMA. */
1837 if (chunk >= obj->base.size >> PAGE_SHIFT)
1838 view.type = I915_GGTT_VIEW_NORMAL;
1844 * i915_gem_fault - fault a page into the GTT
1847 * The fault handler is set up by drm_gem_mmap() when a object is GTT mapped
1848 * from userspace. The fault handler takes care of binding the object to
1849 * the GTT (if needed), allocating and programming a fence register (again,
1850 * only if needed based on whether the old reg is still valid or the object
1851 * is tiled) and inserting a new PTE into the faulting process.
1853 * Note that the faulting process may involve evicting existing objects
1854 * from the GTT and/or fence registers to make room. So performance may
1855 * suffer if the GTT working set is large or there are few fence registers
1858 * The current feature set supported by i915_gem_fault() and thus GTT mmaps
1859 * is exposed via I915_PARAM_MMAP_GTT_VERSION (see i915_gem_mmap_gtt_version).
1861 int i915_gem_fault(struct vm_fault *vmf)
1863 #define MIN_CHUNK_PAGES ((1 << 20) >> PAGE_SHIFT) /* 1 MiB */
1864 struct vm_area_struct *area = vmf->vma;
1865 struct drm_i915_gem_object *obj = to_intel_bo(area->vm_private_data);
1866 struct drm_device *dev = obj->base.dev;
1867 struct drm_i915_private *dev_priv = to_i915(dev);
1868 struct i915_ggtt *ggtt = &dev_priv->ggtt;
1869 bool write = !!(vmf->flags & FAULT_FLAG_WRITE);
1870 struct i915_vma *vma;
1871 pgoff_t page_offset;
1875 /* We don't use vmf->pgoff since that has the fake offset */
1876 page_offset = (vmf->address - area->vm_start) >> PAGE_SHIFT;
1878 trace_i915_gem_object_fault(obj, page_offset, true, write);
1880 /* Try to flush the object off the GPU first without holding the lock.
1881 * Upon acquiring the lock, we will perform our sanity checks and then
1882 * repeat the flush holding the lock in the normal manner to catch cases
1883 * where we are gazumped.
1885 ret = i915_gem_object_wait(obj,
1886 I915_WAIT_INTERRUPTIBLE,
1887 MAX_SCHEDULE_TIMEOUT,
1892 ret = i915_gem_object_pin_pages(obj);
1896 intel_runtime_pm_get(dev_priv);
1898 ret = i915_mutex_lock_interruptible(dev);
1902 /* Access to snoopable pages through the GTT is incoherent. */
1903 if (obj->cache_level != I915_CACHE_NONE && !HAS_LLC(dev_priv)) {
1908 /* If the object is smaller than a couple of partial vma, it is
1909 * not worth only creating a single partial vma - we may as well
1910 * clear enough space for the full object.
1912 flags = PIN_MAPPABLE;
1913 if (obj->base.size > 2 * MIN_CHUNK_PAGES << PAGE_SHIFT)
1914 flags |= PIN_NONBLOCK | PIN_NONFAULT;
1916 /* Now pin it into the GTT as needed */
1917 vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0, flags);
1919 /* Use a partial view if it is bigger than available space */
1920 struct i915_ggtt_view view =
1921 compute_partial_view(obj, page_offset, MIN_CHUNK_PAGES);
1923 /* Userspace is now writing through an untracked VMA, abandon
1924 * all hope that the hardware is able to track future writes.
1926 obj->frontbuffer_ggtt_origin = ORIGIN_CPU;
1928 vma = i915_gem_object_ggtt_pin(obj, &view, 0, 0, PIN_MAPPABLE);
1935 ret = i915_gem_object_set_to_gtt_domain(obj, write);
1939 ret = i915_vma_pin_fence(vma);
1943 /* Finally, remap it using the new GTT offset */
1944 ret = remap_io_mapping(area,
1945 area->vm_start + (vma->ggtt_view.partial.offset << PAGE_SHIFT),
1946 (ggtt->mappable_base + vma->node.start) >> PAGE_SHIFT,
1947 min_t(u64, vma->size, area->vm_end - area->vm_start),
1952 /* Mark as being mmapped into userspace for later revocation */
1953 assert_rpm_wakelock_held(dev_priv);
1954 if (!i915_vma_set_userfault(vma) && !obj->userfault_count++)
1955 list_add(&obj->userfault_link, &dev_priv->mm.userfault_list);
1956 GEM_BUG_ON(!obj->userfault_count);
1959 i915_vma_unpin_fence(vma);
1961 __i915_vma_unpin(vma);
1963 mutex_unlock(&dev->struct_mutex);
1965 intel_runtime_pm_put(dev_priv);
1966 i915_gem_object_unpin_pages(obj);
1971 * We eat errors when the gpu is terminally wedged to avoid
1972 * userspace unduly crashing (gl has no provisions for mmaps to
1973 * fail). But any other -EIO isn't ours (e.g. swap in failure)
1974 * and so needs to be reported.
1976 if (!i915_terminally_wedged(&dev_priv->gpu_error)) {
1977 ret = VM_FAULT_SIGBUS;
1982 * EAGAIN means the gpu is hung and we'll wait for the error
1983 * handler to reset everything when re-faulting in
1984 * i915_mutex_lock_interruptible.
1991 * EBUSY is ok: this just means that another thread
1992 * already did the job.
1994 ret = VM_FAULT_NOPAGE;
2001 ret = VM_FAULT_SIGBUS;
2004 WARN_ONCE(ret, "unhandled error in i915_gem_fault: %i\n", ret);
2005 ret = VM_FAULT_SIGBUS;
2011 static void __i915_gem_object_release_mmap(struct drm_i915_gem_object *obj)
2013 struct i915_vma *vma;
2015 GEM_BUG_ON(!obj->userfault_count);
2017 obj->userfault_count = 0;
2018 list_del(&obj->userfault_link);
2019 drm_vma_node_unmap(&obj->base.vma_node,
2020 obj->base.dev->anon_inode->i_mapping);
2022 list_for_each_entry(vma, &obj->vma_list, obj_link) {
2023 if (!i915_vma_is_ggtt(vma))
2026 i915_vma_unset_userfault(vma);
2031 * i915_gem_release_mmap - remove physical page mappings
2032 * @obj: obj in question
2034 * Preserve the reservation of the mmapping with the DRM core code, but
2035 * relinquish ownership of the pages back to the system.
2037 * It is vital that we remove the page mapping if we have mapped a tiled
2038 * object through the GTT and then lose the fence register due to
2039 * resource pressure. Similarly if the object has been moved out of the
2040 * aperture, than pages mapped into userspace must be revoked. Removing the
2041 * mapping will then trigger a page fault on the next user access, allowing
2042 * fixup by i915_gem_fault().
2045 i915_gem_release_mmap(struct drm_i915_gem_object *obj)
2047 struct drm_i915_private *i915 = to_i915(obj->base.dev);
2049 /* Serialisation between user GTT access and our code depends upon
2050 * revoking the CPU's PTE whilst the mutex is held. The next user
2051 * pagefault then has to wait until we release the mutex.
2053 * Note that RPM complicates somewhat by adding an additional
2054 * requirement that operations to the GGTT be made holding the RPM
2057 lockdep_assert_held(&i915->drm.struct_mutex);
2058 intel_runtime_pm_get(i915);
2060 if (!obj->userfault_count)
2063 __i915_gem_object_release_mmap(obj);
2065 /* Ensure that the CPU's PTE are revoked and there are not outstanding
2066 * memory transactions from userspace before we return. The TLB
2067 * flushing implied above by changing the PTE above *should* be
2068 * sufficient, an extra barrier here just provides us with a bit
2069 * of paranoid documentation about our requirement to serialise
2070 * memory writes before touching registers / GSM.
2075 intel_runtime_pm_put(i915);
2078 void i915_gem_runtime_suspend(struct drm_i915_private *dev_priv)
2080 struct drm_i915_gem_object *obj, *on;
2084 * Only called during RPM suspend. All users of the userfault_list
2085 * must be holding an RPM wakeref to ensure that this can not
2086 * run concurrently with themselves (and use the struct_mutex for
2087 * protection between themselves).
2090 list_for_each_entry_safe(obj, on,
2091 &dev_priv->mm.userfault_list, userfault_link)
2092 __i915_gem_object_release_mmap(obj);
2094 /* The fence will be lost when the device powers down. If any were
2095 * in use by hardware (i.e. they are pinned), we should not be powering
2096 * down! All other fences will be reacquired by the user upon waking.
2098 for (i = 0; i < dev_priv->num_fence_regs; i++) {
2099 struct drm_i915_fence_reg *reg = &dev_priv->fence_regs[i];
2101 /* Ideally we want to assert that the fence register is not
2102 * live at this point (i.e. that no piece of code will be
2103 * trying to write through fence + GTT, as that both violates
2104 * our tracking of activity and associated locking/barriers,
2105 * but also is illegal given that the hw is powered down).
2107 * Previously we used reg->pin_count as a "liveness" indicator.
2108 * That is not sufficient, and we need a more fine-grained
2109 * tool if we want to have a sanity check here.
2115 GEM_BUG_ON(i915_vma_has_userfault(reg->vma));
2120 static int i915_gem_object_create_mmap_offset(struct drm_i915_gem_object *obj)
2122 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
2125 err = drm_gem_create_mmap_offset(&obj->base);
2129 /* Attempt to reap some mmap space from dead objects */
2131 err = i915_gem_wait_for_idle(dev_priv, I915_WAIT_INTERRUPTIBLE);
2135 i915_gem_drain_freed_objects(dev_priv);
2136 err = drm_gem_create_mmap_offset(&obj->base);
2140 } while (flush_delayed_work(&dev_priv->gt.retire_work));
2145 static void i915_gem_object_free_mmap_offset(struct drm_i915_gem_object *obj)
2147 drm_gem_free_mmap_offset(&obj->base);
2151 i915_gem_mmap_gtt(struct drm_file *file,
2152 struct drm_device *dev,
2156 struct drm_i915_gem_object *obj;
2159 obj = i915_gem_object_lookup(file, handle);
2163 ret = i915_gem_object_create_mmap_offset(obj);
2165 *offset = drm_vma_node_offset_addr(&obj->base.vma_node);
2167 i915_gem_object_put(obj);
2172 * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
2174 * @data: GTT mapping ioctl data
2175 * @file: GEM object info
2177 * Simply returns the fake offset to userspace so it can mmap it.
2178 * The mmap call will end up in drm_gem_mmap(), which will set things
2179 * up so we can get faults in the handler above.
2181 * The fault handler will take care of binding the object into the GTT
2182 * (since it may have been evicted to make room for something), allocating
2183 * a fence register, and mapping the appropriate aperture address into
2187 i915_gem_mmap_gtt_ioctl(struct drm_device *dev, void *data,
2188 struct drm_file *file)
2190 struct drm_i915_gem_mmap_gtt *args = data;
2192 return i915_gem_mmap_gtt(file, dev, args->handle, &args->offset);
2195 /* Immediately discard the backing storage */
2197 i915_gem_object_truncate(struct drm_i915_gem_object *obj)
2199 i915_gem_object_free_mmap_offset(obj);
2201 if (obj->base.filp == NULL)
2204 /* Our goal here is to return as much of the memory as
2205 * is possible back to the system as we are called from OOM.
2206 * To do this we must instruct the shmfs to drop all of its
2207 * backing pages, *now*.
2209 shmem_truncate_range(file_inode(obj->base.filp), 0, (loff_t)-1);
2210 obj->mm.madv = __I915_MADV_PURGED;
2211 obj->mm.pages = ERR_PTR(-EFAULT);
2214 /* Try to discard unwanted pages */
2215 void __i915_gem_object_invalidate(struct drm_i915_gem_object *obj)
2217 struct address_space *mapping;
2219 lockdep_assert_held(&obj->mm.lock);
2220 GEM_BUG_ON(i915_gem_object_has_pages(obj));
2222 switch (obj->mm.madv) {
2223 case I915_MADV_DONTNEED:
2224 i915_gem_object_truncate(obj);
2225 case __I915_MADV_PURGED:
2229 if (obj->base.filp == NULL)
2232 mapping = obj->base.filp->f_mapping,
2233 invalidate_mapping_pages(mapping, 0, (loff_t)-1);
2237 i915_gem_object_put_pages_gtt(struct drm_i915_gem_object *obj,
2238 struct sg_table *pages)
2240 struct sgt_iter sgt_iter;
2243 __i915_gem_object_release_shmem(obj, pages, true);
2245 i915_gem_gtt_finish_pages(obj, pages);
2247 if (i915_gem_object_needs_bit17_swizzle(obj))
2248 i915_gem_object_save_bit_17_swizzle(obj, pages);
2250 for_each_sgt_page(page, sgt_iter, pages) {
2252 set_page_dirty(page);
2254 if (obj->mm.madv == I915_MADV_WILLNEED)
2255 mark_page_accessed(page);
2259 obj->mm.dirty = false;
2261 sg_free_table(pages);
2265 static void __i915_gem_object_reset_page_iter(struct drm_i915_gem_object *obj)
2267 struct radix_tree_iter iter;
2270 radix_tree_for_each_slot(slot, &obj->mm.get_page.radix, &iter, 0)
2271 radix_tree_delete(&obj->mm.get_page.radix, iter.index);
2274 void __i915_gem_object_put_pages(struct drm_i915_gem_object *obj,
2275 enum i915_mm_subclass subclass)
2277 struct drm_i915_private *i915 = to_i915(obj->base.dev);
2278 struct sg_table *pages;
2280 if (i915_gem_object_has_pinned_pages(obj))
2283 GEM_BUG_ON(obj->bind_count);
2284 if (!i915_gem_object_has_pages(obj))
2287 /* May be called by shrinker from within get_pages() (on another bo) */
2288 mutex_lock_nested(&obj->mm.lock, subclass);
2289 if (unlikely(atomic_read(&obj->mm.pages_pin_count)))
2292 /* ->put_pages might need to allocate memory for the bit17 swizzle
2293 * array, hence protect them from being reaped by removing them from gtt
2295 pages = fetch_and_zero(&obj->mm.pages);
2298 spin_lock(&i915->mm.obj_lock);
2299 list_del(&obj->mm.link);
2300 spin_unlock(&i915->mm.obj_lock);
2302 if (obj->mm.mapping) {
2305 ptr = page_mask_bits(obj->mm.mapping);
2306 if (is_vmalloc_addr(ptr))
2309 kunmap(kmap_to_page(ptr));
2311 obj->mm.mapping = NULL;
2314 __i915_gem_object_reset_page_iter(obj);
2317 obj->ops->put_pages(obj, pages);
2319 obj->mm.page_sizes.phys = obj->mm.page_sizes.sg = 0;
2322 mutex_unlock(&obj->mm.lock);
2325 static bool i915_sg_trim(struct sg_table *orig_st)
2327 struct sg_table new_st;
2328 struct scatterlist *sg, *new_sg;
2331 if (orig_st->nents == orig_st->orig_nents)
2334 if (sg_alloc_table(&new_st, orig_st->nents, GFP_KERNEL | __GFP_NOWARN))
2337 new_sg = new_st.sgl;
2338 for_each_sg(orig_st->sgl, sg, orig_st->nents, i) {
2339 sg_set_page(new_sg, sg_page(sg), sg->length, 0);
2340 /* called before being DMA mapped, no need to copy sg->dma_* */
2341 new_sg = sg_next(new_sg);
2343 GEM_BUG_ON(new_sg); /* Should walk exactly nents and hit the end */
2345 sg_free_table(orig_st);
2351 static int i915_gem_object_get_pages_gtt(struct drm_i915_gem_object *obj)
2353 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
2354 const unsigned long page_count = obj->base.size / PAGE_SIZE;
2356 struct address_space *mapping;
2357 struct sg_table *st;
2358 struct scatterlist *sg;
2359 struct sgt_iter sgt_iter;
2361 unsigned long last_pfn = 0; /* suppress gcc warning */
2362 unsigned int max_segment = i915_sg_segment_size();
2363 unsigned int sg_page_sizes;
2367 /* Assert that the object is not currently in any GPU domain. As it
2368 * wasn't in the GTT, there shouldn't be any way it could have been in
2371 GEM_BUG_ON(obj->base.read_domains & I915_GEM_GPU_DOMAINS);
2372 GEM_BUG_ON(obj->base.write_domain & I915_GEM_GPU_DOMAINS);
2374 st = kmalloc(sizeof(*st), GFP_KERNEL);
2379 if (sg_alloc_table(st, page_count, GFP_KERNEL)) {
2384 /* Get the list of pages out of our struct file. They'll be pinned
2385 * at this point until we release them.
2387 * Fail silently without starting the shrinker
2389 mapping = obj->base.filp->f_mapping;
2390 noreclaim = mapping_gfp_constraint(mapping, ~__GFP_RECLAIM);
2391 noreclaim |= __GFP_NORETRY | __GFP_NOWARN;
2396 for (i = 0; i < page_count; i++) {
2397 const unsigned int shrink[] = {
2398 I915_SHRINK_BOUND | I915_SHRINK_UNBOUND | I915_SHRINK_PURGEABLE,
2401 gfp_t gfp = noreclaim;
2404 page = shmem_read_mapping_page_gfp(mapping, i, gfp);
2405 if (likely(!IS_ERR(page)))
2409 ret = PTR_ERR(page);
2413 i915_gem_shrink(dev_priv, 2 * page_count, NULL, *s++);
2416 /* We've tried hard to allocate the memory by reaping
2417 * our own buffer, now let the real VM do its job and
2418 * go down in flames if truly OOM.
2420 * However, since graphics tend to be disposable,
2421 * defer the oom here by reporting the ENOMEM back
2425 /* reclaim and warn, but no oom */
2426 gfp = mapping_gfp_mask(mapping);
2428 /* Our bo are always dirty and so we require
2429 * kswapd to reclaim our pages (direct reclaim
2430 * does not effectively begin pageout of our
2431 * buffers on its own). However, direct reclaim
2432 * only waits for kswapd when under allocation
2433 * congestion. So as a result __GFP_RECLAIM is
2434 * unreliable and fails to actually reclaim our
2435 * dirty pages -- unless you try over and over
2436 * again with !__GFP_NORETRY. However, we still
2437 * want to fail this allocation rather than
2438 * trigger the out-of-memory killer and for
2439 * this we want __GFP_RETRY_MAYFAIL.
2441 gfp |= __GFP_RETRY_MAYFAIL;
2446 sg->length >= max_segment ||
2447 page_to_pfn(page) != last_pfn + 1) {
2449 sg_page_sizes |= sg->length;
2453 sg_set_page(sg, page, PAGE_SIZE, 0);
2455 sg->length += PAGE_SIZE;
2457 last_pfn = page_to_pfn(page);
2459 /* Check that the i965g/gm workaround works. */
2460 WARN_ON((gfp & __GFP_DMA32) && (last_pfn >= 0x00100000UL));
2462 if (sg) { /* loop terminated early; short sg table */
2463 sg_page_sizes |= sg->length;
2467 /* Trim unused sg entries to avoid wasting memory. */
2470 ret = i915_gem_gtt_prepare_pages(obj, st);
2472 /* DMA remapping failed? One possible cause is that
2473 * it could not reserve enough large entries, asking
2474 * for PAGE_SIZE chunks instead may be helpful.
2476 if (max_segment > PAGE_SIZE) {
2477 for_each_sgt_page(page, sgt_iter, st)
2481 max_segment = PAGE_SIZE;
2484 dev_warn(&dev_priv->drm.pdev->dev,
2485 "Failed to DMA remap %lu pages\n",
2491 if (i915_gem_object_needs_bit17_swizzle(obj))
2492 i915_gem_object_do_bit_17_swizzle(obj, st);
2494 __i915_gem_object_set_pages(obj, st, sg_page_sizes);
2501 for_each_sgt_page(page, sgt_iter, st)
2506 /* shmemfs first checks if there is enough memory to allocate the page
2507 * and reports ENOSPC should there be insufficient, along with the usual
2508 * ENOMEM for a genuine allocation failure.
2510 * We use ENOSPC in our driver to mean that we have run out of aperture
2511 * space and so want to translate the error from shmemfs back to our
2512 * usual understanding of ENOMEM.
2520 void __i915_gem_object_set_pages(struct drm_i915_gem_object *obj,
2521 struct sg_table *pages,
2522 unsigned int sg_page_sizes)
2524 struct drm_i915_private *i915 = to_i915(obj->base.dev);
2525 unsigned long supported = INTEL_INFO(i915)->page_sizes;
2528 lockdep_assert_held(&obj->mm.lock);
2530 obj->mm.get_page.sg_pos = pages->sgl;
2531 obj->mm.get_page.sg_idx = 0;
2533 obj->mm.pages = pages;
2535 if (i915_gem_object_is_tiled(obj) &&
2536 i915->quirks & QUIRK_PIN_SWIZZLED_PAGES) {
2537 GEM_BUG_ON(obj->mm.quirked);
2538 __i915_gem_object_pin_pages(obj);
2539 obj->mm.quirked = true;
2542 GEM_BUG_ON(!sg_page_sizes);
2543 obj->mm.page_sizes.phys = sg_page_sizes;
2546 * Calculate the supported page-sizes which fit into the given
2547 * sg_page_sizes. This will give us the page-sizes which we may be able
2548 * to use opportunistically when later inserting into the GTT. For
2549 * example if phys=2G, then in theory we should be able to use 1G, 2M,
2550 * 64K or 4K pages, although in practice this will depend on a number of
2553 obj->mm.page_sizes.sg = 0;
2554 for_each_set_bit(i, &supported, ilog2(I915_GTT_MAX_PAGE_SIZE) + 1) {
2555 if (obj->mm.page_sizes.phys & ~0u << i)
2556 obj->mm.page_sizes.sg |= BIT(i);
2558 GEM_BUG_ON(!HAS_PAGE_SIZES(i915, obj->mm.page_sizes.sg));
2560 spin_lock(&i915->mm.obj_lock);
2561 list_add(&obj->mm.link, &i915->mm.unbound_list);
2562 spin_unlock(&i915->mm.obj_lock);
2565 static int ____i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
2569 if (unlikely(obj->mm.madv != I915_MADV_WILLNEED)) {
2570 DRM_DEBUG("Attempting to obtain a purgeable object\n");
2574 err = obj->ops->get_pages(obj);
2575 GEM_BUG_ON(!err && IS_ERR_OR_NULL(obj->mm.pages));
2580 /* Ensure that the associated pages are gathered from the backing storage
2581 * and pinned into our object. i915_gem_object_pin_pages() may be called
2582 * multiple times before they are released by a single call to
2583 * i915_gem_object_unpin_pages() - once the pages are no longer referenced
2584 * either as a result of memory pressure (reaping pages under the shrinker)
2585 * or as the object is itself released.
2587 int __i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
2591 err = mutex_lock_interruptible(&obj->mm.lock);
2595 if (unlikely(!i915_gem_object_has_pages(obj))) {
2596 GEM_BUG_ON(i915_gem_object_has_pinned_pages(obj));
2598 err = ____i915_gem_object_get_pages(obj);
2602 smp_mb__before_atomic();
2604 atomic_inc(&obj->mm.pages_pin_count);
2607 mutex_unlock(&obj->mm.lock);
2611 /* The 'mapping' part of i915_gem_object_pin_map() below */
2612 static void *i915_gem_object_map(const struct drm_i915_gem_object *obj,
2613 enum i915_map_type type)
2615 unsigned long n_pages = obj->base.size >> PAGE_SHIFT;
2616 struct sg_table *sgt = obj->mm.pages;
2617 struct sgt_iter sgt_iter;
2619 struct page *stack_pages[32];
2620 struct page **pages = stack_pages;
2621 unsigned long i = 0;
2625 /* A single page can always be kmapped */
2626 if (n_pages == 1 && type == I915_MAP_WB)
2627 return kmap(sg_page(sgt->sgl));
2629 if (n_pages > ARRAY_SIZE(stack_pages)) {
2630 /* Too big for stack -- allocate temporary array instead */
2631 pages = kvmalloc_array(n_pages, sizeof(*pages), GFP_KERNEL);
2636 for_each_sgt_page(page, sgt_iter, sgt)
2639 /* Check that we have the expected number of pages */
2640 GEM_BUG_ON(i != n_pages);
2645 /* fallthrough to use PAGE_KERNEL anyway */
2647 pgprot = PAGE_KERNEL;
2650 pgprot = pgprot_writecombine(PAGE_KERNEL_IO);
2653 addr = vmap(pages, n_pages, 0, pgprot);
2655 if (pages != stack_pages)
2661 /* get, pin, and map the pages of the object into kernel space */
2662 void *i915_gem_object_pin_map(struct drm_i915_gem_object *obj,
2663 enum i915_map_type type)
2665 enum i915_map_type has_type;
2670 GEM_BUG_ON(!i915_gem_object_has_struct_page(obj));
2672 ret = mutex_lock_interruptible(&obj->mm.lock);
2674 return ERR_PTR(ret);
2676 pinned = !(type & I915_MAP_OVERRIDE);
2677 type &= ~I915_MAP_OVERRIDE;
2679 if (!atomic_inc_not_zero(&obj->mm.pages_pin_count)) {
2680 if (unlikely(!i915_gem_object_has_pages(obj))) {
2681 GEM_BUG_ON(i915_gem_object_has_pinned_pages(obj));
2683 ret = ____i915_gem_object_get_pages(obj);
2687 smp_mb__before_atomic();
2689 atomic_inc(&obj->mm.pages_pin_count);
2692 GEM_BUG_ON(!i915_gem_object_has_pages(obj));
2694 ptr = page_unpack_bits(obj->mm.mapping, &has_type);
2695 if (ptr && has_type != type) {
2701 if (is_vmalloc_addr(ptr))
2704 kunmap(kmap_to_page(ptr));
2706 ptr = obj->mm.mapping = NULL;
2710 ptr = i915_gem_object_map(obj, type);
2716 obj->mm.mapping = page_pack_bits(ptr, type);
2720 mutex_unlock(&obj->mm.lock);
2724 atomic_dec(&obj->mm.pages_pin_count);
2731 i915_gem_object_pwrite_gtt(struct drm_i915_gem_object *obj,
2732 const struct drm_i915_gem_pwrite *arg)
2734 struct address_space *mapping = obj->base.filp->f_mapping;
2735 char __user *user_data = u64_to_user_ptr(arg->data_ptr);
2739 /* Before we instantiate/pin the backing store for our use, we
2740 * can prepopulate the shmemfs filp efficiently using a write into
2741 * the pagecache. We avoid the penalty of instantiating all the
2742 * pages, important if the user is just writing to a few and never
2743 * uses the object on the GPU, and using a direct write into shmemfs
2744 * allows it to avoid the cost of retrieving a page (either swapin
2745 * or clearing-before-use) before it is overwritten.
2747 if (i915_gem_object_has_pages(obj))
2750 if (obj->mm.madv != I915_MADV_WILLNEED)
2753 /* Before the pages are instantiated the object is treated as being
2754 * in the CPU domain. The pages will be clflushed as required before
2755 * use, and we can freely write into the pages directly. If userspace
2756 * races pwrite with any other operation; corruption will ensue -
2757 * that is userspace's prerogative!
2761 offset = arg->offset;
2762 pg = offset_in_page(offset);
2765 unsigned int len, unwritten;
2770 len = PAGE_SIZE - pg;
2774 err = pagecache_write_begin(obj->base.filp, mapping,
2781 unwritten = copy_from_user(vaddr + pg, user_data, len);
2784 err = pagecache_write_end(obj->base.filp, mapping,
2785 offset, len, len - unwritten,
2802 static bool ban_context(const struct i915_gem_context *ctx,
2805 return (i915_gem_context_is_bannable(ctx) &&
2806 score >= CONTEXT_SCORE_BAN_THRESHOLD);
2809 static void i915_gem_context_mark_guilty(struct i915_gem_context *ctx)
2814 atomic_inc(&ctx->guilty_count);
2816 score = atomic_add_return(CONTEXT_SCORE_GUILTY, &ctx->ban_score);
2817 banned = ban_context(ctx, score);
2818 DRM_DEBUG_DRIVER("context %s marked guilty (score %d) banned? %s\n",
2819 ctx->name, score, yesno(banned));
2823 i915_gem_context_set_banned(ctx);
2824 if (!IS_ERR_OR_NULL(ctx->file_priv)) {
2825 atomic_inc(&ctx->file_priv->context_bans);
2826 DRM_DEBUG_DRIVER("client %s has had %d context banned\n",
2827 ctx->name, atomic_read(&ctx->file_priv->context_bans));
2831 static void i915_gem_context_mark_innocent(struct i915_gem_context *ctx)
2833 atomic_inc(&ctx->active_count);
2836 struct drm_i915_gem_request *
2837 i915_gem_find_active_request(struct intel_engine_cs *engine)
2839 struct drm_i915_gem_request *request, *active = NULL;
2840 unsigned long flags;
2842 /* We are called by the error capture and reset at a random
2843 * point in time. In particular, note that neither is crucially
2844 * ordered with an interrupt. After a hang, the GPU is dead and we
2845 * assume that no more writes can happen (we waited long enough for
2846 * all writes that were in transaction to be flushed) - adding an
2847 * extra delay for a recent interrupt is pointless. Hence, we do
2848 * not need an engine->irq_seqno_barrier() before the seqno reads.
2850 spin_lock_irqsave(&engine->timeline->lock, flags);
2851 list_for_each_entry(request, &engine->timeline->requests, link) {
2852 if (__i915_gem_request_completed(request,
2853 request->global_seqno))
2856 GEM_BUG_ON(request->engine != engine);
2857 GEM_BUG_ON(test_bit(DMA_FENCE_FLAG_SIGNALED_BIT,
2858 &request->fence.flags));
2863 spin_unlock_irqrestore(&engine->timeline->lock, flags);
2868 static bool engine_stalled(struct intel_engine_cs *engine)
2870 if (!engine->hangcheck.stalled)
2873 /* Check for possible seqno movement after hang declaration */
2874 if (engine->hangcheck.seqno != intel_engine_get_seqno(engine)) {
2875 DRM_DEBUG_DRIVER("%s pardoned\n", engine->name);
2883 * Ensure irq handler finishes, and not run again.
2884 * Also return the active request so that we only search for it once.
2886 struct drm_i915_gem_request *
2887 i915_gem_reset_prepare_engine(struct intel_engine_cs *engine)
2889 struct drm_i915_gem_request *request = NULL;
2892 * During the reset sequence, we must prevent the engine from
2893 * entering RC6. As the context state is undefined until we restart
2894 * the engine, if it does enter RC6 during the reset, the state
2895 * written to the powercontext is undefined and so we may lose
2896 * GPU state upon resume, i.e. fail to restart after a reset.
2898 intel_uncore_forcewake_get(engine->i915, FORCEWAKE_ALL);
2901 * Prevent the signaler thread from updating the request
2902 * state (by calling dma_fence_signal) as we are processing
2903 * the reset. The write from the GPU of the seqno is
2904 * asynchronous and the signaler thread may see a different
2905 * value to us and declare the request complete, even though
2906 * the reset routine have picked that request as the active
2907 * (incomplete) request. This conflict is not handled
2910 kthread_park(engine->breadcrumbs.signaler);
2913 * Prevent request submission to the hardware until we have
2914 * completed the reset in i915_gem_reset_finish(). If a request
2915 * is completed by one engine, it may then queue a request
2916 * to a second via its engine->irq_tasklet *just* as we are
2917 * calling engine->init_hw() and also writing the ELSP.
2918 * Turning off the engine->irq_tasklet until the reset is over
2919 * prevents the race.
2921 tasklet_kill(&engine->execlists.irq_tasklet);
2922 tasklet_disable(&engine->execlists.irq_tasklet);
2924 if (engine->irq_seqno_barrier)
2925 engine->irq_seqno_barrier(engine);
2927 request = i915_gem_find_active_request(engine);
2928 if (request && request->fence.error == -EIO)
2929 request = ERR_PTR(-EIO); /* Previous reset failed! */
2934 int i915_gem_reset_prepare(struct drm_i915_private *dev_priv)
2936 struct intel_engine_cs *engine;
2937 struct drm_i915_gem_request *request;
2938 enum intel_engine_id id;
2941 for_each_engine(engine, dev_priv, id) {
2942 request = i915_gem_reset_prepare_engine(engine);
2943 if (IS_ERR(request)) {
2944 err = PTR_ERR(request);
2948 engine->hangcheck.active_request = request;
2951 i915_gem_revoke_fences(dev_priv);
2956 static void skip_request(struct drm_i915_gem_request *request)
2958 void *vaddr = request->ring->vaddr;
2961 /* As this request likely depends on state from the lost
2962 * context, clear out all the user operations leaving the
2963 * breadcrumb at the end (so we get the fence notifications).
2965 head = request->head;
2966 if (request->postfix < head) {
2967 memset(vaddr + head, 0, request->ring->size - head);
2970 memset(vaddr + head, 0, request->postfix - head);
2972 dma_fence_set_error(&request->fence, -EIO);
2975 static void engine_skip_context(struct drm_i915_gem_request *request)
2977 struct intel_engine_cs *engine = request->engine;
2978 struct i915_gem_context *hung_ctx = request->ctx;
2979 struct intel_timeline *timeline;
2980 unsigned long flags;
2982 timeline = i915_gem_context_lookup_timeline(hung_ctx, engine);
2984 spin_lock_irqsave(&engine->timeline->lock, flags);
2985 spin_lock(&timeline->lock);
2987 list_for_each_entry_continue(request, &engine->timeline->requests, link)
2988 if (request->ctx == hung_ctx)
2989 skip_request(request);
2991 list_for_each_entry(request, &timeline->requests, link)
2992 skip_request(request);
2994 spin_unlock(&timeline->lock);
2995 spin_unlock_irqrestore(&engine->timeline->lock, flags);
2998 /* Returns the request if it was guilty of the hang */
2999 static struct drm_i915_gem_request *
3000 i915_gem_reset_request(struct intel_engine_cs *engine,
3001 struct drm_i915_gem_request *request)
3003 /* The guilty request will get skipped on a hung engine.
3005 * Users of client default contexts do not rely on logical
3006 * state preserved between batches so it is safe to execute
3007 * queued requests following the hang. Non default contexts
3008 * rely on preserved state, so skipping a batch loses the
3009 * evolution of the state and it needs to be considered corrupted.
3010 * Executing more queued batches on top of corrupted state is
3011 * risky. But we take the risk by trying to advance through
3012 * the queued requests in order to make the client behaviour
3013 * more predictable around resets, by not throwing away random
3014 * amount of batches it has prepared for execution. Sophisticated
3015 * clients can use gem_reset_stats_ioctl and dma fence status
3016 * (exported via sync_file info ioctl on explicit fences) to observe
3017 * when it loses the context state and should rebuild accordingly.
3019 * The context ban, and ultimately the client ban, mechanism are safety
3020 * valves if client submission ends up resulting in nothing more than
3024 if (engine_stalled(engine)) {
3025 i915_gem_context_mark_guilty(request->ctx);
3026 skip_request(request);
3028 /* If this context is now banned, skip all pending requests. */
3029 if (i915_gem_context_is_banned(request->ctx))
3030 engine_skip_context(request);
3033 * Since this is not the hung engine, it may have advanced
3034 * since the hang declaration. Double check by refinding
3035 * the active request at the time of the reset.
3037 request = i915_gem_find_active_request(engine);
3039 i915_gem_context_mark_innocent(request->ctx);
3040 dma_fence_set_error(&request->fence, -EAGAIN);
3042 /* Rewind the engine to replay the incomplete rq */
3043 spin_lock_irq(&engine->timeline->lock);
3044 request = list_prev_entry(request, link);
3045 if (&request->link == &engine->timeline->requests)
3047 spin_unlock_irq(&engine->timeline->lock);
3054 void i915_gem_reset_engine(struct intel_engine_cs *engine,
3055 struct drm_i915_gem_request *request)
3057 engine->irq_posted = 0;
3060 request = i915_gem_reset_request(engine, request);
3063 DRM_DEBUG_DRIVER("resetting %s to restart from tail of request 0x%x\n",
3064 engine->name, request->global_seqno);
3067 /* Setup the CS to resume from the breadcrumb of the hung request */
3068 engine->reset_hw(engine, request);
3071 void i915_gem_reset(struct drm_i915_private *dev_priv)
3073 struct intel_engine_cs *engine;
3074 enum intel_engine_id id;
3076 lockdep_assert_held(&dev_priv->drm.struct_mutex);
3078 i915_gem_retire_requests(dev_priv);
3080 for_each_engine(engine, dev_priv, id) {
3081 struct i915_gem_context *ctx;
3083 i915_gem_reset_engine(engine, engine->hangcheck.active_request);
3084 ctx = fetch_and_zero(&engine->last_retired_context);
3086 engine->context_unpin(engine, ctx);
3089 i915_gem_restore_fences(dev_priv);
3091 if (dev_priv->gt.awake) {
3092 intel_sanitize_gt_powersave(dev_priv);
3093 intel_enable_gt_powersave(dev_priv);
3094 if (INTEL_GEN(dev_priv) >= 6)
3095 gen6_rps_busy(dev_priv);
3099 void i915_gem_reset_finish_engine(struct intel_engine_cs *engine)
3101 tasklet_enable(&engine->execlists.irq_tasklet);
3102 kthread_unpark(engine->breadcrumbs.signaler);
3104 intel_uncore_forcewake_put(engine->i915, FORCEWAKE_ALL);
3107 void i915_gem_reset_finish(struct drm_i915_private *dev_priv)
3109 struct intel_engine_cs *engine;
3110 enum intel_engine_id id;
3112 lockdep_assert_held(&dev_priv->drm.struct_mutex);
3114 for_each_engine(engine, dev_priv, id) {
3115 engine->hangcheck.active_request = NULL;
3116 i915_gem_reset_finish_engine(engine);
3120 static void nop_submit_request(struct drm_i915_gem_request *request)
3122 dma_fence_set_error(&request->fence, -EIO);
3124 i915_gem_request_submit(request);
3127 static void nop_complete_submit_request(struct drm_i915_gem_request *request)
3129 unsigned long flags;
3131 dma_fence_set_error(&request->fence, -EIO);
3133 spin_lock_irqsave(&request->engine->timeline->lock, flags);
3134 __i915_gem_request_submit(request);
3135 intel_engine_init_global_seqno(request->engine, request->global_seqno);
3136 spin_unlock_irqrestore(&request->engine->timeline->lock, flags);
3139 void i915_gem_set_wedged(struct drm_i915_private *i915)
3141 struct intel_engine_cs *engine;
3142 enum intel_engine_id id;
3145 * First, stop submission to hw, but do not yet complete requests by
3146 * rolling the global seqno forward (since this would complete requests
3147 * for which we haven't set the fence error to EIO yet).
3149 for_each_engine(engine, i915, id)
3150 engine->submit_request = nop_submit_request;
3153 * Make sure no one is running the old callback before we proceed with
3154 * cancelling requests and resetting the completion tracking. Otherwise
3155 * we might submit a request to the hardware which never completes.
3159 for_each_engine(engine, i915, id) {
3160 /* Mark all executing requests as skipped */
3161 engine->cancel_requests(engine);
3164 * Only once we've force-cancelled all in-flight requests can we
3165 * start to complete all requests.
3167 engine->submit_request = nop_complete_submit_request;
3171 * Make sure no request can slip through without getting completed by
3172 * either this call here to intel_engine_init_global_seqno, or the one
3173 * in nop_complete_submit_request.
3177 for_each_engine(engine, i915, id) {
3178 unsigned long flags;
3180 /* Mark all pending requests as complete so that any concurrent
3181 * (lockless) lookup doesn't try and wait upon the request as we
3184 spin_lock_irqsave(&engine->timeline->lock, flags);
3185 intel_engine_init_global_seqno(engine,
3186 intel_engine_last_submit(engine));
3187 spin_unlock_irqrestore(&engine->timeline->lock, flags);
3190 set_bit(I915_WEDGED, &i915->gpu_error.flags);
3191 wake_up_all(&i915->gpu_error.reset_queue);
3194 bool i915_gem_unset_wedged(struct drm_i915_private *i915)
3196 struct i915_gem_timeline *tl;
3199 lockdep_assert_held(&i915->drm.struct_mutex);
3200 if (!test_bit(I915_WEDGED, &i915->gpu_error.flags))
3203 /* Before unwedging, make sure that all pending operations
3204 * are flushed and errored out - we may have requests waiting upon
3205 * third party fences. We marked all inflight requests as EIO, and
3206 * every execbuf since returned EIO, for consistency we want all
3207 * the currently pending requests to also be marked as EIO, which
3208 * is done inside our nop_submit_request - and so we must wait.
3210 * No more can be submitted until we reset the wedged bit.
3212 list_for_each_entry(tl, &i915->gt.timelines, link) {
3213 for (i = 0; i < ARRAY_SIZE(tl->engine); i++) {
3214 struct drm_i915_gem_request *rq;
3216 rq = i915_gem_active_peek(&tl->engine[i].last_request,
3217 &i915->drm.struct_mutex);
3221 /* We can't use our normal waiter as we want to
3222 * avoid recursively trying to handle the current
3223 * reset. The basic dma_fence_default_wait() installs
3224 * a callback for dma_fence_signal(), which is
3225 * triggered by our nop handler (indirectly, the
3226 * callback enables the signaler thread which is
3227 * woken by the nop_submit_request() advancing the seqno
3228 * and when the seqno passes the fence, the signaler
3229 * then signals the fence waking us up).
3231 if (dma_fence_default_wait(&rq->fence, true,
3232 MAX_SCHEDULE_TIMEOUT) < 0)
3237 /* Undo nop_submit_request. We prevent all new i915 requests from
3238 * being queued (by disallowing execbuf whilst wedged) so having
3239 * waited for all active requests above, we know the system is idle
3240 * and do not have to worry about a thread being inside
3241 * engine->submit_request() as we swap over. So unlike installing
3242 * the nop_submit_request on reset, we can do this from normal
3243 * context and do not require stop_machine().
3245 intel_engines_reset_default_submission(i915);
3246 i915_gem_contexts_lost(i915);
3248 smp_mb__before_atomic(); /* complete takeover before enabling execbuf */
3249 clear_bit(I915_WEDGED, &i915->gpu_error.flags);
3255 i915_gem_retire_work_handler(struct work_struct *work)
3257 struct drm_i915_private *dev_priv =
3258 container_of(work, typeof(*dev_priv), gt.retire_work.work);
3259 struct drm_device *dev = &dev_priv->drm;
3261 /* Come back later if the device is busy... */
3262 if (mutex_trylock(&dev->struct_mutex)) {
3263 i915_gem_retire_requests(dev_priv);
3264 mutex_unlock(&dev->struct_mutex);
3267 /* Keep the retire handler running until we are finally idle.
3268 * We do not need to do this test under locking as in the worst-case
3269 * we queue the retire worker once too often.
3271 if (READ_ONCE(dev_priv->gt.awake)) {
3272 i915_queue_hangcheck(dev_priv);
3273 queue_delayed_work(dev_priv->wq,
3274 &dev_priv->gt.retire_work,
3275 round_jiffies_up_relative(HZ));
3280 i915_gem_idle_work_handler(struct work_struct *work)
3282 struct drm_i915_private *dev_priv =
3283 container_of(work, typeof(*dev_priv), gt.idle_work.work);
3284 struct drm_device *dev = &dev_priv->drm;
3285 bool rearm_hangcheck;
3287 if (!READ_ONCE(dev_priv->gt.awake))
3291 * Wait for last execlists context complete, but bail out in case a
3292 * new request is submitted.
3294 wait_for(intel_engines_are_idle(dev_priv), 10);
3295 if (READ_ONCE(dev_priv->gt.active_requests))
3299 cancel_delayed_work_sync(&dev_priv->gpu_error.hangcheck_work);
3301 if (!mutex_trylock(&dev->struct_mutex)) {
3302 /* Currently busy, come back later */
3303 mod_delayed_work(dev_priv->wq,
3304 &dev_priv->gt.idle_work,
3305 msecs_to_jiffies(50));
3310 * New request retired after this work handler started, extend active
3311 * period until next instance of the work.
3313 if (work_pending(work))
3316 if (dev_priv->gt.active_requests)
3319 if (wait_for(intel_engines_are_idle(dev_priv), 10))
3320 DRM_ERROR("Timeout waiting for engines to idle\n");
3322 intel_engines_mark_idle(dev_priv);
3323 i915_gem_timelines_mark_idle(dev_priv);
3325 GEM_BUG_ON(!dev_priv->gt.awake);
3326 dev_priv->gt.awake = false;
3327 rearm_hangcheck = false;
3329 if (INTEL_GEN(dev_priv) >= 6)
3330 gen6_rps_idle(dev_priv);
3331 intel_runtime_pm_put(dev_priv);
3333 mutex_unlock(&dev->struct_mutex);
3336 if (rearm_hangcheck) {
3337 GEM_BUG_ON(!dev_priv->gt.awake);
3338 i915_queue_hangcheck(dev_priv);
3342 void i915_gem_close_object(struct drm_gem_object *gem, struct drm_file *file)
3344 struct drm_i915_private *i915 = to_i915(gem->dev);
3345 struct drm_i915_gem_object *obj = to_intel_bo(gem);
3346 struct drm_i915_file_private *fpriv = file->driver_priv;
3347 struct i915_lut_handle *lut, *ln;
3349 mutex_lock(&i915->drm.struct_mutex);
3351 list_for_each_entry_safe(lut, ln, &obj->lut_list, obj_link) {
3352 struct i915_gem_context *ctx = lut->ctx;
3353 struct i915_vma *vma;
3355 GEM_BUG_ON(ctx->file_priv == ERR_PTR(-EBADF));
3356 if (ctx->file_priv != fpriv)
3359 vma = radix_tree_delete(&ctx->handles_vma, lut->handle);
3360 GEM_BUG_ON(vma->obj != obj);
3362 /* We allow the process to have multiple handles to the same
3363 * vma, in the same fd namespace, by virtue of flink/open.
3365 GEM_BUG_ON(!vma->open_count);
3366 if (!--vma->open_count && !i915_vma_is_ggtt(vma))
3367 i915_vma_close(vma);
3369 list_del(&lut->obj_link);
3370 list_del(&lut->ctx_link);
3372 kmem_cache_free(i915->luts, lut);
3373 __i915_gem_object_release_unless_active(obj);
3376 mutex_unlock(&i915->drm.struct_mutex);
3379 static unsigned long to_wait_timeout(s64 timeout_ns)
3382 return MAX_SCHEDULE_TIMEOUT;
3384 if (timeout_ns == 0)
3387 return nsecs_to_jiffies_timeout(timeout_ns);
3391 * i915_gem_wait_ioctl - implements DRM_IOCTL_I915_GEM_WAIT
3392 * @dev: drm device pointer
3393 * @data: ioctl data blob
3394 * @file: drm file pointer
3396 * Returns 0 if successful, else an error is returned with the remaining time in
3397 * the timeout parameter.
3398 * -ETIME: object is still busy after timeout
3399 * -ERESTARTSYS: signal interrupted the wait
3400 * -ENONENT: object doesn't exist
3401 * Also possible, but rare:
3402 * -EAGAIN: incomplete, restart syscall
3404 * -ENODEV: Internal IRQ fail
3405 * -E?: The add request failed
3407 * The wait ioctl with a timeout of 0 reimplements the busy ioctl. With any
3408 * non-zero timeout parameter the wait ioctl will wait for the given number of
3409 * nanoseconds on an object becoming unbusy. Since the wait itself does so
3410 * without holding struct_mutex the object may become re-busied before this
3411 * function completes. A similar but shorter * race condition exists in the busy
3415 i915_gem_wait_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
3417 struct drm_i915_gem_wait *args = data;
3418 struct drm_i915_gem_object *obj;
3422 if (args->flags != 0)
3425 obj = i915_gem_object_lookup(file, args->bo_handle);
3429 start = ktime_get();
3431 ret = i915_gem_object_wait(obj,
3432 I915_WAIT_INTERRUPTIBLE | I915_WAIT_ALL,
3433 to_wait_timeout(args->timeout_ns),
3434 to_rps_client(file));
3436 if (args->timeout_ns > 0) {
3437 args->timeout_ns -= ktime_to_ns(ktime_sub(ktime_get(), start));
3438 if (args->timeout_ns < 0)
3439 args->timeout_ns = 0;
3442 * Apparently ktime isn't accurate enough and occasionally has a
3443 * bit of mismatch in the jiffies<->nsecs<->ktime loop. So patch
3444 * things up to make the test happy. We allow up to 1 jiffy.
3446 * This is a regression from the timespec->ktime conversion.
3448 if (ret == -ETIME && !nsecs_to_jiffies(args->timeout_ns))
3449 args->timeout_ns = 0;
3451 /* Asked to wait beyond the jiffie/scheduler precision? */
3452 if (ret == -ETIME && args->timeout_ns)
3456 i915_gem_object_put(obj);
3460 static int wait_for_timeline(struct i915_gem_timeline *tl, unsigned int flags)
3464 for (i = 0; i < ARRAY_SIZE(tl->engine); i++) {
3465 ret = i915_gem_active_wait(&tl->engine[i].last_request, flags);
3473 static int wait_for_engines(struct drm_i915_private *i915)
3475 if (wait_for(intel_engines_are_idle(i915), 50)) {
3476 DRM_ERROR("Failed to idle engines, declaring wedged!\n");
3477 i915_gem_set_wedged(i915);
3484 int i915_gem_wait_for_idle(struct drm_i915_private *i915, unsigned int flags)
3488 /* If the device is asleep, we have no requests outstanding */
3489 if (!READ_ONCE(i915->gt.awake))
3492 if (flags & I915_WAIT_LOCKED) {
3493 struct i915_gem_timeline *tl;
3495 lockdep_assert_held(&i915->drm.struct_mutex);
3497 list_for_each_entry(tl, &i915->gt.timelines, link) {
3498 ret = wait_for_timeline(tl, flags);
3503 i915_gem_retire_requests(i915);
3504 GEM_BUG_ON(i915->gt.active_requests);
3506 ret = wait_for_engines(i915);
3508 ret = wait_for_timeline(&i915->gt.global_timeline, flags);
3514 static void __i915_gem_object_flush_for_display(struct drm_i915_gem_object *obj)
3517 * We manually flush the CPU domain so that we can override and
3518 * force the flush for the display, and perform it asyncrhonously.
3520 flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
3521 if (obj->cache_dirty)
3522 i915_gem_clflush_object(obj, I915_CLFLUSH_FORCE);
3523 obj->base.write_domain = 0;
3526 void i915_gem_object_flush_if_display(struct drm_i915_gem_object *obj)
3528 if (!READ_ONCE(obj->pin_global))
3531 mutex_lock(&obj->base.dev->struct_mutex);
3532 __i915_gem_object_flush_for_display(obj);
3533 mutex_unlock(&obj->base.dev->struct_mutex);
3537 * Moves a single object to the WC read, and possibly write domain.
3538 * @obj: object to act on
3539 * @write: ask for write access or read only
3541 * This function returns when the move is complete, including waiting on
3545 i915_gem_object_set_to_wc_domain(struct drm_i915_gem_object *obj, bool write)
3549 lockdep_assert_held(&obj->base.dev->struct_mutex);
3551 ret = i915_gem_object_wait(obj,
3552 I915_WAIT_INTERRUPTIBLE |
3554 (write ? I915_WAIT_ALL : 0),
3555 MAX_SCHEDULE_TIMEOUT,
3560 if (obj->base.write_domain == I915_GEM_DOMAIN_WC)
3563 /* Flush and acquire obj->pages so that we are coherent through
3564 * direct access in memory with previous cached writes through
3565 * shmemfs and that our cache domain tracking remains valid.
3566 * For example, if the obj->filp was moved to swap without us
3567 * being notified and releasing the pages, we would mistakenly
3568 * continue to assume that the obj remained out of the CPU cached
3571 ret = i915_gem_object_pin_pages(obj);
3575 flush_write_domain(obj, ~I915_GEM_DOMAIN_WC);
3577 /* Serialise direct access to this object with the barriers for
3578 * coherent writes from the GPU, by effectively invalidating the
3579 * WC domain upon first access.
3581 if ((obj->base.read_domains & I915_GEM_DOMAIN_WC) == 0)
3584 /* It should now be out of any other write domains, and we can update
3585 * the domain values for our changes.
3587 GEM_BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_WC) != 0);
3588 obj->base.read_domains |= I915_GEM_DOMAIN_WC;
3590 obj->base.read_domains = I915_GEM_DOMAIN_WC;
3591 obj->base.write_domain = I915_GEM_DOMAIN_WC;
3592 obj->mm.dirty = true;
3595 i915_gem_object_unpin_pages(obj);
3600 * Moves a single object to the GTT read, and possibly write domain.
3601 * @obj: object to act on
3602 * @write: ask for write access or read only
3604 * This function returns when the move is complete, including waiting on
3608 i915_gem_object_set_to_gtt_domain(struct drm_i915_gem_object *obj, bool write)
3612 lockdep_assert_held(&obj->base.dev->struct_mutex);
3614 ret = i915_gem_object_wait(obj,
3615 I915_WAIT_INTERRUPTIBLE |
3617 (write ? I915_WAIT_ALL : 0),
3618 MAX_SCHEDULE_TIMEOUT,
3623 if (obj->base.write_domain == I915_GEM_DOMAIN_GTT)
3626 /* Flush and acquire obj->pages so that we are coherent through
3627 * direct access in memory with previous cached writes through
3628 * shmemfs and that our cache domain tracking remains valid.
3629 * For example, if the obj->filp was moved to swap without us
3630 * being notified and releasing the pages, we would mistakenly
3631 * continue to assume that the obj remained out of the CPU cached
3634 ret = i915_gem_object_pin_pages(obj);
3638 flush_write_domain(obj, ~I915_GEM_DOMAIN_GTT);
3640 /* Serialise direct access to this object with the barriers for
3641 * coherent writes from the GPU, by effectively invalidating the
3642 * GTT domain upon first access.
3644 if ((obj->base.read_domains & I915_GEM_DOMAIN_GTT) == 0)
3647 /* It should now be out of any other write domains, and we can update
3648 * the domain values for our changes.
3650 GEM_BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
3651 obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
3653 obj->base.read_domains = I915_GEM_DOMAIN_GTT;
3654 obj->base.write_domain = I915_GEM_DOMAIN_GTT;
3655 obj->mm.dirty = true;
3658 i915_gem_object_unpin_pages(obj);
3663 * Changes the cache-level of an object across all VMA.
3664 * @obj: object to act on
3665 * @cache_level: new cache level to set for the object
3667 * After this function returns, the object will be in the new cache-level
3668 * across all GTT and the contents of the backing storage will be coherent,
3669 * with respect to the new cache-level. In order to keep the backing storage
3670 * coherent for all users, we only allow a single cache level to be set
3671 * globally on the object and prevent it from being changed whilst the
3672 * hardware is reading from the object. That is if the object is currently
3673 * on the scanout it will be set to uncached (or equivalent display
3674 * cache coherency) and all non-MOCS GPU access will also be uncached so
3675 * that all direct access to the scanout remains coherent.
3677 int i915_gem_object_set_cache_level(struct drm_i915_gem_object *obj,
3678 enum i915_cache_level cache_level)
3680 struct i915_vma *vma;
3683 lockdep_assert_held(&obj->base.dev->struct_mutex);
3685 if (obj->cache_level == cache_level)
3688 /* Inspect the list of currently bound VMA and unbind any that would
3689 * be invalid given the new cache-level. This is principally to
3690 * catch the issue of the CS prefetch crossing page boundaries and
3691 * reading an invalid PTE on older architectures.
3694 list_for_each_entry(vma, &obj->vma_list, obj_link) {
3695 if (!drm_mm_node_allocated(&vma->node))
3698 if (i915_vma_is_pinned(vma)) {
3699 DRM_DEBUG("can not change the cache level of pinned objects\n");
3703 if (i915_gem_valid_gtt_space(vma, cache_level))
3706 ret = i915_vma_unbind(vma);
3710 /* As unbinding may affect other elements in the
3711 * obj->vma_list (due to side-effects from retiring
3712 * an active vma), play safe and restart the iterator.
3717 /* We can reuse the existing drm_mm nodes but need to change the
3718 * cache-level on the PTE. We could simply unbind them all and
3719 * rebind with the correct cache-level on next use. However since
3720 * we already have a valid slot, dma mapping, pages etc, we may as
3721 * rewrite the PTE in the belief that doing so tramples upon less
3722 * state and so involves less work.
3724 if (obj->bind_count) {
3725 /* Before we change the PTE, the GPU must not be accessing it.
3726 * If we wait upon the object, we know that all the bound
3727 * VMA are no longer active.
3729 ret = i915_gem_object_wait(obj,
3730 I915_WAIT_INTERRUPTIBLE |
3733 MAX_SCHEDULE_TIMEOUT,
3738 if (!HAS_LLC(to_i915(obj->base.dev)) &&
3739 cache_level != I915_CACHE_NONE) {
3740 /* Access to snoopable pages through the GTT is
3741 * incoherent and on some machines causes a hard
3742 * lockup. Relinquish the CPU mmaping to force
3743 * userspace to refault in the pages and we can
3744 * then double check if the GTT mapping is still
3745 * valid for that pointer access.
3747 i915_gem_release_mmap(obj);
3749 /* As we no longer need a fence for GTT access,
3750 * we can relinquish it now (and so prevent having
3751 * to steal a fence from someone else on the next
3752 * fence request). Note GPU activity would have
3753 * dropped the fence as all snoopable access is
3754 * supposed to be linear.
3756 list_for_each_entry(vma, &obj->vma_list, obj_link) {
3757 ret = i915_vma_put_fence(vma);
3762 /* We either have incoherent backing store and
3763 * so no GTT access or the architecture is fully
3764 * coherent. In such cases, existing GTT mmaps
3765 * ignore the cache bit in the PTE and we can
3766 * rewrite it without confusing the GPU or having
3767 * to force userspace to fault back in its mmaps.
3771 list_for_each_entry(vma, &obj->vma_list, obj_link) {
3772 if (!drm_mm_node_allocated(&vma->node))
3775 ret = i915_vma_bind(vma, cache_level, PIN_UPDATE);
3781 list_for_each_entry(vma, &obj->vma_list, obj_link)
3782 vma->node.color = cache_level;
3783 i915_gem_object_set_cache_coherency(obj, cache_level);
3784 obj->cache_dirty = true; /* Always invalidate stale cachelines */
3789 int i915_gem_get_caching_ioctl(struct drm_device *dev, void *data,
3790 struct drm_file *file)
3792 struct drm_i915_gem_caching *args = data;
3793 struct drm_i915_gem_object *obj;
3797 obj = i915_gem_object_lookup_rcu(file, args->handle);
3803 switch (obj->cache_level) {
3804 case I915_CACHE_LLC:
3805 case I915_CACHE_L3_LLC:
3806 args->caching = I915_CACHING_CACHED;
3810 args->caching = I915_CACHING_DISPLAY;
3814 args->caching = I915_CACHING_NONE;
3822 int i915_gem_set_caching_ioctl(struct drm_device *dev, void *data,
3823 struct drm_file *file)
3825 struct drm_i915_private *i915 = to_i915(dev);
3826 struct drm_i915_gem_caching *args = data;
3827 struct drm_i915_gem_object *obj;
3828 enum i915_cache_level level;
3831 switch (args->caching) {
3832 case I915_CACHING_NONE:
3833 level = I915_CACHE_NONE;
3835 case I915_CACHING_CACHED:
3837 * Due to a HW issue on BXT A stepping, GPU stores via a
3838 * snooped mapping may leave stale data in a corresponding CPU
3839 * cacheline, whereas normally such cachelines would get
3842 if (!HAS_LLC(i915) && !HAS_SNOOP(i915))
3845 level = I915_CACHE_LLC;
3847 case I915_CACHING_DISPLAY:
3848 level = HAS_WT(i915) ? I915_CACHE_WT : I915_CACHE_NONE;
3854 obj = i915_gem_object_lookup(file, args->handle);
3858 if (obj->cache_level == level)
3861 ret = i915_gem_object_wait(obj,
3862 I915_WAIT_INTERRUPTIBLE,
3863 MAX_SCHEDULE_TIMEOUT,
3864 to_rps_client(file));
3868 ret = i915_mutex_lock_interruptible(dev);
3872 ret = i915_gem_object_set_cache_level(obj, level);
3873 mutex_unlock(&dev->struct_mutex);
3876 i915_gem_object_put(obj);
3881 * Prepare buffer for display plane (scanout, cursors, etc).
3882 * Can be called from an uninterruptible phase (modesetting) and allows
3883 * any flushes to be pipelined (for pageflips).
3886 i915_gem_object_pin_to_display_plane(struct drm_i915_gem_object *obj,
3888 const struct i915_ggtt_view *view)
3890 struct i915_vma *vma;
3893 lockdep_assert_held(&obj->base.dev->struct_mutex);
3895 /* Mark the global pin early so that we account for the
3896 * display coherency whilst setting up the cache domains.
3900 /* The display engine is not coherent with the LLC cache on gen6. As
3901 * a result, we make sure that the pinning that is about to occur is
3902 * done with uncached PTEs. This is lowest common denominator for all
3905 * However for gen6+, we could do better by using the GFDT bit instead
3906 * of uncaching, which would allow us to flush all the LLC-cached data
3907 * with that bit in the PTE to main memory with just one PIPE_CONTROL.
3909 ret = i915_gem_object_set_cache_level(obj,
3910 HAS_WT(to_i915(obj->base.dev)) ?
3911 I915_CACHE_WT : I915_CACHE_NONE);
3914 goto err_unpin_global;
3917 /* As the user may map the buffer once pinned in the display plane
3918 * (e.g. libkms for the bootup splash), we have to ensure that we
3919 * always use map_and_fenceable for all scanout buffers. However,
3920 * it may simply be too big to fit into mappable, in which case
3921 * put it anyway and hope that userspace can cope (but always first
3922 * try to preserve the existing ABI).
3924 vma = ERR_PTR(-ENOSPC);
3925 if (!view || view->type == I915_GGTT_VIEW_NORMAL)
3926 vma = i915_gem_object_ggtt_pin(obj, view, 0, alignment,
3927 PIN_MAPPABLE | PIN_NONBLOCK);
3929 struct drm_i915_private *i915 = to_i915(obj->base.dev);
3932 /* Valleyview is definitely limited to scanning out the first
3933 * 512MiB. Lets presume this behaviour was inherited from the
3934 * g4x display engine and that all earlier gen are similarly
3935 * limited. Testing suggests that it is a little more
3936 * complicated than this. For example, Cherryview appears quite
3937 * happy to scanout from anywhere within its global aperture.
3940 if (HAS_GMCH_DISPLAY(i915))
3941 flags = PIN_MAPPABLE;
3942 vma = i915_gem_object_ggtt_pin(obj, view, 0, alignment, flags);
3945 goto err_unpin_global;
3947 vma->display_alignment = max_t(u64, vma->display_alignment, alignment);
3949 /* Treat this as an end-of-frame, like intel_user_framebuffer_dirty() */
3950 __i915_gem_object_flush_for_display(obj);
3951 intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
3953 /* It should now be out of any other write domains, and we can update
3954 * the domain values for our changes.
3956 obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
3966 i915_gem_object_unpin_from_display_plane(struct i915_vma *vma)
3968 lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
3970 if (WARN_ON(vma->obj->pin_global == 0))
3973 if (--vma->obj->pin_global == 0)
3974 vma->display_alignment = I915_GTT_MIN_ALIGNMENT;
3976 /* Bump the LRU to try and avoid premature eviction whilst flipping */
3977 i915_gem_object_bump_inactive_ggtt(vma->obj);
3979 i915_vma_unpin(vma);
3983 * Moves a single object to the CPU read, and possibly write domain.
3984 * @obj: object to act on
3985 * @write: requesting write or read-only access
3987 * This function returns when the move is complete, including waiting on
3991 i915_gem_object_set_to_cpu_domain(struct drm_i915_gem_object *obj, bool write)
3995 lockdep_assert_held(&obj->base.dev->struct_mutex);
3997 ret = i915_gem_object_wait(obj,
3998 I915_WAIT_INTERRUPTIBLE |
4000 (write ? I915_WAIT_ALL : 0),
4001 MAX_SCHEDULE_TIMEOUT,
4006 flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
4008 /* Flush the CPU cache if it's still invalid. */
4009 if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0) {
4010 i915_gem_clflush_object(obj, I915_CLFLUSH_SYNC);
4011 obj->base.read_domains |= I915_GEM_DOMAIN_CPU;
4014 /* It should now be out of any other write domains, and we can update
4015 * the domain values for our changes.
4017 GEM_BUG_ON(obj->base.write_domain & ~I915_GEM_DOMAIN_CPU);
4019 /* If we're writing through the CPU, then the GPU read domains will
4020 * need to be invalidated at next use.
4023 __start_cpu_write(obj);
4028 /* Throttle our rendering by waiting until the ring has completed our requests
4029 * emitted over 20 msec ago.
4031 * Note that if we were to use the current jiffies each time around the loop,
4032 * we wouldn't escape the function with any frames outstanding if the time to
4033 * render a frame was over 20ms.
4035 * This should get us reasonable parallelism between CPU and GPU but also
4036 * relatively low latency when blocking on a particular request to finish.
4039 i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file)
4041 struct drm_i915_private *dev_priv = to_i915(dev);
4042 struct drm_i915_file_private *file_priv = file->driver_priv;
4043 unsigned long recent_enough = jiffies - DRM_I915_THROTTLE_JIFFIES;
4044 struct drm_i915_gem_request *request, *target = NULL;
4047 /* ABI: return -EIO if already wedged */
4048 if (i915_terminally_wedged(&dev_priv->gpu_error))
4051 spin_lock(&file_priv->mm.lock);
4052 list_for_each_entry(request, &file_priv->mm.request_list, client_link) {
4053 if (time_after_eq(request->emitted_jiffies, recent_enough))
4057 list_del(&target->client_link);
4058 target->file_priv = NULL;
4064 i915_gem_request_get(target);
4065 spin_unlock(&file_priv->mm.lock);
4070 ret = i915_wait_request(target,
4071 I915_WAIT_INTERRUPTIBLE,
4072 MAX_SCHEDULE_TIMEOUT);
4073 i915_gem_request_put(target);
4075 return ret < 0 ? ret : 0;
4079 i915_gem_object_ggtt_pin(struct drm_i915_gem_object *obj,
4080 const struct i915_ggtt_view *view,
4085 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
4086 struct i915_address_space *vm = &dev_priv->ggtt.base;
4087 struct i915_vma *vma;
4090 lockdep_assert_held(&obj->base.dev->struct_mutex);
4092 if (!view && flags & PIN_MAPPABLE) {
4093 /* If the required space is larger than the available
4094 * aperture, we will not able to find a slot for the
4095 * object and unbinding the object now will be in
4096 * vain. Worse, doing so may cause us to ping-pong
4097 * the object in and out of the Global GTT and
4098 * waste a lot of cycles under the mutex.
4100 if (obj->base.size > dev_priv->ggtt.mappable_end)
4101 return ERR_PTR(-E2BIG);
4103 /* If NONBLOCK is set the caller is optimistically
4104 * trying to cache the full object within the mappable
4105 * aperture, and *must* have a fallback in place for
4106 * situations where we cannot bind the object. We
4107 * can be a little more lax here and use the fallback
4108 * more often to avoid costly migrations of ourselves
4109 * and other objects within the aperture.
4111 * Half-the-aperture is used as a simple heuristic.
4112 * More interesting would to do search for a free
4113 * block prior to making the commitment to unbind.
4114 * That caters for the self-harm case, and with a
4115 * little more heuristics (e.g. NOFAULT, NOEVICT)
4116 * we could try to minimise harm to others.
4118 if (flags & PIN_NONBLOCK &&
4119 obj->base.size > dev_priv->ggtt.mappable_end / 2)
4120 return ERR_PTR(-ENOSPC);
4123 vma = i915_vma_instance(obj, vm, view);
4124 if (unlikely(IS_ERR(vma)))
4127 if (i915_vma_misplaced(vma, size, alignment, flags)) {
4128 if (flags & PIN_NONBLOCK) {
4129 if (i915_vma_is_pinned(vma) || i915_vma_is_active(vma))
4130 return ERR_PTR(-ENOSPC);
4132 if (flags & PIN_MAPPABLE &&
4133 vma->fence_size > dev_priv->ggtt.mappable_end / 2)
4134 return ERR_PTR(-ENOSPC);
4137 WARN(i915_vma_is_pinned(vma),
4138 "bo is already pinned in ggtt with incorrect alignment:"
4139 " offset=%08x, req.alignment=%llx,"
4140 " req.map_and_fenceable=%d, vma->map_and_fenceable=%d\n",
4141 i915_ggtt_offset(vma), alignment,
4142 !!(flags & PIN_MAPPABLE),
4143 i915_vma_is_map_and_fenceable(vma));
4144 ret = i915_vma_unbind(vma);
4146 return ERR_PTR(ret);
4149 ret = i915_vma_pin(vma, size, alignment, flags | PIN_GLOBAL);
4151 return ERR_PTR(ret);
4156 static __always_inline unsigned int __busy_read_flag(unsigned int id)
4158 /* Note that we could alias engines in the execbuf API, but
4159 * that would be very unwise as it prevents userspace from
4160 * fine control over engine selection. Ahem.
4162 * This should be something like EXEC_MAX_ENGINE instead of
4165 BUILD_BUG_ON(I915_NUM_ENGINES > 16);
4166 return 0x10000 << id;
4169 static __always_inline unsigned int __busy_write_id(unsigned int id)
4171 /* The uABI guarantees an active writer is also amongst the read
4172 * engines. This would be true if we accessed the activity tracking
4173 * under the lock, but as we perform the lookup of the object and
4174 * its activity locklessly we can not guarantee that the last_write
4175 * being active implies that we have set the same engine flag from
4176 * last_read - hence we always set both read and write busy for
4179 return id | __busy_read_flag(id);
4182 static __always_inline unsigned int
4183 __busy_set_if_active(const struct dma_fence *fence,
4184 unsigned int (*flag)(unsigned int id))
4186 struct drm_i915_gem_request *rq;
4188 /* We have to check the current hw status of the fence as the uABI
4189 * guarantees forward progress. We could rely on the idle worker
4190 * to eventually flush us, but to minimise latency just ask the
4193 * Note we only report on the status of native fences.
4195 if (!dma_fence_is_i915(fence))
4198 /* opencode to_request() in order to avoid const warnings */
4199 rq = container_of(fence, struct drm_i915_gem_request, fence);
4200 if (i915_gem_request_completed(rq))
4203 return flag(rq->engine->uabi_id);
4206 static __always_inline unsigned int
4207 busy_check_reader(const struct dma_fence *fence)
4209 return __busy_set_if_active(fence, __busy_read_flag);
4212 static __always_inline unsigned int
4213 busy_check_writer(const struct dma_fence *fence)
4218 return __busy_set_if_active(fence, __busy_write_id);
4222 i915_gem_busy_ioctl(struct drm_device *dev, void *data,
4223 struct drm_file *file)
4225 struct drm_i915_gem_busy *args = data;
4226 struct drm_i915_gem_object *obj;
4227 struct reservation_object_list *list;
4233 obj = i915_gem_object_lookup_rcu(file, args->handle);
4237 /* A discrepancy here is that we do not report the status of
4238 * non-i915 fences, i.e. even though we may report the object as idle,
4239 * a call to set-domain may still stall waiting for foreign rendering.
4240 * This also means that wait-ioctl may report an object as busy,
4241 * where busy-ioctl considers it idle.
4243 * We trade the ability to warn of foreign fences to report on which
4244 * i915 engines are active for the object.
4246 * Alternatively, we can trade that extra information on read/write
4249 * !reservation_object_test_signaled_rcu(obj->resv, true);
4250 * to report the overall busyness. This is what the wait-ioctl does.
4254 seq = raw_read_seqcount(&obj->resv->seq);
4256 /* Translate the exclusive fence to the READ *and* WRITE engine */
4257 args->busy = busy_check_writer(rcu_dereference(obj->resv->fence_excl));
4259 /* Translate shared fences to READ set of engines */
4260 list = rcu_dereference(obj->resv->fence);
4262 unsigned int shared_count = list->shared_count, i;
4264 for (i = 0; i < shared_count; ++i) {
4265 struct dma_fence *fence =
4266 rcu_dereference(list->shared[i]);
4268 args->busy |= busy_check_reader(fence);
4272 if (args->busy && read_seqcount_retry(&obj->resv->seq, seq))
4282 i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
4283 struct drm_file *file_priv)
4285 return i915_gem_ring_throttle(dev, file_priv);
4289 i915_gem_madvise_ioctl(struct drm_device *dev, void *data,
4290 struct drm_file *file_priv)
4292 struct drm_i915_private *dev_priv = to_i915(dev);
4293 struct drm_i915_gem_madvise *args = data;
4294 struct drm_i915_gem_object *obj;
4297 switch (args->madv) {
4298 case I915_MADV_DONTNEED:
4299 case I915_MADV_WILLNEED:
4305 obj = i915_gem_object_lookup(file_priv, args->handle);
4309 err = mutex_lock_interruptible(&obj->mm.lock);
4313 if (i915_gem_object_has_pages(obj) &&
4314 i915_gem_object_is_tiled(obj) &&
4315 dev_priv->quirks & QUIRK_PIN_SWIZZLED_PAGES) {
4316 if (obj->mm.madv == I915_MADV_WILLNEED) {
4317 GEM_BUG_ON(!obj->mm.quirked);
4318 __i915_gem_object_unpin_pages(obj);
4319 obj->mm.quirked = false;
4321 if (args->madv == I915_MADV_WILLNEED) {
4322 GEM_BUG_ON(obj->mm.quirked);
4323 __i915_gem_object_pin_pages(obj);
4324 obj->mm.quirked = true;
4328 if (obj->mm.madv != __I915_MADV_PURGED)
4329 obj->mm.madv = args->madv;
4331 /* if the object is no longer attached, discard its backing storage */
4332 if (obj->mm.madv == I915_MADV_DONTNEED &&
4333 !i915_gem_object_has_pages(obj))
4334 i915_gem_object_truncate(obj);
4336 args->retained = obj->mm.madv != __I915_MADV_PURGED;
4337 mutex_unlock(&obj->mm.lock);
4340 i915_gem_object_put(obj);
4345 frontbuffer_retire(struct i915_gem_active *active,
4346 struct drm_i915_gem_request *request)
4348 struct drm_i915_gem_object *obj =
4349 container_of(active, typeof(*obj), frontbuffer_write);
4351 intel_fb_obj_flush(obj, ORIGIN_CS);
4354 void i915_gem_object_init(struct drm_i915_gem_object *obj,
4355 const struct drm_i915_gem_object_ops *ops)
4357 mutex_init(&obj->mm.lock);
4359 INIT_LIST_HEAD(&obj->vma_list);
4360 INIT_LIST_HEAD(&obj->lut_list);
4361 INIT_LIST_HEAD(&obj->batch_pool_link);
4365 reservation_object_init(&obj->__builtin_resv);
4366 obj->resv = &obj->__builtin_resv;
4368 obj->frontbuffer_ggtt_origin = ORIGIN_GTT;
4369 init_request_active(&obj->frontbuffer_write, frontbuffer_retire);
4371 obj->mm.madv = I915_MADV_WILLNEED;
4372 INIT_RADIX_TREE(&obj->mm.get_page.radix, GFP_KERNEL | __GFP_NOWARN);
4373 mutex_init(&obj->mm.get_page.lock);
4375 i915_gem_info_add_obj(to_i915(obj->base.dev), obj->base.size);
4378 static const struct drm_i915_gem_object_ops i915_gem_object_ops = {
4379 .flags = I915_GEM_OBJECT_HAS_STRUCT_PAGE |
4380 I915_GEM_OBJECT_IS_SHRINKABLE,
4382 .get_pages = i915_gem_object_get_pages_gtt,
4383 .put_pages = i915_gem_object_put_pages_gtt,
4385 .pwrite = i915_gem_object_pwrite_gtt,
4388 static int i915_gem_object_create_shmem(struct drm_device *dev,
4389 struct drm_gem_object *obj,
4392 struct drm_i915_private *i915 = to_i915(dev);
4393 unsigned long flags = VM_NORESERVE;
4396 drm_gem_private_object_init(dev, obj, size);
4399 filp = shmem_file_setup_with_mnt(i915->mm.gemfs, "i915", size,
4402 filp = shmem_file_setup("i915", size, flags);
4405 return PTR_ERR(filp);
4412 struct drm_i915_gem_object *
4413 i915_gem_object_create(struct drm_i915_private *dev_priv, u64 size)
4415 struct drm_i915_gem_object *obj;
4416 struct address_space *mapping;
4417 unsigned int cache_level;
4421 /* There is a prevalence of the assumption that we fit the object's
4422 * page count inside a 32bit _signed_ variable. Let's document this and
4423 * catch if we ever need to fix it. In the meantime, if you do spot
4424 * such a local variable, please consider fixing!
4426 if (size >> PAGE_SHIFT > INT_MAX)
4427 return ERR_PTR(-E2BIG);
4429 if (overflows_type(size, obj->base.size))
4430 return ERR_PTR(-E2BIG);
4432 obj = i915_gem_object_alloc(dev_priv);
4434 return ERR_PTR(-ENOMEM);
4436 ret = i915_gem_object_create_shmem(&dev_priv->drm, &obj->base, size);
4440 mask = GFP_HIGHUSER | __GFP_RECLAIMABLE;
4441 if (IS_I965GM(dev_priv) || IS_I965G(dev_priv)) {
4442 /* 965gm cannot relocate objects above 4GiB. */
4443 mask &= ~__GFP_HIGHMEM;
4444 mask |= __GFP_DMA32;
4447 mapping = obj->base.filp->f_mapping;
4448 mapping_set_gfp_mask(mapping, mask);
4449 GEM_BUG_ON(!(mapping_gfp_mask(mapping) & __GFP_RECLAIM));
4451 i915_gem_object_init(obj, &i915_gem_object_ops);
4453 obj->base.write_domain = I915_GEM_DOMAIN_CPU;
4454 obj->base.read_domains = I915_GEM_DOMAIN_CPU;
4456 if (HAS_LLC(dev_priv))
4457 /* On some devices, we can have the GPU use the LLC (the CPU
4458 * cache) for about a 10% performance improvement
4459 * compared to uncached. Graphics requests other than
4460 * display scanout are coherent with the CPU in
4461 * accessing this cache. This means in this mode we
4462 * don't need to clflush on the CPU side, and on the
4463 * GPU side we only need to flush internal caches to
4464 * get data visible to the CPU.
4466 * However, we maintain the display planes as UC, and so
4467 * need to rebind when first used as such.
4469 cache_level = I915_CACHE_LLC;
4471 cache_level = I915_CACHE_NONE;
4473 i915_gem_object_set_cache_coherency(obj, cache_level);
4475 trace_i915_gem_object_create(obj);
4480 i915_gem_object_free(obj);
4481 return ERR_PTR(ret);
4484 static bool discard_backing_storage(struct drm_i915_gem_object *obj)
4486 /* If we are the last user of the backing storage (be it shmemfs
4487 * pages or stolen etc), we know that the pages are going to be
4488 * immediately released. In this case, we can then skip copying
4489 * back the contents from the GPU.
4492 if (obj->mm.madv != I915_MADV_WILLNEED)
4495 if (obj->base.filp == NULL)
4498 /* At first glance, this looks racy, but then again so would be
4499 * userspace racing mmap against close. However, the first external
4500 * reference to the filp can only be obtained through the
4501 * i915_gem_mmap_ioctl() which safeguards us against the user
4502 * acquiring such a reference whilst we are in the middle of
4503 * freeing the object.
4505 return atomic_long_read(&obj->base.filp->f_count) == 1;
4508 static void __i915_gem_free_objects(struct drm_i915_private *i915,
4509 struct llist_node *freed)
4511 struct drm_i915_gem_object *obj, *on;
4513 intel_runtime_pm_get(i915);
4514 llist_for_each_entry_safe(obj, on, freed, freed) {
4515 struct i915_vma *vma, *vn;
4517 trace_i915_gem_object_destroy(obj);
4519 mutex_lock(&i915->drm.struct_mutex);
4521 GEM_BUG_ON(i915_gem_object_is_active(obj));
4522 list_for_each_entry_safe(vma, vn,
4523 &obj->vma_list, obj_link) {
4524 GEM_BUG_ON(i915_vma_is_active(vma));
4525 vma->flags &= ~I915_VMA_PIN_MASK;
4526 i915_vma_close(vma);
4528 GEM_BUG_ON(!list_empty(&obj->vma_list));
4529 GEM_BUG_ON(!RB_EMPTY_ROOT(&obj->vma_tree));
4531 /* This serializes freeing with the shrinker. Since the free
4532 * is delayed, first by RCU then by the workqueue, we want the
4533 * shrinker to be able to free pages of unreferenced objects,
4534 * or else we may oom whilst there are plenty of deferred
4537 if (i915_gem_object_has_pages(obj)) {
4538 spin_lock(&i915->mm.obj_lock);
4539 list_del_init(&obj->mm.link);
4540 spin_unlock(&i915->mm.obj_lock);
4543 mutex_unlock(&i915->drm.struct_mutex);
4545 GEM_BUG_ON(obj->bind_count);
4546 GEM_BUG_ON(obj->userfault_count);
4547 GEM_BUG_ON(atomic_read(&obj->frontbuffer_bits));
4548 GEM_BUG_ON(!list_empty(&obj->lut_list));
4550 if (obj->ops->release)
4551 obj->ops->release(obj);
4553 if (WARN_ON(i915_gem_object_has_pinned_pages(obj)))
4554 atomic_set(&obj->mm.pages_pin_count, 0);
4555 __i915_gem_object_put_pages(obj, I915_MM_NORMAL);
4556 GEM_BUG_ON(i915_gem_object_has_pages(obj));
4558 if (obj->base.import_attach)
4559 drm_prime_gem_destroy(&obj->base, NULL);
4561 reservation_object_fini(&obj->__builtin_resv);
4562 drm_gem_object_release(&obj->base);
4563 i915_gem_info_remove_obj(i915, obj->base.size);
4566 i915_gem_object_free(obj);
4571 intel_runtime_pm_put(i915);
4574 static void i915_gem_flush_free_objects(struct drm_i915_private *i915)
4576 struct llist_node *freed;
4578 /* Free the oldest, most stale object to keep the free_list short */
4580 if (!llist_empty(&i915->mm.free_list)) { /* quick test for hotpath */
4581 /* Only one consumer of llist_del_first() allowed */
4582 spin_lock(&i915->mm.free_lock);
4583 freed = llist_del_first(&i915->mm.free_list);
4584 spin_unlock(&i915->mm.free_lock);
4586 if (unlikely(freed)) {
4588 __i915_gem_free_objects(i915, freed);
4592 static void __i915_gem_free_work(struct work_struct *work)
4594 struct drm_i915_private *i915 =
4595 container_of(work, struct drm_i915_private, mm.free_work);
4596 struct llist_node *freed;
4598 /* All file-owned VMA should have been released by this point through
4599 * i915_gem_close_object(), or earlier by i915_gem_context_close().
4600 * However, the object may also be bound into the global GTT (e.g.
4601 * older GPUs without per-process support, or for direct access through
4602 * the GTT either for the user or for scanout). Those VMA still need to
4606 spin_lock(&i915->mm.free_lock);
4607 while ((freed = llist_del_all(&i915->mm.free_list))) {
4608 spin_unlock(&i915->mm.free_lock);
4610 __i915_gem_free_objects(i915, freed);
4614 spin_lock(&i915->mm.free_lock);
4616 spin_unlock(&i915->mm.free_lock);
4619 static void __i915_gem_free_object_rcu(struct rcu_head *head)
4621 struct drm_i915_gem_object *obj =
4622 container_of(head, typeof(*obj), rcu);
4623 struct drm_i915_private *i915 = to_i915(obj->base.dev);
4625 /* We can't simply use call_rcu() from i915_gem_free_object()
4626 * as we need to block whilst unbinding, and the call_rcu
4627 * task may be called from softirq context. So we take a
4628 * detour through a worker.
4630 if (llist_add(&obj->freed, &i915->mm.free_list))
4631 schedule_work(&i915->mm.free_work);
4634 void i915_gem_free_object(struct drm_gem_object *gem_obj)
4636 struct drm_i915_gem_object *obj = to_intel_bo(gem_obj);
4638 if (obj->mm.quirked)
4639 __i915_gem_object_unpin_pages(obj);
4641 if (discard_backing_storage(obj))
4642 obj->mm.madv = I915_MADV_DONTNEED;
4644 /* Before we free the object, make sure any pure RCU-only
4645 * read-side critical sections are complete, e.g.
4646 * i915_gem_busy_ioctl(). For the corresponding synchronized
4647 * lookup see i915_gem_object_lookup_rcu().
4649 call_rcu(&obj->rcu, __i915_gem_free_object_rcu);
4652 void __i915_gem_object_release_unless_active(struct drm_i915_gem_object *obj)
4654 lockdep_assert_held(&obj->base.dev->struct_mutex);
4656 if (!i915_gem_object_has_active_reference(obj) &&
4657 i915_gem_object_is_active(obj))
4658 i915_gem_object_set_active_reference(obj);
4660 i915_gem_object_put(obj);
4663 static void assert_kernel_context_is_current(struct drm_i915_private *dev_priv)
4665 struct intel_engine_cs *engine;
4666 enum intel_engine_id id;
4668 for_each_engine(engine, dev_priv, id)
4669 GEM_BUG_ON(engine->last_retired_context &&
4670 !i915_gem_context_is_kernel(engine->last_retired_context));
4673 void i915_gem_sanitize(struct drm_i915_private *i915)
4675 if (i915_terminally_wedged(&i915->gpu_error)) {
4676 mutex_lock(&i915->drm.struct_mutex);
4677 i915_gem_unset_wedged(i915);
4678 mutex_unlock(&i915->drm.struct_mutex);
4682 * If we inherit context state from the BIOS or earlier occupants
4683 * of the GPU, the GPU may be in an inconsistent state when we
4684 * try to take over. The only way to remove the earlier state
4685 * is by resetting. However, resetting on earlier gen is tricky as
4686 * it may impact the display and we are uncertain about the stability
4687 * of the reset, so this could be applied to even earlier gen.
4689 if (INTEL_GEN(i915) >= 5) {
4690 int reset = intel_gpu_reset(i915, ALL_ENGINES);
4691 WARN_ON(reset && reset != -ENODEV);
4695 int i915_gem_suspend(struct drm_i915_private *dev_priv)
4697 struct drm_device *dev = &dev_priv->drm;
4700 intel_runtime_pm_get(dev_priv);
4701 intel_suspend_gt_powersave(dev_priv);
4703 mutex_lock(&dev->struct_mutex);
4705 /* We have to flush all the executing contexts to main memory so
4706 * that they can saved in the hibernation image. To ensure the last
4707 * context image is coherent, we have to switch away from it. That
4708 * leaves the dev_priv->kernel_context still active when
4709 * we actually suspend, and its image in memory may not match the GPU
4710 * state. Fortunately, the kernel_context is disposable and we do
4711 * not rely on its state.
4713 ret = i915_gem_switch_to_kernel_context(dev_priv);
4717 ret = i915_gem_wait_for_idle(dev_priv,
4718 I915_WAIT_INTERRUPTIBLE |
4720 if (ret && ret != -EIO)
4723 assert_kernel_context_is_current(dev_priv);
4724 i915_gem_contexts_lost(dev_priv);
4725 mutex_unlock(&dev->struct_mutex);
4727 intel_guc_suspend(dev_priv);
4729 cancel_delayed_work_sync(&dev_priv->gpu_error.hangcheck_work);
4730 cancel_delayed_work_sync(&dev_priv->gt.retire_work);
4732 /* As the idle_work is rearming if it detects a race, play safe and
4733 * repeat the flush until it is definitely idle.
4735 drain_delayed_work(&dev_priv->gt.idle_work);
4737 /* Assert that we sucessfully flushed all the work and
4738 * reset the GPU back to its idle, low power state.
4740 WARN_ON(dev_priv->gt.awake);
4741 if (WARN_ON(!intel_engines_are_idle(dev_priv)))
4742 i915_gem_set_wedged(dev_priv); /* no hope, discard everything */
4745 * Neither the BIOS, ourselves or any other kernel
4746 * expects the system to be in execlists mode on startup,
4747 * so we need to reset the GPU back to legacy mode. And the only
4748 * known way to disable logical contexts is through a GPU reset.
4750 * So in order to leave the system in a known default configuration,
4751 * always reset the GPU upon unload and suspend. Afterwards we then
4752 * clean up the GEM state tracking, flushing off the requests and
4753 * leaving the system in a known idle state.
4755 * Note that is of the upmost importance that the GPU is idle and
4756 * all stray writes are flushed *before* we dismantle the backing
4757 * storage for the pinned objects.
4759 * However, since we are uncertain that resetting the GPU on older
4760 * machines is a good idea, we don't - just in case it leaves the
4761 * machine in an unusable condition.
4763 i915_gem_sanitize(dev_priv);
4765 intel_runtime_pm_put(dev_priv);
4769 mutex_unlock(&dev->struct_mutex);
4770 intel_runtime_pm_put(dev_priv);
4774 void i915_gem_resume(struct drm_i915_private *dev_priv)
4776 struct drm_device *dev = &dev_priv->drm;
4778 WARN_ON(dev_priv->gt.awake);
4780 mutex_lock(&dev->struct_mutex);
4781 i915_gem_restore_gtt_mappings(dev_priv);
4782 i915_gem_restore_fences(dev_priv);
4784 /* As we didn't flush the kernel context before suspend, we cannot
4785 * guarantee that the context image is complete. So let's just reset
4786 * it and start again.
4788 dev_priv->gt.resume(dev_priv);
4790 mutex_unlock(&dev->struct_mutex);
4793 void i915_gem_init_swizzling(struct drm_i915_private *dev_priv)
4795 if (INTEL_GEN(dev_priv) < 5 ||
4796 dev_priv->mm.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_NONE)
4799 I915_WRITE(DISP_ARB_CTL, I915_READ(DISP_ARB_CTL) |
4800 DISP_TILE_SURFACE_SWIZZLING);
4802 if (IS_GEN5(dev_priv))
4805 I915_WRITE(TILECTL, I915_READ(TILECTL) | TILECTL_SWZCTL);
4806 if (IS_GEN6(dev_priv))
4807 I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_SNB));
4808 else if (IS_GEN7(dev_priv))
4809 I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_IVB));
4810 else if (IS_GEN8(dev_priv))
4811 I915_WRITE(GAMTARBMODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_BDW));
4816 static void init_unused_ring(struct drm_i915_private *dev_priv, u32 base)
4818 I915_WRITE(RING_CTL(base), 0);
4819 I915_WRITE(RING_HEAD(base), 0);
4820 I915_WRITE(RING_TAIL(base), 0);
4821 I915_WRITE(RING_START(base), 0);
4824 static void init_unused_rings(struct drm_i915_private *dev_priv)
4826 if (IS_I830(dev_priv)) {
4827 init_unused_ring(dev_priv, PRB1_BASE);
4828 init_unused_ring(dev_priv, SRB0_BASE);
4829 init_unused_ring(dev_priv, SRB1_BASE);
4830 init_unused_ring(dev_priv, SRB2_BASE);
4831 init_unused_ring(dev_priv, SRB3_BASE);
4832 } else if (IS_GEN2(dev_priv)) {
4833 init_unused_ring(dev_priv, SRB0_BASE);
4834 init_unused_ring(dev_priv, SRB1_BASE);
4835 } else if (IS_GEN3(dev_priv)) {
4836 init_unused_ring(dev_priv, PRB1_BASE);
4837 init_unused_ring(dev_priv, PRB2_BASE);
4841 static int __i915_gem_restart_engines(void *data)
4843 struct drm_i915_private *i915 = data;
4844 struct intel_engine_cs *engine;
4845 enum intel_engine_id id;
4848 for_each_engine(engine, i915, id) {
4849 err = engine->init_hw(engine);
4857 int i915_gem_init_hw(struct drm_i915_private *dev_priv)
4861 dev_priv->gt.last_init_time = ktime_get();
4863 /* Double layer security blanket, see i915_gem_init() */
4864 intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
4866 if (HAS_EDRAM(dev_priv) && INTEL_GEN(dev_priv) < 9)
4867 I915_WRITE(HSW_IDICR, I915_READ(HSW_IDICR) | IDIHASHMSK(0xf));
4869 if (IS_HASWELL(dev_priv))
4870 I915_WRITE(MI_PREDICATE_RESULT_2, IS_HSW_GT3(dev_priv) ?
4871 LOWER_SLICE_ENABLED : LOWER_SLICE_DISABLED);
4873 if (HAS_PCH_NOP(dev_priv)) {
4874 if (IS_IVYBRIDGE(dev_priv)) {
4875 u32 temp = I915_READ(GEN7_MSG_CTL);
4876 temp &= ~(WAIT_FOR_PCH_FLR_ACK | WAIT_FOR_PCH_RESET_ACK);
4877 I915_WRITE(GEN7_MSG_CTL, temp);
4878 } else if (INTEL_GEN(dev_priv) >= 7) {
4879 u32 temp = I915_READ(HSW_NDE_RSTWRN_OPT);
4880 temp &= ~RESET_PCH_HANDSHAKE_ENABLE;
4881 I915_WRITE(HSW_NDE_RSTWRN_OPT, temp);
4885 i915_gem_init_swizzling(dev_priv);
4888 * At least 830 can leave some of the unused rings
4889 * "active" (ie. head != tail) after resume which
4890 * will prevent c3 entry. Makes sure all unused rings
4893 init_unused_rings(dev_priv);
4895 BUG_ON(!dev_priv->kernel_context);
4896 if (i915_terminally_wedged(&dev_priv->gpu_error)) {
4901 ret = i915_ppgtt_init_hw(dev_priv);
4903 DRM_ERROR("PPGTT enable HW failed %d\n", ret);
4907 /* Need to do basic initialisation of all rings first: */
4908 ret = __i915_gem_restart_engines(dev_priv);
4912 intel_mocs_init_l3cc_table(dev_priv);
4914 /* We can't enable contexts until all firmware is loaded */
4915 ret = intel_uc_init_hw(dev_priv);
4920 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
4924 bool intel_sanitize_semaphores(struct drm_i915_private *dev_priv, int value)
4926 if (INTEL_INFO(dev_priv)->gen < 6)
4929 /* TODO: make semaphores and Execlists play nicely together */
4930 if (i915_modparams.enable_execlists)
4936 /* Enable semaphores on SNB when IO remapping is off */
4937 if (IS_GEN6(dev_priv) && intel_vtd_active())
4943 int i915_gem_init(struct drm_i915_private *dev_priv)
4947 mutex_lock(&dev_priv->drm.struct_mutex);
4950 * We need to fallback to 4K pages since gvt gtt handling doesn't
4951 * support huge page entries - we will need to check either hypervisor
4952 * mm can support huge guest page or just do emulation in gvt.
4954 if (intel_vgpu_active(dev_priv))
4955 mkwrite_device_info(dev_priv)->page_sizes =
4956 I915_GTT_PAGE_SIZE_4K;
4958 dev_priv->mm.unordered_timeline = dma_fence_context_alloc(1);
4960 if (!i915_modparams.enable_execlists) {
4961 dev_priv->gt.resume = intel_legacy_submission_resume;
4962 dev_priv->gt.cleanup_engine = intel_engine_cleanup;
4964 dev_priv->gt.resume = intel_lr_context_resume;
4965 dev_priv->gt.cleanup_engine = intel_logical_ring_cleanup;
4968 /* This is just a security blanket to placate dragons.
4969 * On some systems, we very sporadically observe that the first TLBs
4970 * used by the CS may be stale, despite us poking the TLB reset. If
4971 * we hold the forcewake during initialisation these problems
4972 * just magically go away.
4974 intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
4976 ret = i915_gem_init_userptr(dev_priv);
4980 ret = i915_gem_init_ggtt(dev_priv);
4984 ret = i915_gem_contexts_init(dev_priv);
4988 ret = intel_engines_init(dev_priv);
4992 ret = i915_gem_init_hw(dev_priv);
4994 /* Allow engine initialisation to fail by marking the GPU as
4995 * wedged. But we only want to do this where the GPU is angry,
4996 * for all other failure, such as an allocation failure, bail.
4998 if (!i915_terminally_wedged(&dev_priv->gpu_error)) {
4999 DRM_ERROR("Failed to initialize GPU, declaring it wedged\n");
5000 i915_gem_set_wedged(dev_priv);
5006 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
5007 mutex_unlock(&dev_priv->drm.struct_mutex);
5012 void i915_gem_init_mmio(struct drm_i915_private *i915)
5014 i915_gem_sanitize(i915);
5018 i915_gem_cleanup_engines(struct drm_i915_private *dev_priv)
5020 struct intel_engine_cs *engine;
5021 enum intel_engine_id id;
5023 for_each_engine(engine, dev_priv, id)
5024 dev_priv->gt.cleanup_engine(engine);
5028 i915_gem_load_init_fences(struct drm_i915_private *dev_priv)
5032 if (INTEL_INFO(dev_priv)->gen >= 7 && !IS_VALLEYVIEW(dev_priv) &&
5033 !IS_CHERRYVIEW(dev_priv))
5034 dev_priv->num_fence_regs = 32;
5035 else if (INTEL_INFO(dev_priv)->gen >= 4 ||
5036 IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
5037 IS_G33(dev_priv) || IS_PINEVIEW(dev_priv))
5038 dev_priv->num_fence_regs = 16;
5040 dev_priv->num_fence_regs = 8;
5042 if (intel_vgpu_active(dev_priv))
5043 dev_priv->num_fence_regs =
5044 I915_READ(vgtif_reg(avail_rs.fence_num));
5046 /* Initialize fence registers to zero */
5047 for (i = 0; i < dev_priv->num_fence_regs; i++) {
5048 struct drm_i915_fence_reg *fence = &dev_priv->fence_regs[i];
5050 fence->i915 = dev_priv;
5052 list_add_tail(&fence->link, &dev_priv->mm.fence_list);
5054 i915_gem_restore_fences(dev_priv);
5056 i915_gem_detect_bit_6_swizzle(dev_priv);
5060 i915_gem_load_init(struct drm_i915_private *dev_priv)
5064 dev_priv->objects = KMEM_CACHE(drm_i915_gem_object, SLAB_HWCACHE_ALIGN);
5065 if (!dev_priv->objects)
5068 dev_priv->vmas = KMEM_CACHE(i915_vma, SLAB_HWCACHE_ALIGN);
5069 if (!dev_priv->vmas)
5072 dev_priv->luts = KMEM_CACHE(i915_lut_handle, 0);
5073 if (!dev_priv->luts)
5076 dev_priv->requests = KMEM_CACHE(drm_i915_gem_request,
5077 SLAB_HWCACHE_ALIGN |
5078 SLAB_RECLAIM_ACCOUNT |
5079 SLAB_TYPESAFE_BY_RCU);
5080 if (!dev_priv->requests)
5083 dev_priv->dependencies = KMEM_CACHE(i915_dependency,
5084 SLAB_HWCACHE_ALIGN |
5085 SLAB_RECLAIM_ACCOUNT);
5086 if (!dev_priv->dependencies)
5089 dev_priv->priorities = KMEM_CACHE(i915_priolist, SLAB_HWCACHE_ALIGN);
5090 if (!dev_priv->priorities)
5091 goto err_dependencies;
5093 mutex_lock(&dev_priv->drm.struct_mutex);
5094 INIT_LIST_HEAD(&dev_priv->gt.timelines);
5095 err = i915_gem_timeline_init__global(dev_priv);
5096 mutex_unlock(&dev_priv->drm.struct_mutex);
5098 goto err_priorities;
5100 INIT_WORK(&dev_priv->mm.free_work, __i915_gem_free_work);
5102 spin_lock_init(&dev_priv->mm.obj_lock);
5103 spin_lock_init(&dev_priv->mm.free_lock);
5104 init_llist_head(&dev_priv->mm.free_list);
5105 INIT_LIST_HEAD(&dev_priv->mm.unbound_list);
5106 INIT_LIST_HEAD(&dev_priv->mm.bound_list);
5107 INIT_LIST_HEAD(&dev_priv->mm.fence_list);
5108 INIT_LIST_HEAD(&dev_priv->mm.userfault_list);
5110 INIT_DELAYED_WORK(&dev_priv->gt.retire_work,
5111 i915_gem_retire_work_handler);
5112 INIT_DELAYED_WORK(&dev_priv->gt.idle_work,
5113 i915_gem_idle_work_handler);
5114 init_waitqueue_head(&dev_priv->gpu_error.wait_queue);
5115 init_waitqueue_head(&dev_priv->gpu_error.reset_queue);
5117 atomic_set(&dev_priv->mm.bsd_engine_dispatch_index, 0);
5119 spin_lock_init(&dev_priv->fb_tracking.lock);
5121 err = i915_gemfs_init(dev_priv);
5123 DRM_NOTE("Unable to create a private tmpfs mount, hugepage support will be disabled(%d).\n", err);
5128 kmem_cache_destroy(dev_priv->priorities);
5130 kmem_cache_destroy(dev_priv->dependencies);
5132 kmem_cache_destroy(dev_priv->requests);
5134 kmem_cache_destroy(dev_priv->luts);
5136 kmem_cache_destroy(dev_priv->vmas);
5138 kmem_cache_destroy(dev_priv->objects);
5143 void i915_gem_load_cleanup(struct drm_i915_private *dev_priv)
5145 i915_gem_drain_freed_objects(dev_priv);
5146 WARN_ON(!llist_empty(&dev_priv->mm.free_list));
5147 WARN_ON(dev_priv->mm.object_count);
5149 mutex_lock(&dev_priv->drm.struct_mutex);
5150 i915_gem_timeline_fini(&dev_priv->gt.global_timeline);
5151 WARN_ON(!list_empty(&dev_priv->gt.timelines));
5152 mutex_unlock(&dev_priv->drm.struct_mutex);
5154 kmem_cache_destroy(dev_priv->priorities);
5155 kmem_cache_destroy(dev_priv->dependencies);
5156 kmem_cache_destroy(dev_priv->requests);
5157 kmem_cache_destroy(dev_priv->luts);
5158 kmem_cache_destroy(dev_priv->vmas);
5159 kmem_cache_destroy(dev_priv->objects);
5161 /* And ensure that our DESTROY_BY_RCU slabs are truly destroyed */
5164 i915_gemfs_fini(dev_priv);
5167 int i915_gem_freeze(struct drm_i915_private *dev_priv)
5169 /* Discard all purgeable objects, let userspace recover those as
5170 * required after resuming.
5172 i915_gem_shrink_all(dev_priv);
5177 int i915_gem_freeze_late(struct drm_i915_private *dev_priv)
5179 struct drm_i915_gem_object *obj;
5180 struct list_head *phases[] = {
5181 &dev_priv->mm.unbound_list,
5182 &dev_priv->mm.bound_list,
5186 /* Called just before we write the hibernation image.
5188 * We need to update the domain tracking to reflect that the CPU
5189 * will be accessing all the pages to create and restore from the
5190 * hibernation, and so upon restoration those pages will be in the
5193 * To make sure the hibernation image contains the latest state,
5194 * we update that state just before writing out the image.
5196 * To try and reduce the hibernation image, we manually shrink
5197 * the objects as well, see i915_gem_freeze()
5200 i915_gem_shrink(dev_priv, -1UL, NULL, I915_SHRINK_UNBOUND);
5201 i915_gem_drain_freed_objects(dev_priv);
5203 spin_lock(&dev_priv->mm.obj_lock);
5204 for (p = phases; *p; p++) {
5205 list_for_each_entry(obj, *p, mm.link)
5206 __start_cpu_write(obj);
5208 spin_unlock(&dev_priv->mm.obj_lock);
5213 void i915_gem_release(struct drm_device *dev, struct drm_file *file)
5215 struct drm_i915_file_private *file_priv = file->driver_priv;
5216 struct drm_i915_gem_request *request;
5218 /* Clean up our request list when the client is going away, so that
5219 * later retire_requests won't dereference our soon-to-be-gone
5222 spin_lock(&file_priv->mm.lock);
5223 list_for_each_entry(request, &file_priv->mm.request_list, client_link)
5224 request->file_priv = NULL;
5225 spin_unlock(&file_priv->mm.lock);
5228 int i915_gem_open(struct drm_i915_private *i915, struct drm_file *file)
5230 struct drm_i915_file_private *file_priv;
5235 file_priv = kzalloc(sizeof(*file_priv), GFP_KERNEL);
5239 file->driver_priv = file_priv;
5240 file_priv->dev_priv = i915;
5241 file_priv->file = file;
5243 spin_lock_init(&file_priv->mm.lock);
5244 INIT_LIST_HEAD(&file_priv->mm.request_list);
5246 file_priv->bsd_engine = -1;
5248 ret = i915_gem_context_open(i915, file);
5256 * i915_gem_track_fb - update frontbuffer tracking
5257 * @old: current GEM buffer for the frontbuffer slots
5258 * @new: new GEM buffer for the frontbuffer slots
5259 * @frontbuffer_bits: bitmask of frontbuffer slots
5261 * This updates the frontbuffer tracking bits @frontbuffer_bits by clearing them
5262 * from @old and setting them in @new. Both @old and @new can be NULL.
5264 void i915_gem_track_fb(struct drm_i915_gem_object *old,
5265 struct drm_i915_gem_object *new,
5266 unsigned frontbuffer_bits)
5268 /* Control of individual bits within the mask are guarded by
5269 * the owning plane->mutex, i.e. we can never see concurrent
5270 * manipulation of individual bits. But since the bitfield as a whole
5271 * is updated using RMW, we need to use atomics in order to update
5274 BUILD_BUG_ON(INTEL_FRONTBUFFER_BITS_PER_PIPE * I915_MAX_PIPES >
5275 sizeof(atomic_t) * BITS_PER_BYTE);
5278 WARN_ON(!(atomic_read(&old->frontbuffer_bits) & frontbuffer_bits));
5279 atomic_andnot(frontbuffer_bits, &old->frontbuffer_bits);
5283 WARN_ON(atomic_read(&new->frontbuffer_bits) & frontbuffer_bits);
5284 atomic_or(frontbuffer_bits, &new->frontbuffer_bits);
5288 /* Allocate a new GEM object and fill it with the supplied data */
5289 struct drm_i915_gem_object *
5290 i915_gem_object_create_from_data(struct drm_i915_private *dev_priv,
5291 const void *data, size_t size)
5293 struct drm_i915_gem_object *obj;
5298 obj = i915_gem_object_create(dev_priv, round_up(size, PAGE_SIZE));
5302 GEM_BUG_ON(obj->base.write_domain != I915_GEM_DOMAIN_CPU);
5304 file = obj->base.filp;
5307 unsigned int len = min_t(typeof(size), size, PAGE_SIZE);
5309 void *pgdata, *vaddr;
5311 err = pagecache_write_begin(file, file->f_mapping,
5318 memcpy(vaddr, data, len);
5321 err = pagecache_write_end(file, file->f_mapping,
5335 i915_gem_object_put(obj);
5336 return ERR_PTR(err);
5339 struct scatterlist *
5340 i915_gem_object_get_sg(struct drm_i915_gem_object *obj,
5342 unsigned int *offset)
5344 struct i915_gem_object_page_iter *iter = &obj->mm.get_page;
5345 struct scatterlist *sg;
5346 unsigned int idx, count;
5349 GEM_BUG_ON(n >= obj->base.size >> PAGE_SHIFT);
5350 GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
5352 /* As we iterate forward through the sg, we record each entry in a
5353 * radixtree for quick repeated (backwards) lookups. If we have seen
5354 * this index previously, we will have an entry for it.
5356 * Initial lookup is O(N), but this is amortized to O(1) for
5357 * sequential page access (where each new request is consecutive
5358 * to the previous one). Repeated lookups are O(lg(obj->base.size)),
5359 * i.e. O(1) with a large constant!
5361 if (n < READ_ONCE(iter->sg_idx))
5364 mutex_lock(&iter->lock);
5366 /* We prefer to reuse the last sg so that repeated lookup of this
5367 * (or the subsequent) sg are fast - comparing against the last
5368 * sg is faster than going through the radixtree.
5373 count = __sg_page_count(sg);
5375 while (idx + count <= n) {
5376 unsigned long exception, i;
5379 /* If we cannot allocate and insert this entry, or the
5380 * individual pages from this range, cancel updating the
5381 * sg_idx so that on this lookup we are forced to linearly
5382 * scan onwards, but on future lookups we will try the
5383 * insertion again (in which case we need to be careful of
5384 * the error return reporting that we have already inserted
5387 ret = radix_tree_insert(&iter->radix, idx, sg);
5388 if (ret && ret != -EEXIST)
5392 RADIX_TREE_EXCEPTIONAL_ENTRY |
5393 idx << RADIX_TREE_EXCEPTIONAL_SHIFT;
5394 for (i = 1; i < count; i++) {
5395 ret = radix_tree_insert(&iter->radix, idx + i,
5397 if (ret && ret != -EEXIST)
5402 sg = ____sg_next(sg);
5403 count = __sg_page_count(sg);
5410 mutex_unlock(&iter->lock);
5412 if (unlikely(n < idx)) /* insertion completed by another thread */
5415 /* In case we failed to insert the entry into the radixtree, we need
5416 * to look beyond the current sg.
5418 while (idx + count <= n) {
5420 sg = ____sg_next(sg);
5421 count = __sg_page_count(sg);
5430 sg = radix_tree_lookup(&iter->radix, n);
5433 /* If this index is in the middle of multi-page sg entry,
5434 * the radixtree will contain an exceptional entry that points
5435 * to the start of that range. We will return the pointer to
5436 * the base page and the offset of this page within the
5440 if (unlikely(radix_tree_exception(sg))) {
5441 unsigned long base =
5442 (unsigned long)sg >> RADIX_TREE_EXCEPTIONAL_SHIFT;
5444 sg = radix_tree_lookup(&iter->radix, base);
5456 i915_gem_object_get_page(struct drm_i915_gem_object *obj, unsigned int n)
5458 struct scatterlist *sg;
5459 unsigned int offset;
5461 GEM_BUG_ON(!i915_gem_object_has_struct_page(obj));
5463 sg = i915_gem_object_get_sg(obj, n, &offset);
5464 return nth_page(sg_page(sg), offset);
5467 /* Like i915_gem_object_get_page(), but mark the returned page dirty */
5469 i915_gem_object_get_dirty_page(struct drm_i915_gem_object *obj,
5474 page = i915_gem_object_get_page(obj, n);
5476 set_page_dirty(page);
5482 i915_gem_object_get_dma_address(struct drm_i915_gem_object *obj,
5485 struct scatterlist *sg;
5486 unsigned int offset;
5488 sg = i915_gem_object_get_sg(obj, n, &offset);
5489 return sg_dma_address(sg) + (offset << PAGE_SHIFT);
5492 int i915_gem_object_attach_phys(struct drm_i915_gem_object *obj, int align)
5494 struct sg_table *pages;
5497 if (align > obj->base.size)
5500 if (obj->ops == &i915_gem_phys_ops)
5503 if (obj->ops != &i915_gem_object_ops)
5506 err = i915_gem_object_unbind(obj);
5510 mutex_lock(&obj->mm.lock);
5512 if (obj->mm.madv != I915_MADV_WILLNEED) {
5517 if (obj->mm.quirked) {
5522 if (obj->mm.mapping) {
5527 pages = fetch_and_zero(&obj->mm.pages);
5529 struct drm_i915_private *i915 = to_i915(obj->base.dev);
5531 __i915_gem_object_reset_page_iter(obj);
5533 spin_lock(&i915->mm.obj_lock);
5534 list_del(&obj->mm.link);
5535 spin_unlock(&i915->mm.obj_lock);
5538 obj->ops = &i915_gem_phys_ops;
5540 err = ____i915_gem_object_get_pages(obj);
5544 /* Perma-pin (until release) the physical set of pages */
5545 __i915_gem_object_pin_pages(obj);
5547 if (!IS_ERR_OR_NULL(pages))
5548 i915_gem_object_ops.put_pages(obj, pages);
5549 mutex_unlock(&obj->mm.lock);
5553 obj->ops = &i915_gem_object_ops;
5554 obj->mm.pages = pages;
5556 mutex_unlock(&obj->mm.lock);
5560 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
5561 #include "selftests/scatterlist.c"
5562 #include "selftests/mock_gem_device.c"
5563 #include "selftests/huge_gem_object.c"
5564 #include "selftests/huge_pages.c"
5565 #include "selftests/i915_gem_object.c"
5566 #include "selftests/i915_gem_coherency.c"