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 <linux/dma-fence-array.h>
39 #include <linux/kthread.h>
40 #include <linux/reservation.h>
41 #include <linux/shmem_fs.h>
42 #include <linux/slab.h>
43 #include <linux/stop_machine.h>
44 #include <linux/swap.h>
45 #include <linux/pci.h>
46 #include <linux/dma-buf.h>
48 static void i915_gem_flush_free_objects(struct drm_i915_private *i915);
50 static bool cpu_write_needs_clflush(struct drm_i915_gem_object *obj)
55 if (!(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_WRITE))
58 return obj->pin_display;
62 insert_mappable_node(struct i915_ggtt *ggtt,
63 struct drm_mm_node *node, u32 size)
65 memset(node, 0, sizeof(*node));
66 return drm_mm_insert_node_in_range(&ggtt->base.mm, node,
67 size, 0, I915_COLOR_UNEVICTABLE,
68 0, ggtt->mappable_end,
73 remove_mappable_node(struct drm_mm_node *node)
75 drm_mm_remove_node(node);
78 /* some bookkeeping */
79 static void i915_gem_info_add_obj(struct drm_i915_private *dev_priv,
82 spin_lock(&dev_priv->mm.object_stat_lock);
83 dev_priv->mm.object_count++;
84 dev_priv->mm.object_memory += size;
85 spin_unlock(&dev_priv->mm.object_stat_lock);
88 static void i915_gem_info_remove_obj(struct drm_i915_private *dev_priv,
91 spin_lock(&dev_priv->mm.object_stat_lock);
92 dev_priv->mm.object_count--;
93 dev_priv->mm.object_memory -= size;
94 spin_unlock(&dev_priv->mm.object_stat_lock);
98 i915_gem_wait_for_error(struct i915_gpu_error *error)
105 * Only wait 10 seconds for the gpu reset to complete to avoid hanging
106 * userspace. If it takes that long something really bad is going on and
107 * we should simply try to bail out and fail as gracefully as possible.
109 ret = wait_event_interruptible_timeout(error->reset_queue,
110 !i915_reset_backoff(error),
113 DRM_ERROR("Timed out waiting for the gpu reset to complete\n");
115 } else if (ret < 0) {
122 int i915_mutex_lock_interruptible(struct drm_device *dev)
124 struct drm_i915_private *dev_priv = to_i915(dev);
127 ret = i915_gem_wait_for_error(&dev_priv->gpu_error);
131 ret = mutex_lock_interruptible(&dev->struct_mutex);
139 i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
140 struct drm_file *file)
142 struct drm_i915_private *dev_priv = to_i915(dev);
143 struct i915_ggtt *ggtt = &dev_priv->ggtt;
144 struct drm_i915_gem_get_aperture *args = data;
145 struct i915_vma *vma;
148 pinned = ggtt->base.reserved;
149 mutex_lock(&dev->struct_mutex);
150 list_for_each_entry(vma, &ggtt->base.active_list, vm_link)
151 if (i915_vma_is_pinned(vma))
152 pinned += vma->node.size;
153 list_for_each_entry(vma, &ggtt->base.inactive_list, vm_link)
154 if (i915_vma_is_pinned(vma))
155 pinned += vma->node.size;
156 mutex_unlock(&dev->struct_mutex);
158 args->aper_size = ggtt->base.total;
159 args->aper_available_size = args->aper_size - pinned;
164 static struct sg_table *
165 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;
174 if (WARN_ON(i915_gem_object_needs_bit17_swizzle(obj)))
175 return ERR_PTR(-EINVAL);
177 /* Always aligning to the object size, allows a single allocation
178 * to handle all possible callers, and given typical object sizes,
179 * the alignment of the buddy allocation will naturally match.
181 phys = drm_pci_alloc(obj->base.dev,
183 roundup_pow_of_two(obj->base.size));
185 return ERR_PTR(-ENOMEM);
188 for (i = 0; i < obj->base.size / PAGE_SIZE; i++) {
192 page = shmem_read_mapping_page(mapping, i);
198 src = kmap_atomic(page);
199 memcpy(vaddr, src, PAGE_SIZE);
200 drm_clflush_virt_range(vaddr, PAGE_SIZE);
207 i915_gem_chipset_flush(to_i915(obj->base.dev));
209 st = kmalloc(sizeof(*st), GFP_KERNEL);
211 st = ERR_PTR(-ENOMEM);
215 if (sg_alloc_table(st, 1, GFP_KERNEL)) {
217 st = ERR_PTR(-ENOMEM);
223 sg->length = obj->base.size;
225 sg_dma_address(sg) = phys->busaddr;
226 sg_dma_len(sg) = obj->base.size;
228 obj->phys_handle = phys;
232 drm_pci_free(obj->base.dev, phys);
236 static void __start_cpu_write(struct drm_i915_gem_object *obj)
238 obj->base.read_domains = I915_GEM_DOMAIN_CPU;
239 obj->base.write_domain = I915_GEM_DOMAIN_CPU;
240 if (cpu_write_needs_clflush(obj))
241 obj->cache_dirty = true;
245 __i915_gem_object_release_shmem(struct drm_i915_gem_object *obj,
246 struct sg_table *pages,
249 GEM_BUG_ON(obj->mm.madv == __I915_MADV_PURGED);
251 if (obj->mm.madv == I915_MADV_DONTNEED)
252 obj->mm.dirty = false;
255 (obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0 &&
256 !(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ))
257 drm_clflush_sg(pages);
259 __start_cpu_write(obj);
263 i915_gem_object_put_pages_phys(struct drm_i915_gem_object *obj,
264 struct sg_table *pages)
266 __i915_gem_object_release_shmem(obj, pages, false);
269 struct address_space *mapping = obj->base.filp->f_mapping;
270 char *vaddr = obj->phys_handle->vaddr;
273 for (i = 0; i < obj->base.size / PAGE_SIZE; i++) {
277 page = shmem_read_mapping_page(mapping, i);
281 dst = kmap_atomic(page);
282 drm_clflush_virt_range(vaddr, PAGE_SIZE);
283 memcpy(dst, vaddr, PAGE_SIZE);
286 set_page_dirty(page);
287 if (obj->mm.madv == I915_MADV_WILLNEED)
288 mark_page_accessed(page);
292 obj->mm.dirty = false;
295 sg_free_table(pages);
298 drm_pci_free(obj->base.dev, obj->phys_handle);
302 i915_gem_object_release_phys(struct drm_i915_gem_object *obj)
304 i915_gem_object_unpin_pages(obj);
307 static const struct drm_i915_gem_object_ops i915_gem_phys_ops = {
308 .get_pages = i915_gem_object_get_pages_phys,
309 .put_pages = i915_gem_object_put_pages_phys,
310 .release = i915_gem_object_release_phys,
313 static const struct drm_i915_gem_object_ops i915_gem_object_ops;
315 int i915_gem_object_unbind(struct drm_i915_gem_object *obj)
317 struct i915_vma *vma;
318 LIST_HEAD(still_in_list);
321 lockdep_assert_held(&obj->base.dev->struct_mutex);
323 /* Closed vma are removed from the obj->vma_list - but they may
324 * still have an active binding on the object. To remove those we
325 * must wait for all rendering to complete to the object (as unbinding
326 * must anyway), and retire the requests.
328 ret = i915_gem_object_set_to_cpu_domain(obj, false);
332 while ((vma = list_first_entry_or_null(&obj->vma_list,
335 list_move_tail(&vma->obj_link, &still_in_list);
336 ret = i915_vma_unbind(vma);
340 list_splice(&still_in_list, &obj->vma_list);
346 i915_gem_object_wait_fence(struct dma_fence *fence,
349 struct intel_rps_client *rps)
351 struct drm_i915_gem_request *rq;
353 BUILD_BUG_ON(I915_WAIT_INTERRUPTIBLE != 0x1);
355 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
358 if (!dma_fence_is_i915(fence))
359 return dma_fence_wait_timeout(fence,
360 flags & I915_WAIT_INTERRUPTIBLE,
363 rq = to_request(fence);
364 if (i915_gem_request_completed(rq))
367 /* This client is about to stall waiting for the GPU. In many cases
368 * this is undesirable and limits the throughput of the system, as
369 * many clients cannot continue processing user input/output whilst
370 * blocked. RPS autotuning may take tens of milliseconds to respond
371 * to the GPU load and thus incurs additional latency for the client.
372 * We can circumvent that by promoting the GPU frequency to maximum
373 * before we wait. This makes the GPU throttle up much more quickly
374 * (good for benchmarks and user experience, e.g. window animations),
375 * but at a cost of spending more power processing the workload
376 * (bad for battery). Not all clients even want their results
377 * immediately and for them we should just let the GPU select its own
378 * frequency to maximise efficiency. To prevent a single client from
379 * forcing the clocks too high for the whole system, we only allow
380 * each client to waitboost once in a busy period.
383 if (INTEL_GEN(rq->i915) >= 6)
384 gen6_rps_boost(rq, rps);
389 timeout = i915_wait_request(rq, flags, timeout);
392 if (flags & I915_WAIT_LOCKED && i915_gem_request_completed(rq))
393 i915_gem_request_retire_upto(rq);
399 i915_gem_object_wait_reservation(struct reservation_object *resv,
402 struct intel_rps_client *rps)
404 unsigned int seq = __read_seqcount_begin(&resv->seq);
405 struct dma_fence *excl;
406 bool prune_fences = false;
408 if (flags & I915_WAIT_ALL) {
409 struct dma_fence **shared;
410 unsigned int count, i;
413 ret = reservation_object_get_fences_rcu(resv,
414 &excl, &count, &shared);
418 for (i = 0; i < count; i++) {
419 timeout = i915_gem_object_wait_fence(shared[i],
425 dma_fence_put(shared[i]);
428 for (; i < count; i++)
429 dma_fence_put(shared[i]);
432 prune_fences = count && timeout >= 0;
434 excl = reservation_object_get_excl_rcu(resv);
437 if (excl && timeout >= 0) {
438 timeout = i915_gem_object_wait_fence(excl, flags, timeout, rps);
439 prune_fences = timeout >= 0;
444 /* Oportunistically prune the fences iff we know they have *all* been
445 * signaled and that the reservation object has not been changed (i.e.
446 * no new fences have been added).
448 if (prune_fences && !__read_seqcount_retry(&resv->seq, seq)) {
449 if (reservation_object_trylock(resv)) {
450 if (!__read_seqcount_retry(&resv->seq, seq))
451 reservation_object_add_excl_fence(resv, NULL);
452 reservation_object_unlock(resv);
459 static void __fence_set_priority(struct dma_fence *fence, int prio)
461 struct drm_i915_gem_request *rq;
462 struct intel_engine_cs *engine;
464 if (!dma_fence_is_i915(fence))
467 rq = to_request(fence);
469 if (!engine->schedule)
472 engine->schedule(rq, prio);
475 static void fence_set_priority(struct dma_fence *fence, int prio)
477 /* Recurse once into a fence-array */
478 if (dma_fence_is_array(fence)) {
479 struct dma_fence_array *array = to_dma_fence_array(fence);
482 for (i = 0; i < array->num_fences; i++)
483 __fence_set_priority(array->fences[i], prio);
485 __fence_set_priority(fence, prio);
490 i915_gem_object_wait_priority(struct drm_i915_gem_object *obj,
494 struct dma_fence *excl;
496 if (flags & I915_WAIT_ALL) {
497 struct dma_fence **shared;
498 unsigned int count, i;
501 ret = reservation_object_get_fences_rcu(obj->resv,
502 &excl, &count, &shared);
506 for (i = 0; i < count; i++) {
507 fence_set_priority(shared[i], prio);
508 dma_fence_put(shared[i]);
513 excl = reservation_object_get_excl_rcu(obj->resv);
517 fence_set_priority(excl, prio);
524 * Waits for rendering to the object to be completed
525 * @obj: i915 gem object
526 * @flags: how to wait (under a lock, for all rendering or just for writes etc)
527 * @timeout: how long to wait
528 * @rps: client (user process) to charge for any waitboosting
531 i915_gem_object_wait(struct drm_i915_gem_object *obj,
534 struct intel_rps_client *rps)
537 #if IS_ENABLED(CONFIG_LOCKDEP)
538 GEM_BUG_ON(debug_locks &&
539 !!lockdep_is_held(&obj->base.dev->struct_mutex) !=
540 !!(flags & I915_WAIT_LOCKED));
542 GEM_BUG_ON(timeout < 0);
544 timeout = i915_gem_object_wait_reservation(obj->resv,
547 return timeout < 0 ? timeout : 0;
550 static struct intel_rps_client *to_rps_client(struct drm_file *file)
552 struct drm_i915_file_private *fpriv = file->driver_priv;
558 i915_gem_phys_pwrite(struct drm_i915_gem_object *obj,
559 struct drm_i915_gem_pwrite *args,
560 struct drm_file *file)
562 void *vaddr = obj->phys_handle->vaddr + args->offset;
563 char __user *user_data = u64_to_user_ptr(args->data_ptr);
565 /* We manually control the domain here and pretend that it
566 * remains coherent i.e. in the GTT domain, like shmem_pwrite.
568 intel_fb_obj_invalidate(obj, ORIGIN_CPU);
569 if (copy_from_user(vaddr, user_data, args->size))
572 drm_clflush_virt_range(vaddr, args->size);
573 i915_gem_chipset_flush(to_i915(obj->base.dev));
575 intel_fb_obj_flush(obj, ORIGIN_CPU);
579 void *i915_gem_object_alloc(struct drm_i915_private *dev_priv)
581 return kmem_cache_zalloc(dev_priv->objects, GFP_KERNEL);
584 void i915_gem_object_free(struct drm_i915_gem_object *obj)
586 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
587 kmem_cache_free(dev_priv->objects, obj);
591 i915_gem_create(struct drm_file *file,
592 struct drm_i915_private *dev_priv,
596 struct drm_i915_gem_object *obj;
600 size = roundup(size, PAGE_SIZE);
604 /* Allocate the new object */
605 obj = i915_gem_object_create(dev_priv, size);
609 ret = drm_gem_handle_create(file, &obj->base, &handle);
610 /* drop reference from allocate - handle holds it now */
611 i915_gem_object_put(obj);
620 i915_gem_dumb_create(struct drm_file *file,
621 struct drm_device *dev,
622 struct drm_mode_create_dumb *args)
624 /* have to work out size/pitch and return them */
625 args->pitch = ALIGN(args->width * DIV_ROUND_UP(args->bpp, 8), 64);
626 args->size = args->pitch * args->height;
627 return i915_gem_create(file, to_i915(dev),
628 args->size, &args->handle);
631 static bool gpu_write_needs_clflush(struct drm_i915_gem_object *obj)
633 return !(obj->cache_level == I915_CACHE_NONE ||
634 obj->cache_level == I915_CACHE_WT);
638 * Creates a new mm object and returns a handle to it.
639 * @dev: drm device pointer
640 * @data: ioctl data blob
641 * @file: drm file pointer
644 i915_gem_create_ioctl(struct drm_device *dev, void *data,
645 struct drm_file *file)
647 struct drm_i915_private *dev_priv = to_i915(dev);
648 struct drm_i915_gem_create *args = data;
650 i915_gem_flush_free_objects(dev_priv);
652 return i915_gem_create(file, dev_priv,
653 args->size, &args->handle);
656 static inline enum fb_op_origin
657 fb_write_origin(struct drm_i915_gem_object *obj, unsigned int domain)
659 return (domain == I915_GEM_DOMAIN_GTT ?
660 obj->frontbuffer_ggtt_origin : ORIGIN_CPU);
664 flush_write_domain(struct drm_i915_gem_object *obj, unsigned int flush_domains)
666 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
668 if (!(obj->base.write_domain & flush_domains))
671 /* No actual flushing is required for the GTT write domain. Writes
672 * to it "immediately" go to main memory as far as we know, so there's
673 * no chipset flush. It also doesn't land in render cache.
675 * However, we do have to enforce the order so that all writes through
676 * the GTT land before any writes to the device, such as updates to
679 * We also have to wait a bit for the writes to land from the GTT.
680 * An uncached read (i.e. mmio) seems to be ideal for the round-trip
681 * timing. This issue has only been observed when switching quickly
682 * between GTT writes and CPU reads from inside the kernel on recent hw,
683 * and it appears to only affect discrete GTT blocks (i.e. on LLC
684 * system agents we cannot reproduce this behaviour).
688 switch (obj->base.write_domain) {
689 case I915_GEM_DOMAIN_GTT:
690 if (!HAS_LLC(dev_priv)) {
691 intel_runtime_pm_get(dev_priv);
692 spin_lock_irq(&dev_priv->uncore.lock);
693 POSTING_READ_FW(RING_HEAD(dev_priv->engine[RCS]->mmio_base));
694 spin_unlock_irq(&dev_priv->uncore.lock);
695 intel_runtime_pm_put(dev_priv);
698 intel_fb_obj_flush(obj,
699 fb_write_origin(obj, I915_GEM_DOMAIN_GTT));
702 case I915_GEM_DOMAIN_CPU:
703 i915_gem_clflush_object(obj, I915_CLFLUSH_SYNC);
706 case I915_GEM_DOMAIN_RENDER:
707 if (gpu_write_needs_clflush(obj))
708 obj->cache_dirty = true;
712 obj->base.write_domain = 0;
716 __copy_to_user_swizzled(char __user *cpu_vaddr,
717 const char *gpu_vaddr, int gpu_offset,
720 int ret, cpu_offset = 0;
723 int cacheline_end = ALIGN(gpu_offset + 1, 64);
724 int this_length = min(cacheline_end - gpu_offset, length);
725 int swizzled_gpu_offset = gpu_offset ^ 64;
727 ret = __copy_to_user(cpu_vaddr + cpu_offset,
728 gpu_vaddr + swizzled_gpu_offset,
733 cpu_offset += this_length;
734 gpu_offset += this_length;
735 length -= this_length;
742 __copy_from_user_swizzled(char *gpu_vaddr, int gpu_offset,
743 const char __user *cpu_vaddr,
746 int ret, cpu_offset = 0;
749 int cacheline_end = ALIGN(gpu_offset + 1, 64);
750 int this_length = min(cacheline_end - gpu_offset, length);
751 int swizzled_gpu_offset = gpu_offset ^ 64;
753 ret = __copy_from_user(gpu_vaddr + swizzled_gpu_offset,
754 cpu_vaddr + cpu_offset,
759 cpu_offset += this_length;
760 gpu_offset += this_length;
761 length -= this_length;
768 * Pins the specified object's pages and synchronizes the object with
769 * GPU accesses. Sets needs_clflush to non-zero if the caller should
770 * flush the object from the CPU cache.
772 int i915_gem_obj_prepare_shmem_read(struct drm_i915_gem_object *obj,
773 unsigned int *needs_clflush)
777 lockdep_assert_held(&obj->base.dev->struct_mutex);
780 if (!i915_gem_object_has_struct_page(obj))
783 ret = i915_gem_object_wait(obj,
784 I915_WAIT_INTERRUPTIBLE |
786 MAX_SCHEDULE_TIMEOUT,
791 ret = i915_gem_object_pin_pages(obj);
795 if (obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ ||
796 !static_cpu_has(X86_FEATURE_CLFLUSH)) {
797 ret = i915_gem_object_set_to_cpu_domain(obj, false);
804 flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
806 /* If we're not in the cpu read domain, set ourself into the gtt
807 * read domain and manually flush cachelines (if required). This
808 * optimizes for the case when the gpu will dirty the data
809 * anyway again before the next pread happens.
811 if (!obj->cache_dirty &&
812 !(obj->base.read_domains & I915_GEM_DOMAIN_CPU))
813 *needs_clflush = CLFLUSH_BEFORE;
816 /* return with the pages pinned */
820 i915_gem_object_unpin_pages(obj);
824 int i915_gem_obj_prepare_shmem_write(struct drm_i915_gem_object *obj,
825 unsigned int *needs_clflush)
829 lockdep_assert_held(&obj->base.dev->struct_mutex);
832 if (!i915_gem_object_has_struct_page(obj))
835 ret = i915_gem_object_wait(obj,
836 I915_WAIT_INTERRUPTIBLE |
839 MAX_SCHEDULE_TIMEOUT,
844 ret = i915_gem_object_pin_pages(obj);
848 if (obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_WRITE ||
849 !static_cpu_has(X86_FEATURE_CLFLUSH)) {
850 ret = i915_gem_object_set_to_cpu_domain(obj, true);
857 flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
859 /* If we're not in the cpu write domain, set ourself into the
860 * gtt write domain and manually flush cachelines (as required).
861 * This optimizes for the case when the gpu will use the data
862 * right away and we therefore have to clflush anyway.
864 if (!obj->cache_dirty) {
865 *needs_clflush |= CLFLUSH_AFTER;
868 * Same trick applies to invalidate partially written
869 * cachelines read before writing.
871 if (!(obj->base.read_domains & I915_GEM_DOMAIN_CPU))
872 *needs_clflush |= CLFLUSH_BEFORE;
876 intel_fb_obj_invalidate(obj, ORIGIN_CPU);
877 obj->mm.dirty = true;
878 /* return with the pages pinned */
882 i915_gem_object_unpin_pages(obj);
887 shmem_clflush_swizzled_range(char *addr, unsigned long length,
890 if (unlikely(swizzled)) {
891 unsigned long start = (unsigned long) addr;
892 unsigned long end = (unsigned long) addr + length;
894 /* For swizzling simply ensure that we always flush both
895 * channels. Lame, but simple and it works. Swizzled
896 * pwrite/pread is far from a hotpath - current userspace
897 * doesn't use it at all. */
898 start = round_down(start, 128);
899 end = round_up(end, 128);
901 drm_clflush_virt_range((void *)start, end - start);
903 drm_clflush_virt_range(addr, length);
908 /* Only difference to the fast-path function is that this can handle bit17
909 * and uses non-atomic copy and kmap functions. */
911 shmem_pread_slow(struct page *page, int offset, int length,
912 char __user *user_data,
913 bool page_do_bit17_swizzling, bool needs_clflush)
920 shmem_clflush_swizzled_range(vaddr + offset, length,
921 page_do_bit17_swizzling);
923 if (page_do_bit17_swizzling)
924 ret = __copy_to_user_swizzled(user_data, vaddr, offset, length);
926 ret = __copy_to_user(user_data, vaddr + offset, length);
929 return ret ? - EFAULT : 0;
933 shmem_pread(struct page *page, int offset, int length, char __user *user_data,
934 bool page_do_bit17_swizzling, bool needs_clflush)
939 if (!page_do_bit17_swizzling) {
940 char *vaddr = kmap_atomic(page);
943 drm_clflush_virt_range(vaddr + offset, length);
944 ret = __copy_to_user_inatomic(user_data, vaddr + offset, length);
945 kunmap_atomic(vaddr);
950 return shmem_pread_slow(page, offset, length, user_data,
951 page_do_bit17_swizzling, needs_clflush);
955 i915_gem_shmem_pread(struct drm_i915_gem_object *obj,
956 struct drm_i915_gem_pread *args)
958 char __user *user_data;
960 unsigned int obj_do_bit17_swizzling;
961 unsigned int needs_clflush;
962 unsigned int idx, offset;
965 obj_do_bit17_swizzling = 0;
966 if (i915_gem_object_needs_bit17_swizzle(obj))
967 obj_do_bit17_swizzling = BIT(17);
969 ret = mutex_lock_interruptible(&obj->base.dev->struct_mutex);
973 ret = i915_gem_obj_prepare_shmem_read(obj, &needs_clflush);
974 mutex_unlock(&obj->base.dev->struct_mutex);
979 user_data = u64_to_user_ptr(args->data_ptr);
980 offset = offset_in_page(args->offset);
981 for (idx = args->offset >> PAGE_SHIFT; remain; idx++) {
982 struct page *page = i915_gem_object_get_page(obj, idx);
983 unsigned int length = min_t(u64, remain, PAGE_SIZE - offset);
985 ret = shmem_pread(page, offset, length, user_data,
986 page_to_phys(page) & obj_do_bit17_swizzling,
996 i915_gem_obj_finish_shmem_access(obj);
1001 gtt_user_read(struct io_mapping *mapping,
1002 loff_t base, int offset,
1003 char __user *user_data, int length)
1006 unsigned long unwritten;
1008 /* We can use the cpu mem copy function because this is X86. */
1009 vaddr = (void __force *)io_mapping_map_atomic_wc(mapping, base);
1010 unwritten = __copy_to_user_inatomic(user_data, vaddr + offset, length);
1011 io_mapping_unmap_atomic(vaddr);
1013 vaddr = (void __force *)
1014 io_mapping_map_wc(mapping, base, PAGE_SIZE);
1015 unwritten = copy_to_user(user_data, vaddr + offset, length);
1016 io_mapping_unmap(vaddr);
1022 i915_gem_gtt_pread(struct drm_i915_gem_object *obj,
1023 const struct drm_i915_gem_pread *args)
1025 struct drm_i915_private *i915 = to_i915(obj->base.dev);
1026 struct i915_ggtt *ggtt = &i915->ggtt;
1027 struct drm_mm_node node;
1028 struct i915_vma *vma;
1029 void __user *user_data;
1033 ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
1037 intel_runtime_pm_get(i915);
1038 vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
1039 PIN_MAPPABLE | PIN_NONBLOCK);
1041 node.start = i915_ggtt_offset(vma);
1042 node.allocated = false;
1043 ret = i915_vma_put_fence(vma);
1045 i915_vma_unpin(vma);
1050 ret = insert_mappable_node(ggtt, &node, PAGE_SIZE);
1053 GEM_BUG_ON(!node.allocated);
1056 ret = i915_gem_object_set_to_gtt_domain(obj, false);
1060 mutex_unlock(&i915->drm.struct_mutex);
1062 user_data = u64_to_user_ptr(args->data_ptr);
1063 remain = args->size;
1064 offset = args->offset;
1066 while (remain > 0) {
1067 /* Operation in this page
1069 * page_base = page offset within aperture
1070 * page_offset = offset within page
1071 * page_length = bytes to copy for this page
1073 u32 page_base = node.start;
1074 unsigned page_offset = offset_in_page(offset);
1075 unsigned page_length = PAGE_SIZE - page_offset;
1076 page_length = remain < page_length ? remain : page_length;
1077 if (node.allocated) {
1079 ggtt->base.insert_page(&ggtt->base,
1080 i915_gem_object_get_dma_address(obj, offset >> PAGE_SHIFT),
1081 node.start, I915_CACHE_NONE, 0);
1084 page_base += offset & PAGE_MASK;
1087 if (gtt_user_read(&ggtt->mappable, page_base, page_offset,
1088 user_data, page_length)) {
1093 remain -= page_length;
1094 user_data += page_length;
1095 offset += page_length;
1098 mutex_lock(&i915->drm.struct_mutex);
1100 if (node.allocated) {
1102 ggtt->base.clear_range(&ggtt->base,
1103 node.start, node.size);
1104 remove_mappable_node(&node);
1106 i915_vma_unpin(vma);
1109 intel_runtime_pm_put(i915);
1110 mutex_unlock(&i915->drm.struct_mutex);
1116 * Reads data from the object referenced by handle.
1117 * @dev: drm device pointer
1118 * @data: ioctl data blob
1119 * @file: drm file pointer
1121 * On error, the contents of *data are undefined.
1124 i915_gem_pread_ioctl(struct drm_device *dev, void *data,
1125 struct drm_file *file)
1127 struct drm_i915_gem_pread *args = data;
1128 struct drm_i915_gem_object *obj;
1131 if (args->size == 0)
1134 if (!access_ok(VERIFY_WRITE,
1135 u64_to_user_ptr(args->data_ptr),
1139 obj = i915_gem_object_lookup(file, args->handle);
1143 /* Bounds check source. */
1144 if (range_overflows_t(u64, args->offset, args->size, obj->base.size)) {
1149 trace_i915_gem_object_pread(obj, args->offset, args->size);
1151 ret = i915_gem_object_wait(obj,
1152 I915_WAIT_INTERRUPTIBLE,
1153 MAX_SCHEDULE_TIMEOUT,
1154 to_rps_client(file));
1158 ret = i915_gem_object_pin_pages(obj);
1162 ret = i915_gem_shmem_pread(obj, args);
1163 if (ret == -EFAULT || ret == -ENODEV)
1164 ret = i915_gem_gtt_pread(obj, args);
1166 i915_gem_object_unpin_pages(obj);
1168 i915_gem_object_put(obj);
1172 /* This is the fast write path which cannot handle
1173 * page faults in the source data
1177 ggtt_write(struct io_mapping *mapping,
1178 loff_t base, int offset,
1179 char __user *user_data, int length)
1182 unsigned long unwritten;
1184 /* We can use the cpu mem copy function because this is X86. */
1185 vaddr = (void __force *)io_mapping_map_atomic_wc(mapping, base);
1186 unwritten = __copy_from_user_inatomic_nocache(vaddr + offset,
1188 io_mapping_unmap_atomic(vaddr);
1190 vaddr = (void __force *)
1191 io_mapping_map_wc(mapping, base, PAGE_SIZE);
1192 unwritten = copy_from_user(vaddr + offset, user_data, length);
1193 io_mapping_unmap(vaddr);
1200 * This is the fast pwrite path, where we copy the data directly from the
1201 * user into the GTT, uncached.
1202 * @obj: i915 GEM object
1203 * @args: pwrite arguments structure
1206 i915_gem_gtt_pwrite_fast(struct drm_i915_gem_object *obj,
1207 const struct drm_i915_gem_pwrite *args)
1209 struct drm_i915_private *i915 = to_i915(obj->base.dev);
1210 struct i915_ggtt *ggtt = &i915->ggtt;
1211 struct drm_mm_node node;
1212 struct i915_vma *vma;
1214 void __user *user_data;
1217 ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
1221 intel_runtime_pm_get(i915);
1222 vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
1223 PIN_MAPPABLE | PIN_NONBLOCK);
1225 node.start = i915_ggtt_offset(vma);
1226 node.allocated = false;
1227 ret = i915_vma_put_fence(vma);
1229 i915_vma_unpin(vma);
1234 ret = insert_mappable_node(ggtt, &node, PAGE_SIZE);
1237 GEM_BUG_ON(!node.allocated);
1240 ret = i915_gem_object_set_to_gtt_domain(obj, true);
1244 mutex_unlock(&i915->drm.struct_mutex);
1246 intel_fb_obj_invalidate(obj, ORIGIN_CPU);
1248 user_data = u64_to_user_ptr(args->data_ptr);
1249 offset = args->offset;
1250 remain = args->size;
1252 /* Operation in this page
1254 * page_base = page offset within aperture
1255 * page_offset = offset within page
1256 * page_length = bytes to copy for this page
1258 u32 page_base = node.start;
1259 unsigned int page_offset = offset_in_page(offset);
1260 unsigned int page_length = PAGE_SIZE - page_offset;
1261 page_length = remain < page_length ? remain : page_length;
1262 if (node.allocated) {
1263 wmb(); /* flush the write before we modify the GGTT */
1264 ggtt->base.insert_page(&ggtt->base,
1265 i915_gem_object_get_dma_address(obj, offset >> PAGE_SHIFT),
1266 node.start, I915_CACHE_NONE, 0);
1267 wmb(); /* flush modifications to the GGTT (insert_page) */
1269 page_base += offset & PAGE_MASK;
1271 /* If we get a fault while copying data, then (presumably) our
1272 * source page isn't available. Return the error and we'll
1273 * retry in the slow path.
1274 * If the object is non-shmem backed, we retry again with the
1275 * path that handles page fault.
1277 if (ggtt_write(&ggtt->mappable, page_base, page_offset,
1278 user_data, page_length)) {
1283 remain -= page_length;
1284 user_data += page_length;
1285 offset += page_length;
1287 intel_fb_obj_flush(obj, ORIGIN_CPU);
1289 mutex_lock(&i915->drm.struct_mutex);
1291 if (node.allocated) {
1293 ggtt->base.clear_range(&ggtt->base,
1294 node.start, node.size);
1295 remove_mappable_node(&node);
1297 i915_vma_unpin(vma);
1300 intel_runtime_pm_put(i915);
1301 mutex_unlock(&i915->drm.struct_mutex);
1306 shmem_pwrite_slow(struct page *page, int offset, int length,
1307 char __user *user_data,
1308 bool page_do_bit17_swizzling,
1309 bool needs_clflush_before,
1310 bool needs_clflush_after)
1316 if (unlikely(needs_clflush_before || page_do_bit17_swizzling))
1317 shmem_clflush_swizzled_range(vaddr + offset, length,
1318 page_do_bit17_swizzling);
1319 if (page_do_bit17_swizzling)
1320 ret = __copy_from_user_swizzled(vaddr, offset, user_data,
1323 ret = __copy_from_user(vaddr + offset, user_data, length);
1324 if (needs_clflush_after)
1325 shmem_clflush_swizzled_range(vaddr + offset, length,
1326 page_do_bit17_swizzling);
1329 return ret ? -EFAULT : 0;
1332 /* Per-page copy function for the shmem pwrite fastpath.
1333 * Flushes invalid cachelines before writing to the target if
1334 * needs_clflush_before is set and flushes out any written cachelines after
1335 * writing if needs_clflush is set.
1338 shmem_pwrite(struct page *page, int offset, int len, char __user *user_data,
1339 bool page_do_bit17_swizzling,
1340 bool needs_clflush_before,
1341 bool needs_clflush_after)
1346 if (!page_do_bit17_swizzling) {
1347 char *vaddr = kmap_atomic(page);
1349 if (needs_clflush_before)
1350 drm_clflush_virt_range(vaddr + offset, len);
1351 ret = __copy_from_user_inatomic(vaddr + offset, user_data, len);
1352 if (needs_clflush_after)
1353 drm_clflush_virt_range(vaddr + offset, len);
1355 kunmap_atomic(vaddr);
1360 return shmem_pwrite_slow(page, offset, len, user_data,
1361 page_do_bit17_swizzling,
1362 needs_clflush_before,
1363 needs_clflush_after);
1367 i915_gem_shmem_pwrite(struct drm_i915_gem_object *obj,
1368 const struct drm_i915_gem_pwrite *args)
1370 struct drm_i915_private *i915 = to_i915(obj->base.dev);
1371 void __user *user_data;
1373 unsigned int obj_do_bit17_swizzling;
1374 unsigned int partial_cacheline_write;
1375 unsigned int needs_clflush;
1376 unsigned int offset, idx;
1379 ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
1383 ret = i915_gem_obj_prepare_shmem_write(obj, &needs_clflush);
1384 mutex_unlock(&i915->drm.struct_mutex);
1388 obj_do_bit17_swizzling = 0;
1389 if (i915_gem_object_needs_bit17_swizzle(obj))
1390 obj_do_bit17_swizzling = BIT(17);
1392 /* If we don't overwrite a cacheline completely we need to be
1393 * careful to have up-to-date data by first clflushing. Don't
1394 * overcomplicate things and flush the entire patch.
1396 partial_cacheline_write = 0;
1397 if (needs_clflush & CLFLUSH_BEFORE)
1398 partial_cacheline_write = boot_cpu_data.x86_clflush_size - 1;
1400 user_data = u64_to_user_ptr(args->data_ptr);
1401 remain = args->size;
1402 offset = offset_in_page(args->offset);
1403 for (idx = args->offset >> PAGE_SHIFT; remain; idx++) {
1404 struct page *page = i915_gem_object_get_page(obj, idx);
1405 unsigned int length = min_t(u64, remain, PAGE_SIZE - offset);
1407 ret = shmem_pwrite(page, offset, length, user_data,
1408 page_to_phys(page) & obj_do_bit17_swizzling,
1409 (offset | length) & partial_cacheline_write,
1410 needs_clflush & CLFLUSH_AFTER);
1415 user_data += length;
1419 intel_fb_obj_flush(obj, ORIGIN_CPU);
1420 i915_gem_obj_finish_shmem_access(obj);
1425 * Writes data to the object referenced by handle.
1427 * @data: ioctl data blob
1430 * On error, the contents of the buffer that were to be modified are undefined.
1433 i915_gem_pwrite_ioctl(struct drm_device *dev, void *data,
1434 struct drm_file *file)
1436 struct drm_i915_gem_pwrite *args = data;
1437 struct drm_i915_gem_object *obj;
1440 if (args->size == 0)
1443 if (!access_ok(VERIFY_READ,
1444 u64_to_user_ptr(args->data_ptr),
1448 obj = i915_gem_object_lookup(file, args->handle);
1452 /* Bounds check destination. */
1453 if (range_overflows_t(u64, args->offset, args->size, obj->base.size)) {
1458 trace_i915_gem_object_pwrite(obj, args->offset, args->size);
1461 if (obj->ops->pwrite)
1462 ret = obj->ops->pwrite(obj, args);
1466 ret = i915_gem_object_wait(obj,
1467 I915_WAIT_INTERRUPTIBLE |
1469 MAX_SCHEDULE_TIMEOUT,
1470 to_rps_client(file));
1474 ret = i915_gem_object_pin_pages(obj);
1479 /* We can only do the GTT pwrite on untiled buffers, as otherwise
1480 * it would end up going through the fenced access, and we'll get
1481 * different detiling behavior between reading and writing.
1482 * pread/pwrite currently are reading and writing from the CPU
1483 * perspective, requiring manual detiling by the client.
1485 if (!i915_gem_object_has_struct_page(obj) ||
1486 cpu_write_needs_clflush(obj))
1487 /* Note that the gtt paths might fail with non-page-backed user
1488 * pointers (e.g. gtt mappings when moving data between
1489 * textures). Fallback to the shmem path in that case.
1491 ret = i915_gem_gtt_pwrite_fast(obj, args);
1493 if (ret == -EFAULT || ret == -ENOSPC) {
1494 if (obj->phys_handle)
1495 ret = i915_gem_phys_pwrite(obj, args, file);
1497 ret = i915_gem_shmem_pwrite(obj, args);
1500 i915_gem_object_unpin_pages(obj);
1502 i915_gem_object_put(obj);
1506 static void i915_gem_object_bump_inactive_ggtt(struct drm_i915_gem_object *obj)
1508 struct drm_i915_private *i915;
1509 struct list_head *list;
1510 struct i915_vma *vma;
1512 list_for_each_entry(vma, &obj->vma_list, obj_link) {
1513 if (!i915_vma_is_ggtt(vma))
1516 if (i915_vma_is_active(vma))
1519 if (!drm_mm_node_allocated(&vma->node))
1522 list_move_tail(&vma->vm_link, &vma->vm->inactive_list);
1525 i915 = to_i915(obj->base.dev);
1526 list = obj->bind_count ? &i915->mm.bound_list : &i915->mm.unbound_list;
1527 list_move_tail(&obj->global_link, list);
1531 * Called when user space prepares to use an object with the CPU, either
1532 * through the mmap ioctl's mapping or a GTT mapping.
1534 * @data: ioctl data blob
1538 i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
1539 struct drm_file *file)
1541 struct drm_i915_gem_set_domain *args = data;
1542 struct drm_i915_gem_object *obj;
1543 uint32_t read_domains = args->read_domains;
1544 uint32_t write_domain = args->write_domain;
1547 /* Only handle setting domains to types used by the CPU. */
1548 if ((write_domain | read_domains) & I915_GEM_GPU_DOMAINS)
1551 /* Having something in the write domain implies it's in the read
1552 * domain, and only that read domain. Enforce that in the request.
1554 if (write_domain != 0 && read_domains != write_domain)
1557 obj = i915_gem_object_lookup(file, args->handle);
1561 /* Try to flush the object off the GPU without holding the lock.
1562 * We will repeat the flush holding the lock in the normal manner
1563 * to catch cases where we are gazumped.
1565 err = i915_gem_object_wait(obj,
1566 I915_WAIT_INTERRUPTIBLE |
1567 (write_domain ? I915_WAIT_ALL : 0),
1568 MAX_SCHEDULE_TIMEOUT,
1569 to_rps_client(file));
1573 /* Flush and acquire obj->pages so that we are coherent through
1574 * direct access in memory with previous cached writes through
1575 * shmemfs and that our cache domain tracking remains valid.
1576 * For example, if the obj->filp was moved to swap without us
1577 * being notified and releasing the pages, we would mistakenly
1578 * continue to assume that the obj remained out of the CPU cached
1581 err = i915_gem_object_pin_pages(obj);
1585 err = i915_mutex_lock_interruptible(dev);
1589 if (read_domains & I915_GEM_DOMAIN_WC)
1590 err = i915_gem_object_set_to_wc_domain(obj, write_domain);
1591 else if (read_domains & I915_GEM_DOMAIN_GTT)
1592 err = i915_gem_object_set_to_gtt_domain(obj, write_domain);
1594 err = i915_gem_object_set_to_cpu_domain(obj, write_domain);
1596 /* And bump the LRU for this access */
1597 i915_gem_object_bump_inactive_ggtt(obj);
1599 mutex_unlock(&dev->struct_mutex);
1601 if (write_domain != 0)
1602 intel_fb_obj_invalidate(obj,
1603 fb_write_origin(obj, write_domain));
1606 i915_gem_object_unpin_pages(obj);
1608 i915_gem_object_put(obj);
1613 * Called when user space has done writes to this buffer
1615 * @data: ioctl data blob
1619 i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
1620 struct drm_file *file)
1622 struct drm_i915_gem_sw_finish *args = data;
1623 struct drm_i915_gem_object *obj;
1625 obj = i915_gem_object_lookup(file, args->handle);
1629 /* Pinned buffers may be scanout, so flush the cache */
1630 i915_gem_object_flush_if_display(obj);
1631 i915_gem_object_put(obj);
1637 __vma_matches(struct vm_area_struct *vma, struct file *filp,
1638 unsigned long addr, unsigned long size)
1640 if (vma->vm_file != filp)
1643 return vma->vm_start == addr &&
1644 (vma->vm_end - vma->vm_start) == PAGE_ALIGN(size);
1648 * i915_gem_mmap_ioctl - Maps the contents of an object, returning the address
1651 * @data: ioctl data blob
1654 * While the mapping holds a reference on the contents of the object, it doesn't
1655 * imply a ref on the object itself.
1659 * DRM driver writers who look a this function as an example for how to do GEM
1660 * mmap support, please don't implement mmap support like here. The modern way
1661 * to implement DRM mmap support is with an mmap offset ioctl (like
1662 * i915_gem_mmap_gtt) and then using the mmap syscall on the DRM fd directly.
1663 * That way debug tooling like valgrind will understand what's going on, hiding
1664 * the mmap call in a driver private ioctl will break that. The i915 driver only
1665 * does cpu mmaps this way because we didn't know better.
1668 i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
1669 struct drm_file *file)
1671 struct drm_i915_gem_mmap *args = data;
1672 struct drm_i915_gem_object *obj;
1675 if (args->flags & ~(I915_MMAP_WC))
1678 if (args->flags & I915_MMAP_WC && !boot_cpu_has(X86_FEATURE_PAT))
1681 obj = i915_gem_object_lookup(file, args->handle);
1685 /* prime objects have no backing filp to GEM mmap
1688 if (!obj->base.filp) {
1689 i915_gem_object_put(obj);
1693 addr = vm_mmap(obj->base.filp, 0, args->size,
1694 PROT_READ | PROT_WRITE, MAP_SHARED,
1696 if (args->flags & I915_MMAP_WC) {
1697 struct mm_struct *mm = current->mm;
1698 struct vm_area_struct *vma;
1700 if (down_write_killable(&mm->mmap_sem)) {
1701 i915_gem_object_put(obj);
1704 vma = find_vma(mm, addr);
1705 if (vma && __vma_matches(vma, obj->base.filp, addr, args->size))
1707 pgprot_writecombine(vm_get_page_prot(vma->vm_flags));
1710 up_write(&mm->mmap_sem);
1712 /* This may race, but that's ok, it only gets set */
1713 WRITE_ONCE(obj->frontbuffer_ggtt_origin, ORIGIN_CPU);
1715 i915_gem_object_put(obj);
1716 if (IS_ERR((void *)addr))
1719 args->addr_ptr = (uint64_t) addr;
1724 static unsigned int tile_row_pages(struct drm_i915_gem_object *obj)
1726 return i915_gem_object_get_tile_row_size(obj) >> PAGE_SHIFT;
1730 * i915_gem_mmap_gtt_version - report the current feature set for GTT mmaps
1732 * A history of the GTT mmap interface:
1734 * 0 - Everything had to fit into the GTT. Both parties of a memcpy had to
1735 * aligned and suitable for fencing, and still fit into the available
1736 * mappable space left by the pinned display objects. A classic problem
1737 * we called the page-fault-of-doom where we would ping-pong between
1738 * two objects that could not fit inside the GTT and so the memcpy
1739 * would page one object in at the expense of the other between every
1742 * 1 - Objects can be any size, and have any compatible fencing (X Y, or none
1743 * as set via i915_gem_set_tiling() [DRM_I915_GEM_SET_TILING]). If the
1744 * object is too large for the available space (or simply too large
1745 * for the mappable aperture!), a view is created instead and faulted
1746 * into userspace. (This view is aligned and sized appropriately for
1749 * 2 - Recognise WC as a separate cache domain so that we can flush the
1750 * delayed writes via GTT before performing direct access via WC.
1754 * * snoopable objects cannot be accessed via the GTT. It can cause machine
1755 * hangs on some architectures, corruption on others. An attempt to service
1756 * a GTT page fault from a snoopable object will generate a SIGBUS.
1758 * * the object must be able to fit into RAM (physical memory, though no
1759 * limited to the mappable aperture).
1764 * * a new GTT page fault will synchronize rendering from the GPU and flush
1765 * all data to system memory. Subsequent access will not be synchronized.
1767 * * all mappings are revoked on runtime device suspend.
1769 * * there are only 8, 16 or 32 fence registers to share between all users
1770 * (older machines require fence register for display and blitter access
1771 * as well). Contention of the fence registers will cause the previous users
1772 * to be unmapped and any new access will generate new page faults.
1774 * * running out of memory while servicing a fault may generate a SIGBUS,
1775 * rather than the expected SIGSEGV.
1777 int i915_gem_mmap_gtt_version(void)
1782 static inline struct i915_ggtt_view
1783 compute_partial_view(struct drm_i915_gem_object *obj,
1784 pgoff_t page_offset,
1787 struct i915_ggtt_view view;
1789 if (i915_gem_object_is_tiled(obj))
1790 chunk = roundup(chunk, tile_row_pages(obj));
1792 view.type = I915_GGTT_VIEW_PARTIAL;
1793 view.partial.offset = rounddown(page_offset, chunk);
1795 min_t(unsigned int, chunk,
1796 (obj->base.size >> PAGE_SHIFT) - view.partial.offset);
1798 /* If the partial covers the entire object, just create a normal VMA. */
1799 if (chunk >= obj->base.size >> PAGE_SHIFT)
1800 view.type = I915_GGTT_VIEW_NORMAL;
1806 * i915_gem_fault - fault a page into the GTT
1809 * The fault handler is set up by drm_gem_mmap() when a object is GTT mapped
1810 * from userspace. The fault handler takes care of binding the object to
1811 * the GTT (if needed), allocating and programming a fence register (again,
1812 * only if needed based on whether the old reg is still valid or the object
1813 * is tiled) and inserting a new PTE into the faulting process.
1815 * Note that the faulting process may involve evicting existing objects
1816 * from the GTT and/or fence registers to make room. So performance may
1817 * suffer if the GTT working set is large or there are few fence registers
1820 * The current feature set supported by i915_gem_fault() and thus GTT mmaps
1821 * is exposed via I915_PARAM_MMAP_GTT_VERSION (see i915_gem_mmap_gtt_version).
1823 int i915_gem_fault(struct vm_fault *vmf)
1825 #define MIN_CHUNK_PAGES ((1 << 20) >> PAGE_SHIFT) /* 1 MiB */
1826 struct vm_area_struct *area = vmf->vma;
1827 struct drm_i915_gem_object *obj = to_intel_bo(area->vm_private_data);
1828 struct drm_device *dev = obj->base.dev;
1829 struct drm_i915_private *dev_priv = to_i915(dev);
1830 struct i915_ggtt *ggtt = &dev_priv->ggtt;
1831 bool write = !!(vmf->flags & FAULT_FLAG_WRITE);
1832 struct i915_vma *vma;
1833 pgoff_t page_offset;
1837 /* Sanity check that we allow writing into this object */
1838 if (i915_gem_object_is_readonly(obj) && write)
1839 return VM_FAULT_SIGBUS;
1841 /* We don't use vmf->pgoff since that has the fake offset */
1842 page_offset = (vmf->address - area->vm_start) >> PAGE_SHIFT;
1844 trace_i915_gem_object_fault(obj, page_offset, true, write);
1846 /* Try to flush the object off the GPU first without holding the lock.
1847 * Upon acquiring the lock, we will perform our sanity checks and then
1848 * repeat the flush holding the lock in the normal manner to catch cases
1849 * where we are gazumped.
1851 ret = i915_gem_object_wait(obj,
1852 I915_WAIT_INTERRUPTIBLE,
1853 MAX_SCHEDULE_TIMEOUT,
1858 ret = i915_gem_object_pin_pages(obj);
1862 intel_runtime_pm_get(dev_priv);
1864 ret = i915_mutex_lock_interruptible(dev);
1868 /* Access to snoopable pages through the GTT is incoherent. */
1869 if (obj->cache_level != I915_CACHE_NONE && !HAS_LLC(dev_priv)) {
1874 /* If the object is smaller than a couple of partial vma, it is
1875 * not worth only creating a single partial vma - we may as well
1876 * clear enough space for the full object.
1878 flags = PIN_MAPPABLE;
1879 if (obj->base.size > 2 * MIN_CHUNK_PAGES << PAGE_SHIFT)
1880 flags |= PIN_NONBLOCK | PIN_NONFAULT;
1882 /* Now pin it into the GTT as needed */
1883 vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0, flags);
1885 /* Use a partial view if it is bigger than available space */
1886 struct i915_ggtt_view view =
1887 compute_partial_view(obj, page_offset, MIN_CHUNK_PAGES);
1889 /* Userspace is now writing through an untracked VMA, abandon
1890 * all hope that the hardware is able to track future writes.
1892 obj->frontbuffer_ggtt_origin = ORIGIN_CPU;
1894 vma = i915_gem_object_ggtt_pin(obj, &view, 0, 0, PIN_MAPPABLE);
1901 ret = i915_gem_object_set_to_gtt_domain(obj, write);
1905 ret = i915_vma_get_fence(vma);
1909 /* Mark as being mmapped into userspace for later revocation */
1910 assert_rpm_wakelock_held(dev_priv);
1911 if (list_empty(&obj->userfault_link))
1912 list_add(&obj->userfault_link, &dev_priv->mm.userfault_list);
1914 /* Finally, remap it using the new GTT offset */
1915 ret = remap_io_mapping(area,
1916 area->vm_start + (vma->ggtt_view.partial.offset << PAGE_SHIFT),
1917 (ggtt->mappable_base + vma->node.start) >> PAGE_SHIFT,
1918 min_t(u64, vma->size, area->vm_end - area->vm_start),
1922 __i915_vma_unpin(vma);
1924 mutex_unlock(&dev->struct_mutex);
1926 intel_runtime_pm_put(dev_priv);
1927 i915_gem_object_unpin_pages(obj);
1932 * We eat errors when the gpu is terminally wedged to avoid
1933 * userspace unduly crashing (gl has no provisions for mmaps to
1934 * fail). But any other -EIO isn't ours (e.g. swap in failure)
1935 * and so needs to be reported.
1937 if (!i915_terminally_wedged(&dev_priv->gpu_error)) {
1938 ret = VM_FAULT_SIGBUS;
1943 * EAGAIN means the gpu is hung and we'll wait for the error
1944 * handler to reset everything when re-faulting in
1945 * i915_mutex_lock_interruptible.
1952 * EBUSY is ok: this just means that another thread
1953 * already did the job.
1955 ret = VM_FAULT_NOPAGE;
1962 ret = VM_FAULT_SIGBUS;
1965 WARN_ONCE(ret, "unhandled error in i915_gem_fault: %i\n", ret);
1966 ret = VM_FAULT_SIGBUS;
1973 * i915_gem_release_mmap - remove physical page mappings
1974 * @obj: obj in question
1976 * Preserve the reservation of the mmapping with the DRM core code, but
1977 * relinquish ownership of the pages back to the system.
1979 * It is vital that we remove the page mapping if we have mapped a tiled
1980 * object through the GTT and then lose the fence register due to
1981 * resource pressure. Similarly if the object has been moved out of the
1982 * aperture, than pages mapped into userspace must be revoked. Removing the
1983 * mapping will then trigger a page fault on the next user access, allowing
1984 * fixup by i915_gem_fault().
1987 i915_gem_release_mmap(struct drm_i915_gem_object *obj)
1989 struct drm_i915_private *i915 = to_i915(obj->base.dev);
1991 /* Serialisation between user GTT access and our code depends upon
1992 * revoking the CPU's PTE whilst the mutex is held. The next user
1993 * pagefault then has to wait until we release the mutex.
1995 * Note that RPM complicates somewhat by adding an additional
1996 * requirement that operations to the GGTT be made holding the RPM
1999 lockdep_assert_held(&i915->drm.struct_mutex);
2000 intel_runtime_pm_get(i915);
2002 if (list_empty(&obj->userfault_link))
2005 list_del_init(&obj->userfault_link);
2006 drm_vma_node_unmap(&obj->base.vma_node,
2007 obj->base.dev->anon_inode->i_mapping);
2009 /* Ensure that the CPU's PTE are revoked and there are not outstanding
2010 * memory transactions from userspace before we return. The TLB
2011 * flushing implied above by changing the PTE above *should* be
2012 * sufficient, an extra barrier here just provides us with a bit
2013 * of paranoid documentation about our requirement to serialise
2014 * memory writes before touching registers / GSM.
2019 intel_runtime_pm_put(i915);
2022 void i915_gem_runtime_suspend(struct drm_i915_private *dev_priv)
2024 struct drm_i915_gem_object *obj, *on;
2028 * Only called during RPM suspend. All users of the userfault_list
2029 * must be holding an RPM wakeref to ensure that this can not
2030 * run concurrently with themselves (and use the struct_mutex for
2031 * protection between themselves).
2034 list_for_each_entry_safe(obj, on,
2035 &dev_priv->mm.userfault_list, userfault_link) {
2036 list_del_init(&obj->userfault_link);
2037 drm_vma_node_unmap(&obj->base.vma_node,
2038 obj->base.dev->anon_inode->i_mapping);
2041 /* The fence will be lost when the device powers down. If any were
2042 * in use by hardware (i.e. they are pinned), we should not be powering
2043 * down! All other fences will be reacquired by the user upon waking.
2045 for (i = 0; i < dev_priv->num_fence_regs; i++) {
2046 struct drm_i915_fence_reg *reg = &dev_priv->fence_regs[i];
2048 /* Ideally we want to assert that the fence register is not
2049 * live at this point (i.e. that no piece of code will be
2050 * trying to write through fence + GTT, as that both violates
2051 * our tracking of activity and associated locking/barriers,
2052 * but also is illegal given that the hw is powered down).
2054 * Previously we used reg->pin_count as a "liveness" indicator.
2055 * That is not sufficient, and we need a more fine-grained
2056 * tool if we want to have a sanity check here.
2062 GEM_BUG_ON(!list_empty(®->vma->obj->userfault_link));
2067 static int i915_gem_object_create_mmap_offset(struct drm_i915_gem_object *obj)
2069 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
2072 err = drm_gem_create_mmap_offset(&obj->base);
2076 /* Attempt to reap some mmap space from dead objects */
2078 err = i915_gem_wait_for_idle(dev_priv, I915_WAIT_INTERRUPTIBLE);
2082 i915_gem_drain_freed_objects(dev_priv);
2083 err = drm_gem_create_mmap_offset(&obj->base);
2087 } while (flush_delayed_work(&dev_priv->gt.retire_work));
2092 static void i915_gem_object_free_mmap_offset(struct drm_i915_gem_object *obj)
2094 drm_gem_free_mmap_offset(&obj->base);
2098 i915_gem_mmap_gtt(struct drm_file *file,
2099 struct drm_device *dev,
2103 struct drm_i915_gem_object *obj;
2106 obj = i915_gem_object_lookup(file, handle);
2110 ret = i915_gem_object_create_mmap_offset(obj);
2112 *offset = drm_vma_node_offset_addr(&obj->base.vma_node);
2114 i915_gem_object_put(obj);
2119 * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
2121 * @data: GTT mapping ioctl data
2122 * @file: GEM object info
2124 * Simply returns the fake offset to userspace so it can mmap it.
2125 * The mmap call will end up in drm_gem_mmap(), which will set things
2126 * up so we can get faults in the handler above.
2128 * The fault handler will take care of binding the object into the GTT
2129 * (since it may have been evicted to make room for something), allocating
2130 * a fence register, and mapping the appropriate aperture address into
2134 i915_gem_mmap_gtt_ioctl(struct drm_device *dev, void *data,
2135 struct drm_file *file)
2137 struct drm_i915_gem_mmap_gtt *args = data;
2139 return i915_gem_mmap_gtt(file, dev, args->handle, &args->offset);
2142 /* Immediately discard the backing storage */
2144 i915_gem_object_truncate(struct drm_i915_gem_object *obj)
2146 i915_gem_object_free_mmap_offset(obj);
2148 if (obj->base.filp == NULL)
2151 /* Our goal here is to return as much of the memory as
2152 * is possible back to the system as we are called from OOM.
2153 * To do this we must instruct the shmfs to drop all of its
2154 * backing pages, *now*.
2156 shmem_truncate_range(file_inode(obj->base.filp), 0, (loff_t)-1);
2157 obj->mm.madv = __I915_MADV_PURGED;
2158 obj->mm.pages = ERR_PTR(-EFAULT);
2161 /* Try to discard unwanted pages */
2162 void __i915_gem_object_invalidate(struct drm_i915_gem_object *obj)
2164 struct address_space *mapping;
2166 lockdep_assert_held(&obj->mm.lock);
2167 GEM_BUG_ON(obj->mm.pages);
2169 switch (obj->mm.madv) {
2170 case I915_MADV_DONTNEED:
2171 i915_gem_object_truncate(obj);
2172 case __I915_MADV_PURGED:
2176 if (obj->base.filp == NULL)
2179 mapping = obj->base.filp->f_mapping,
2180 invalidate_mapping_pages(mapping, 0, (loff_t)-1);
2184 i915_gem_object_put_pages_gtt(struct drm_i915_gem_object *obj,
2185 struct sg_table *pages)
2187 struct sgt_iter sgt_iter;
2190 __i915_gem_object_release_shmem(obj, pages, true);
2192 i915_gem_gtt_finish_pages(obj, pages);
2194 if (i915_gem_object_needs_bit17_swizzle(obj))
2195 i915_gem_object_save_bit_17_swizzle(obj, pages);
2197 for_each_sgt_page(page, sgt_iter, pages) {
2199 set_page_dirty(page);
2201 if (obj->mm.madv == I915_MADV_WILLNEED)
2202 mark_page_accessed(page);
2206 obj->mm.dirty = false;
2208 sg_free_table(pages);
2212 static void __i915_gem_object_reset_page_iter(struct drm_i915_gem_object *obj)
2214 struct radix_tree_iter iter;
2218 radix_tree_for_each_slot(slot, &obj->mm.get_page.radix, &iter, 0)
2219 radix_tree_delete(&obj->mm.get_page.radix, iter.index);
2223 struct reg_and_bit {
2228 static struct reg_and_bit
2229 get_reg_and_bit(const struct intel_engine_cs *engine,
2230 const i915_reg_t *regs, const unsigned int num)
2232 const unsigned int class = engine->class;
2233 struct reg_and_bit rb = { .bit = 1 };
2235 if (WARN_ON_ONCE(class >= num || !regs[class].reg))
2238 rb.reg = regs[class];
2239 if (class == VIDEO_DECODE_CLASS)
2240 rb.reg.reg += 4 * engine->instance; /* GEN8_M2TCR */
2245 static void invalidate_tlbs(struct drm_i915_private *dev_priv)
2247 static const i915_reg_t gen8_regs[] = {
2248 [RENDER_CLASS] = GEN8_RTCR,
2249 [VIDEO_DECODE_CLASS] = GEN8_M1TCR, /* , GEN8_M2TCR */
2250 [VIDEO_ENHANCEMENT_CLASS] = GEN8_VTCR,
2251 [COPY_ENGINE_CLASS] = GEN8_BTCR,
2253 const unsigned int num = ARRAY_SIZE(gen8_regs);
2254 const i915_reg_t *regs = gen8_regs;
2255 struct intel_engine_cs *engine;
2256 enum intel_engine_id id;
2258 if (INTEL_GEN(dev_priv) < 8)
2261 assert_rpm_wakelock_held(dev_priv);
2263 mutex_lock(&dev_priv->tlb_invalidate_lock);
2264 intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
2266 for_each_engine(engine, dev_priv, id) {
2268 * HW architecture suggest typical invalidation time at 40us,
2269 * with pessimistic cases up to 100us and a recommendation to
2270 * cap at 1ms. We go a bit higher just in case.
2272 const unsigned int timeout_us = 100;
2273 const unsigned int timeout_ms = 4;
2274 struct reg_and_bit rb;
2276 rb = get_reg_and_bit(engine, regs, num);
2277 if (!i915_mmio_reg_offset(rb.reg))
2280 I915_WRITE_FW(rb.reg, rb.bit);
2281 if (__intel_wait_for_register_fw(dev_priv,
2283 timeout_us, timeout_ms,
2285 DRM_ERROR_RATELIMITED("%s TLB invalidation did not complete in %ums!\n",
2286 engine->name, timeout_ms);
2289 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
2290 mutex_unlock(&dev_priv->tlb_invalidate_lock);
2293 void __i915_gem_object_put_pages(struct drm_i915_gem_object *obj,
2294 enum i915_mm_subclass subclass)
2296 struct sg_table *pages;
2298 if (i915_gem_object_has_pinned_pages(obj))
2301 GEM_BUG_ON(obj->bind_count);
2302 if (!READ_ONCE(obj->mm.pages))
2305 /* May be called by shrinker from within get_pages() (on another bo) */
2306 mutex_lock_nested(&obj->mm.lock, subclass);
2307 if (unlikely(atomic_read(&obj->mm.pages_pin_count)))
2310 /* ->put_pages might need to allocate memory for the bit17 swizzle
2311 * array, hence protect them from being reaped by removing them from gtt
2313 pages = fetch_and_zero(&obj->mm.pages);
2316 if (obj->mm.mapping) {
2319 ptr = page_mask_bits(obj->mm.mapping);
2320 if (is_vmalloc_addr(ptr))
2323 kunmap(kmap_to_page(ptr));
2325 obj->mm.mapping = NULL;
2328 __i915_gem_object_reset_page_iter(obj);
2330 if (!IS_ERR(pages)) {
2331 if (test_and_clear_bit(I915_BO_WAS_BOUND_BIT, &obj->flags)) {
2332 struct drm_i915_private *i915 = to_i915(obj->base.dev);
2334 if (intel_runtime_pm_get_if_in_use(i915)) {
2335 invalidate_tlbs(i915);
2336 intel_runtime_pm_put(i915);
2340 obj->ops->put_pages(obj, pages);
2344 mutex_unlock(&obj->mm.lock);
2347 static bool i915_sg_trim(struct sg_table *orig_st)
2349 struct sg_table new_st;
2350 struct scatterlist *sg, *new_sg;
2353 if (orig_st->nents == orig_st->orig_nents)
2356 if (sg_alloc_table(&new_st, orig_st->nents, GFP_KERNEL | __GFP_NOWARN))
2359 new_sg = new_st.sgl;
2360 for_each_sg(orig_st->sgl, sg, orig_st->nents, i) {
2361 sg_set_page(new_sg, sg_page(sg), sg->length, 0);
2362 /* called before being DMA mapped, no need to copy sg->dma_* */
2363 new_sg = sg_next(new_sg);
2365 GEM_BUG_ON(new_sg); /* Should walk exactly nents and hit the end */
2367 sg_free_table(orig_st);
2373 static struct sg_table *
2374 i915_gem_object_get_pages_gtt(struct drm_i915_gem_object *obj)
2376 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
2377 const unsigned long page_count = obj->base.size / PAGE_SIZE;
2379 struct address_space *mapping;
2380 struct sg_table *st;
2381 struct scatterlist *sg;
2382 struct sgt_iter sgt_iter;
2384 unsigned long last_pfn = 0; /* suppress gcc warning */
2385 unsigned int max_segment;
2389 /* Assert that the object is not currently in any GPU domain. As it
2390 * wasn't in the GTT, there shouldn't be any way it could have been in
2393 GEM_BUG_ON(obj->base.read_domains & I915_GEM_GPU_DOMAINS);
2394 GEM_BUG_ON(obj->base.write_domain & I915_GEM_GPU_DOMAINS);
2396 max_segment = swiotlb_max_segment();
2398 max_segment = rounddown(UINT_MAX, PAGE_SIZE);
2400 st = kmalloc(sizeof(*st), GFP_KERNEL);
2402 return ERR_PTR(-ENOMEM);
2405 if (sg_alloc_table(st, page_count, GFP_KERNEL)) {
2407 return ERR_PTR(-ENOMEM);
2410 /* Get the list of pages out of our struct file. They'll be pinned
2411 * at this point until we release them.
2413 * Fail silently without starting the shrinker
2415 mapping = obj->base.filp->f_mapping;
2416 noreclaim = mapping_gfp_constraint(mapping, ~__GFP_RECLAIM);
2417 noreclaim |= __GFP_NORETRY | __GFP_NOWARN;
2421 for (i = 0; i < page_count; i++) {
2422 const unsigned int shrink[] = {
2423 I915_SHRINK_BOUND | I915_SHRINK_UNBOUND | I915_SHRINK_PURGEABLE,
2426 gfp_t gfp = noreclaim;
2429 page = shmem_read_mapping_page_gfp(mapping, i, gfp);
2430 if (likely(!IS_ERR(page)))
2434 ret = PTR_ERR(page);
2438 i915_gem_shrink(dev_priv, 2 * page_count, NULL, *s++);
2441 /* We've tried hard to allocate the memory by reaping
2442 * our own buffer, now let the real VM do its job and
2443 * go down in flames if truly OOM.
2445 * However, since graphics tend to be disposable,
2446 * defer the oom here by reporting the ENOMEM back
2450 /* reclaim and warn, but no oom */
2451 gfp = mapping_gfp_mask(mapping);
2453 /* Our bo are always dirty and so we require
2454 * kswapd to reclaim our pages (direct reclaim
2455 * does not effectively begin pageout of our
2456 * buffers on its own). However, direct reclaim
2457 * only waits for kswapd when under allocation
2458 * congestion. So as a result __GFP_RECLAIM is
2459 * unreliable and fails to actually reclaim our
2460 * dirty pages -- unless you try over and over
2461 * again with !__GFP_NORETRY. However, we still
2462 * want to fail this allocation rather than
2463 * trigger the out-of-memory killer and for
2464 * this we want __GFP_RETRY_MAYFAIL.
2466 gfp |= __GFP_RETRY_MAYFAIL;
2471 sg->length >= max_segment ||
2472 page_to_pfn(page) != last_pfn + 1) {
2476 sg_set_page(sg, page, PAGE_SIZE, 0);
2478 sg->length += PAGE_SIZE;
2480 last_pfn = page_to_pfn(page);
2482 /* Check that the i965g/gm workaround works. */
2483 WARN_ON((gfp & __GFP_DMA32) && (last_pfn >= 0x00100000UL));
2485 if (sg) /* loop terminated early; short sg table */
2488 /* Trim unused sg entries to avoid wasting memory. */
2491 ret = i915_gem_gtt_prepare_pages(obj, st);
2493 /* DMA remapping failed? One possible cause is that
2494 * it could not reserve enough large entries, asking
2495 * for PAGE_SIZE chunks instead may be helpful.
2497 if (max_segment > PAGE_SIZE) {
2498 for_each_sgt_page(page, sgt_iter, st)
2502 max_segment = PAGE_SIZE;
2505 dev_warn(&dev_priv->drm.pdev->dev,
2506 "Failed to DMA remap %lu pages\n",
2512 if (i915_gem_object_needs_bit17_swizzle(obj))
2513 i915_gem_object_do_bit_17_swizzle(obj, st);
2520 for_each_sgt_page(page, sgt_iter, st)
2525 /* shmemfs first checks if there is enough memory to allocate the page
2526 * and reports ENOSPC should there be insufficient, along with the usual
2527 * ENOMEM for a genuine allocation failure.
2529 * We use ENOSPC in our driver to mean that we have run out of aperture
2530 * space and so want to translate the error from shmemfs back to our
2531 * usual understanding of ENOMEM.
2536 return ERR_PTR(ret);
2539 void __i915_gem_object_set_pages(struct drm_i915_gem_object *obj,
2540 struct sg_table *pages)
2542 lockdep_assert_held(&obj->mm.lock);
2544 obj->mm.get_page.sg_pos = pages->sgl;
2545 obj->mm.get_page.sg_idx = 0;
2547 obj->mm.pages = pages;
2549 if (i915_gem_object_is_tiled(obj) &&
2550 to_i915(obj->base.dev)->quirks & QUIRK_PIN_SWIZZLED_PAGES) {
2551 GEM_BUG_ON(obj->mm.quirked);
2552 __i915_gem_object_pin_pages(obj);
2553 obj->mm.quirked = true;
2557 static int ____i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
2559 struct sg_table *pages;
2561 GEM_BUG_ON(i915_gem_object_has_pinned_pages(obj));
2563 if (unlikely(obj->mm.madv != I915_MADV_WILLNEED)) {
2564 DRM_DEBUG("Attempting to obtain a purgeable object\n");
2568 pages = obj->ops->get_pages(obj);
2569 if (unlikely(IS_ERR(pages)))
2570 return PTR_ERR(pages);
2572 __i915_gem_object_set_pages(obj, pages);
2576 /* Ensure that the associated pages are gathered from the backing storage
2577 * and pinned into our object. i915_gem_object_pin_pages() may be called
2578 * multiple times before they are released by a single call to
2579 * i915_gem_object_unpin_pages() - once the pages are no longer referenced
2580 * either as a result of memory pressure (reaping pages under the shrinker)
2581 * or as the object is itself released.
2583 int __i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
2587 err = mutex_lock_interruptible(&obj->mm.lock);
2591 if (unlikely(IS_ERR_OR_NULL(obj->mm.pages))) {
2592 err = ____i915_gem_object_get_pages(obj);
2596 smp_mb__before_atomic();
2598 atomic_inc(&obj->mm.pages_pin_count);
2601 mutex_unlock(&obj->mm.lock);
2605 /* The 'mapping' part of i915_gem_object_pin_map() below */
2606 static void *i915_gem_object_map(const struct drm_i915_gem_object *obj,
2607 enum i915_map_type type)
2609 unsigned long n_pages = obj->base.size >> PAGE_SHIFT;
2610 struct sg_table *sgt = obj->mm.pages;
2611 struct sgt_iter sgt_iter;
2613 struct page *stack_pages[32];
2614 struct page **pages = stack_pages;
2615 unsigned long i = 0;
2619 /* A single page can always be kmapped */
2620 if (n_pages == 1 && type == I915_MAP_WB)
2621 return kmap(sg_page(sgt->sgl));
2623 if (n_pages > ARRAY_SIZE(stack_pages)) {
2624 /* Too big for stack -- allocate temporary array instead */
2625 pages = kvmalloc_array(n_pages, sizeof(*pages), GFP_KERNEL);
2630 for_each_sgt_page(page, sgt_iter, sgt)
2633 /* Check that we have the expected number of pages */
2634 GEM_BUG_ON(i != n_pages);
2639 /* fallthrough to use PAGE_KERNEL anyway */
2641 pgprot = PAGE_KERNEL;
2644 pgprot = pgprot_writecombine(PAGE_KERNEL_IO);
2647 addr = vmap(pages, n_pages, 0, pgprot);
2649 if (pages != stack_pages)
2655 /* get, pin, and map the pages of the object into kernel space */
2656 void *i915_gem_object_pin_map(struct drm_i915_gem_object *obj,
2657 enum i915_map_type type)
2659 enum i915_map_type has_type;
2664 GEM_BUG_ON(!i915_gem_object_has_struct_page(obj));
2666 ret = mutex_lock_interruptible(&obj->mm.lock);
2668 return ERR_PTR(ret);
2670 pinned = !(type & I915_MAP_OVERRIDE);
2671 type &= ~I915_MAP_OVERRIDE;
2673 if (!atomic_inc_not_zero(&obj->mm.pages_pin_count)) {
2674 if (unlikely(IS_ERR_OR_NULL(obj->mm.pages))) {
2675 ret = ____i915_gem_object_get_pages(obj);
2679 smp_mb__before_atomic();
2681 atomic_inc(&obj->mm.pages_pin_count);
2684 GEM_BUG_ON(!obj->mm.pages);
2686 ptr = page_unpack_bits(obj->mm.mapping, &has_type);
2687 if (ptr && has_type != type) {
2693 if (is_vmalloc_addr(ptr))
2696 kunmap(kmap_to_page(ptr));
2698 ptr = obj->mm.mapping = NULL;
2702 ptr = i915_gem_object_map(obj, type);
2708 obj->mm.mapping = page_pack_bits(ptr, type);
2712 mutex_unlock(&obj->mm.lock);
2716 atomic_dec(&obj->mm.pages_pin_count);
2723 i915_gem_object_pwrite_gtt(struct drm_i915_gem_object *obj,
2724 const struct drm_i915_gem_pwrite *arg)
2726 struct address_space *mapping = obj->base.filp->f_mapping;
2727 char __user *user_data = u64_to_user_ptr(arg->data_ptr);
2731 /* Before we instantiate/pin the backing store for our use, we
2732 * can prepopulate the shmemfs filp efficiently using a write into
2733 * the pagecache. We avoid the penalty of instantiating all the
2734 * pages, important if the user is just writing to a few and never
2735 * uses the object on the GPU, and using a direct write into shmemfs
2736 * allows it to avoid the cost of retrieving a page (either swapin
2737 * or clearing-before-use) before it is overwritten.
2739 if (READ_ONCE(obj->mm.pages))
2742 if (obj->mm.madv != I915_MADV_WILLNEED)
2745 /* Before the pages are instantiated the object is treated as being
2746 * in the CPU domain. The pages will be clflushed as required before
2747 * use, and we can freely write into the pages directly. If userspace
2748 * races pwrite with any other operation; corruption will ensue -
2749 * that is userspace's prerogative!
2753 offset = arg->offset;
2754 pg = offset_in_page(offset);
2757 unsigned int len, unwritten;
2762 len = PAGE_SIZE - pg;
2766 err = pagecache_write_begin(obj->base.filp, mapping,
2773 unwritten = copy_from_user(vaddr + pg, user_data, len);
2776 err = pagecache_write_end(obj->base.filp, mapping,
2777 offset, len, len - unwritten,
2794 static bool ban_context(const struct i915_gem_context *ctx,
2797 return (i915_gem_context_is_bannable(ctx) &&
2798 score >= CONTEXT_SCORE_BAN_THRESHOLD);
2801 static void i915_gem_context_mark_guilty(struct i915_gem_context *ctx)
2806 atomic_inc(&ctx->guilty_count);
2808 score = atomic_add_return(CONTEXT_SCORE_GUILTY, &ctx->ban_score);
2809 banned = ban_context(ctx, score);
2810 DRM_DEBUG_DRIVER("context %s marked guilty (score %d) banned? %s\n",
2811 ctx->name, score, yesno(banned));
2815 i915_gem_context_set_banned(ctx);
2816 if (!IS_ERR_OR_NULL(ctx->file_priv)) {
2817 atomic_inc(&ctx->file_priv->context_bans);
2818 DRM_DEBUG_DRIVER("client %s has had %d context banned\n",
2819 ctx->name, atomic_read(&ctx->file_priv->context_bans));
2823 static void i915_gem_context_mark_innocent(struct i915_gem_context *ctx)
2825 atomic_inc(&ctx->active_count);
2828 struct drm_i915_gem_request *
2829 i915_gem_find_active_request(struct intel_engine_cs *engine)
2831 struct drm_i915_gem_request *request, *active = NULL;
2832 unsigned long flags;
2834 /* We are called by the error capture and reset at a random
2835 * point in time. In particular, note that neither is crucially
2836 * ordered with an interrupt. After a hang, the GPU is dead and we
2837 * assume that no more writes can happen (we waited long enough for
2838 * all writes that were in transaction to be flushed) - adding an
2839 * extra delay for a recent interrupt is pointless. Hence, we do
2840 * not need an engine->irq_seqno_barrier() before the seqno reads.
2842 spin_lock_irqsave(&engine->timeline->lock, flags);
2843 list_for_each_entry(request, &engine->timeline->requests, link) {
2844 if (__i915_gem_request_completed(request,
2845 request->global_seqno))
2848 GEM_BUG_ON(request->engine != engine);
2849 GEM_BUG_ON(test_bit(DMA_FENCE_FLAG_SIGNALED_BIT,
2850 &request->fence.flags));
2855 spin_unlock_irqrestore(&engine->timeline->lock, flags);
2860 static bool engine_stalled(struct intel_engine_cs *engine)
2862 if (!engine->hangcheck.stalled)
2865 /* Check for possible seqno movement after hang declaration */
2866 if (engine->hangcheck.seqno != intel_engine_get_seqno(engine)) {
2867 DRM_DEBUG_DRIVER("%s pardoned\n", engine->name);
2875 * Ensure irq handler finishes, and not run again.
2876 * Also return the active request so that we only search for it once.
2878 struct drm_i915_gem_request *
2879 i915_gem_reset_prepare_engine(struct intel_engine_cs *engine)
2881 struct drm_i915_gem_request *request = NULL;
2883 /* Prevent the signaler thread from updating the request
2884 * state (by calling dma_fence_signal) as we are processing
2885 * the reset. The write from the GPU of the seqno is
2886 * asynchronous and the signaler thread may see a different
2887 * value to us and declare the request complete, even though
2888 * the reset routine have picked that request as the active
2889 * (incomplete) request. This conflict is not handled
2892 kthread_park(engine->breadcrumbs.signaler);
2894 /* Prevent request submission to the hardware until we have
2895 * completed the reset in i915_gem_reset_finish(). If a request
2896 * is completed by one engine, it may then queue a request
2897 * to a second via its engine->irq_tasklet *just* as we are
2898 * calling engine->init_hw() and also writing the ELSP.
2899 * Turning off the engine->irq_tasklet until the reset is over
2900 * prevents the race.
2902 tasklet_kill(&engine->irq_tasklet);
2903 tasklet_disable(&engine->irq_tasklet);
2905 if (engine->irq_seqno_barrier)
2906 engine->irq_seqno_barrier(engine);
2908 request = i915_gem_find_active_request(engine);
2909 if (request && request->fence.error == -EIO)
2910 request = ERR_PTR(-EIO); /* Previous reset failed! */
2915 int i915_gem_reset_prepare(struct drm_i915_private *dev_priv)
2917 struct intel_engine_cs *engine;
2918 struct drm_i915_gem_request *request;
2919 enum intel_engine_id id;
2922 for_each_engine(engine, dev_priv, id) {
2923 request = i915_gem_reset_prepare_engine(engine);
2924 if (IS_ERR(request)) {
2925 err = PTR_ERR(request);
2929 engine->hangcheck.active_request = request;
2932 i915_gem_revoke_fences(dev_priv);
2937 static void skip_request(struct drm_i915_gem_request *request)
2939 void *vaddr = request->ring->vaddr;
2942 /* As this request likely depends on state from the lost
2943 * context, clear out all the user operations leaving the
2944 * breadcrumb at the end (so we get the fence notifications).
2946 head = request->head;
2947 if (request->postfix < head) {
2948 memset(vaddr + head, 0, request->ring->size - head);
2951 memset(vaddr + head, 0, request->postfix - head);
2953 dma_fence_set_error(&request->fence, -EIO);
2956 static void engine_skip_context(struct drm_i915_gem_request *request)
2958 struct intel_engine_cs *engine = request->engine;
2959 struct i915_gem_context *hung_ctx = request->ctx;
2960 struct intel_timeline *timeline;
2961 unsigned long flags;
2963 timeline = i915_gem_context_lookup_timeline(hung_ctx, engine);
2965 spin_lock_irqsave(&engine->timeline->lock, flags);
2966 spin_lock(&timeline->lock);
2968 list_for_each_entry_continue(request, &engine->timeline->requests, link)
2969 if (request->ctx == hung_ctx)
2970 skip_request(request);
2972 list_for_each_entry(request, &timeline->requests, link)
2973 skip_request(request);
2975 spin_unlock(&timeline->lock);
2976 spin_unlock_irqrestore(&engine->timeline->lock, flags);
2979 /* Returns the request if it was guilty of the hang */
2980 static struct drm_i915_gem_request *
2981 i915_gem_reset_request(struct intel_engine_cs *engine,
2982 struct drm_i915_gem_request *request)
2984 /* The guilty request will get skipped on a hung engine.
2986 * Users of client default contexts do not rely on logical
2987 * state preserved between batches so it is safe to execute
2988 * queued requests following the hang. Non default contexts
2989 * rely on preserved state, so skipping a batch loses the
2990 * evolution of the state and it needs to be considered corrupted.
2991 * Executing more queued batches on top of corrupted state is
2992 * risky. But we take the risk by trying to advance through
2993 * the queued requests in order to make the client behaviour
2994 * more predictable around resets, by not throwing away random
2995 * amount of batches it has prepared for execution. Sophisticated
2996 * clients can use gem_reset_stats_ioctl and dma fence status
2997 * (exported via sync_file info ioctl on explicit fences) to observe
2998 * when it loses the context state and should rebuild accordingly.
3000 * The context ban, and ultimately the client ban, mechanism are safety
3001 * valves if client submission ends up resulting in nothing more than
3005 if (engine_stalled(engine)) {
3006 i915_gem_context_mark_guilty(request->ctx);
3007 skip_request(request);
3009 /* If this context is now banned, skip all pending requests. */
3010 if (i915_gem_context_is_banned(request->ctx))
3011 engine_skip_context(request);
3014 * Since this is not the hung engine, it may have advanced
3015 * since the hang declaration. Double check by refinding
3016 * the active request at the time of the reset.
3018 request = i915_gem_find_active_request(engine);
3020 i915_gem_context_mark_innocent(request->ctx);
3021 dma_fence_set_error(&request->fence, -EAGAIN);
3023 /* Rewind the engine to replay the incomplete rq */
3024 spin_lock_irq(&engine->timeline->lock);
3025 request = list_prev_entry(request, link);
3026 if (&request->link == &engine->timeline->requests)
3028 spin_unlock_irq(&engine->timeline->lock);
3035 void i915_gem_reset_engine(struct intel_engine_cs *engine,
3036 struct drm_i915_gem_request *request)
3038 engine->irq_posted = 0;
3041 request = i915_gem_reset_request(engine, request);
3044 DRM_DEBUG_DRIVER("resetting %s to restart from tail of request 0x%x\n",
3045 engine->name, request->global_seqno);
3048 /* Setup the CS to resume from the breadcrumb of the hung request */
3049 engine->reset_hw(engine, request);
3052 void i915_gem_reset(struct drm_i915_private *dev_priv)
3054 struct intel_engine_cs *engine;
3055 enum intel_engine_id id;
3057 lockdep_assert_held(&dev_priv->drm.struct_mutex);
3059 i915_gem_retire_requests(dev_priv);
3061 for_each_engine(engine, dev_priv, id) {
3062 struct i915_gem_context *ctx;
3064 i915_gem_reset_engine(engine, engine->hangcheck.active_request);
3065 ctx = fetch_and_zero(&engine->last_retired_context);
3067 engine->context_unpin(engine, ctx);
3070 i915_gem_restore_fences(dev_priv);
3072 if (dev_priv->gt.awake) {
3073 intel_sanitize_gt_powersave(dev_priv);
3074 intel_enable_gt_powersave(dev_priv);
3075 if (INTEL_GEN(dev_priv) >= 6)
3076 gen6_rps_busy(dev_priv);
3080 void i915_gem_reset_finish_engine(struct intel_engine_cs *engine)
3082 tasklet_enable(&engine->irq_tasklet);
3083 kthread_unpark(engine->breadcrumbs.signaler);
3086 void i915_gem_reset_finish(struct drm_i915_private *dev_priv)
3088 struct intel_engine_cs *engine;
3089 enum intel_engine_id id;
3091 lockdep_assert_held(&dev_priv->drm.struct_mutex);
3093 for_each_engine(engine, dev_priv, id) {
3094 engine->hangcheck.active_request = NULL;
3095 i915_gem_reset_finish_engine(engine);
3099 static void nop_submit_request(struct drm_i915_gem_request *request)
3101 unsigned long flags;
3103 GEM_BUG_ON(!i915_terminally_wedged(&request->i915->gpu_error));
3104 dma_fence_set_error(&request->fence, -EIO);
3106 spin_lock_irqsave(&request->engine->timeline->lock, flags);
3107 __i915_gem_request_submit(request);
3108 intel_engine_init_global_seqno(request->engine, request->global_seqno);
3109 spin_unlock_irqrestore(&request->engine->timeline->lock, flags);
3112 static void engine_set_wedged(struct intel_engine_cs *engine)
3114 struct drm_i915_gem_request *request;
3115 unsigned long flags;
3117 /* We need to be sure that no thread is running the old callback as
3118 * we install the nop handler (otherwise we would submit a request
3119 * to hardware that will never complete). In order to prevent this
3120 * race, we wait until the machine is idle before making the swap
3121 * (using stop_machine()).
3123 engine->submit_request = nop_submit_request;
3125 /* Mark all executing requests as skipped */
3126 spin_lock_irqsave(&engine->timeline->lock, flags);
3127 list_for_each_entry(request, &engine->timeline->requests, link)
3128 if (!i915_gem_request_completed(request))
3129 dma_fence_set_error(&request->fence, -EIO);
3130 spin_unlock_irqrestore(&engine->timeline->lock, flags);
3133 * Clear the execlists queue up before freeing the requests, as those
3134 * are the ones that keep the context and ringbuffer backing objects
3138 if (i915.enable_execlists) {
3139 struct execlist_port *port = engine->execlist_port;
3140 unsigned long flags;
3143 spin_lock_irqsave(&engine->timeline->lock, flags);
3145 for (n = 0; n < ARRAY_SIZE(engine->execlist_port); n++)
3146 i915_gem_request_put(port_request(&port[n]));
3147 memset(engine->execlist_port, 0, sizeof(engine->execlist_port));
3148 engine->execlist_queue = RB_ROOT;
3149 engine->execlist_first = NULL;
3151 spin_unlock_irqrestore(&engine->timeline->lock, flags);
3153 /* The port is checked prior to scheduling a tasklet, but
3154 * just in case we have suspended the tasklet to do the
3155 * wedging make sure that when it wakes, it decides there
3156 * is no work to do by clearing the irq_posted bit.
3158 clear_bit(ENGINE_IRQ_EXECLIST, &engine->irq_posted);
3161 /* Mark all pending requests as complete so that any concurrent
3162 * (lockless) lookup doesn't try and wait upon the request as we
3165 intel_engine_init_global_seqno(engine,
3166 intel_engine_last_submit(engine));
3169 static int __i915_gem_set_wedged_BKL(void *data)
3171 struct drm_i915_private *i915 = data;
3172 struct intel_engine_cs *engine;
3173 enum intel_engine_id id;
3175 for_each_engine(engine, i915, id)
3176 engine_set_wedged(engine);
3178 set_bit(I915_WEDGED, &i915->gpu_error.flags);
3179 wake_up_all(&i915->gpu_error.reset_queue);
3184 void i915_gem_set_wedged(struct drm_i915_private *dev_priv)
3186 stop_machine(__i915_gem_set_wedged_BKL, dev_priv, NULL);
3189 bool i915_gem_unset_wedged(struct drm_i915_private *i915)
3191 struct i915_gem_timeline *tl;
3194 lockdep_assert_held(&i915->drm.struct_mutex);
3195 if (!test_bit(I915_WEDGED, &i915->gpu_error.flags))
3198 /* Before unwedging, make sure that all pending operations
3199 * are flushed and errored out - we may have requests waiting upon
3200 * third party fences. We marked all inflight requests as EIO, and
3201 * every execbuf since returned EIO, for consistency we want all
3202 * the currently pending requests to also be marked as EIO, which
3203 * is done inside our nop_submit_request - and so we must wait.
3205 * No more can be submitted until we reset the wedged bit.
3207 list_for_each_entry(tl, &i915->gt.timelines, link) {
3208 for (i = 0; i < ARRAY_SIZE(tl->engine); i++) {
3209 struct drm_i915_gem_request *rq;
3211 rq = i915_gem_active_peek(&tl->engine[i].last_request,
3212 &i915->drm.struct_mutex);
3216 /* We can't use our normal waiter as we want to
3217 * avoid recursively trying to handle the current
3218 * reset. The basic dma_fence_default_wait() installs
3219 * a callback for dma_fence_signal(), which is
3220 * triggered by our nop handler (indirectly, the
3221 * callback enables the signaler thread which is
3222 * woken by the nop_submit_request() advancing the seqno
3223 * and when the seqno passes the fence, the signaler
3224 * then signals the fence waking us up).
3226 if (dma_fence_default_wait(&rq->fence, true,
3227 MAX_SCHEDULE_TIMEOUT) < 0)
3232 /* Undo nop_submit_request. We prevent all new i915 requests from
3233 * being queued (by disallowing execbuf whilst wedged) so having
3234 * waited for all active requests above, we know the system is idle
3235 * and do not have to worry about a thread being inside
3236 * engine->submit_request() as we swap over. So unlike installing
3237 * the nop_submit_request on reset, we can do this from normal
3238 * context and do not require stop_machine().
3240 intel_engines_reset_default_submission(i915);
3241 i915_gem_contexts_lost(i915);
3243 smp_mb__before_atomic(); /* complete takeover before enabling execbuf */
3244 clear_bit(I915_WEDGED, &i915->gpu_error.flags);
3250 i915_gem_retire_work_handler(struct work_struct *work)
3252 struct drm_i915_private *dev_priv =
3253 container_of(work, typeof(*dev_priv), gt.retire_work.work);
3254 struct drm_device *dev = &dev_priv->drm;
3256 /* Come back later if the device is busy... */
3257 if (mutex_trylock(&dev->struct_mutex)) {
3258 i915_gem_retire_requests(dev_priv);
3259 mutex_unlock(&dev->struct_mutex);
3262 /* Keep the retire handler running until we are finally idle.
3263 * We do not need to do this test under locking as in the worst-case
3264 * we queue the retire worker once too often.
3266 if (READ_ONCE(dev_priv->gt.awake)) {
3267 i915_queue_hangcheck(dev_priv);
3268 queue_delayed_work(dev_priv->wq,
3269 &dev_priv->gt.retire_work,
3270 round_jiffies_up_relative(HZ));
3275 i915_gem_idle_work_handler(struct work_struct *work)
3277 struct drm_i915_private *dev_priv =
3278 container_of(work, typeof(*dev_priv), gt.idle_work.work);
3279 struct drm_device *dev = &dev_priv->drm;
3280 bool rearm_hangcheck;
3282 if (!READ_ONCE(dev_priv->gt.awake))
3286 * Wait for last execlists context complete, but bail out in case a
3287 * new request is submitted.
3289 wait_for(intel_engines_are_idle(dev_priv), 10);
3290 if (READ_ONCE(dev_priv->gt.active_requests))
3294 cancel_delayed_work_sync(&dev_priv->gpu_error.hangcheck_work);
3296 if (!mutex_trylock(&dev->struct_mutex)) {
3297 /* Currently busy, come back later */
3298 mod_delayed_work(dev_priv->wq,
3299 &dev_priv->gt.idle_work,
3300 msecs_to_jiffies(50));
3305 * New request retired after this work handler started, extend active
3306 * period until next instance of the work.
3308 if (work_pending(work))
3311 if (dev_priv->gt.active_requests)
3314 if (wait_for(intel_engines_are_idle(dev_priv), 10))
3315 DRM_ERROR("Timeout waiting for engines to idle\n");
3317 intel_engines_mark_idle(dev_priv);
3318 i915_gem_timelines_mark_idle(dev_priv);
3320 GEM_BUG_ON(!dev_priv->gt.awake);
3321 dev_priv->gt.awake = false;
3322 rearm_hangcheck = false;
3324 if (INTEL_GEN(dev_priv) >= 6)
3325 gen6_rps_idle(dev_priv);
3327 if (NEEDS_RC6_CTX_CORRUPTION_WA(dev_priv)) {
3328 i915_rc6_ctx_wa_check(dev_priv);
3329 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
3332 intel_runtime_pm_put(dev_priv);
3334 mutex_unlock(&dev->struct_mutex);
3337 if (rearm_hangcheck) {
3338 GEM_BUG_ON(!dev_priv->gt.awake);
3339 i915_queue_hangcheck(dev_priv);
3343 void i915_gem_close_object(struct drm_gem_object *gem, struct drm_file *file)
3345 struct drm_i915_private *i915 = to_i915(gem->dev);
3346 struct drm_i915_gem_object *obj = to_intel_bo(gem);
3347 struct drm_i915_file_private *fpriv = file->driver_priv;
3348 struct i915_lut_handle *lut, *ln;
3350 mutex_lock(&i915->drm.struct_mutex);
3352 list_for_each_entry_safe(lut, ln, &obj->lut_list, obj_link) {
3353 struct i915_gem_context *ctx = lut->ctx;
3354 struct i915_vma *vma;
3356 if (ctx->file_priv != fpriv)
3359 vma = radix_tree_delete(&ctx->handles_vma, lut->handle);
3361 GEM_BUG_ON(vma->obj != obj);
3363 /* We allow the process to have multiple handles to the same
3364 * vma, in the same fd namespace, by virtue of flink/open.
3366 GEM_BUG_ON(!vma->open_count);
3367 if (!--vma->open_count && !i915_vma_is_ggtt(vma))
3368 i915_vma_close(vma);
3370 list_del(&lut->obj_link);
3371 list_del(&lut->ctx_link);
3373 kmem_cache_free(i915->luts, lut);
3374 __i915_gem_object_release_unless_active(obj);
3377 mutex_unlock(&i915->drm.struct_mutex);
3380 static unsigned long to_wait_timeout(s64 timeout_ns)
3383 return MAX_SCHEDULE_TIMEOUT;
3385 if (timeout_ns == 0)
3388 return nsecs_to_jiffies_timeout(timeout_ns);
3392 * i915_gem_wait_ioctl - implements DRM_IOCTL_I915_GEM_WAIT
3393 * @dev: drm device pointer
3394 * @data: ioctl data blob
3395 * @file: drm file pointer
3397 * Returns 0 if successful, else an error is returned with the remaining time in
3398 * the timeout parameter.
3399 * -ETIME: object is still busy after timeout
3400 * -ERESTARTSYS: signal interrupted the wait
3401 * -ENONENT: object doesn't exist
3402 * Also possible, but rare:
3403 * -EAGAIN: incomplete, restart syscall
3405 * -ENODEV: Internal IRQ fail
3406 * -E?: The add request failed
3408 * The wait ioctl with a timeout of 0 reimplements the busy ioctl. With any
3409 * non-zero timeout parameter the wait ioctl will wait for the given number of
3410 * nanoseconds on an object becoming unbusy. Since the wait itself does so
3411 * without holding struct_mutex the object may become re-busied before this
3412 * function completes. A similar but shorter * race condition exists in the busy
3416 i915_gem_wait_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
3418 struct drm_i915_gem_wait *args = data;
3419 struct drm_i915_gem_object *obj;
3423 if (args->flags != 0)
3426 obj = i915_gem_object_lookup(file, args->bo_handle);
3430 start = ktime_get();
3432 ret = i915_gem_object_wait(obj,
3433 I915_WAIT_INTERRUPTIBLE | I915_WAIT_ALL,
3434 to_wait_timeout(args->timeout_ns),
3435 to_rps_client(file));
3437 if (args->timeout_ns > 0) {
3438 args->timeout_ns -= ktime_to_ns(ktime_sub(ktime_get(), start));
3439 if (args->timeout_ns < 0)
3440 args->timeout_ns = 0;
3443 * Apparently ktime isn't accurate enough and occasionally has a
3444 * bit of mismatch in the jiffies<->nsecs<->ktime loop. So patch
3445 * things up to make the test happy. We allow up to 1 jiffy.
3447 * This is a regression from the timespec->ktime conversion.
3449 if (ret == -ETIME && !nsecs_to_jiffies(args->timeout_ns))
3450 args->timeout_ns = 0;
3452 /* Asked to wait beyond the jiffie/scheduler precision? */
3453 if (ret == -ETIME && args->timeout_ns)
3457 i915_gem_object_put(obj);
3461 static int wait_for_timeline(struct i915_gem_timeline *tl, unsigned int flags)
3465 for (i = 0; i < ARRAY_SIZE(tl->engine); i++) {
3466 ret = i915_gem_active_wait(&tl->engine[i].last_request, flags);
3474 static int wait_for_engines(struct drm_i915_private *i915)
3476 if (wait_for(intel_engines_are_idle(i915), 50)) {
3477 DRM_ERROR("Failed to idle engines, declaring wedged!\n");
3478 i915_gem_set_wedged(i915);
3485 int i915_gem_wait_for_idle(struct drm_i915_private *i915, unsigned int flags)
3489 /* If the device is asleep, we have no requests outstanding */
3490 if (!READ_ONCE(i915->gt.awake))
3493 if (flags & I915_WAIT_LOCKED) {
3494 struct i915_gem_timeline *tl;
3496 lockdep_assert_held(&i915->drm.struct_mutex);
3498 list_for_each_entry(tl, &i915->gt.timelines, link) {
3499 ret = wait_for_timeline(tl, flags);
3504 i915_gem_retire_requests(i915);
3505 GEM_BUG_ON(i915->gt.active_requests);
3507 ret = wait_for_engines(i915);
3509 ret = wait_for_timeline(&i915->gt.global_timeline, flags);
3515 static void __i915_gem_object_flush_for_display(struct drm_i915_gem_object *obj)
3518 * We manually flush the CPU domain so that we can override and
3519 * force the flush for the display, and perform it asyncrhonously.
3521 flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
3522 if (obj->cache_dirty)
3523 i915_gem_clflush_object(obj, I915_CLFLUSH_FORCE);
3524 obj->base.write_domain = 0;
3527 void i915_gem_object_flush_if_display(struct drm_i915_gem_object *obj)
3529 if (!READ_ONCE(obj->pin_display))
3532 mutex_lock(&obj->base.dev->struct_mutex);
3533 __i915_gem_object_flush_for_display(obj);
3534 mutex_unlock(&obj->base.dev->struct_mutex);
3538 * Moves a single object to the WC read, and possibly write domain.
3539 * @obj: object to act on
3540 * @write: ask for write access or read only
3542 * This function returns when the move is complete, including waiting on
3546 i915_gem_object_set_to_wc_domain(struct drm_i915_gem_object *obj, bool write)
3550 lockdep_assert_held(&obj->base.dev->struct_mutex);
3552 ret = i915_gem_object_wait(obj,
3553 I915_WAIT_INTERRUPTIBLE |
3555 (write ? I915_WAIT_ALL : 0),
3556 MAX_SCHEDULE_TIMEOUT,
3561 if (obj->base.write_domain == I915_GEM_DOMAIN_WC)
3564 /* Flush and acquire obj->pages so that we are coherent through
3565 * direct access in memory with previous cached writes through
3566 * shmemfs and that our cache domain tracking remains valid.
3567 * For example, if the obj->filp was moved to swap without us
3568 * being notified and releasing the pages, we would mistakenly
3569 * continue to assume that the obj remained out of the CPU cached
3572 ret = i915_gem_object_pin_pages(obj);
3576 flush_write_domain(obj, ~I915_GEM_DOMAIN_WC);
3578 /* Serialise direct access to this object with the barriers for
3579 * coherent writes from the GPU, by effectively invalidating the
3580 * WC domain upon first access.
3582 if ((obj->base.read_domains & I915_GEM_DOMAIN_WC) == 0)
3585 /* It should now be out of any other write domains, and we can update
3586 * the domain values for our changes.
3588 GEM_BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_WC) != 0);
3589 obj->base.read_domains |= I915_GEM_DOMAIN_WC;
3591 obj->base.read_domains = I915_GEM_DOMAIN_WC;
3592 obj->base.write_domain = I915_GEM_DOMAIN_WC;
3593 obj->mm.dirty = true;
3596 i915_gem_object_unpin_pages(obj);
3601 * Moves a single object to the GTT read, and possibly write domain.
3602 * @obj: object to act on
3603 * @write: ask for write access or read only
3605 * This function returns when the move is complete, including waiting on
3609 i915_gem_object_set_to_gtt_domain(struct drm_i915_gem_object *obj, bool write)
3613 lockdep_assert_held(&obj->base.dev->struct_mutex);
3615 ret = i915_gem_object_wait(obj,
3616 I915_WAIT_INTERRUPTIBLE |
3618 (write ? I915_WAIT_ALL : 0),
3619 MAX_SCHEDULE_TIMEOUT,
3624 if (obj->base.write_domain == I915_GEM_DOMAIN_GTT)
3627 /* Flush and acquire obj->pages so that we are coherent through
3628 * direct access in memory with previous cached writes through
3629 * shmemfs and that our cache domain tracking remains valid.
3630 * For example, if the obj->filp was moved to swap without us
3631 * being notified and releasing the pages, we would mistakenly
3632 * continue to assume that the obj remained out of the CPU cached
3635 ret = i915_gem_object_pin_pages(obj);
3639 flush_write_domain(obj, ~I915_GEM_DOMAIN_GTT);
3641 /* Serialise direct access to this object with the barriers for
3642 * coherent writes from the GPU, by effectively invalidating the
3643 * GTT domain upon first access.
3645 if ((obj->base.read_domains & I915_GEM_DOMAIN_GTT) == 0)
3648 /* It should now be out of any other write domains, and we can update
3649 * the domain values for our changes.
3651 GEM_BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
3652 obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
3654 obj->base.read_domains = I915_GEM_DOMAIN_GTT;
3655 obj->base.write_domain = I915_GEM_DOMAIN_GTT;
3656 obj->mm.dirty = true;
3659 i915_gem_object_unpin_pages(obj);
3664 * Changes the cache-level of an object across all VMA.
3665 * @obj: object to act on
3666 * @cache_level: new cache level to set for the object
3668 * After this function returns, the object will be in the new cache-level
3669 * across all GTT and the contents of the backing storage will be coherent,
3670 * with respect to the new cache-level. In order to keep the backing storage
3671 * coherent for all users, we only allow a single cache level to be set
3672 * globally on the object and prevent it from being changed whilst the
3673 * hardware is reading from the object. That is if the object is currently
3674 * on the scanout it will be set to uncached (or equivalent display
3675 * cache coherency) and all non-MOCS GPU access will also be uncached so
3676 * that all direct access to the scanout remains coherent.
3678 int i915_gem_object_set_cache_level(struct drm_i915_gem_object *obj,
3679 enum i915_cache_level cache_level)
3681 struct i915_vma *vma;
3684 lockdep_assert_held(&obj->base.dev->struct_mutex);
3686 if (obj->cache_level == cache_level)
3689 /* Inspect the list of currently bound VMA and unbind any that would
3690 * be invalid given the new cache-level. This is principally to
3691 * catch the issue of the CS prefetch crossing page boundaries and
3692 * reading an invalid PTE on older architectures.
3695 list_for_each_entry(vma, &obj->vma_list, obj_link) {
3696 if (!drm_mm_node_allocated(&vma->node))
3699 if (i915_vma_is_pinned(vma)) {
3700 DRM_DEBUG("can not change the cache level of pinned objects\n");
3704 if (!i915_vma_is_closed(vma) &&
3705 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 pin_display 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_display;
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_display;
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_display == 0))
3975 if (--vma->obj->pin_display == 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;
4090 return i915_gem_object_pin(obj, vm, view, size, alignment,
4091 flags | PIN_GLOBAL);
4095 i915_gem_object_pin(struct drm_i915_gem_object *obj,
4096 struct i915_address_space *vm,
4097 const struct i915_ggtt_view *view,
4102 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
4103 struct i915_vma *vma;
4106 lockdep_assert_held(&obj->base.dev->struct_mutex);
4108 vma = i915_vma_instance(obj, vm, view);
4109 if (unlikely(IS_ERR(vma)))
4112 if (i915_vma_misplaced(vma, size, alignment, flags)) {
4113 if (flags & PIN_NONBLOCK &&
4114 (i915_vma_is_pinned(vma) || i915_vma_is_active(vma)))
4115 return ERR_PTR(-ENOSPC);
4117 if (flags & PIN_MAPPABLE) {
4118 /* If the required space is larger than the available
4119 * aperture, we will not able to find a slot for the
4120 * object and unbinding the object now will be in
4121 * vain. Worse, doing so may cause us to ping-pong
4122 * the object in and out of the Global GTT and
4123 * waste a lot of cycles under the mutex.
4125 if (vma->fence_size > dev_priv->ggtt.mappable_end)
4126 return ERR_PTR(-E2BIG);
4128 /* If NONBLOCK is set the caller is optimistically
4129 * trying to cache the full object within the mappable
4130 * aperture, and *must* have a fallback in place for
4131 * situations where we cannot bind the object. We
4132 * can be a little more lax here and use the fallback
4133 * more often to avoid costly migrations of ourselves
4134 * and other objects within the aperture.
4136 * Half-the-aperture is used as a simple heuristic.
4137 * More interesting would to do search for a free
4138 * block prior to making the commitment to unbind.
4139 * That caters for the self-harm case, and with a
4140 * little more heuristics (e.g. NOFAULT, NOEVICT)
4141 * we could try to minimise harm to others.
4143 if (flags & PIN_NONBLOCK &&
4144 vma->fence_size > dev_priv->ggtt.mappable_end / 2)
4145 return ERR_PTR(-ENOSPC);
4148 WARN(i915_vma_is_pinned(vma),
4149 "bo is already pinned in ggtt with incorrect alignment:"
4150 " offset=%08x, req.alignment=%llx,"
4151 " req.map_and_fenceable=%d, vma->map_and_fenceable=%d\n",
4152 i915_ggtt_offset(vma), alignment,
4153 !!(flags & PIN_MAPPABLE),
4154 i915_vma_is_map_and_fenceable(vma));
4155 ret = i915_vma_unbind(vma);
4157 return ERR_PTR(ret);
4160 ret = i915_vma_pin(vma, size, alignment, flags);
4162 return ERR_PTR(ret);
4167 static __always_inline unsigned int __busy_read_flag(unsigned int id)
4169 /* Note that we could alias engines in the execbuf API, but
4170 * that would be very unwise as it prevents userspace from
4171 * fine control over engine selection. Ahem.
4173 * This should be something like EXEC_MAX_ENGINE instead of
4176 BUILD_BUG_ON(I915_NUM_ENGINES > 16);
4177 return 0x10000 << id;
4180 static __always_inline unsigned int __busy_write_id(unsigned int id)
4182 /* The uABI guarantees an active writer is also amongst the read
4183 * engines. This would be true if we accessed the activity tracking
4184 * under the lock, but as we perform the lookup of the object and
4185 * its activity locklessly we can not guarantee that the last_write
4186 * being active implies that we have set the same engine flag from
4187 * last_read - hence we always set both read and write busy for
4190 return id | __busy_read_flag(id);
4193 static __always_inline unsigned int
4194 __busy_set_if_active(const struct dma_fence *fence,
4195 unsigned int (*flag)(unsigned int id))
4197 struct drm_i915_gem_request *rq;
4199 /* We have to check the current hw status of the fence as the uABI
4200 * guarantees forward progress. We could rely on the idle worker
4201 * to eventually flush us, but to minimise latency just ask the
4204 * Note we only report on the status of native fences.
4206 if (!dma_fence_is_i915(fence))
4209 /* opencode to_request() in order to avoid const warnings */
4210 rq = container_of(fence, struct drm_i915_gem_request, fence);
4211 if (i915_gem_request_completed(rq))
4214 return flag(rq->engine->uabi_id);
4217 static __always_inline unsigned int
4218 busy_check_reader(const struct dma_fence *fence)
4220 return __busy_set_if_active(fence, __busy_read_flag);
4223 static __always_inline unsigned int
4224 busy_check_writer(const struct dma_fence *fence)
4229 return __busy_set_if_active(fence, __busy_write_id);
4233 i915_gem_busy_ioctl(struct drm_device *dev, void *data,
4234 struct drm_file *file)
4236 struct drm_i915_gem_busy *args = data;
4237 struct drm_i915_gem_object *obj;
4238 struct reservation_object_list *list;
4244 obj = i915_gem_object_lookup_rcu(file, args->handle);
4248 /* A discrepancy here is that we do not report the status of
4249 * non-i915 fences, i.e. even though we may report the object as idle,
4250 * a call to set-domain may still stall waiting for foreign rendering.
4251 * This also means that wait-ioctl may report an object as busy,
4252 * where busy-ioctl considers it idle.
4254 * We trade the ability to warn of foreign fences to report on which
4255 * i915 engines are active for the object.
4257 * Alternatively, we can trade that extra information on read/write
4260 * !reservation_object_test_signaled_rcu(obj->resv, true);
4261 * to report the overall busyness. This is what the wait-ioctl does.
4265 seq = raw_read_seqcount(&obj->resv->seq);
4267 /* Translate the exclusive fence to the READ *and* WRITE engine */
4268 args->busy = busy_check_writer(rcu_dereference(obj->resv->fence_excl));
4270 /* Translate shared fences to READ set of engines */
4271 list = rcu_dereference(obj->resv->fence);
4273 unsigned int shared_count = list->shared_count, i;
4275 for (i = 0; i < shared_count; ++i) {
4276 struct dma_fence *fence =
4277 rcu_dereference(list->shared[i]);
4279 args->busy |= busy_check_reader(fence);
4283 if (args->busy && read_seqcount_retry(&obj->resv->seq, seq))
4293 i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
4294 struct drm_file *file_priv)
4296 return i915_gem_ring_throttle(dev, file_priv);
4300 i915_gem_madvise_ioctl(struct drm_device *dev, void *data,
4301 struct drm_file *file_priv)
4303 struct drm_i915_private *dev_priv = to_i915(dev);
4304 struct drm_i915_gem_madvise *args = data;
4305 struct drm_i915_gem_object *obj;
4308 switch (args->madv) {
4309 case I915_MADV_DONTNEED:
4310 case I915_MADV_WILLNEED:
4316 obj = i915_gem_object_lookup(file_priv, args->handle);
4320 err = mutex_lock_interruptible(&obj->mm.lock);
4324 if (obj->mm.pages &&
4325 i915_gem_object_is_tiled(obj) &&
4326 dev_priv->quirks & QUIRK_PIN_SWIZZLED_PAGES) {
4327 if (obj->mm.madv == I915_MADV_WILLNEED) {
4328 GEM_BUG_ON(!obj->mm.quirked);
4329 __i915_gem_object_unpin_pages(obj);
4330 obj->mm.quirked = false;
4332 if (args->madv == I915_MADV_WILLNEED) {
4333 GEM_BUG_ON(obj->mm.quirked);
4334 __i915_gem_object_pin_pages(obj);
4335 obj->mm.quirked = true;
4339 if (obj->mm.madv != __I915_MADV_PURGED)
4340 obj->mm.madv = args->madv;
4342 /* if the object is no longer attached, discard its backing storage */
4343 if (obj->mm.madv == I915_MADV_DONTNEED && !obj->mm.pages)
4344 i915_gem_object_truncate(obj);
4346 args->retained = obj->mm.madv != __I915_MADV_PURGED;
4347 mutex_unlock(&obj->mm.lock);
4350 i915_gem_object_put(obj);
4355 frontbuffer_retire(struct i915_gem_active *active,
4356 struct drm_i915_gem_request *request)
4358 struct drm_i915_gem_object *obj =
4359 container_of(active, typeof(*obj), frontbuffer_write);
4361 intel_fb_obj_flush(obj, ORIGIN_CS);
4364 void i915_gem_object_init(struct drm_i915_gem_object *obj,
4365 const struct drm_i915_gem_object_ops *ops)
4367 mutex_init(&obj->mm.lock);
4369 INIT_LIST_HEAD(&obj->global_link);
4370 INIT_LIST_HEAD(&obj->userfault_link);
4371 INIT_LIST_HEAD(&obj->vma_list);
4372 INIT_LIST_HEAD(&obj->lut_list);
4373 INIT_LIST_HEAD(&obj->batch_pool_link);
4377 reservation_object_init(&obj->__builtin_resv);
4378 obj->resv = &obj->__builtin_resv;
4380 obj->frontbuffer_ggtt_origin = ORIGIN_GTT;
4381 init_request_active(&obj->frontbuffer_write, frontbuffer_retire);
4383 obj->mm.madv = I915_MADV_WILLNEED;
4384 INIT_RADIX_TREE(&obj->mm.get_page.radix, GFP_KERNEL | __GFP_NOWARN);
4385 mutex_init(&obj->mm.get_page.lock);
4387 i915_gem_info_add_obj(to_i915(obj->base.dev), obj->base.size);
4390 static const struct drm_i915_gem_object_ops i915_gem_object_ops = {
4391 .flags = I915_GEM_OBJECT_HAS_STRUCT_PAGE |
4392 I915_GEM_OBJECT_IS_SHRINKABLE,
4394 .get_pages = i915_gem_object_get_pages_gtt,
4395 .put_pages = i915_gem_object_put_pages_gtt,
4397 .pwrite = i915_gem_object_pwrite_gtt,
4400 struct drm_i915_gem_object *
4401 i915_gem_object_create(struct drm_i915_private *dev_priv, u64 size)
4403 struct drm_i915_gem_object *obj;
4404 struct address_space *mapping;
4405 unsigned int cache_level;
4409 /* There is a prevalence of the assumption that we fit the object's
4410 * page count inside a 32bit _signed_ variable. Let's document this and
4411 * catch if we ever need to fix it. In the meantime, if you do spot
4412 * such a local variable, please consider fixing!
4414 if (size >> PAGE_SHIFT > INT_MAX)
4415 return ERR_PTR(-E2BIG);
4417 if (overflows_type(size, obj->base.size))
4418 return ERR_PTR(-E2BIG);
4420 obj = i915_gem_object_alloc(dev_priv);
4422 return ERR_PTR(-ENOMEM);
4424 ret = drm_gem_object_init(&dev_priv->drm, &obj->base, size);
4428 mask = GFP_HIGHUSER | __GFP_RECLAIMABLE;
4429 if (IS_I965GM(dev_priv) || IS_I965G(dev_priv)) {
4430 /* 965gm cannot relocate objects above 4GiB. */
4431 mask &= ~__GFP_HIGHMEM;
4432 mask |= __GFP_DMA32;
4435 mapping = obj->base.filp->f_mapping;
4436 mapping_set_gfp_mask(mapping, mask);
4437 GEM_BUG_ON(!(mapping_gfp_mask(mapping) & __GFP_RECLAIM));
4439 i915_gem_object_init(obj, &i915_gem_object_ops);
4441 obj->base.write_domain = I915_GEM_DOMAIN_CPU;
4442 obj->base.read_domains = I915_GEM_DOMAIN_CPU;
4444 if (HAS_LLC(dev_priv))
4445 /* On some devices, we can have the GPU use the LLC (the CPU
4446 * cache) for about a 10% performance improvement
4447 * compared to uncached. Graphics requests other than
4448 * display scanout are coherent with the CPU in
4449 * accessing this cache. This means in this mode we
4450 * don't need to clflush on the CPU side, and on the
4451 * GPU side we only need to flush internal caches to
4452 * get data visible to the CPU.
4454 * However, we maintain the display planes as UC, and so
4455 * need to rebind when first used as such.
4457 cache_level = I915_CACHE_LLC;
4459 cache_level = I915_CACHE_NONE;
4461 i915_gem_object_set_cache_coherency(obj, cache_level);
4463 trace_i915_gem_object_create(obj);
4468 i915_gem_object_free(obj);
4469 return ERR_PTR(ret);
4472 static bool discard_backing_storage(struct drm_i915_gem_object *obj)
4474 /* If we are the last user of the backing storage (be it shmemfs
4475 * pages or stolen etc), we know that the pages are going to be
4476 * immediately released. In this case, we can then skip copying
4477 * back the contents from the GPU.
4480 if (obj->mm.madv != I915_MADV_WILLNEED)
4483 if (obj->base.filp == NULL)
4486 /* At first glance, this looks racy, but then again so would be
4487 * userspace racing mmap against close. However, the first external
4488 * reference to the filp can only be obtained through the
4489 * i915_gem_mmap_ioctl() which safeguards us against the user
4490 * acquiring such a reference whilst we are in the middle of
4491 * freeing the object.
4493 return atomic_long_read(&obj->base.filp->f_count) == 1;
4496 static void __i915_gem_free_objects(struct drm_i915_private *i915,
4497 struct llist_node *freed)
4499 struct drm_i915_gem_object *obj, *on;
4501 mutex_lock(&i915->drm.struct_mutex);
4502 intel_runtime_pm_get(i915);
4503 llist_for_each_entry(obj, freed, freed) {
4504 struct i915_vma *vma, *vn;
4506 trace_i915_gem_object_destroy(obj);
4508 GEM_BUG_ON(i915_gem_object_is_active(obj));
4509 list_for_each_entry_safe(vma, vn,
4510 &obj->vma_list, obj_link) {
4511 GEM_BUG_ON(i915_vma_is_active(vma));
4512 vma->flags &= ~I915_VMA_PIN_MASK;
4513 i915_vma_close(vma);
4515 GEM_BUG_ON(!list_empty(&obj->vma_list));
4516 GEM_BUG_ON(!RB_EMPTY_ROOT(&obj->vma_tree));
4518 list_del(&obj->global_link);
4520 intel_runtime_pm_put(i915);
4521 mutex_unlock(&i915->drm.struct_mutex);
4525 llist_for_each_entry_safe(obj, on, freed, freed) {
4526 GEM_BUG_ON(obj->bind_count);
4527 GEM_BUG_ON(atomic_read(&obj->frontbuffer_bits));
4529 if (obj->ops->release)
4530 obj->ops->release(obj);
4532 if (WARN_ON(i915_gem_object_has_pinned_pages(obj)))
4533 atomic_set(&obj->mm.pages_pin_count, 0);
4534 __i915_gem_object_put_pages(obj, I915_MM_NORMAL);
4535 GEM_BUG_ON(obj->mm.pages);
4537 if (obj->base.import_attach)
4538 drm_prime_gem_destroy(&obj->base, NULL);
4540 reservation_object_fini(&obj->__builtin_resv);
4541 drm_gem_object_release(&obj->base);
4542 i915_gem_info_remove_obj(i915, obj->base.size);
4545 i915_gem_object_free(obj);
4549 static void i915_gem_flush_free_objects(struct drm_i915_private *i915)
4551 struct llist_node *freed;
4553 freed = llist_del_all(&i915->mm.free_list);
4554 if (unlikely(freed))
4555 __i915_gem_free_objects(i915, freed);
4558 static void __i915_gem_free_work(struct work_struct *work)
4560 struct drm_i915_private *i915 =
4561 container_of(work, struct drm_i915_private, mm.free_work);
4562 struct llist_node *freed;
4564 /* All file-owned VMA should have been released by this point through
4565 * i915_gem_close_object(), or earlier by i915_gem_context_close().
4566 * However, the object may also be bound into the global GTT (e.g.
4567 * older GPUs without per-process support, or for direct access through
4568 * the GTT either for the user or for scanout). Those VMA still need to
4572 while ((freed = llist_del_all(&i915->mm.free_list))) {
4573 __i915_gem_free_objects(i915, freed);
4579 static void __i915_gem_free_object_rcu(struct rcu_head *head)
4581 struct drm_i915_gem_object *obj =
4582 container_of(head, typeof(*obj), rcu);
4583 struct drm_i915_private *i915 = to_i915(obj->base.dev);
4585 /* We can't simply use call_rcu() from i915_gem_free_object()
4586 * as we need to block whilst unbinding, and the call_rcu
4587 * task may be called from softirq context. So we take a
4588 * detour through a worker.
4590 if (llist_add(&obj->freed, &i915->mm.free_list))
4591 schedule_work(&i915->mm.free_work);
4594 void i915_gem_free_object(struct drm_gem_object *gem_obj)
4596 struct drm_i915_gem_object *obj = to_intel_bo(gem_obj);
4598 if (obj->mm.quirked)
4599 __i915_gem_object_unpin_pages(obj);
4601 if (discard_backing_storage(obj))
4602 obj->mm.madv = I915_MADV_DONTNEED;
4604 /* Before we free the object, make sure any pure RCU-only
4605 * read-side critical sections are complete, e.g.
4606 * i915_gem_busy_ioctl(). For the corresponding synchronized
4607 * lookup see i915_gem_object_lookup_rcu().
4609 call_rcu(&obj->rcu, __i915_gem_free_object_rcu);
4612 void __i915_gem_object_release_unless_active(struct drm_i915_gem_object *obj)
4614 lockdep_assert_held(&obj->base.dev->struct_mutex);
4616 if (!i915_gem_object_has_active_reference(obj) &&
4617 i915_gem_object_is_active(obj))
4618 i915_gem_object_set_active_reference(obj);
4620 i915_gem_object_put(obj);
4623 static void assert_kernel_context_is_current(struct drm_i915_private *dev_priv)
4625 struct intel_engine_cs *engine;
4626 enum intel_engine_id id;
4628 for_each_engine(engine, dev_priv, id)
4629 GEM_BUG_ON(engine->last_retired_context &&
4630 !i915_gem_context_is_kernel(engine->last_retired_context));
4633 void i915_gem_sanitize(struct drm_i915_private *i915)
4636 * If we inherit context state from the BIOS or earlier occupants
4637 * of the GPU, the GPU may be in an inconsistent state when we
4638 * try to take over. The only way to remove the earlier state
4639 * is by resetting. However, resetting on earlier gen is tricky as
4640 * it may impact the display and we are uncertain about the stability
4641 * of the reset, so this could be applied to even earlier gen.
4643 if (INTEL_GEN(i915) >= 5) {
4644 int reset = intel_gpu_reset(i915, ALL_ENGINES);
4645 WARN_ON(reset && reset != -ENODEV);
4649 int i915_gem_suspend(struct drm_i915_private *dev_priv)
4651 struct drm_device *dev = &dev_priv->drm;
4654 intel_runtime_pm_get(dev_priv);
4655 intel_suspend_gt_powersave(dev_priv);
4657 mutex_lock(&dev->struct_mutex);
4659 /* We have to flush all the executing contexts to main memory so
4660 * that they can saved in the hibernation image. To ensure the last
4661 * context image is coherent, we have to switch away from it. That
4662 * leaves the dev_priv->kernel_context still active when
4663 * we actually suspend, and its image in memory may not match the GPU
4664 * state. Fortunately, the kernel_context is disposable and we do
4665 * not rely on its state.
4667 ret = i915_gem_switch_to_kernel_context(dev_priv);
4671 ret = i915_gem_wait_for_idle(dev_priv,
4672 I915_WAIT_INTERRUPTIBLE |
4674 if (ret && ret != -EIO)
4677 assert_kernel_context_is_current(dev_priv);
4678 i915_gem_contexts_lost(dev_priv);
4679 mutex_unlock(&dev->struct_mutex);
4681 intel_guc_suspend(dev_priv);
4683 cancel_delayed_work_sync(&dev_priv->gpu_error.hangcheck_work);
4684 cancel_delayed_work_sync(&dev_priv->gt.retire_work);
4686 /* As the idle_work is rearming if it detects a race, play safe and
4687 * repeat the flush until it is definitely idle.
4689 while (flush_delayed_work(&dev_priv->gt.idle_work))
4692 /* Assert that we sucessfully flushed all the work and
4693 * reset the GPU back to its idle, low power state.
4695 WARN_ON(dev_priv->gt.awake);
4696 WARN_ON(!intel_engines_are_idle(dev_priv));
4699 * Neither the BIOS, ourselves or any other kernel
4700 * expects the system to be in execlists mode on startup,
4701 * so we need to reset the GPU back to legacy mode. And the only
4702 * known way to disable logical contexts is through a GPU reset.
4704 * So in order to leave the system in a known default configuration,
4705 * always reset the GPU upon unload and suspend. Afterwards we then
4706 * clean up the GEM state tracking, flushing off the requests and
4707 * leaving the system in a known idle state.
4709 * Note that is of the upmost importance that the GPU is idle and
4710 * all stray writes are flushed *before* we dismantle the backing
4711 * storage for the pinned objects.
4713 * However, since we are uncertain that resetting the GPU on older
4714 * machines is a good idea, we don't - just in case it leaves the
4715 * machine in an unusable condition.
4717 i915_gem_sanitize(dev_priv);
4719 intel_runtime_pm_put(dev_priv);
4723 mutex_unlock(&dev->struct_mutex);
4724 intel_runtime_pm_put(dev_priv);
4728 void i915_gem_resume(struct drm_i915_private *dev_priv)
4730 struct drm_device *dev = &dev_priv->drm;
4732 WARN_ON(dev_priv->gt.awake);
4734 mutex_lock(&dev->struct_mutex);
4735 i915_gem_restore_gtt_mappings(dev_priv);
4737 /* As we didn't flush the kernel context before suspend, we cannot
4738 * guarantee that the context image is complete. So let's just reset
4739 * it and start again.
4741 dev_priv->gt.resume(dev_priv);
4743 mutex_unlock(&dev->struct_mutex);
4746 void i915_gem_init_swizzling(struct drm_i915_private *dev_priv)
4748 if (INTEL_GEN(dev_priv) < 5 ||
4749 dev_priv->mm.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_NONE)
4752 I915_WRITE(DISP_ARB_CTL, I915_READ(DISP_ARB_CTL) |
4753 DISP_TILE_SURFACE_SWIZZLING);
4755 if (IS_GEN5(dev_priv))
4758 I915_WRITE(TILECTL, I915_READ(TILECTL) | TILECTL_SWZCTL);
4759 if (IS_GEN6(dev_priv))
4760 I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_SNB));
4761 else if (IS_GEN7(dev_priv))
4762 I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_IVB));
4763 else if (IS_GEN8(dev_priv))
4764 I915_WRITE(GAMTARBMODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_BDW));
4769 static void init_unused_ring(struct drm_i915_private *dev_priv, u32 base)
4771 I915_WRITE(RING_CTL(base), 0);
4772 I915_WRITE(RING_HEAD(base), 0);
4773 I915_WRITE(RING_TAIL(base), 0);
4774 I915_WRITE(RING_START(base), 0);
4777 static void init_unused_rings(struct drm_i915_private *dev_priv)
4779 if (IS_I830(dev_priv)) {
4780 init_unused_ring(dev_priv, PRB1_BASE);
4781 init_unused_ring(dev_priv, SRB0_BASE);
4782 init_unused_ring(dev_priv, SRB1_BASE);
4783 init_unused_ring(dev_priv, SRB2_BASE);
4784 init_unused_ring(dev_priv, SRB3_BASE);
4785 } else if (IS_GEN2(dev_priv)) {
4786 init_unused_ring(dev_priv, SRB0_BASE);
4787 init_unused_ring(dev_priv, SRB1_BASE);
4788 } else if (IS_GEN3(dev_priv)) {
4789 init_unused_ring(dev_priv, PRB1_BASE);
4790 init_unused_ring(dev_priv, PRB2_BASE);
4794 static int __i915_gem_restart_engines(void *data)
4796 struct drm_i915_private *i915 = data;
4797 struct intel_engine_cs *engine;
4798 enum intel_engine_id id;
4801 for_each_engine(engine, i915, id) {
4802 err = engine->init_hw(engine);
4810 int i915_gem_init_hw(struct drm_i915_private *dev_priv)
4814 dev_priv->gt.last_init_time = ktime_get();
4816 /* Double layer security blanket, see i915_gem_init() */
4817 intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
4819 if (HAS_EDRAM(dev_priv) && INTEL_GEN(dev_priv) < 9)
4820 I915_WRITE(HSW_IDICR, I915_READ(HSW_IDICR) | IDIHASHMSK(0xf));
4822 if (IS_HASWELL(dev_priv))
4823 I915_WRITE(MI_PREDICATE_RESULT_2, IS_HSW_GT3(dev_priv) ?
4824 LOWER_SLICE_ENABLED : LOWER_SLICE_DISABLED);
4826 if (HAS_PCH_NOP(dev_priv)) {
4827 if (IS_IVYBRIDGE(dev_priv)) {
4828 u32 temp = I915_READ(GEN7_MSG_CTL);
4829 temp &= ~(WAIT_FOR_PCH_FLR_ACK | WAIT_FOR_PCH_RESET_ACK);
4830 I915_WRITE(GEN7_MSG_CTL, temp);
4831 } else if (INTEL_GEN(dev_priv) >= 7) {
4832 u32 temp = I915_READ(HSW_NDE_RSTWRN_OPT);
4833 temp &= ~RESET_PCH_HANDSHAKE_ENABLE;
4834 I915_WRITE(HSW_NDE_RSTWRN_OPT, temp);
4838 i915_gem_init_swizzling(dev_priv);
4841 * At least 830 can leave some of the unused rings
4842 * "active" (ie. head != tail) after resume which
4843 * will prevent c3 entry. Makes sure all unused rings
4846 init_unused_rings(dev_priv);
4848 BUG_ON(!dev_priv->kernel_context);
4850 ret = i915_ppgtt_init_hw(dev_priv);
4852 DRM_ERROR("PPGTT enable HW failed %d\n", ret);
4856 /* Need to do basic initialisation of all rings first: */
4857 ret = __i915_gem_restart_engines(dev_priv);
4861 intel_mocs_init_l3cc_table(dev_priv);
4863 /* We can't enable contexts until all firmware is loaded */
4864 ret = intel_uc_init_hw(dev_priv);
4869 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
4873 bool intel_sanitize_semaphores(struct drm_i915_private *dev_priv, int value)
4875 if (INTEL_INFO(dev_priv)->gen < 6)
4878 /* TODO: make semaphores and Execlists play nicely together */
4879 if (i915.enable_execlists)
4885 /* Enable semaphores on SNB when IO remapping is off */
4886 if (IS_GEN6(dev_priv) && intel_vtd_active())
4892 int i915_gem_init(struct drm_i915_private *dev_priv)
4896 mutex_lock(&dev_priv->drm.struct_mutex);
4898 dev_priv->mm.unordered_timeline = dma_fence_context_alloc(1);
4900 if (!i915.enable_execlists) {
4901 dev_priv->gt.resume = intel_legacy_submission_resume;
4902 dev_priv->gt.cleanup_engine = intel_engine_cleanup;
4904 dev_priv->gt.resume = intel_lr_context_resume;
4905 dev_priv->gt.cleanup_engine = intel_logical_ring_cleanup;
4908 /* This is just a security blanket to placate dragons.
4909 * On some systems, we very sporadically observe that the first TLBs
4910 * used by the CS may be stale, despite us poking the TLB reset. If
4911 * we hold the forcewake during initialisation these problems
4912 * just magically go away.
4914 intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
4916 ret = i915_gem_init_userptr(dev_priv);
4920 ret = i915_gem_init_ggtt(dev_priv);
4924 ret = i915_gem_contexts_init(dev_priv);
4928 ret = intel_engines_init(dev_priv);
4932 ret = i915_gem_init_hw(dev_priv);
4934 /* Allow engine initialisation to fail by marking the GPU as
4935 * wedged. But we only want to do this where the GPU is angry,
4936 * for all other failure, such as an allocation failure, bail.
4938 DRM_ERROR("Failed to initialize GPU, declaring it wedged\n");
4939 i915_gem_set_wedged(dev_priv);
4944 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
4945 mutex_unlock(&dev_priv->drm.struct_mutex);
4950 void i915_gem_init_mmio(struct drm_i915_private *i915)
4952 i915_gem_sanitize(i915);
4956 i915_gem_cleanup_engines(struct drm_i915_private *dev_priv)
4958 struct intel_engine_cs *engine;
4959 enum intel_engine_id id;
4961 for_each_engine(engine, dev_priv, id)
4962 dev_priv->gt.cleanup_engine(engine);
4966 i915_gem_load_init_fences(struct drm_i915_private *dev_priv)
4970 if (INTEL_INFO(dev_priv)->gen >= 7 && !IS_VALLEYVIEW(dev_priv) &&
4971 !IS_CHERRYVIEW(dev_priv))
4972 dev_priv->num_fence_regs = 32;
4973 else if (INTEL_INFO(dev_priv)->gen >= 4 ||
4974 IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
4975 IS_G33(dev_priv) || IS_PINEVIEW(dev_priv))
4976 dev_priv->num_fence_regs = 16;
4978 dev_priv->num_fence_regs = 8;
4980 if (intel_vgpu_active(dev_priv))
4981 dev_priv->num_fence_regs =
4982 I915_READ(vgtif_reg(avail_rs.fence_num));
4984 /* Initialize fence registers to zero */
4985 for (i = 0; i < dev_priv->num_fence_regs; i++) {
4986 struct drm_i915_fence_reg *fence = &dev_priv->fence_regs[i];
4988 fence->i915 = dev_priv;
4990 list_add_tail(&fence->link, &dev_priv->mm.fence_list);
4992 i915_gem_restore_fences(dev_priv);
4994 i915_gem_detect_bit_6_swizzle(dev_priv);
4998 i915_gem_load_init(struct drm_i915_private *dev_priv)
5002 dev_priv->objects = KMEM_CACHE(drm_i915_gem_object, SLAB_HWCACHE_ALIGN);
5003 if (!dev_priv->objects)
5006 dev_priv->vmas = KMEM_CACHE(i915_vma, SLAB_HWCACHE_ALIGN);
5007 if (!dev_priv->vmas)
5010 dev_priv->luts = KMEM_CACHE(i915_lut_handle, 0);
5011 if (!dev_priv->luts)
5014 dev_priv->requests = KMEM_CACHE(drm_i915_gem_request,
5015 SLAB_HWCACHE_ALIGN |
5016 SLAB_RECLAIM_ACCOUNT |
5017 SLAB_TYPESAFE_BY_RCU);
5018 if (!dev_priv->requests)
5021 dev_priv->dependencies = KMEM_CACHE(i915_dependency,
5022 SLAB_HWCACHE_ALIGN |
5023 SLAB_RECLAIM_ACCOUNT);
5024 if (!dev_priv->dependencies)
5027 dev_priv->priorities = KMEM_CACHE(i915_priolist, SLAB_HWCACHE_ALIGN);
5028 if (!dev_priv->priorities)
5029 goto err_dependencies;
5031 mutex_lock(&dev_priv->drm.struct_mutex);
5032 INIT_LIST_HEAD(&dev_priv->gt.timelines);
5033 err = i915_gem_timeline_init__global(dev_priv);
5034 mutex_unlock(&dev_priv->drm.struct_mutex);
5036 goto err_priorities;
5038 INIT_WORK(&dev_priv->mm.free_work, __i915_gem_free_work);
5039 init_llist_head(&dev_priv->mm.free_list);
5040 INIT_LIST_HEAD(&dev_priv->mm.unbound_list);
5041 INIT_LIST_HEAD(&dev_priv->mm.bound_list);
5042 INIT_LIST_HEAD(&dev_priv->mm.fence_list);
5043 INIT_LIST_HEAD(&dev_priv->mm.userfault_list);
5044 INIT_DELAYED_WORK(&dev_priv->gt.retire_work,
5045 i915_gem_retire_work_handler);
5046 INIT_DELAYED_WORK(&dev_priv->gt.idle_work,
5047 i915_gem_idle_work_handler);
5048 init_waitqueue_head(&dev_priv->gpu_error.wait_queue);
5049 init_waitqueue_head(&dev_priv->gpu_error.reset_queue);
5051 atomic_set(&dev_priv->mm.bsd_engine_dispatch_index, 0);
5053 spin_lock_init(&dev_priv->fb_tracking.lock);
5055 mutex_init(&dev_priv->tlb_invalidate_lock);
5060 kmem_cache_destroy(dev_priv->priorities);
5062 kmem_cache_destroy(dev_priv->dependencies);
5064 kmem_cache_destroy(dev_priv->requests);
5066 kmem_cache_destroy(dev_priv->luts);
5068 kmem_cache_destroy(dev_priv->vmas);
5070 kmem_cache_destroy(dev_priv->objects);
5075 void i915_gem_load_cleanup(struct drm_i915_private *dev_priv)
5077 i915_gem_drain_freed_objects(dev_priv);
5078 WARN_ON(!llist_empty(&dev_priv->mm.free_list));
5079 WARN_ON(dev_priv->mm.object_count);
5081 mutex_lock(&dev_priv->drm.struct_mutex);
5082 i915_gem_timeline_fini(&dev_priv->gt.global_timeline);
5083 WARN_ON(!list_empty(&dev_priv->gt.timelines));
5084 mutex_unlock(&dev_priv->drm.struct_mutex);
5086 kmem_cache_destroy(dev_priv->priorities);
5087 kmem_cache_destroy(dev_priv->dependencies);
5088 kmem_cache_destroy(dev_priv->requests);
5089 kmem_cache_destroy(dev_priv->luts);
5090 kmem_cache_destroy(dev_priv->vmas);
5091 kmem_cache_destroy(dev_priv->objects);
5093 /* And ensure that our DESTROY_BY_RCU slabs are truly destroyed */
5097 int i915_gem_freeze(struct drm_i915_private *dev_priv)
5099 /* Discard all purgeable objects, let userspace recover those as
5100 * required after resuming.
5102 i915_gem_shrink_all(dev_priv);
5107 int i915_gem_freeze_late(struct drm_i915_private *dev_priv)
5109 struct drm_i915_gem_object *obj;
5110 struct list_head *phases[] = {
5111 &dev_priv->mm.unbound_list,
5112 &dev_priv->mm.bound_list,
5116 /* Called just before we write the hibernation image.
5118 * We need to update the domain tracking to reflect that the CPU
5119 * will be accessing all the pages to create and restore from the
5120 * hibernation, and so upon restoration those pages will be in the
5123 * To make sure the hibernation image contains the latest state,
5124 * we update that state just before writing out the image.
5126 * To try and reduce the hibernation image, we manually shrink
5127 * the objects as well, see i915_gem_freeze()
5130 i915_gem_shrink(dev_priv, -1UL, NULL, I915_SHRINK_UNBOUND);
5131 i915_gem_drain_freed_objects(dev_priv);
5133 mutex_lock(&dev_priv->drm.struct_mutex);
5134 for (p = phases; *p; p++) {
5135 list_for_each_entry(obj, *p, global_link)
5136 __start_cpu_write(obj);
5138 mutex_unlock(&dev_priv->drm.struct_mutex);
5143 void i915_gem_release(struct drm_device *dev, struct drm_file *file)
5145 struct drm_i915_file_private *file_priv = file->driver_priv;
5146 struct drm_i915_gem_request *request;
5148 /* Clean up our request list when the client is going away, so that
5149 * later retire_requests won't dereference our soon-to-be-gone
5152 spin_lock(&file_priv->mm.lock);
5153 list_for_each_entry(request, &file_priv->mm.request_list, client_link)
5154 request->file_priv = NULL;
5155 spin_unlock(&file_priv->mm.lock);
5158 int i915_gem_open(struct drm_i915_private *i915, struct drm_file *file)
5160 struct drm_i915_file_private *file_priv;
5165 file_priv = kzalloc(sizeof(*file_priv), GFP_KERNEL);
5169 file->driver_priv = file_priv;
5170 file_priv->dev_priv = i915;
5171 file_priv->file = file;
5173 spin_lock_init(&file_priv->mm.lock);
5174 INIT_LIST_HEAD(&file_priv->mm.request_list);
5176 file_priv->bsd_engine = -1;
5178 ret = i915_gem_context_open(i915, file);
5186 * i915_gem_track_fb - update frontbuffer tracking
5187 * @old: current GEM buffer for the frontbuffer slots
5188 * @new: new GEM buffer for the frontbuffer slots
5189 * @frontbuffer_bits: bitmask of frontbuffer slots
5191 * This updates the frontbuffer tracking bits @frontbuffer_bits by clearing them
5192 * from @old and setting them in @new. Both @old and @new can be NULL.
5194 void i915_gem_track_fb(struct drm_i915_gem_object *old,
5195 struct drm_i915_gem_object *new,
5196 unsigned frontbuffer_bits)
5198 /* Control of individual bits within the mask are guarded by
5199 * the owning plane->mutex, i.e. we can never see concurrent
5200 * manipulation of individual bits. But since the bitfield as a whole
5201 * is updated using RMW, we need to use atomics in order to update
5204 BUILD_BUG_ON(INTEL_FRONTBUFFER_BITS_PER_PIPE * I915_MAX_PIPES >
5205 sizeof(atomic_t) * BITS_PER_BYTE);
5208 WARN_ON(!(atomic_read(&old->frontbuffer_bits) & frontbuffer_bits));
5209 atomic_andnot(frontbuffer_bits, &old->frontbuffer_bits);
5213 WARN_ON(atomic_read(&new->frontbuffer_bits) & frontbuffer_bits);
5214 atomic_or(frontbuffer_bits, &new->frontbuffer_bits);
5218 /* Allocate a new GEM object and fill it with the supplied data */
5219 struct drm_i915_gem_object *
5220 i915_gem_object_create_from_data(struct drm_i915_private *dev_priv,
5221 const void *data, size_t size)
5223 struct drm_i915_gem_object *obj;
5228 obj = i915_gem_object_create(dev_priv, round_up(size, PAGE_SIZE));
5232 GEM_BUG_ON(obj->base.write_domain != I915_GEM_DOMAIN_CPU);
5234 file = obj->base.filp;
5237 unsigned int len = min_t(typeof(size), size, PAGE_SIZE);
5239 void *pgdata, *vaddr;
5241 err = pagecache_write_begin(file, file->f_mapping,
5248 memcpy(vaddr, data, len);
5251 err = pagecache_write_end(file, file->f_mapping,
5265 i915_gem_object_put(obj);
5266 return ERR_PTR(err);
5269 struct scatterlist *
5270 i915_gem_object_get_sg(struct drm_i915_gem_object *obj,
5272 unsigned int *offset)
5274 struct i915_gem_object_page_iter *iter = &obj->mm.get_page;
5275 struct scatterlist *sg;
5276 unsigned int idx, count;
5279 GEM_BUG_ON(n >= obj->base.size >> PAGE_SHIFT);
5280 GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
5282 /* As we iterate forward through the sg, we record each entry in a
5283 * radixtree for quick repeated (backwards) lookups. If we have seen
5284 * this index previously, we will have an entry for it.
5286 * Initial lookup is O(N), but this is amortized to O(1) for
5287 * sequential page access (where each new request is consecutive
5288 * to the previous one). Repeated lookups are O(lg(obj->base.size)),
5289 * i.e. O(1) with a large constant!
5291 if (n < READ_ONCE(iter->sg_idx))
5294 mutex_lock(&iter->lock);
5296 /* We prefer to reuse the last sg so that repeated lookup of this
5297 * (or the subsequent) sg are fast - comparing against the last
5298 * sg is faster than going through the radixtree.
5303 count = __sg_page_count(sg);
5305 while (idx + count <= n) {
5306 unsigned long exception, i;
5309 /* If we cannot allocate and insert this entry, or the
5310 * individual pages from this range, cancel updating the
5311 * sg_idx so that on this lookup we are forced to linearly
5312 * scan onwards, but on future lookups we will try the
5313 * insertion again (in which case we need to be careful of
5314 * the error return reporting that we have already inserted
5317 ret = radix_tree_insert(&iter->radix, idx, sg);
5318 if (ret && ret != -EEXIST)
5322 RADIX_TREE_EXCEPTIONAL_ENTRY |
5323 idx << RADIX_TREE_EXCEPTIONAL_SHIFT;
5324 for (i = 1; i < count; i++) {
5325 ret = radix_tree_insert(&iter->radix, idx + i,
5327 if (ret && ret != -EEXIST)
5332 sg = ____sg_next(sg);
5333 count = __sg_page_count(sg);
5340 mutex_unlock(&iter->lock);
5342 if (unlikely(n < idx)) /* insertion completed by another thread */
5345 /* In case we failed to insert the entry into the radixtree, we need
5346 * to look beyond the current sg.
5348 while (idx + count <= n) {
5350 sg = ____sg_next(sg);
5351 count = __sg_page_count(sg);
5360 sg = radix_tree_lookup(&iter->radix, n);
5363 /* If this index is in the middle of multi-page sg entry,
5364 * the radixtree will contain an exceptional entry that points
5365 * to the start of that range. We will return the pointer to
5366 * the base page and the offset of this page within the
5370 if (unlikely(radix_tree_exception(sg))) {
5371 unsigned long base =
5372 (unsigned long)sg >> RADIX_TREE_EXCEPTIONAL_SHIFT;
5374 sg = radix_tree_lookup(&iter->radix, base);
5386 i915_gem_object_get_page(struct drm_i915_gem_object *obj, unsigned int n)
5388 struct scatterlist *sg;
5389 unsigned int offset;
5391 GEM_BUG_ON(!i915_gem_object_has_struct_page(obj));
5393 sg = i915_gem_object_get_sg(obj, n, &offset);
5394 return nth_page(sg_page(sg), offset);
5397 /* Like i915_gem_object_get_page(), but mark the returned page dirty */
5399 i915_gem_object_get_dirty_page(struct drm_i915_gem_object *obj,
5404 page = i915_gem_object_get_page(obj, n);
5406 set_page_dirty(page);
5412 i915_gem_object_get_dma_address(struct drm_i915_gem_object *obj,
5415 struct scatterlist *sg;
5416 unsigned int offset;
5418 sg = i915_gem_object_get_sg(obj, n, &offset);
5419 return sg_dma_address(sg) + (offset << PAGE_SHIFT);
5422 int i915_gem_object_attach_phys(struct drm_i915_gem_object *obj, int align)
5424 struct sg_table *pages;
5427 if (align > obj->base.size)
5430 if (obj->ops == &i915_gem_phys_ops)
5433 if (obj->ops != &i915_gem_object_ops)
5436 err = i915_gem_object_unbind(obj);
5440 mutex_lock(&obj->mm.lock);
5442 if (obj->mm.madv != I915_MADV_WILLNEED) {
5447 if (obj->mm.quirked) {
5452 if (obj->mm.mapping) {
5457 pages = obj->mm.pages;
5458 obj->ops = &i915_gem_phys_ops;
5460 err = ____i915_gem_object_get_pages(obj);
5464 /* Perma-pin (until release) the physical set of pages */
5465 __i915_gem_object_pin_pages(obj);
5467 if (!IS_ERR_OR_NULL(pages))
5468 i915_gem_object_ops.put_pages(obj, pages);
5469 mutex_unlock(&obj->mm.lock);
5473 obj->ops = &i915_gem_object_ops;
5474 obj->mm.pages = pages;
5476 mutex_unlock(&obj->mm.lock);
5480 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
5481 #include "selftests/scatterlist.c"
5482 #include "selftests/mock_gem_device.c"
5483 #include "selftests/huge_gem_object.c"
5484 #include "selftests/i915_gem_object.c"
5485 #include "selftests/i915_gem_coherency.c"