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;
2271 radix_tree_for_each_slot(slot, &obj->mm.get_page.radix, &iter, 0)
2272 radix_tree_delete(&obj->mm.get_page.radix, iter.index);
2276 void __i915_gem_object_put_pages(struct drm_i915_gem_object *obj,
2277 enum i915_mm_subclass subclass)
2279 struct drm_i915_private *i915 = to_i915(obj->base.dev);
2280 struct sg_table *pages;
2282 if (i915_gem_object_has_pinned_pages(obj))
2285 GEM_BUG_ON(obj->bind_count);
2286 if (!i915_gem_object_has_pages(obj))
2289 /* May be called by shrinker from within get_pages() (on another bo) */
2290 mutex_lock_nested(&obj->mm.lock, subclass);
2291 if (unlikely(atomic_read(&obj->mm.pages_pin_count)))
2294 /* ->put_pages might need to allocate memory for the bit17 swizzle
2295 * array, hence protect them from being reaped by removing them from gtt
2297 pages = fetch_and_zero(&obj->mm.pages);
2300 spin_lock(&i915->mm.obj_lock);
2301 list_del(&obj->mm.link);
2302 spin_unlock(&i915->mm.obj_lock);
2304 if (obj->mm.mapping) {
2307 ptr = page_mask_bits(obj->mm.mapping);
2308 if (is_vmalloc_addr(ptr))
2311 kunmap(kmap_to_page(ptr));
2313 obj->mm.mapping = NULL;
2316 __i915_gem_object_reset_page_iter(obj);
2319 obj->ops->put_pages(obj, pages);
2321 obj->mm.page_sizes.phys = obj->mm.page_sizes.sg = 0;
2324 mutex_unlock(&obj->mm.lock);
2327 static bool i915_sg_trim(struct sg_table *orig_st)
2329 struct sg_table new_st;
2330 struct scatterlist *sg, *new_sg;
2333 if (orig_st->nents == orig_st->orig_nents)
2336 if (sg_alloc_table(&new_st, orig_st->nents, GFP_KERNEL | __GFP_NOWARN))
2339 new_sg = new_st.sgl;
2340 for_each_sg(orig_st->sgl, sg, orig_st->nents, i) {
2341 sg_set_page(new_sg, sg_page(sg), sg->length, 0);
2342 /* called before being DMA mapped, no need to copy sg->dma_* */
2343 new_sg = sg_next(new_sg);
2345 GEM_BUG_ON(new_sg); /* Should walk exactly nents and hit the end */
2347 sg_free_table(orig_st);
2353 static int i915_gem_object_get_pages_gtt(struct drm_i915_gem_object *obj)
2355 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
2356 const unsigned long page_count = obj->base.size / PAGE_SIZE;
2358 struct address_space *mapping;
2359 struct sg_table *st;
2360 struct scatterlist *sg;
2361 struct sgt_iter sgt_iter;
2363 unsigned long last_pfn = 0; /* suppress gcc warning */
2364 unsigned int max_segment = i915_sg_segment_size();
2365 unsigned int sg_page_sizes;
2369 /* Assert that the object is not currently in any GPU domain. As it
2370 * wasn't in the GTT, there shouldn't be any way it could have been in
2373 GEM_BUG_ON(obj->base.read_domains & I915_GEM_GPU_DOMAINS);
2374 GEM_BUG_ON(obj->base.write_domain & I915_GEM_GPU_DOMAINS);
2376 st = kmalloc(sizeof(*st), GFP_KERNEL);
2381 if (sg_alloc_table(st, page_count, GFP_KERNEL)) {
2386 /* Get the list of pages out of our struct file. They'll be pinned
2387 * at this point until we release them.
2389 * Fail silently without starting the shrinker
2391 mapping = obj->base.filp->f_mapping;
2392 noreclaim = mapping_gfp_constraint(mapping, ~__GFP_RECLAIM);
2393 noreclaim |= __GFP_NORETRY | __GFP_NOWARN;
2398 for (i = 0; i < page_count; i++) {
2399 const unsigned int shrink[] = {
2400 I915_SHRINK_BOUND | I915_SHRINK_UNBOUND | I915_SHRINK_PURGEABLE,
2403 gfp_t gfp = noreclaim;
2406 page = shmem_read_mapping_page_gfp(mapping, i, gfp);
2407 if (likely(!IS_ERR(page)))
2411 ret = PTR_ERR(page);
2415 i915_gem_shrink(dev_priv, 2 * page_count, NULL, *s++);
2418 /* We've tried hard to allocate the memory by reaping
2419 * our own buffer, now let the real VM do its job and
2420 * go down in flames if truly OOM.
2422 * However, since graphics tend to be disposable,
2423 * defer the oom here by reporting the ENOMEM back
2427 /* reclaim and warn, but no oom */
2428 gfp = mapping_gfp_mask(mapping);
2430 /* Our bo are always dirty and so we require
2431 * kswapd to reclaim our pages (direct reclaim
2432 * does not effectively begin pageout of our
2433 * buffers on its own). However, direct reclaim
2434 * only waits for kswapd when under allocation
2435 * congestion. So as a result __GFP_RECLAIM is
2436 * unreliable and fails to actually reclaim our
2437 * dirty pages -- unless you try over and over
2438 * again with !__GFP_NORETRY. However, we still
2439 * want to fail this allocation rather than
2440 * trigger the out-of-memory killer and for
2441 * this we want __GFP_RETRY_MAYFAIL.
2443 gfp |= __GFP_RETRY_MAYFAIL;
2448 sg->length >= max_segment ||
2449 page_to_pfn(page) != last_pfn + 1) {
2451 sg_page_sizes |= sg->length;
2455 sg_set_page(sg, page, PAGE_SIZE, 0);
2457 sg->length += PAGE_SIZE;
2459 last_pfn = page_to_pfn(page);
2461 /* Check that the i965g/gm workaround works. */
2462 WARN_ON((gfp & __GFP_DMA32) && (last_pfn >= 0x00100000UL));
2464 if (sg) { /* loop terminated early; short sg table */
2465 sg_page_sizes |= sg->length;
2469 /* Trim unused sg entries to avoid wasting memory. */
2472 ret = i915_gem_gtt_prepare_pages(obj, st);
2474 /* DMA remapping failed? One possible cause is that
2475 * it could not reserve enough large entries, asking
2476 * for PAGE_SIZE chunks instead may be helpful.
2478 if (max_segment > PAGE_SIZE) {
2479 for_each_sgt_page(page, sgt_iter, st)
2483 max_segment = PAGE_SIZE;
2486 dev_warn(&dev_priv->drm.pdev->dev,
2487 "Failed to DMA remap %lu pages\n",
2493 if (i915_gem_object_needs_bit17_swizzle(obj))
2494 i915_gem_object_do_bit_17_swizzle(obj, st);
2496 __i915_gem_object_set_pages(obj, st, sg_page_sizes);
2503 for_each_sgt_page(page, sgt_iter, st)
2508 /* shmemfs first checks if there is enough memory to allocate the page
2509 * and reports ENOSPC should there be insufficient, along with the usual
2510 * ENOMEM for a genuine allocation failure.
2512 * We use ENOSPC in our driver to mean that we have run out of aperture
2513 * space and so want to translate the error from shmemfs back to our
2514 * usual understanding of ENOMEM.
2522 void __i915_gem_object_set_pages(struct drm_i915_gem_object *obj,
2523 struct sg_table *pages,
2524 unsigned int sg_page_sizes)
2526 struct drm_i915_private *i915 = to_i915(obj->base.dev);
2527 unsigned long supported = INTEL_INFO(i915)->page_sizes;
2530 lockdep_assert_held(&obj->mm.lock);
2532 obj->mm.get_page.sg_pos = pages->sgl;
2533 obj->mm.get_page.sg_idx = 0;
2535 obj->mm.pages = pages;
2537 if (i915_gem_object_is_tiled(obj) &&
2538 i915->quirks & QUIRK_PIN_SWIZZLED_PAGES) {
2539 GEM_BUG_ON(obj->mm.quirked);
2540 __i915_gem_object_pin_pages(obj);
2541 obj->mm.quirked = true;
2544 GEM_BUG_ON(!sg_page_sizes);
2545 obj->mm.page_sizes.phys = sg_page_sizes;
2548 * Calculate the supported page-sizes which fit into the given
2549 * sg_page_sizes. This will give us the page-sizes which we may be able
2550 * to use opportunistically when later inserting into the GTT. For
2551 * example if phys=2G, then in theory we should be able to use 1G, 2M,
2552 * 64K or 4K pages, although in practice this will depend on a number of
2555 obj->mm.page_sizes.sg = 0;
2556 for_each_set_bit(i, &supported, ilog2(I915_GTT_MAX_PAGE_SIZE) + 1) {
2557 if (obj->mm.page_sizes.phys & ~0u << i)
2558 obj->mm.page_sizes.sg |= BIT(i);
2560 GEM_BUG_ON(!HAS_PAGE_SIZES(i915, obj->mm.page_sizes.sg));
2562 spin_lock(&i915->mm.obj_lock);
2563 list_add(&obj->mm.link, &i915->mm.unbound_list);
2564 spin_unlock(&i915->mm.obj_lock);
2567 static int ____i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
2571 if (unlikely(obj->mm.madv != I915_MADV_WILLNEED)) {
2572 DRM_DEBUG("Attempting to obtain a purgeable object\n");
2576 err = obj->ops->get_pages(obj);
2577 GEM_BUG_ON(!err && IS_ERR_OR_NULL(obj->mm.pages));
2582 /* Ensure that the associated pages are gathered from the backing storage
2583 * and pinned into our object. i915_gem_object_pin_pages() may be called
2584 * multiple times before they are released by a single call to
2585 * i915_gem_object_unpin_pages() - once the pages are no longer referenced
2586 * either as a result of memory pressure (reaping pages under the shrinker)
2587 * or as the object is itself released.
2589 int __i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
2593 err = mutex_lock_interruptible(&obj->mm.lock);
2597 if (unlikely(!i915_gem_object_has_pages(obj))) {
2598 GEM_BUG_ON(i915_gem_object_has_pinned_pages(obj));
2600 err = ____i915_gem_object_get_pages(obj);
2604 smp_mb__before_atomic();
2606 atomic_inc(&obj->mm.pages_pin_count);
2609 mutex_unlock(&obj->mm.lock);
2613 /* The 'mapping' part of i915_gem_object_pin_map() below */
2614 static void *i915_gem_object_map(const struct drm_i915_gem_object *obj,
2615 enum i915_map_type type)
2617 unsigned long n_pages = obj->base.size >> PAGE_SHIFT;
2618 struct sg_table *sgt = obj->mm.pages;
2619 struct sgt_iter sgt_iter;
2621 struct page *stack_pages[32];
2622 struct page **pages = stack_pages;
2623 unsigned long i = 0;
2627 /* A single page can always be kmapped */
2628 if (n_pages == 1 && type == I915_MAP_WB)
2629 return kmap(sg_page(sgt->sgl));
2631 if (n_pages > ARRAY_SIZE(stack_pages)) {
2632 /* Too big for stack -- allocate temporary array instead */
2633 pages = kvmalloc_array(n_pages, sizeof(*pages), GFP_KERNEL);
2638 for_each_sgt_page(page, sgt_iter, sgt)
2641 /* Check that we have the expected number of pages */
2642 GEM_BUG_ON(i != n_pages);
2647 /* fallthrough to use PAGE_KERNEL anyway */
2649 pgprot = PAGE_KERNEL;
2652 pgprot = pgprot_writecombine(PAGE_KERNEL_IO);
2655 addr = vmap(pages, n_pages, 0, pgprot);
2657 if (pages != stack_pages)
2663 /* get, pin, and map the pages of the object into kernel space */
2664 void *i915_gem_object_pin_map(struct drm_i915_gem_object *obj,
2665 enum i915_map_type type)
2667 enum i915_map_type has_type;
2672 GEM_BUG_ON(!i915_gem_object_has_struct_page(obj));
2674 ret = mutex_lock_interruptible(&obj->mm.lock);
2676 return ERR_PTR(ret);
2678 pinned = !(type & I915_MAP_OVERRIDE);
2679 type &= ~I915_MAP_OVERRIDE;
2681 if (!atomic_inc_not_zero(&obj->mm.pages_pin_count)) {
2682 if (unlikely(!i915_gem_object_has_pages(obj))) {
2683 GEM_BUG_ON(i915_gem_object_has_pinned_pages(obj));
2685 ret = ____i915_gem_object_get_pages(obj);
2689 smp_mb__before_atomic();
2691 atomic_inc(&obj->mm.pages_pin_count);
2694 GEM_BUG_ON(!i915_gem_object_has_pages(obj));
2696 ptr = page_unpack_bits(obj->mm.mapping, &has_type);
2697 if (ptr && has_type != type) {
2703 if (is_vmalloc_addr(ptr))
2706 kunmap(kmap_to_page(ptr));
2708 ptr = obj->mm.mapping = NULL;
2712 ptr = i915_gem_object_map(obj, type);
2718 obj->mm.mapping = page_pack_bits(ptr, type);
2722 mutex_unlock(&obj->mm.lock);
2726 atomic_dec(&obj->mm.pages_pin_count);
2733 i915_gem_object_pwrite_gtt(struct drm_i915_gem_object *obj,
2734 const struct drm_i915_gem_pwrite *arg)
2736 struct address_space *mapping = obj->base.filp->f_mapping;
2737 char __user *user_data = u64_to_user_ptr(arg->data_ptr);
2741 /* Before we instantiate/pin the backing store for our use, we
2742 * can prepopulate the shmemfs filp efficiently using a write into
2743 * the pagecache. We avoid the penalty of instantiating all the
2744 * pages, important if the user is just writing to a few and never
2745 * uses the object on the GPU, and using a direct write into shmemfs
2746 * allows it to avoid the cost of retrieving a page (either swapin
2747 * or clearing-before-use) before it is overwritten.
2749 if (i915_gem_object_has_pages(obj))
2752 if (obj->mm.madv != I915_MADV_WILLNEED)
2755 /* Before the pages are instantiated the object is treated as being
2756 * in the CPU domain. The pages will be clflushed as required before
2757 * use, and we can freely write into the pages directly. If userspace
2758 * races pwrite with any other operation; corruption will ensue -
2759 * that is userspace's prerogative!
2763 offset = arg->offset;
2764 pg = offset_in_page(offset);
2767 unsigned int len, unwritten;
2772 len = PAGE_SIZE - pg;
2776 err = pagecache_write_begin(obj->base.filp, mapping,
2783 unwritten = copy_from_user(vaddr + pg, user_data, len);
2786 err = pagecache_write_end(obj->base.filp, mapping,
2787 offset, len, len - unwritten,
2804 static bool ban_context(const struct i915_gem_context *ctx,
2807 return (i915_gem_context_is_bannable(ctx) &&
2808 score >= CONTEXT_SCORE_BAN_THRESHOLD);
2811 static void i915_gem_context_mark_guilty(struct i915_gem_context *ctx)
2816 atomic_inc(&ctx->guilty_count);
2818 score = atomic_add_return(CONTEXT_SCORE_GUILTY, &ctx->ban_score);
2819 banned = ban_context(ctx, score);
2820 DRM_DEBUG_DRIVER("context %s marked guilty (score %d) banned? %s\n",
2821 ctx->name, score, yesno(banned));
2825 i915_gem_context_set_banned(ctx);
2826 if (!IS_ERR_OR_NULL(ctx->file_priv)) {
2827 atomic_inc(&ctx->file_priv->context_bans);
2828 DRM_DEBUG_DRIVER("client %s has had %d context banned\n",
2829 ctx->name, atomic_read(&ctx->file_priv->context_bans));
2833 static void i915_gem_context_mark_innocent(struct i915_gem_context *ctx)
2835 atomic_inc(&ctx->active_count);
2838 struct drm_i915_gem_request *
2839 i915_gem_find_active_request(struct intel_engine_cs *engine)
2841 struct drm_i915_gem_request *request, *active = NULL;
2842 unsigned long flags;
2844 /* We are called by the error capture and reset at a random
2845 * point in time. In particular, note that neither is crucially
2846 * ordered with an interrupt. After a hang, the GPU is dead and we
2847 * assume that no more writes can happen (we waited long enough for
2848 * all writes that were in transaction to be flushed) - adding an
2849 * extra delay for a recent interrupt is pointless. Hence, we do
2850 * not need an engine->irq_seqno_barrier() before the seqno reads.
2852 spin_lock_irqsave(&engine->timeline->lock, flags);
2853 list_for_each_entry(request, &engine->timeline->requests, link) {
2854 if (__i915_gem_request_completed(request,
2855 request->global_seqno))
2858 GEM_BUG_ON(request->engine != engine);
2859 GEM_BUG_ON(test_bit(DMA_FENCE_FLAG_SIGNALED_BIT,
2860 &request->fence.flags));
2865 spin_unlock_irqrestore(&engine->timeline->lock, flags);
2870 static bool engine_stalled(struct intel_engine_cs *engine)
2872 if (!engine->hangcheck.stalled)
2875 /* Check for possible seqno movement after hang declaration */
2876 if (engine->hangcheck.seqno != intel_engine_get_seqno(engine)) {
2877 DRM_DEBUG_DRIVER("%s pardoned\n", engine->name);
2885 * Ensure irq handler finishes, and not run again.
2886 * Also return the active request so that we only search for it once.
2888 struct drm_i915_gem_request *
2889 i915_gem_reset_prepare_engine(struct intel_engine_cs *engine)
2891 struct drm_i915_gem_request *request = NULL;
2894 * During the reset sequence, we must prevent the engine from
2895 * entering RC6. As the context state is undefined until we restart
2896 * the engine, if it does enter RC6 during the reset, the state
2897 * written to the powercontext is undefined and so we may lose
2898 * GPU state upon resume, i.e. fail to restart after a reset.
2900 intel_uncore_forcewake_get(engine->i915, FORCEWAKE_ALL);
2903 * Prevent the signaler thread from updating the request
2904 * state (by calling dma_fence_signal) as we are processing
2905 * the reset. The write from the GPU of the seqno is
2906 * asynchronous and the signaler thread may see a different
2907 * value to us and declare the request complete, even though
2908 * the reset routine have picked that request as the active
2909 * (incomplete) request. This conflict is not handled
2912 kthread_park(engine->breadcrumbs.signaler);
2915 * Prevent request submission to the hardware until we have
2916 * completed the reset in i915_gem_reset_finish(). If a request
2917 * is completed by one engine, it may then queue a request
2918 * to a second via its engine->irq_tasklet *just* as we are
2919 * calling engine->init_hw() and also writing the ELSP.
2920 * Turning off the engine->irq_tasklet until the reset is over
2921 * prevents the race.
2923 tasklet_kill(&engine->execlists.irq_tasklet);
2924 tasklet_disable(&engine->execlists.irq_tasklet);
2926 if (engine->irq_seqno_barrier)
2927 engine->irq_seqno_barrier(engine);
2929 request = i915_gem_find_active_request(engine);
2930 if (request && request->fence.error == -EIO)
2931 request = ERR_PTR(-EIO); /* Previous reset failed! */
2936 int i915_gem_reset_prepare(struct drm_i915_private *dev_priv)
2938 struct intel_engine_cs *engine;
2939 struct drm_i915_gem_request *request;
2940 enum intel_engine_id id;
2943 for_each_engine(engine, dev_priv, id) {
2944 request = i915_gem_reset_prepare_engine(engine);
2945 if (IS_ERR(request)) {
2946 err = PTR_ERR(request);
2950 engine->hangcheck.active_request = request;
2953 i915_gem_revoke_fences(dev_priv);
2958 static void skip_request(struct drm_i915_gem_request *request)
2960 void *vaddr = request->ring->vaddr;
2963 /* As this request likely depends on state from the lost
2964 * context, clear out all the user operations leaving the
2965 * breadcrumb at the end (so we get the fence notifications).
2967 head = request->head;
2968 if (request->postfix < head) {
2969 memset(vaddr + head, 0, request->ring->size - head);
2972 memset(vaddr + head, 0, request->postfix - head);
2974 dma_fence_set_error(&request->fence, -EIO);
2977 static void engine_skip_context(struct drm_i915_gem_request *request)
2979 struct intel_engine_cs *engine = request->engine;
2980 struct i915_gem_context *hung_ctx = request->ctx;
2981 struct intel_timeline *timeline;
2982 unsigned long flags;
2984 timeline = i915_gem_context_lookup_timeline(hung_ctx, engine);
2986 spin_lock_irqsave(&engine->timeline->lock, flags);
2987 spin_lock(&timeline->lock);
2989 list_for_each_entry_continue(request, &engine->timeline->requests, link)
2990 if (request->ctx == hung_ctx)
2991 skip_request(request);
2993 list_for_each_entry(request, &timeline->requests, link)
2994 skip_request(request);
2996 spin_unlock(&timeline->lock);
2997 spin_unlock_irqrestore(&engine->timeline->lock, flags);
3000 /* Returns the request if it was guilty of the hang */
3001 static struct drm_i915_gem_request *
3002 i915_gem_reset_request(struct intel_engine_cs *engine,
3003 struct drm_i915_gem_request *request)
3005 /* The guilty request will get skipped on a hung engine.
3007 * Users of client default contexts do not rely on logical
3008 * state preserved between batches so it is safe to execute
3009 * queued requests following the hang. Non default contexts
3010 * rely on preserved state, so skipping a batch loses the
3011 * evolution of the state and it needs to be considered corrupted.
3012 * Executing more queued batches on top of corrupted state is
3013 * risky. But we take the risk by trying to advance through
3014 * the queued requests in order to make the client behaviour
3015 * more predictable around resets, by not throwing away random
3016 * amount of batches it has prepared for execution. Sophisticated
3017 * clients can use gem_reset_stats_ioctl and dma fence status
3018 * (exported via sync_file info ioctl on explicit fences) to observe
3019 * when it loses the context state and should rebuild accordingly.
3021 * The context ban, and ultimately the client ban, mechanism are safety
3022 * valves if client submission ends up resulting in nothing more than
3026 if (engine_stalled(engine)) {
3027 i915_gem_context_mark_guilty(request->ctx);
3028 skip_request(request);
3030 /* If this context is now banned, skip all pending requests. */
3031 if (i915_gem_context_is_banned(request->ctx))
3032 engine_skip_context(request);
3035 * Since this is not the hung engine, it may have advanced
3036 * since the hang declaration. Double check by refinding
3037 * the active request at the time of the reset.
3039 request = i915_gem_find_active_request(engine);
3041 i915_gem_context_mark_innocent(request->ctx);
3042 dma_fence_set_error(&request->fence, -EAGAIN);
3044 /* Rewind the engine to replay the incomplete rq */
3045 spin_lock_irq(&engine->timeline->lock);
3046 request = list_prev_entry(request, link);
3047 if (&request->link == &engine->timeline->requests)
3049 spin_unlock_irq(&engine->timeline->lock);
3056 void i915_gem_reset_engine(struct intel_engine_cs *engine,
3057 struct drm_i915_gem_request *request)
3059 engine->irq_posted = 0;
3062 request = i915_gem_reset_request(engine, request);
3065 DRM_DEBUG_DRIVER("resetting %s to restart from tail of request 0x%x\n",
3066 engine->name, request->global_seqno);
3069 /* Setup the CS to resume from the breadcrumb of the hung request */
3070 engine->reset_hw(engine, request);
3073 void i915_gem_reset(struct drm_i915_private *dev_priv)
3075 struct intel_engine_cs *engine;
3076 enum intel_engine_id id;
3078 lockdep_assert_held(&dev_priv->drm.struct_mutex);
3080 i915_gem_retire_requests(dev_priv);
3082 for_each_engine(engine, dev_priv, id) {
3083 struct i915_gem_context *ctx;
3085 i915_gem_reset_engine(engine, engine->hangcheck.active_request);
3086 ctx = fetch_and_zero(&engine->last_retired_context);
3088 engine->context_unpin(engine, ctx);
3091 i915_gem_restore_fences(dev_priv);
3093 if (dev_priv->gt.awake) {
3094 intel_sanitize_gt_powersave(dev_priv);
3095 intel_enable_gt_powersave(dev_priv);
3096 if (INTEL_GEN(dev_priv) >= 6)
3097 gen6_rps_busy(dev_priv);
3101 void i915_gem_reset_finish_engine(struct intel_engine_cs *engine)
3103 tasklet_enable(&engine->execlists.irq_tasklet);
3104 kthread_unpark(engine->breadcrumbs.signaler);
3106 intel_uncore_forcewake_put(engine->i915, FORCEWAKE_ALL);
3109 void i915_gem_reset_finish(struct drm_i915_private *dev_priv)
3111 struct intel_engine_cs *engine;
3112 enum intel_engine_id id;
3114 lockdep_assert_held(&dev_priv->drm.struct_mutex);
3116 for_each_engine(engine, dev_priv, id) {
3117 engine->hangcheck.active_request = NULL;
3118 i915_gem_reset_finish_engine(engine);
3122 static void nop_submit_request(struct drm_i915_gem_request *request)
3124 dma_fence_set_error(&request->fence, -EIO);
3126 i915_gem_request_submit(request);
3129 static void nop_complete_submit_request(struct drm_i915_gem_request *request)
3131 unsigned long flags;
3133 dma_fence_set_error(&request->fence, -EIO);
3135 spin_lock_irqsave(&request->engine->timeline->lock, flags);
3136 __i915_gem_request_submit(request);
3137 intel_engine_init_global_seqno(request->engine, request->global_seqno);
3138 spin_unlock_irqrestore(&request->engine->timeline->lock, flags);
3141 void i915_gem_set_wedged(struct drm_i915_private *i915)
3143 struct intel_engine_cs *engine;
3144 enum intel_engine_id id;
3147 * First, stop submission to hw, but do not yet complete requests by
3148 * rolling the global seqno forward (since this would complete requests
3149 * for which we haven't set the fence error to EIO yet).
3151 for_each_engine(engine, i915, id)
3152 engine->submit_request = nop_submit_request;
3155 * Make sure no one is running the old callback before we proceed with
3156 * cancelling requests and resetting the completion tracking. Otherwise
3157 * we might submit a request to the hardware which never completes.
3161 for_each_engine(engine, i915, id) {
3162 /* Mark all executing requests as skipped */
3163 engine->cancel_requests(engine);
3166 * Only once we've force-cancelled all in-flight requests can we
3167 * start to complete all requests.
3169 engine->submit_request = nop_complete_submit_request;
3173 * Make sure no request can slip through without getting completed by
3174 * either this call here to intel_engine_init_global_seqno, or the one
3175 * in nop_complete_submit_request.
3179 for_each_engine(engine, i915, id) {
3180 unsigned long flags;
3182 /* Mark all pending requests as complete so that any concurrent
3183 * (lockless) lookup doesn't try and wait upon the request as we
3186 spin_lock_irqsave(&engine->timeline->lock, flags);
3187 intel_engine_init_global_seqno(engine,
3188 intel_engine_last_submit(engine));
3189 spin_unlock_irqrestore(&engine->timeline->lock, flags);
3192 set_bit(I915_WEDGED, &i915->gpu_error.flags);
3193 wake_up_all(&i915->gpu_error.reset_queue);
3196 bool i915_gem_unset_wedged(struct drm_i915_private *i915)
3198 struct i915_gem_timeline *tl;
3201 lockdep_assert_held(&i915->drm.struct_mutex);
3202 if (!test_bit(I915_WEDGED, &i915->gpu_error.flags))
3205 /* Before unwedging, make sure that all pending operations
3206 * are flushed and errored out - we may have requests waiting upon
3207 * third party fences. We marked all inflight requests as EIO, and
3208 * every execbuf since returned EIO, for consistency we want all
3209 * the currently pending requests to also be marked as EIO, which
3210 * is done inside our nop_submit_request - and so we must wait.
3212 * No more can be submitted until we reset the wedged bit.
3214 list_for_each_entry(tl, &i915->gt.timelines, link) {
3215 for (i = 0; i < ARRAY_SIZE(tl->engine); i++) {
3216 struct drm_i915_gem_request *rq;
3218 rq = i915_gem_active_peek(&tl->engine[i].last_request,
3219 &i915->drm.struct_mutex);
3223 /* We can't use our normal waiter as we want to
3224 * avoid recursively trying to handle the current
3225 * reset. The basic dma_fence_default_wait() installs
3226 * a callback for dma_fence_signal(), which is
3227 * triggered by our nop handler (indirectly, the
3228 * callback enables the signaler thread which is
3229 * woken by the nop_submit_request() advancing the seqno
3230 * and when the seqno passes the fence, the signaler
3231 * then signals the fence waking us up).
3233 if (dma_fence_default_wait(&rq->fence, true,
3234 MAX_SCHEDULE_TIMEOUT) < 0)
3239 /* Undo nop_submit_request. We prevent all new i915 requests from
3240 * being queued (by disallowing execbuf whilst wedged) so having
3241 * waited for all active requests above, we know the system is idle
3242 * and do not have to worry about a thread being inside
3243 * engine->submit_request() as we swap over. So unlike installing
3244 * the nop_submit_request on reset, we can do this from normal
3245 * context and do not require stop_machine().
3247 intel_engines_reset_default_submission(i915);
3248 i915_gem_contexts_lost(i915);
3250 smp_mb__before_atomic(); /* complete takeover before enabling execbuf */
3251 clear_bit(I915_WEDGED, &i915->gpu_error.flags);
3257 i915_gem_retire_work_handler(struct work_struct *work)
3259 struct drm_i915_private *dev_priv =
3260 container_of(work, typeof(*dev_priv), gt.retire_work.work);
3261 struct drm_device *dev = &dev_priv->drm;
3263 /* Come back later if the device is busy... */
3264 if (mutex_trylock(&dev->struct_mutex)) {
3265 i915_gem_retire_requests(dev_priv);
3266 mutex_unlock(&dev->struct_mutex);
3269 /* Keep the retire handler running until we are finally idle.
3270 * We do not need to do this test under locking as in the worst-case
3271 * we queue the retire worker once too often.
3273 if (READ_ONCE(dev_priv->gt.awake)) {
3274 i915_queue_hangcheck(dev_priv);
3275 queue_delayed_work(dev_priv->wq,
3276 &dev_priv->gt.retire_work,
3277 round_jiffies_up_relative(HZ));
3282 i915_gem_idle_work_handler(struct work_struct *work)
3284 struct drm_i915_private *dev_priv =
3285 container_of(work, typeof(*dev_priv), gt.idle_work.work);
3286 struct drm_device *dev = &dev_priv->drm;
3287 bool rearm_hangcheck;
3289 if (!READ_ONCE(dev_priv->gt.awake))
3293 * Wait for last execlists context complete, but bail out in case a
3294 * new request is submitted.
3296 wait_for(intel_engines_are_idle(dev_priv), 10);
3297 if (READ_ONCE(dev_priv->gt.active_requests))
3301 cancel_delayed_work_sync(&dev_priv->gpu_error.hangcheck_work);
3303 if (!mutex_trylock(&dev->struct_mutex)) {
3304 /* Currently busy, come back later */
3305 mod_delayed_work(dev_priv->wq,
3306 &dev_priv->gt.idle_work,
3307 msecs_to_jiffies(50));
3312 * New request retired after this work handler started, extend active
3313 * period until next instance of the work.
3315 if (work_pending(work))
3318 if (dev_priv->gt.active_requests)
3321 if (wait_for(intel_engines_are_idle(dev_priv), 10))
3322 DRM_ERROR("Timeout waiting for engines to idle\n");
3324 intel_engines_mark_idle(dev_priv);
3325 i915_gem_timelines_mark_idle(dev_priv);
3327 GEM_BUG_ON(!dev_priv->gt.awake);
3328 dev_priv->gt.awake = false;
3329 rearm_hangcheck = false;
3331 if (INTEL_GEN(dev_priv) >= 6)
3332 gen6_rps_idle(dev_priv);
3333 intel_runtime_pm_put(dev_priv);
3335 mutex_unlock(&dev->struct_mutex);
3338 if (rearm_hangcheck) {
3339 GEM_BUG_ON(!dev_priv->gt.awake);
3340 i915_queue_hangcheck(dev_priv);
3344 void i915_gem_close_object(struct drm_gem_object *gem, struct drm_file *file)
3346 struct drm_i915_private *i915 = to_i915(gem->dev);
3347 struct drm_i915_gem_object *obj = to_intel_bo(gem);
3348 struct drm_i915_file_private *fpriv = file->driver_priv;
3349 struct i915_lut_handle *lut, *ln;
3351 mutex_lock(&i915->drm.struct_mutex);
3353 list_for_each_entry_safe(lut, ln, &obj->lut_list, obj_link) {
3354 struct i915_gem_context *ctx = lut->ctx;
3355 struct i915_vma *vma;
3357 GEM_BUG_ON(ctx->file_priv == ERR_PTR(-EBADF));
3358 if (ctx->file_priv != fpriv)
3361 vma = radix_tree_delete(&ctx->handles_vma, lut->handle);
3362 GEM_BUG_ON(vma->obj != obj);
3364 /* We allow the process to have multiple handles to the same
3365 * vma, in the same fd namespace, by virtue of flink/open.
3367 GEM_BUG_ON(!vma->open_count);
3368 if (!--vma->open_count && !i915_vma_is_ggtt(vma))
3369 i915_vma_close(vma);
3371 list_del(&lut->obj_link);
3372 list_del(&lut->ctx_link);
3374 kmem_cache_free(i915->luts, lut);
3375 __i915_gem_object_release_unless_active(obj);
3378 mutex_unlock(&i915->drm.struct_mutex);
3381 static unsigned long to_wait_timeout(s64 timeout_ns)
3384 return MAX_SCHEDULE_TIMEOUT;
3386 if (timeout_ns == 0)
3389 return nsecs_to_jiffies_timeout(timeout_ns);
3393 * i915_gem_wait_ioctl - implements DRM_IOCTL_I915_GEM_WAIT
3394 * @dev: drm device pointer
3395 * @data: ioctl data blob
3396 * @file: drm file pointer
3398 * Returns 0 if successful, else an error is returned with the remaining time in
3399 * the timeout parameter.
3400 * -ETIME: object is still busy after timeout
3401 * -ERESTARTSYS: signal interrupted the wait
3402 * -ENONENT: object doesn't exist
3403 * Also possible, but rare:
3404 * -EAGAIN: incomplete, restart syscall
3406 * -ENODEV: Internal IRQ fail
3407 * -E?: The add request failed
3409 * The wait ioctl with a timeout of 0 reimplements the busy ioctl. With any
3410 * non-zero timeout parameter the wait ioctl will wait for the given number of
3411 * nanoseconds on an object becoming unbusy. Since the wait itself does so
3412 * without holding struct_mutex the object may become re-busied before this
3413 * function completes. A similar but shorter * race condition exists in the busy
3417 i915_gem_wait_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
3419 struct drm_i915_gem_wait *args = data;
3420 struct drm_i915_gem_object *obj;
3424 if (args->flags != 0)
3427 obj = i915_gem_object_lookup(file, args->bo_handle);
3431 start = ktime_get();
3433 ret = i915_gem_object_wait(obj,
3434 I915_WAIT_INTERRUPTIBLE | I915_WAIT_ALL,
3435 to_wait_timeout(args->timeout_ns),
3436 to_rps_client(file));
3438 if (args->timeout_ns > 0) {
3439 args->timeout_ns -= ktime_to_ns(ktime_sub(ktime_get(), start));
3440 if (args->timeout_ns < 0)
3441 args->timeout_ns = 0;
3444 * Apparently ktime isn't accurate enough and occasionally has a
3445 * bit of mismatch in the jiffies<->nsecs<->ktime loop. So patch
3446 * things up to make the test happy. We allow up to 1 jiffy.
3448 * This is a regression from the timespec->ktime conversion.
3450 if (ret == -ETIME && !nsecs_to_jiffies(args->timeout_ns))
3451 args->timeout_ns = 0;
3453 /* Asked to wait beyond the jiffie/scheduler precision? */
3454 if (ret == -ETIME && args->timeout_ns)
3458 i915_gem_object_put(obj);
3462 static int wait_for_timeline(struct i915_gem_timeline *tl, unsigned int flags)
3466 for (i = 0; i < ARRAY_SIZE(tl->engine); i++) {
3467 ret = i915_gem_active_wait(&tl->engine[i].last_request, flags);
3475 static int wait_for_engines(struct drm_i915_private *i915)
3477 if (wait_for(intel_engines_are_idle(i915), 50)) {
3478 DRM_ERROR("Failed to idle engines, declaring wedged!\n");
3479 i915_gem_set_wedged(i915);
3486 int i915_gem_wait_for_idle(struct drm_i915_private *i915, unsigned int flags)
3490 /* If the device is asleep, we have no requests outstanding */
3491 if (!READ_ONCE(i915->gt.awake))
3494 if (flags & I915_WAIT_LOCKED) {
3495 struct i915_gem_timeline *tl;
3497 lockdep_assert_held(&i915->drm.struct_mutex);
3499 list_for_each_entry(tl, &i915->gt.timelines, link) {
3500 ret = wait_for_timeline(tl, flags);
3505 i915_gem_retire_requests(i915);
3506 GEM_BUG_ON(i915->gt.active_requests);
3508 ret = wait_for_engines(i915);
3510 ret = wait_for_timeline(&i915->gt.global_timeline, flags);
3516 static void __i915_gem_object_flush_for_display(struct drm_i915_gem_object *obj)
3519 * We manually flush the CPU domain so that we can override and
3520 * force the flush for the display, and perform it asyncrhonously.
3522 flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
3523 if (obj->cache_dirty)
3524 i915_gem_clflush_object(obj, I915_CLFLUSH_FORCE);
3525 obj->base.write_domain = 0;
3528 void i915_gem_object_flush_if_display(struct drm_i915_gem_object *obj)
3530 if (!READ_ONCE(obj->pin_global))
3533 mutex_lock(&obj->base.dev->struct_mutex);
3534 __i915_gem_object_flush_for_display(obj);
3535 mutex_unlock(&obj->base.dev->struct_mutex);
3539 * Moves a single object to the WC read, and possibly write domain.
3540 * @obj: object to act on
3541 * @write: ask for write access or read only
3543 * This function returns when the move is complete, including waiting on
3547 i915_gem_object_set_to_wc_domain(struct drm_i915_gem_object *obj, bool write)
3551 lockdep_assert_held(&obj->base.dev->struct_mutex);
3553 ret = i915_gem_object_wait(obj,
3554 I915_WAIT_INTERRUPTIBLE |
3556 (write ? I915_WAIT_ALL : 0),
3557 MAX_SCHEDULE_TIMEOUT,
3562 if (obj->base.write_domain == I915_GEM_DOMAIN_WC)
3565 /* Flush and acquire obj->pages so that we are coherent through
3566 * direct access in memory with previous cached writes through
3567 * shmemfs and that our cache domain tracking remains valid.
3568 * For example, if the obj->filp was moved to swap without us
3569 * being notified and releasing the pages, we would mistakenly
3570 * continue to assume that the obj remained out of the CPU cached
3573 ret = i915_gem_object_pin_pages(obj);
3577 flush_write_domain(obj, ~I915_GEM_DOMAIN_WC);
3579 /* Serialise direct access to this object with the barriers for
3580 * coherent writes from the GPU, by effectively invalidating the
3581 * WC domain upon first access.
3583 if ((obj->base.read_domains & I915_GEM_DOMAIN_WC) == 0)
3586 /* It should now be out of any other write domains, and we can update
3587 * the domain values for our changes.
3589 GEM_BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_WC) != 0);
3590 obj->base.read_domains |= I915_GEM_DOMAIN_WC;
3592 obj->base.read_domains = I915_GEM_DOMAIN_WC;
3593 obj->base.write_domain = I915_GEM_DOMAIN_WC;
3594 obj->mm.dirty = true;
3597 i915_gem_object_unpin_pages(obj);
3602 * Moves a single object to the GTT read, and possibly write domain.
3603 * @obj: object to act on
3604 * @write: ask for write access or read only
3606 * This function returns when the move is complete, including waiting on
3610 i915_gem_object_set_to_gtt_domain(struct drm_i915_gem_object *obj, bool write)
3614 lockdep_assert_held(&obj->base.dev->struct_mutex);
3616 ret = i915_gem_object_wait(obj,
3617 I915_WAIT_INTERRUPTIBLE |
3619 (write ? I915_WAIT_ALL : 0),
3620 MAX_SCHEDULE_TIMEOUT,
3625 if (obj->base.write_domain == I915_GEM_DOMAIN_GTT)
3628 /* Flush and acquire obj->pages so that we are coherent through
3629 * direct access in memory with previous cached writes through
3630 * shmemfs and that our cache domain tracking remains valid.
3631 * For example, if the obj->filp was moved to swap without us
3632 * being notified and releasing the pages, we would mistakenly
3633 * continue to assume that the obj remained out of the CPU cached
3636 ret = i915_gem_object_pin_pages(obj);
3640 flush_write_domain(obj, ~I915_GEM_DOMAIN_GTT);
3642 /* Serialise direct access to this object with the barriers for
3643 * coherent writes from the GPU, by effectively invalidating the
3644 * GTT domain upon first access.
3646 if ((obj->base.read_domains & I915_GEM_DOMAIN_GTT) == 0)
3649 /* It should now be out of any other write domains, and we can update
3650 * the domain values for our changes.
3652 GEM_BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
3653 obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
3655 obj->base.read_domains = I915_GEM_DOMAIN_GTT;
3656 obj->base.write_domain = I915_GEM_DOMAIN_GTT;
3657 obj->mm.dirty = true;
3660 i915_gem_object_unpin_pages(obj);
3665 * Changes the cache-level of an object across all VMA.
3666 * @obj: object to act on
3667 * @cache_level: new cache level to set for the object
3669 * After this function returns, the object will be in the new cache-level
3670 * across all GTT and the contents of the backing storage will be coherent,
3671 * with respect to the new cache-level. In order to keep the backing storage
3672 * coherent for all users, we only allow a single cache level to be set
3673 * globally on the object and prevent it from being changed whilst the
3674 * hardware is reading from the object. That is if the object is currently
3675 * on the scanout it will be set to uncached (or equivalent display
3676 * cache coherency) and all non-MOCS GPU access will also be uncached so
3677 * that all direct access to the scanout remains coherent.
3679 int i915_gem_object_set_cache_level(struct drm_i915_gem_object *obj,
3680 enum i915_cache_level cache_level)
3682 struct i915_vma *vma;
3685 lockdep_assert_held(&obj->base.dev->struct_mutex);
3687 if (obj->cache_level == cache_level)
3690 /* Inspect the list of currently bound VMA and unbind any that would
3691 * be invalid given the new cache-level. This is principally to
3692 * catch the issue of the CS prefetch crossing page boundaries and
3693 * reading an invalid PTE on older architectures.
3696 list_for_each_entry(vma, &obj->vma_list, obj_link) {
3697 if (!drm_mm_node_allocated(&vma->node))
3700 if (i915_vma_is_pinned(vma)) {
3701 DRM_DEBUG("can not change the cache level of pinned objects\n");
3705 if (i915_gem_valid_gtt_space(vma, cache_level))
3708 ret = i915_vma_unbind(vma);
3712 /* As unbinding may affect other elements in the
3713 * obj->vma_list (due to side-effects from retiring
3714 * an active vma), play safe and restart the iterator.
3719 /* We can reuse the existing drm_mm nodes but need to change the
3720 * cache-level on the PTE. We could simply unbind them all and
3721 * rebind with the correct cache-level on next use. However since
3722 * we already have a valid slot, dma mapping, pages etc, we may as
3723 * rewrite the PTE in the belief that doing so tramples upon less
3724 * state and so involves less work.
3726 if (obj->bind_count) {
3727 /* Before we change the PTE, the GPU must not be accessing it.
3728 * If we wait upon the object, we know that all the bound
3729 * VMA are no longer active.
3731 ret = i915_gem_object_wait(obj,
3732 I915_WAIT_INTERRUPTIBLE |
3735 MAX_SCHEDULE_TIMEOUT,
3740 if (!HAS_LLC(to_i915(obj->base.dev)) &&
3741 cache_level != I915_CACHE_NONE) {
3742 /* Access to snoopable pages through the GTT is
3743 * incoherent and on some machines causes a hard
3744 * lockup. Relinquish the CPU mmaping to force
3745 * userspace to refault in the pages and we can
3746 * then double check if the GTT mapping is still
3747 * valid for that pointer access.
3749 i915_gem_release_mmap(obj);
3751 /* As we no longer need a fence for GTT access,
3752 * we can relinquish it now (and so prevent having
3753 * to steal a fence from someone else on the next
3754 * fence request). Note GPU activity would have
3755 * dropped the fence as all snoopable access is
3756 * supposed to be linear.
3758 list_for_each_entry(vma, &obj->vma_list, obj_link) {
3759 ret = i915_vma_put_fence(vma);
3764 /* We either have incoherent backing store and
3765 * so no GTT access or the architecture is fully
3766 * coherent. In such cases, existing GTT mmaps
3767 * ignore the cache bit in the PTE and we can
3768 * rewrite it without confusing the GPU or having
3769 * to force userspace to fault back in its mmaps.
3773 list_for_each_entry(vma, &obj->vma_list, obj_link) {
3774 if (!drm_mm_node_allocated(&vma->node))
3777 ret = i915_vma_bind(vma, cache_level, PIN_UPDATE);
3783 list_for_each_entry(vma, &obj->vma_list, obj_link)
3784 vma->node.color = cache_level;
3785 i915_gem_object_set_cache_coherency(obj, cache_level);
3786 obj->cache_dirty = true; /* Always invalidate stale cachelines */
3791 int i915_gem_get_caching_ioctl(struct drm_device *dev, void *data,
3792 struct drm_file *file)
3794 struct drm_i915_gem_caching *args = data;
3795 struct drm_i915_gem_object *obj;
3799 obj = i915_gem_object_lookup_rcu(file, args->handle);
3805 switch (obj->cache_level) {
3806 case I915_CACHE_LLC:
3807 case I915_CACHE_L3_LLC:
3808 args->caching = I915_CACHING_CACHED;
3812 args->caching = I915_CACHING_DISPLAY;
3816 args->caching = I915_CACHING_NONE;
3824 int i915_gem_set_caching_ioctl(struct drm_device *dev, void *data,
3825 struct drm_file *file)
3827 struct drm_i915_private *i915 = to_i915(dev);
3828 struct drm_i915_gem_caching *args = data;
3829 struct drm_i915_gem_object *obj;
3830 enum i915_cache_level level;
3833 switch (args->caching) {
3834 case I915_CACHING_NONE:
3835 level = I915_CACHE_NONE;
3837 case I915_CACHING_CACHED:
3839 * Due to a HW issue on BXT A stepping, GPU stores via a
3840 * snooped mapping may leave stale data in a corresponding CPU
3841 * cacheline, whereas normally such cachelines would get
3844 if (!HAS_LLC(i915) && !HAS_SNOOP(i915))
3847 level = I915_CACHE_LLC;
3849 case I915_CACHING_DISPLAY:
3850 level = HAS_WT(i915) ? I915_CACHE_WT : I915_CACHE_NONE;
3856 obj = i915_gem_object_lookup(file, args->handle);
3860 if (obj->cache_level == level)
3863 ret = i915_gem_object_wait(obj,
3864 I915_WAIT_INTERRUPTIBLE,
3865 MAX_SCHEDULE_TIMEOUT,
3866 to_rps_client(file));
3870 ret = i915_mutex_lock_interruptible(dev);
3874 ret = i915_gem_object_set_cache_level(obj, level);
3875 mutex_unlock(&dev->struct_mutex);
3878 i915_gem_object_put(obj);
3883 * Prepare buffer for display plane (scanout, cursors, etc).
3884 * Can be called from an uninterruptible phase (modesetting) and allows
3885 * any flushes to be pipelined (for pageflips).
3888 i915_gem_object_pin_to_display_plane(struct drm_i915_gem_object *obj,
3890 const struct i915_ggtt_view *view)
3892 struct i915_vma *vma;
3895 lockdep_assert_held(&obj->base.dev->struct_mutex);
3897 /* Mark the global pin early so that we account for the
3898 * display coherency whilst setting up the cache domains.
3902 /* The display engine is not coherent with the LLC cache on gen6. As
3903 * a result, we make sure that the pinning that is about to occur is
3904 * done with uncached PTEs. This is lowest common denominator for all
3907 * However for gen6+, we could do better by using the GFDT bit instead
3908 * of uncaching, which would allow us to flush all the LLC-cached data
3909 * with that bit in the PTE to main memory with just one PIPE_CONTROL.
3911 ret = i915_gem_object_set_cache_level(obj,
3912 HAS_WT(to_i915(obj->base.dev)) ?
3913 I915_CACHE_WT : I915_CACHE_NONE);
3916 goto err_unpin_global;
3919 /* As the user may map the buffer once pinned in the display plane
3920 * (e.g. libkms for the bootup splash), we have to ensure that we
3921 * always use map_and_fenceable for all scanout buffers. However,
3922 * it may simply be too big to fit into mappable, in which case
3923 * put it anyway and hope that userspace can cope (but always first
3924 * try to preserve the existing ABI).
3926 vma = ERR_PTR(-ENOSPC);
3927 if (!view || view->type == I915_GGTT_VIEW_NORMAL)
3928 vma = i915_gem_object_ggtt_pin(obj, view, 0, alignment,
3929 PIN_MAPPABLE | PIN_NONBLOCK);
3931 struct drm_i915_private *i915 = to_i915(obj->base.dev);
3934 /* Valleyview is definitely limited to scanning out the first
3935 * 512MiB. Lets presume this behaviour was inherited from the
3936 * g4x display engine and that all earlier gen are similarly
3937 * limited. Testing suggests that it is a little more
3938 * complicated than this. For example, Cherryview appears quite
3939 * happy to scanout from anywhere within its global aperture.
3942 if (HAS_GMCH_DISPLAY(i915))
3943 flags = PIN_MAPPABLE;
3944 vma = i915_gem_object_ggtt_pin(obj, view, 0, alignment, flags);
3947 goto err_unpin_global;
3949 vma->display_alignment = max_t(u64, vma->display_alignment, alignment);
3951 /* Treat this as an end-of-frame, like intel_user_framebuffer_dirty() */
3952 __i915_gem_object_flush_for_display(obj);
3953 intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
3955 /* It should now be out of any other write domains, and we can update
3956 * the domain values for our changes.
3958 obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
3968 i915_gem_object_unpin_from_display_plane(struct i915_vma *vma)
3970 lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
3972 if (WARN_ON(vma->obj->pin_global == 0))
3975 if (--vma->obj->pin_global == 0)
3976 vma->display_alignment = I915_GTT_MIN_ALIGNMENT;
3978 /* Bump the LRU to try and avoid premature eviction whilst flipping */
3979 i915_gem_object_bump_inactive_ggtt(vma->obj);
3981 i915_vma_unpin(vma);
3985 * Moves a single object to the CPU read, and possibly write domain.
3986 * @obj: object to act on
3987 * @write: requesting write or read-only access
3989 * This function returns when the move is complete, including waiting on
3993 i915_gem_object_set_to_cpu_domain(struct drm_i915_gem_object *obj, bool write)
3997 lockdep_assert_held(&obj->base.dev->struct_mutex);
3999 ret = i915_gem_object_wait(obj,
4000 I915_WAIT_INTERRUPTIBLE |
4002 (write ? I915_WAIT_ALL : 0),
4003 MAX_SCHEDULE_TIMEOUT,
4008 flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
4010 /* Flush the CPU cache if it's still invalid. */
4011 if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0) {
4012 i915_gem_clflush_object(obj, I915_CLFLUSH_SYNC);
4013 obj->base.read_domains |= I915_GEM_DOMAIN_CPU;
4016 /* It should now be out of any other write domains, and we can update
4017 * the domain values for our changes.
4019 GEM_BUG_ON(obj->base.write_domain & ~I915_GEM_DOMAIN_CPU);
4021 /* If we're writing through the CPU, then the GPU read domains will
4022 * need to be invalidated at next use.
4025 __start_cpu_write(obj);
4030 /* Throttle our rendering by waiting until the ring has completed our requests
4031 * emitted over 20 msec ago.
4033 * Note that if we were to use the current jiffies each time around the loop,
4034 * we wouldn't escape the function with any frames outstanding if the time to
4035 * render a frame was over 20ms.
4037 * This should get us reasonable parallelism between CPU and GPU but also
4038 * relatively low latency when blocking on a particular request to finish.
4041 i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file)
4043 struct drm_i915_private *dev_priv = to_i915(dev);
4044 struct drm_i915_file_private *file_priv = file->driver_priv;
4045 unsigned long recent_enough = jiffies - DRM_I915_THROTTLE_JIFFIES;
4046 struct drm_i915_gem_request *request, *target = NULL;
4049 /* ABI: return -EIO if already wedged */
4050 if (i915_terminally_wedged(&dev_priv->gpu_error))
4053 spin_lock(&file_priv->mm.lock);
4054 list_for_each_entry(request, &file_priv->mm.request_list, client_link) {
4055 if (time_after_eq(request->emitted_jiffies, recent_enough))
4059 list_del(&target->client_link);
4060 target->file_priv = NULL;
4066 i915_gem_request_get(target);
4067 spin_unlock(&file_priv->mm.lock);
4072 ret = i915_wait_request(target,
4073 I915_WAIT_INTERRUPTIBLE,
4074 MAX_SCHEDULE_TIMEOUT);
4075 i915_gem_request_put(target);
4077 return ret < 0 ? ret : 0;
4081 i915_gem_object_ggtt_pin(struct drm_i915_gem_object *obj,
4082 const struct i915_ggtt_view *view,
4087 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
4088 struct i915_address_space *vm = &dev_priv->ggtt.base;
4089 struct i915_vma *vma;
4092 lockdep_assert_held(&obj->base.dev->struct_mutex);
4094 if (!view && flags & PIN_MAPPABLE) {
4095 /* If the required space is larger than the available
4096 * aperture, we will not able to find a slot for the
4097 * object and unbinding the object now will be in
4098 * vain. Worse, doing so may cause us to ping-pong
4099 * the object in and out of the Global GTT and
4100 * waste a lot of cycles under the mutex.
4102 if (obj->base.size > dev_priv->ggtt.mappable_end)
4103 return ERR_PTR(-E2BIG);
4105 /* If NONBLOCK is set the caller is optimistically
4106 * trying to cache the full object within the mappable
4107 * aperture, and *must* have a fallback in place for
4108 * situations where we cannot bind the object. We
4109 * can be a little more lax here and use the fallback
4110 * more often to avoid costly migrations of ourselves
4111 * and other objects within the aperture.
4113 * Half-the-aperture is used as a simple heuristic.
4114 * More interesting would to do search for a free
4115 * block prior to making the commitment to unbind.
4116 * That caters for the self-harm case, and with a
4117 * little more heuristics (e.g. NOFAULT, NOEVICT)
4118 * we could try to minimise harm to others.
4120 if (flags & PIN_NONBLOCK &&
4121 obj->base.size > dev_priv->ggtt.mappable_end / 2)
4122 return ERR_PTR(-ENOSPC);
4125 vma = i915_vma_instance(obj, vm, view);
4126 if (unlikely(IS_ERR(vma)))
4129 if (i915_vma_misplaced(vma, size, alignment, flags)) {
4130 if (flags & PIN_NONBLOCK) {
4131 if (i915_vma_is_pinned(vma) || i915_vma_is_active(vma))
4132 return ERR_PTR(-ENOSPC);
4134 if (flags & PIN_MAPPABLE &&
4135 vma->fence_size > dev_priv->ggtt.mappable_end / 2)
4136 return ERR_PTR(-ENOSPC);
4139 WARN(i915_vma_is_pinned(vma),
4140 "bo is already pinned in ggtt with incorrect alignment:"
4141 " offset=%08x, req.alignment=%llx,"
4142 " req.map_and_fenceable=%d, vma->map_and_fenceable=%d\n",
4143 i915_ggtt_offset(vma), alignment,
4144 !!(flags & PIN_MAPPABLE),
4145 i915_vma_is_map_and_fenceable(vma));
4146 ret = i915_vma_unbind(vma);
4148 return ERR_PTR(ret);
4151 ret = i915_vma_pin(vma, size, alignment, flags | PIN_GLOBAL);
4153 return ERR_PTR(ret);
4158 static __always_inline unsigned int __busy_read_flag(unsigned int id)
4160 /* Note that we could alias engines in the execbuf API, but
4161 * that would be very unwise as it prevents userspace from
4162 * fine control over engine selection. Ahem.
4164 * This should be something like EXEC_MAX_ENGINE instead of
4167 BUILD_BUG_ON(I915_NUM_ENGINES > 16);
4168 return 0x10000 << id;
4171 static __always_inline unsigned int __busy_write_id(unsigned int id)
4173 /* The uABI guarantees an active writer is also amongst the read
4174 * engines. This would be true if we accessed the activity tracking
4175 * under the lock, but as we perform the lookup of the object and
4176 * its activity locklessly we can not guarantee that the last_write
4177 * being active implies that we have set the same engine flag from
4178 * last_read - hence we always set both read and write busy for
4181 return id | __busy_read_flag(id);
4184 static __always_inline unsigned int
4185 __busy_set_if_active(const struct dma_fence *fence,
4186 unsigned int (*flag)(unsigned int id))
4188 struct drm_i915_gem_request *rq;
4190 /* We have to check the current hw status of the fence as the uABI
4191 * guarantees forward progress. We could rely on the idle worker
4192 * to eventually flush us, but to minimise latency just ask the
4195 * Note we only report on the status of native fences.
4197 if (!dma_fence_is_i915(fence))
4200 /* opencode to_request() in order to avoid const warnings */
4201 rq = container_of(fence, struct drm_i915_gem_request, fence);
4202 if (i915_gem_request_completed(rq))
4205 return flag(rq->engine->uabi_id);
4208 static __always_inline unsigned int
4209 busy_check_reader(const struct dma_fence *fence)
4211 return __busy_set_if_active(fence, __busy_read_flag);
4214 static __always_inline unsigned int
4215 busy_check_writer(const struct dma_fence *fence)
4220 return __busy_set_if_active(fence, __busy_write_id);
4224 i915_gem_busy_ioctl(struct drm_device *dev, void *data,
4225 struct drm_file *file)
4227 struct drm_i915_gem_busy *args = data;
4228 struct drm_i915_gem_object *obj;
4229 struct reservation_object_list *list;
4235 obj = i915_gem_object_lookup_rcu(file, args->handle);
4239 /* A discrepancy here is that we do not report the status of
4240 * non-i915 fences, i.e. even though we may report the object as idle,
4241 * a call to set-domain may still stall waiting for foreign rendering.
4242 * This also means that wait-ioctl may report an object as busy,
4243 * where busy-ioctl considers it idle.
4245 * We trade the ability to warn of foreign fences to report on which
4246 * i915 engines are active for the object.
4248 * Alternatively, we can trade that extra information on read/write
4251 * !reservation_object_test_signaled_rcu(obj->resv, true);
4252 * to report the overall busyness. This is what the wait-ioctl does.
4256 seq = raw_read_seqcount(&obj->resv->seq);
4258 /* Translate the exclusive fence to the READ *and* WRITE engine */
4259 args->busy = busy_check_writer(rcu_dereference(obj->resv->fence_excl));
4261 /* Translate shared fences to READ set of engines */
4262 list = rcu_dereference(obj->resv->fence);
4264 unsigned int shared_count = list->shared_count, i;
4266 for (i = 0; i < shared_count; ++i) {
4267 struct dma_fence *fence =
4268 rcu_dereference(list->shared[i]);
4270 args->busy |= busy_check_reader(fence);
4274 if (args->busy && read_seqcount_retry(&obj->resv->seq, seq))
4284 i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
4285 struct drm_file *file_priv)
4287 return i915_gem_ring_throttle(dev, file_priv);
4291 i915_gem_madvise_ioctl(struct drm_device *dev, void *data,
4292 struct drm_file *file_priv)
4294 struct drm_i915_private *dev_priv = to_i915(dev);
4295 struct drm_i915_gem_madvise *args = data;
4296 struct drm_i915_gem_object *obj;
4299 switch (args->madv) {
4300 case I915_MADV_DONTNEED:
4301 case I915_MADV_WILLNEED:
4307 obj = i915_gem_object_lookup(file_priv, args->handle);
4311 err = mutex_lock_interruptible(&obj->mm.lock);
4315 if (i915_gem_object_has_pages(obj) &&
4316 i915_gem_object_is_tiled(obj) &&
4317 dev_priv->quirks & QUIRK_PIN_SWIZZLED_PAGES) {
4318 if (obj->mm.madv == I915_MADV_WILLNEED) {
4319 GEM_BUG_ON(!obj->mm.quirked);
4320 __i915_gem_object_unpin_pages(obj);
4321 obj->mm.quirked = false;
4323 if (args->madv == I915_MADV_WILLNEED) {
4324 GEM_BUG_ON(obj->mm.quirked);
4325 __i915_gem_object_pin_pages(obj);
4326 obj->mm.quirked = true;
4330 if (obj->mm.madv != __I915_MADV_PURGED)
4331 obj->mm.madv = args->madv;
4333 /* if the object is no longer attached, discard its backing storage */
4334 if (obj->mm.madv == I915_MADV_DONTNEED &&
4335 !i915_gem_object_has_pages(obj))
4336 i915_gem_object_truncate(obj);
4338 args->retained = obj->mm.madv != __I915_MADV_PURGED;
4339 mutex_unlock(&obj->mm.lock);
4342 i915_gem_object_put(obj);
4347 frontbuffer_retire(struct i915_gem_active *active,
4348 struct drm_i915_gem_request *request)
4350 struct drm_i915_gem_object *obj =
4351 container_of(active, typeof(*obj), frontbuffer_write);
4353 intel_fb_obj_flush(obj, ORIGIN_CS);
4356 void i915_gem_object_init(struct drm_i915_gem_object *obj,
4357 const struct drm_i915_gem_object_ops *ops)
4359 mutex_init(&obj->mm.lock);
4361 INIT_LIST_HEAD(&obj->vma_list);
4362 INIT_LIST_HEAD(&obj->lut_list);
4363 INIT_LIST_HEAD(&obj->batch_pool_link);
4367 reservation_object_init(&obj->__builtin_resv);
4368 obj->resv = &obj->__builtin_resv;
4370 obj->frontbuffer_ggtt_origin = ORIGIN_GTT;
4371 init_request_active(&obj->frontbuffer_write, frontbuffer_retire);
4373 obj->mm.madv = I915_MADV_WILLNEED;
4374 INIT_RADIX_TREE(&obj->mm.get_page.radix, GFP_KERNEL | __GFP_NOWARN);
4375 mutex_init(&obj->mm.get_page.lock);
4377 i915_gem_info_add_obj(to_i915(obj->base.dev), obj->base.size);
4380 static const struct drm_i915_gem_object_ops i915_gem_object_ops = {
4381 .flags = I915_GEM_OBJECT_HAS_STRUCT_PAGE |
4382 I915_GEM_OBJECT_IS_SHRINKABLE,
4384 .get_pages = i915_gem_object_get_pages_gtt,
4385 .put_pages = i915_gem_object_put_pages_gtt,
4387 .pwrite = i915_gem_object_pwrite_gtt,
4390 static int i915_gem_object_create_shmem(struct drm_device *dev,
4391 struct drm_gem_object *obj,
4394 struct drm_i915_private *i915 = to_i915(dev);
4395 unsigned long flags = VM_NORESERVE;
4398 drm_gem_private_object_init(dev, obj, size);
4401 filp = shmem_file_setup_with_mnt(i915->mm.gemfs, "i915", size,
4404 filp = shmem_file_setup("i915", size, flags);
4407 return PTR_ERR(filp);
4414 struct drm_i915_gem_object *
4415 i915_gem_object_create(struct drm_i915_private *dev_priv, u64 size)
4417 struct drm_i915_gem_object *obj;
4418 struct address_space *mapping;
4419 unsigned int cache_level;
4423 /* There is a prevalence of the assumption that we fit the object's
4424 * page count inside a 32bit _signed_ variable. Let's document this and
4425 * catch if we ever need to fix it. In the meantime, if you do spot
4426 * such a local variable, please consider fixing!
4428 if (size >> PAGE_SHIFT > INT_MAX)
4429 return ERR_PTR(-E2BIG);
4431 if (overflows_type(size, obj->base.size))
4432 return ERR_PTR(-E2BIG);
4434 obj = i915_gem_object_alloc(dev_priv);
4436 return ERR_PTR(-ENOMEM);
4438 ret = i915_gem_object_create_shmem(&dev_priv->drm, &obj->base, size);
4442 mask = GFP_HIGHUSER | __GFP_RECLAIMABLE;
4443 if (IS_I965GM(dev_priv) || IS_I965G(dev_priv)) {
4444 /* 965gm cannot relocate objects above 4GiB. */
4445 mask &= ~__GFP_HIGHMEM;
4446 mask |= __GFP_DMA32;
4449 mapping = obj->base.filp->f_mapping;
4450 mapping_set_gfp_mask(mapping, mask);
4451 GEM_BUG_ON(!(mapping_gfp_mask(mapping) & __GFP_RECLAIM));
4453 i915_gem_object_init(obj, &i915_gem_object_ops);
4455 obj->base.write_domain = I915_GEM_DOMAIN_CPU;
4456 obj->base.read_domains = I915_GEM_DOMAIN_CPU;
4458 if (HAS_LLC(dev_priv))
4459 /* On some devices, we can have the GPU use the LLC (the CPU
4460 * cache) for about a 10% performance improvement
4461 * compared to uncached. Graphics requests other than
4462 * display scanout are coherent with the CPU in
4463 * accessing this cache. This means in this mode we
4464 * don't need to clflush on the CPU side, and on the
4465 * GPU side we only need to flush internal caches to
4466 * get data visible to the CPU.
4468 * However, we maintain the display planes as UC, and so
4469 * need to rebind when first used as such.
4471 cache_level = I915_CACHE_LLC;
4473 cache_level = I915_CACHE_NONE;
4475 i915_gem_object_set_cache_coherency(obj, cache_level);
4477 trace_i915_gem_object_create(obj);
4482 i915_gem_object_free(obj);
4483 return ERR_PTR(ret);
4486 static bool discard_backing_storage(struct drm_i915_gem_object *obj)
4488 /* If we are the last user of the backing storage (be it shmemfs
4489 * pages or stolen etc), we know that the pages are going to be
4490 * immediately released. In this case, we can then skip copying
4491 * back the contents from the GPU.
4494 if (obj->mm.madv != I915_MADV_WILLNEED)
4497 if (obj->base.filp == NULL)
4500 /* At first glance, this looks racy, but then again so would be
4501 * userspace racing mmap against close. However, the first external
4502 * reference to the filp can only be obtained through the
4503 * i915_gem_mmap_ioctl() which safeguards us against the user
4504 * acquiring such a reference whilst we are in the middle of
4505 * freeing the object.
4507 return atomic_long_read(&obj->base.filp->f_count) == 1;
4510 static void __i915_gem_free_objects(struct drm_i915_private *i915,
4511 struct llist_node *freed)
4513 struct drm_i915_gem_object *obj, *on;
4515 intel_runtime_pm_get(i915);
4516 llist_for_each_entry_safe(obj, on, freed, freed) {
4517 struct i915_vma *vma, *vn;
4519 trace_i915_gem_object_destroy(obj);
4521 mutex_lock(&i915->drm.struct_mutex);
4523 GEM_BUG_ON(i915_gem_object_is_active(obj));
4524 list_for_each_entry_safe(vma, vn,
4525 &obj->vma_list, obj_link) {
4526 GEM_BUG_ON(i915_vma_is_active(vma));
4527 vma->flags &= ~I915_VMA_PIN_MASK;
4528 i915_vma_close(vma);
4530 GEM_BUG_ON(!list_empty(&obj->vma_list));
4531 GEM_BUG_ON(!RB_EMPTY_ROOT(&obj->vma_tree));
4533 /* This serializes freeing with the shrinker. Since the free
4534 * is delayed, first by RCU then by the workqueue, we want the
4535 * shrinker to be able to free pages of unreferenced objects,
4536 * or else we may oom whilst there are plenty of deferred
4539 if (i915_gem_object_has_pages(obj)) {
4540 spin_lock(&i915->mm.obj_lock);
4541 list_del_init(&obj->mm.link);
4542 spin_unlock(&i915->mm.obj_lock);
4545 mutex_unlock(&i915->drm.struct_mutex);
4547 GEM_BUG_ON(obj->bind_count);
4548 GEM_BUG_ON(obj->userfault_count);
4549 GEM_BUG_ON(atomic_read(&obj->frontbuffer_bits));
4550 GEM_BUG_ON(!list_empty(&obj->lut_list));
4552 if (obj->ops->release)
4553 obj->ops->release(obj);
4555 if (WARN_ON(i915_gem_object_has_pinned_pages(obj)))
4556 atomic_set(&obj->mm.pages_pin_count, 0);
4557 __i915_gem_object_put_pages(obj, I915_MM_NORMAL);
4558 GEM_BUG_ON(i915_gem_object_has_pages(obj));
4560 if (obj->base.import_attach)
4561 drm_prime_gem_destroy(&obj->base, NULL);
4563 reservation_object_fini(&obj->__builtin_resv);
4564 drm_gem_object_release(&obj->base);
4565 i915_gem_info_remove_obj(i915, obj->base.size);
4568 i915_gem_object_free(obj);
4573 intel_runtime_pm_put(i915);
4576 static void i915_gem_flush_free_objects(struct drm_i915_private *i915)
4578 struct llist_node *freed;
4580 /* Free the oldest, most stale object to keep the free_list short */
4582 if (!llist_empty(&i915->mm.free_list)) { /* quick test for hotpath */
4583 /* Only one consumer of llist_del_first() allowed */
4584 spin_lock(&i915->mm.free_lock);
4585 freed = llist_del_first(&i915->mm.free_list);
4586 spin_unlock(&i915->mm.free_lock);
4588 if (unlikely(freed)) {
4590 __i915_gem_free_objects(i915, freed);
4594 static void __i915_gem_free_work(struct work_struct *work)
4596 struct drm_i915_private *i915 =
4597 container_of(work, struct drm_i915_private, mm.free_work);
4598 struct llist_node *freed;
4600 /* All file-owned VMA should have been released by this point through
4601 * i915_gem_close_object(), or earlier by i915_gem_context_close().
4602 * However, the object may also be bound into the global GTT (e.g.
4603 * older GPUs without per-process support, or for direct access through
4604 * the GTT either for the user or for scanout). Those VMA still need to
4608 spin_lock(&i915->mm.free_lock);
4609 while ((freed = llist_del_all(&i915->mm.free_list))) {
4610 spin_unlock(&i915->mm.free_lock);
4612 __i915_gem_free_objects(i915, freed);
4616 spin_lock(&i915->mm.free_lock);
4618 spin_unlock(&i915->mm.free_lock);
4621 static void __i915_gem_free_object_rcu(struct rcu_head *head)
4623 struct drm_i915_gem_object *obj =
4624 container_of(head, typeof(*obj), rcu);
4625 struct drm_i915_private *i915 = to_i915(obj->base.dev);
4627 /* We can't simply use call_rcu() from i915_gem_free_object()
4628 * as we need to block whilst unbinding, and the call_rcu
4629 * task may be called from softirq context. So we take a
4630 * detour through a worker.
4632 if (llist_add(&obj->freed, &i915->mm.free_list))
4633 schedule_work(&i915->mm.free_work);
4636 void i915_gem_free_object(struct drm_gem_object *gem_obj)
4638 struct drm_i915_gem_object *obj = to_intel_bo(gem_obj);
4640 if (obj->mm.quirked)
4641 __i915_gem_object_unpin_pages(obj);
4643 if (discard_backing_storage(obj))
4644 obj->mm.madv = I915_MADV_DONTNEED;
4646 /* Before we free the object, make sure any pure RCU-only
4647 * read-side critical sections are complete, e.g.
4648 * i915_gem_busy_ioctl(). For the corresponding synchronized
4649 * lookup see i915_gem_object_lookup_rcu().
4651 call_rcu(&obj->rcu, __i915_gem_free_object_rcu);
4654 void __i915_gem_object_release_unless_active(struct drm_i915_gem_object *obj)
4656 lockdep_assert_held(&obj->base.dev->struct_mutex);
4658 if (!i915_gem_object_has_active_reference(obj) &&
4659 i915_gem_object_is_active(obj))
4660 i915_gem_object_set_active_reference(obj);
4662 i915_gem_object_put(obj);
4665 static void assert_kernel_context_is_current(struct drm_i915_private *dev_priv)
4667 struct intel_engine_cs *engine;
4668 enum intel_engine_id id;
4670 for_each_engine(engine, dev_priv, id)
4671 GEM_BUG_ON(engine->last_retired_context &&
4672 !i915_gem_context_is_kernel(engine->last_retired_context));
4675 void i915_gem_sanitize(struct drm_i915_private *i915)
4677 if (i915_terminally_wedged(&i915->gpu_error)) {
4678 mutex_lock(&i915->drm.struct_mutex);
4679 i915_gem_unset_wedged(i915);
4680 mutex_unlock(&i915->drm.struct_mutex);
4684 * If we inherit context state from the BIOS or earlier occupants
4685 * of the GPU, the GPU may be in an inconsistent state when we
4686 * try to take over. The only way to remove the earlier state
4687 * is by resetting. However, resetting on earlier gen is tricky as
4688 * it may impact the display and we are uncertain about the stability
4689 * of the reset, so this could be applied to even earlier gen.
4691 if (INTEL_GEN(i915) >= 5) {
4692 int reset = intel_gpu_reset(i915, ALL_ENGINES);
4693 WARN_ON(reset && reset != -ENODEV);
4697 int i915_gem_suspend(struct drm_i915_private *dev_priv)
4699 struct drm_device *dev = &dev_priv->drm;
4702 intel_runtime_pm_get(dev_priv);
4703 intel_suspend_gt_powersave(dev_priv);
4705 mutex_lock(&dev->struct_mutex);
4707 /* We have to flush all the executing contexts to main memory so
4708 * that they can saved in the hibernation image. To ensure the last
4709 * context image is coherent, we have to switch away from it. That
4710 * leaves the dev_priv->kernel_context still active when
4711 * we actually suspend, and its image in memory may not match the GPU
4712 * state. Fortunately, the kernel_context is disposable and we do
4713 * not rely on its state.
4715 ret = i915_gem_switch_to_kernel_context(dev_priv);
4719 ret = i915_gem_wait_for_idle(dev_priv,
4720 I915_WAIT_INTERRUPTIBLE |
4722 if (ret && ret != -EIO)
4725 assert_kernel_context_is_current(dev_priv);
4726 i915_gem_contexts_lost(dev_priv);
4727 mutex_unlock(&dev->struct_mutex);
4729 intel_guc_suspend(dev_priv);
4731 cancel_delayed_work_sync(&dev_priv->gpu_error.hangcheck_work);
4732 cancel_delayed_work_sync(&dev_priv->gt.retire_work);
4734 /* As the idle_work is rearming if it detects a race, play safe and
4735 * repeat the flush until it is definitely idle.
4737 drain_delayed_work(&dev_priv->gt.idle_work);
4739 /* Assert that we sucessfully flushed all the work and
4740 * reset the GPU back to its idle, low power state.
4742 WARN_ON(dev_priv->gt.awake);
4743 if (WARN_ON(!intel_engines_are_idle(dev_priv)))
4744 i915_gem_set_wedged(dev_priv); /* no hope, discard everything */
4747 * Neither the BIOS, ourselves or any other kernel
4748 * expects the system to be in execlists mode on startup,
4749 * so we need to reset the GPU back to legacy mode. And the only
4750 * known way to disable logical contexts is through a GPU reset.
4752 * So in order to leave the system in a known default configuration,
4753 * always reset the GPU upon unload and suspend. Afterwards we then
4754 * clean up the GEM state tracking, flushing off the requests and
4755 * leaving the system in a known idle state.
4757 * Note that is of the upmost importance that the GPU is idle and
4758 * all stray writes are flushed *before* we dismantle the backing
4759 * storage for the pinned objects.
4761 * However, since we are uncertain that resetting the GPU on older
4762 * machines is a good idea, we don't - just in case it leaves the
4763 * machine in an unusable condition.
4765 i915_gem_sanitize(dev_priv);
4767 intel_runtime_pm_put(dev_priv);
4771 mutex_unlock(&dev->struct_mutex);
4772 intel_runtime_pm_put(dev_priv);
4776 void i915_gem_resume(struct drm_i915_private *dev_priv)
4778 struct drm_device *dev = &dev_priv->drm;
4780 WARN_ON(dev_priv->gt.awake);
4782 mutex_lock(&dev->struct_mutex);
4783 i915_gem_restore_gtt_mappings(dev_priv);
4784 i915_gem_restore_fences(dev_priv);
4786 /* As we didn't flush the kernel context before suspend, we cannot
4787 * guarantee that the context image is complete. So let's just reset
4788 * it and start again.
4790 dev_priv->gt.resume(dev_priv);
4792 mutex_unlock(&dev->struct_mutex);
4795 void i915_gem_init_swizzling(struct drm_i915_private *dev_priv)
4797 if (INTEL_GEN(dev_priv) < 5 ||
4798 dev_priv->mm.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_NONE)
4801 I915_WRITE(DISP_ARB_CTL, I915_READ(DISP_ARB_CTL) |
4802 DISP_TILE_SURFACE_SWIZZLING);
4804 if (IS_GEN5(dev_priv))
4807 I915_WRITE(TILECTL, I915_READ(TILECTL) | TILECTL_SWZCTL);
4808 if (IS_GEN6(dev_priv))
4809 I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_SNB));
4810 else if (IS_GEN7(dev_priv))
4811 I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_IVB));
4812 else if (IS_GEN8(dev_priv))
4813 I915_WRITE(GAMTARBMODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_BDW));
4818 static void init_unused_ring(struct drm_i915_private *dev_priv, u32 base)
4820 I915_WRITE(RING_CTL(base), 0);
4821 I915_WRITE(RING_HEAD(base), 0);
4822 I915_WRITE(RING_TAIL(base), 0);
4823 I915_WRITE(RING_START(base), 0);
4826 static void init_unused_rings(struct drm_i915_private *dev_priv)
4828 if (IS_I830(dev_priv)) {
4829 init_unused_ring(dev_priv, PRB1_BASE);
4830 init_unused_ring(dev_priv, SRB0_BASE);
4831 init_unused_ring(dev_priv, SRB1_BASE);
4832 init_unused_ring(dev_priv, SRB2_BASE);
4833 init_unused_ring(dev_priv, SRB3_BASE);
4834 } else if (IS_GEN2(dev_priv)) {
4835 init_unused_ring(dev_priv, SRB0_BASE);
4836 init_unused_ring(dev_priv, SRB1_BASE);
4837 } else if (IS_GEN3(dev_priv)) {
4838 init_unused_ring(dev_priv, PRB1_BASE);
4839 init_unused_ring(dev_priv, PRB2_BASE);
4843 static int __i915_gem_restart_engines(void *data)
4845 struct drm_i915_private *i915 = data;
4846 struct intel_engine_cs *engine;
4847 enum intel_engine_id id;
4850 for_each_engine(engine, i915, id) {
4851 err = engine->init_hw(engine);
4859 int i915_gem_init_hw(struct drm_i915_private *dev_priv)
4863 dev_priv->gt.last_init_time = ktime_get();
4865 /* Double layer security blanket, see i915_gem_init() */
4866 intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
4868 if (HAS_EDRAM(dev_priv) && INTEL_GEN(dev_priv) < 9)
4869 I915_WRITE(HSW_IDICR, I915_READ(HSW_IDICR) | IDIHASHMSK(0xf));
4871 if (IS_HASWELL(dev_priv))
4872 I915_WRITE(MI_PREDICATE_RESULT_2, IS_HSW_GT3(dev_priv) ?
4873 LOWER_SLICE_ENABLED : LOWER_SLICE_DISABLED);
4875 if (HAS_PCH_NOP(dev_priv)) {
4876 if (IS_IVYBRIDGE(dev_priv)) {
4877 u32 temp = I915_READ(GEN7_MSG_CTL);
4878 temp &= ~(WAIT_FOR_PCH_FLR_ACK | WAIT_FOR_PCH_RESET_ACK);
4879 I915_WRITE(GEN7_MSG_CTL, temp);
4880 } else if (INTEL_GEN(dev_priv) >= 7) {
4881 u32 temp = I915_READ(HSW_NDE_RSTWRN_OPT);
4882 temp &= ~RESET_PCH_HANDSHAKE_ENABLE;
4883 I915_WRITE(HSW_NDE_RSTWRN_OPT, temp);
4887 i915_gem_init_swizzling(dev_priv);
4890 * At least 830 can leave some of the unused rings
4891 * "active" (ie. head != tail) after resume which
4892 * will prevent c3 entry. Makes sure all unused rings
4895 init_unused_rings(dev_priv);
4897 BUG_ON(!dev_priv->kernel_context);
4898 if (i915_terminally_wedged(&dev_priv->gpu_error)) {
4903 ret = i915_ppgtt_init_hw(dev_priv);
4905 DRM_ERROR("PPGTT enable HW failed %d\n", ret);
4909 /* Need to do basic initialisation of all rings first: */
4910 ret = __i915_gem_restart_engines(dev_priv);
4914 intel_mocs_init_l3cc_table(dev_priv);
4916 /* We can't enable contexts until all firmware is loaded */
4917 ret = intel_uc_init_hw(dev_priv);
4922 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
4926 bool intel_sanitize_semaphores(struct drm_i915_private *dev_priv, int value)
4928 if (INTEL_INFO(dev_priv)->gen < 6)
4931 /* TODO: make semaphores and Execlists play nicely together */
4932 if (i915_modparams.enable_execlists)
4938 /* Enable semaphores on SNB when IO remapping is off */
4939 if (IS_GEN6(dev_priv) && intel_vtd_active())
4945 int i915_gem_init(struct drm_i915_private *dev_priv)
4949 mutex_lock(&dev_priv->drm.struct_mutex);
4952 * We need to fallback to 4K pages since gvt gtt handling doesn't
4953 * support huge page entries - we will need to check either hypervisor
4954 * mm can support huge guest page or just do emulation in gvt.
4956 if (intel_vgpu_active(dev_priv))
4957 mkwrite_device_info(dev_priv)->page_sizes =
4958 I915_GTT_PAGE_SIZE_4K;
4960 dev_priv->mm.unordered_timeline = dma_fence_context_alloc(1);
4962 if (!i915_modparams.enable_execlists) {
4963 dev_priv->gt.resume = intel_legacy_submission_resume;
4964 dev_priv->gt.cleanup_engine = intel_engine_cleanup;
4966 dev_priv->gt.resume = intel_lr_context_resume;
4967 dev_priv->gt.cleanup_engine = intel_logical_ring_cleanup;
4970 /* This is just a security blanket to placate dragons.
4971 * On some systems, we very sporadically observe that the first TLBs
4972 * used by the CS may be stale, despite us poking the TLB reset. If
4973 * we hold the forcewake during initialisation these problems
4974 * just magically go away.
4976 intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
4978 ret = i915_gem_init_userptr(dev_priv);
4982 ret = i915_gem_init_ggtt(dev_priv);
4986 ret = i915_gem_contexts_init(dev_priv);
4990 ret = intel_engines_init(dev_priv);
4994 ret = i915_gem_init_hw(dev_priv);
4996 /* Allow engine initialisation to fail by marking the GPU as
4997 * wedged. But we only want to do this where the GPU is angry,
4998 * for all other failure, such as an allocation failure, bail.
5000 if (!i915_terminally_wedged(&dev_priv->gpu_error)) {
5001 DRM_ERROR("Failed to initialize GPU, declaring it wedged\n");
5002 i915_gem_set_wedged(dev_priv);
5008 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
5009 mutex_unlock(&dev_priv->drm.struct_mutex);
5014 void i915_gem_init_mmio(struct drm_i915_private *i915)
5016 i915_gem_sanitize(i915);
5020 i915_gem_cleanup_engines(struct drm_i915_private *dev_priv)
5022 struct intel_engine_cs *engine;
5023 enum intel_engine_id id;
5025 for_each_engine(engine, dev_priv, id)
5026 dev_priv->gt.cleanup_engine(engine);
5030 i915_gem_load_init_fences(struct drm_i915_private *dev_priv)
5034 if (INTEL_INFO(dev_priv)->gen >= 7 && !IS_VALLEYVIEW(dev_priv) &&
5035 !IS_CHERRYVIEW(dev_priv))
5036 dev_priv->num_fence_regs = 32;
5037 else if (INTEL_INFO(dev_priv)->gen >= 4 ||
5038 IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
5039 IS_G33(dev_priv) || IS_PINEVIEW(dev_priv))
5040 dev_priv->num_fence_regs = 16;
5042 dev_priv->num_fence_regs = 8;
5044 if (intel_vgpu_active(dev_priv))
5045 dev_priv->num_fence_regs =
5046 I915_READ(vgtif_reg(avail_rs.fence_num));
5048 /* Initialize fence registers to zero */
5049 for (i = 0; i < dev_priv->num_fence_regs; i++) {
5050 struct drm_i915_fence_reg *fence = &dev_priv->fence_regs[i];
5052 fence->i915 = dev_priv;
5054 list_add_tail(&fence->link, &dev_priv->mm.fence_list);
5056 i915_gem_restore_fences(dev_priv);
5058 i915_gem_detect_bit_6_swizzle(dev_priv);
5062 i915_gem_load_init(struct drm_i915_private *dev_priv)
5066 dev_priv->objects = KMEM_CACHE(drm_i915_gem_object, SLAB_HWCACHE_ALIGN);
5067 if (!dev_priv->objects)
5070 dev_priv->vmas = KMEM_CACHE(i915_vma, SLAB_HWCACHE_ALIGN);
5071 if (!dev_priv->vmas)
5074 dev_priv->luts = KMEM_CACHE(i915_lut_handle, 0);
5075 if (!dev_priv->luts)
5078 dev_priv->requests = KMEM_CACHE(drm_i915_gem_request,
5079 SLAB_HWCACHE_ALIGN |
5080 SLAB_RECLAIM_ACCOUNT |
5081 SLAB_TYPESAFE_BY_RCU);
5082 if (!dev_priv->requests)
5085 dev_priv->dependencies = KMEM_CACHE(i915_dependency,
5086 SLAB_HWCACHE_ALIGN |
5087 SLAB_RECLAIM_ACCOUNT);
5088 if (!dev_priv->dependencies)
5091 dev_priv->priorities = KMEM_CACHE(i915_priolist, SLAB_HWCACHE_ALIGN);
5092 if (!dev_priv->priorities)
5093 goto err_dependencies;
5095 mutex_lock(&dev_priv->drm.struct_mutex);
5096 INIT_LIST_HEAD(&dev_priv->gt.timelines);
5097 err = i915_gem_timeline_init__global(dev_priv);
5098 mutex_unlock(&dev_priv->drm.struct_mutex);
5100 goto err_priorities;
5102 INIT_WORK(&dev_priv->mm.free_work, __i915_gem_free_work);
5104 spin_lock_init(&dev_priv->mm.obj_lock);
5105 spin_lock_init(&dev_priv->mm.free_lock);
5106 init_llist_head(&dev_priv->mm.free_list);
5107 INIT_LIST_HEAD(&dev_priv->mm.unbound_list);
5108 INIT_LIST_HEAD(&dev_priv->mm.bound_list);
5109 INIT_LIST_HEAD(&dev_priv->mm.fence_list);
5110 INIT_LIST_HEAD(&dev_priv->mm.userfault_list);
5112 INIT_DELAYED_WORK(&dev_priv->gt.retire_work,
5113 i915_gem_retire_work_handler);
5114 INIT_DELAYED_WORK(&dev_priv->gt.idle_work,
5115 i915_gem_idle_work_handler);
5116 init_waitqueue_head(&dev_priv->gpu_error.wait_queue);
5117 init_waitqueue_head(&dev_priv->gpu_error.reset_queue);
5119 atomic_set(&dev_priv->mm.bsd_engine_dispatch_index, 0);
5121 spin_lock_init(&dev_priv->fb_tracking.lock);
5123 err = i915_gemfs_init(dev_priv);
5125 DRM_NOTE("Unable to create a private tmpfs mount, hugepage support will be disabled(%d).\n", err);
5130 kmem_cache_destroy(dev_priv->priorities);
5132 kmem_cache_destroy(dev_priv->dependencies);
5134 kmem_cache_destroy(dev_priv->requests);
5136 kmem_cache_destroy(dev_priv->luts);
5138 kmem_cache_destroy(dev_priv->vmas);
5140 kmem_cache_destroy(dev_priv->objects);
5145 void i915_gem_load_cleanup(struct drm_i915_private *dev_priv)
5147 i915_gem_drain_freed_objects(dev_priv);
5148 WARN_ON(!llist_empty(&dev_priv->mm.free_list));
5149 WARN_ON(dev_priv->mm.object_count);
5151 mutex_lock(&dev_priv->drm.struct_mutex);
5152 i915_gem_timeline_fini(&dev_priv->gt.global_timeline);
5153 WARN_ON(!list_empty(&dev_priv->gt.timelines));
5154 mutex_unlock(&dev_priv->drm.struct_mutex);
5156 kmem_cache_destroy(dev_priv->priorities);
5157 kmem_cache_destroy(dev_priv->dependencies);
5158 kmem_cache_destroy(dev_priv->requests);
5159 kmem_cache_destroy(dev_priv->luts);
5160 kmem_cache_destroy(dev_priv->vmas);
5161 kmem_cache_destroy(dev_priv->objects);
5163 /* And ensure that our DESTROY_BY_RCU slabs are truly destroyed */
5166 i915_gemfs_fini(dev_priv);
5169 int i915_gem_freeze(struct drm_i915_private *dev_priv)
5171 /* Discard all purgeable objects, let userspace recover those as
5172 * required after resuming.
5174 i915_gem_shrink_all(dev_priv);
5179 int i915_gem_freeze_late(struct drm_i915_private *dev_priv)
5181 struct drm_i915_gem_object *obj;
5182 struct list_head *phases[] = {
5183 &dev_priv->mm.unbound_list,
5184 &dev_priv->mm.bound_list,
5188 /* Called just before we write the hibernation image.
5190 * We need to update the domain tracking to reflect that the CPU
5191 * will be accessing all the pages to create and restore from the
5192 * hibernation, and so upon restoration those pages will be in the
5195 * To make sure the hibernation image contains the latest state,
5196 * we update that state just before writing out the image.
5198 * To try and reduce the hibernation image, we manually shrink
5199 * the objects as well, see i915_gem_freeze()
5202 i915_gem_shrink(dev_priv, -1UL, NULL, I915_SHRINK_UNBOUND);
5203 i915_gem_drain_freed_objects(dev_priv);
5205 spin_lock(&dev_priv->mm.obj_lock);
5206 for (p = phases; *p; p++) {
5207 list_for_each_entry(obj, *p, mm.link)
5208 __start_cpu_write(obj);
5210 spin_unlock(&dev_priv->mm.obj_lock);
5215 void i915_gem_release(struct drm_device *dev, struct drm_file *file)
5217 struct drm_i915_file_private *file_priv = file->driver_priv;
5218 struct drm_i915_gem_request *request;
5220 /* Clean up our request list when the client is going away, so that
5221 * later retire_requests won't dereference our soon-to-be-gone
5224 spin_lock(&file_priv->mm.lock);
5225 list_for_each_entry(request, &file_priv->mm.request_list, client_link)
5226 request->file_priv = NULL;
5227 spin_unlock(&file_priv->mm.lock);
5230 int i915_gem_open(struct drm_i915_private *i915, struct drm_file *file)
5232 struct drm_i915_file_private *file_priv;
5237 file_priv = kzalloc(sizeof(*file_priv), GFP_KERNEL);
5241 file->driver_priv = file_priv;
5242 file_priv->dev_priv = i915;
5243 file_priv->file = file;
5245 spin_lock_init(&file_priv->mm.lock);
5246 INIT_LIST_HEAD(&file_priv->mm.request_list);
5248 file_priv->bsd_engine = -1;
5250 ret = i915_gem_context_open(i915, file);
5258 * i915_gem_track_fb - update frontbuffer tracking
5259 * @old: current GEM buffer for the frontbuffer slots
5260 * @new: new GEM buffer for the frontbuffer slots
5261 * @frontbuffer_bits: bitmask of frontbuffer slots
5263 * This updates the frontbuffer tracking bits @frontbuffer_bits by clearing them
5264 * from @old and setting them in @new. Both @old and @new can be NULL.
5266 void i915_gem_track_fb(struct drm_i915_gem_object *old,
5267 struct drm_i915_gem_object *new,
5268 unsigned frontbuffer_bits)
5270 /* Control of individual bits within the mask are guarded by
5271 * the owning plane->mutex, i.e. we can never see concurrent
5272 * manipulation of individual bits. But since the bitfield as a whole
5273 * is updated using RMW, we need to use atomics in order to update
5276 BUILD_BUG_ON(INTEL_FRONTBUFFER_BITS_PER_PIPE * I915_MAX_PIPES >
5277 sizeof(atomic_t) * BITS_PER_BYTE);
5280 WARN_ON(!(atomic_read(&old->frontbuffer_bits) & frontbuffer_bits));
5281 atomic_andnot(frontbuffer_bits, &old->frontbuffer_bits);
5285 WARN_ON(atomic_read(&new->frontbuffer_bits) & frontbuffer_bits);
5286 atomic_or(frontbuffer_bits, &new->frontbuffer_bits);
5290 /* Allocate a new GEM object and fill it with the supplied data */
5291 struct drm_i915_gem_object *
5292 i915_gem_object_create_from_data(struct drm_i915_private *dev_priv,
5293 const void *data, size_t size)
5295 struct drm_i915_gem_object *obj;
5300 obj = i915_gem_object_create(dev_priv, round_up(size, PAGE_SIZE));
5304 GEM_BUG_ON(obj->base.write_domain != I915_GEM_DOMAIN_CPU);
5306 file = obj->base.filp;
5309 unsigned int len = min_t(typeof(size), size, PAGE_SIZE);
5311 void *pgdata, *vaddr;
5313 err = pagecache_write_begin(file, file->f_mapping,
5320 memcpy(vaddr, data, len);
5323 err = pagecache_write_end(file, file->f_mapping,
5337 i915_gem_object_put(obj);
5338 return ERR_PTR(err);
5341 struct scatterlist *
5342 i915_gem_object_get_sg(struct drm_i915_gem_object *obj,
5344 unsigned int *offset)
5346 struct i915_gem_object_page_iter *iter = &obj->mm.get_page;
5347 struct scatterlist *sg;
5348 unsigned int idx, count;
5351 GEM_BUG_ON(n >= obj->base.size >> PAGE_SHIFT);
5352 GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
5354 /* As we iterate forward through the sg, we record each entry in a
5355 * radixtree for quick repeated (backwards) lookups. If we have seen
5356 * this index previously, we will have an entry for it.
5358 * Initial lookup is O(N), but this is amortized to O(1) for
5359 * sequential page access (where each new request is consecutive
5360 * to the previous one). Repeated lookups are O(lg(obj->base.size)),
5361 * i.e. O(1) with a large constant!
5363 if (n < READ_ONCE(iter->sg_idx))
5366 mutex_lock(&iter->lock);
5368 /* We prefer to reuse the last sg so that repeated lookup of this
5369 * (or the subsequent) sg are fast - comparing against the last
5370 * sg is faster than going through the radixtree.
5375 count = __sg_page_count(sg);
5377 while (idx + count <= n) {
5378 unsigned long exception, i;
5381 /* If we cannot allocate and insert this entry, or the
5382 * individual pages from this range, cancel updating the
5383 * sg_idx so that on this lookup we are forced to linearly
5384 * scan onwards, but on future lookups we will try the
5385 * insertion again (in which case we need to be careful of
5386 * the error return reporting that we have already inserted
5389 ret = radix_tree_insert(&iter->radix, idx, sg);
5390 if (ret && ret != -EEXIST)
5394 RADIX_TREE_EXCEPTIONAL_ENTRY |
5395 idx << RADIX_TREE_EXCEPTIONAL_SHIFT;
5396 for (i = 1; i < count; i++) {
5397 ret = radix_tree_insert(&iter->radix, idx + i,
5399 if (ret && ret != -EEXIST)
5404 sg = ____sg_next(sg);
5405 count = __sg_page_count(sg);
5412 mutex_unlock(&iter->lock);
5414 if (unlikely(n < idx)) /* insertion completed by another thread */
5417 /* In case we failed to insert the entry into the radixtree, we need
5418 * to look beyond the current sg.
5420 while (idx + count <= n) {
5422 sg = ____sg_next(sg);
5423 count = __sg_page_count(sg);
5432 sg = radix_tree_lookup(&iter->radix, n);
5435 /* If this index is in the middle of multi-page sg entry,
5436 * the radixtree will contain an exceptional entry that points
5437 * to the start of that range. We will return the pointer to
5438 * the base page and the offset of this page within the
5442 if (unlikely(radix_tree_exception(sg))) {
5443 unsigned long base =
5444 (unsigned long)sg >> RADIX_TREE_EXCEPTIONAL_SHIFT;
5446 sg = radix_tree_lookup(&iter->radix, base);
5458 i915_gem_object_get_page(struct drm_i915_gem_object *obj, unsigned int n)
5460 struct scatterlist *sg;
5461 unsigned int offset;
5463 GEM_BUG_ON(!i915_gem_object_has_struct_page(obj));
5465 sg = i915_gem_object_get_sg(obj, n, &offset);
5466 return nth_page(sg_page(sg), offset);
5469 /* Like i915_gem_object_get_page(), but mark the returned page dirty */
5471 i915_gem_object_get_dirty_page(struct drm_i915_gem_object *obj,
5476 page = i915_gem_object_get_page(obj, n);
5478 set_page_dirty(page);
5484 i915_gem_object_get_dma_address(struct drm_i915_gem_object *obj,
5487 struct scatterlist *sg;
5488 unsigned int offset;
5490 sg = i915_gem_object_get_sg(obj, n, &offset);
5491 return sg_dma_address(sg) + (offset << PAGE_SHIFT);
5494 int i915_gem_object_attach_phys(struct drm_i915_gem_object *obj, int align)
5496 struct sg_table *pages;
5499 if (align > obj->base.size)
5502 if (obj->ops == &i915_gem_phys_ops)
5505 if (obj->ops != &i915_gem_object_ops)
5508 err = i915_gem_object_unbind(obj);
5512 mutex_lock(&obj->mm.lock);
5514 if (obj->mm.madv != I915_MADV_WILLNEED) {
5519 if (obj->mm.quirked) {
5524 if (obj->mm.mapping) {
5529 pages = fetch_and_zero(&obj->mm.pages);
5531 struct drm_i915_private *i915 = to_i915(obj->base.dev);
5533 __i915_gem_object_reset_page_iter(obj);
5535 spin_lock(&i915->mm.obj_lock);
5536 list_del(&obj->mm.link);
5537 spin_unlock(&i915->mm.obj_lock);
5540 obj->ops = &i915_gem_phys_ops;
5542 err = ____i915_gem_object_get_pages(obj);
5546 /* Perma-pin (until release) the physical set of pages */
5547 __i915_gem_object_pin_pages(obj);
5549 if (!IS_ERR_OR_NULL(pages))
5550 i915_gem_object_ops.put_pages(obj, pages);
5551 mutex_unlock(&obj->mm.lock);
5555 obj->ops = &i915_gem_object_ops;
5556 obj->mm.pages = pages;
5558 mutex_unlock(&obj->mm.lock);
5562 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
5563 #include "selftests/scatterlist.c"
5564 #include "selftests/mock_gem_device.c"
5565 #include "selftests/huge_gem_object.c"
5566 #include "selftests/huge_pages.c"
5567 #include "selftests/i915_gem_object.c"
5568 #include "selftests/i915_gem_coherency.c"