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>
28 #include <drm/drm_vma_manager.h>
29 #include <drm/drm_pci.h>
30 #include <drm/i915_drm.h>
31 #include <linux/dma-fence-array.h>
32 #include <linux/kthread.h>
33 #include <linux/reservation.h>
34 #include <linux/shmem_fs.h>
35 #include <linux/slab.h>
36 #include <linux/stop_machine.h>
37 #include <linux/swap.h>
38 #include <linux/pci.h>
39 #include <linux/dma-buf.h>
40 #include <linux/mman.h>
43 #include "i915_gem_clflush.h"
44 #include "i915_gemfs.h"
45 #include "i915_reset.h"
46 #include "i915_trace.h"
47 #include "i915_vgpu.h"
49 #include "intel_drv.h"
50 #include "intel_frontbuffer.h"
51 #include "intel_mocs.h"
52 #include "intel_workarounds.h"
54 static void i915_gem_flush_free_objects(struct drm_i915_private *i915);
56 static bool cpu_write_needs_clflush(struct drm_i915_gem_object *obj)
61 if (!(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_WRITE))
64 return obj->pin_global; /* currently in use by HW, keep flushed */
68 insert_mappable_node(struct i915_ggtt *ggtt,
69 struct drm_mm_node *node, u32 size)
71 memset(node, 0, sizeof(*node));
72 return drm_mm_insert_node_in_range(&ggtt->vm.mm, node,
73 size, 0, I915_COLOR_UNEVICTABLE,
74 0, ggtt->mappable_end,
79 remove_mappable_node(struct drm_mm_node *node)
81 drm_mm_remove_node(node);
84 /* some bookkeeping */
85 static void i915_gem_info_add_obj(struct drm_i915_private *dev_priv,
88 spin_lock(&dev_priv->mm.object_stat_lock);
89 dev_priv->mm.object_count++;
90 dev_priv->mm.object_memory += size;
91 spin_unlock(&dev_priv->mm.object_stat_lock);
94 static void i915_gem_info_remove_obj(struct drm_i915_private *dev_priv,
97 spin_lock(&dev_priv->mm.object_stat_lock);
98 dev_priv->mm.object_count--;
99 dev_priv->mm.object_memory -= size;
100 spin_unlock(&dev_priv->mm.object_stat_lock);
104 i915_gem_wait_for_error(struct i915_gpu_error *error)
111 * Only wait 10 seconds for the gpu reset to complete to avoid hanging
112 * userspace. If it takes that long something really bad is going on and
113 * we should simply try to bail out and fail as gracefully as possible.
115 ret = wait_event_interruptible_timeout(error->reset_queue,
116 !i915_reset_backoff(error),
119 DRM_ERROR("Timed out waiting for the gpu reset to complete\n");
121 } else if (ret < 0) {
128 int i915_mutex_lock_interruptible(struct drm_device *dev)
130 struct drm_i915_private *dev_priv = to_i915(dev);
133 ret = i915_gem_wait_for_error(&dev_priv->gpu_error);
137 ret = mutex_lock_interruptible(&dev->struct_mutex);
144 static u32 __i915_gem_park(struct drm_i915_private *i915)
146 intel_wakeref_t wakeref;
150 lockdep_assert_held(&i915->drm.struct_mutex);
151 GEM_BUG_ON(i915->gt.active_requests);
152 GEM_BUG_ON(!list_empty(&i915->gt.active_rings));
155 return I915_EPOCH_INVALID;
157 GEM_BUG_ON(i915->gt.epoch == I915_EPOCH_INVALID);
160 * Be paranoid and flush a concurrent interrupt to make sure
161 * we don't reactivate any irq tasklets after parking.
163 * FIXME: Note that even though we have waited for execlists to be idle,
164 * there may still be an in-flight interrupt even though the CSB
165 * is now empty. synchronize_irq() makes sure that a residual interrupt
166 * is completed before we continue, but it doesn't prevent the HW from
167 * raising a spurious interrupt later. To complete the shield we should
168 * coordinate disabling the CS irq with flushing the interrupts.
170 synchronize_irq(i915->drm.irq);
172 intel_engines_park(i915);
173 i915_timelines_park(i915);
175 i915_pmu_gt_parked(i915);
176 i915_vma_parked(i915);
178 wakeref = fetch_and_zero(&i915->gt.awake);
179 GEM_BUG_ON(!wakeref);
181 if (INTEL_GEN(i915) >= 6)
184 intel_display_power_put(i915, POWER_DOMAIN_GT_IRQ, wakeref);
186 return i915->gt.epoch;
189 void i915_gem_park(struct drm_i915_private *i915)
193 lockdep_assert_held(&i915->drm.struct_mutex);
194 GEM_BUG_ON(i915->gt.active_requests);
199 /* Defer the actual call to __i915_gem_park() to prevent ping-pongs */
200 mod_delayed_work(i915->wq, &i915->gt.idle_work, msecs_to_jiffies(100));
203 void i915_gem_unpark(struct drm_i915_private *i915)
207 lockdep_assert_held(&i915->drm.struct_mutex);
208 GEM_BUG_ON(!i915->gt.active_requests);
209 assert_rpm_wakelock_held(i915);
215 * It seems that the DMC likes to transition between the DC states a lot
216 * when there are no connected displays (no active power domains) during
217 * command submission.
219 * This activity has negative impact on the performance of the chip with
220 * huge latencies observed in the interrupt handler and elsewhere.
222 * Work around it by grabbing a GT IRQ power domain whilst there is any
223 * GT activity, preventing any DC state transitions.
225 i915->gt.awake = intel_display_power_get(i915, POWER_DOMAIN_GT_IRQ);
226 GEM_BUG_ON(!i915->gt.awake);
228 if (unlikely(++i915->gt.epoch == 0)) /* keep 0 as invalid */
231 intel_enable_gt_powersave(i915);
232 i915_update_gfx_val(i915);
233 if (INTEL_GEN(i915) >= 6)
235 i915_pmu_gt_unparked(i915);
237 intel_engines_unpark(i915);
239 i915_queue_hangcheck(i915);
241 queue_delayed_work(i915->wq,
242 &i915->gt.retire_work,
243 round_jiffies_up_relative(HZ));
247 i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
248 struct drm_file *file)
250 struct i915_ggtt *ggtt = &to_i915(dev)->ggtt;
251 struct drm_i915_gem_get_aperture *args = data;
252 struct i915_vma *vma;
255 mutex_lock(&ggtt->vm.mutex);
257 pinned = ggtt->vm.reserved;
258 list_for_each_entry(vma, &ggtt->vm.bound_list, vm_link)
259 if (i915_vma_is_pinned(vma))
260 pinned += vma->node.size;
262 mutex_unlock(&ggtt->vm.mutex);
264 args->aper_size = ggtt->vm.total;
265 args->aper_available_size = args->aper_size - pinned;
270 static int i915_gem_object_get_pages_phys(struct drm_i915_gem_object *obj)
272 struct address_space *mapping = obj->base.filp->f_mapping;
273 drm_dma_handle_t *phys;
275 struct scatterlist *sg;
280 if (WARN_ON(i915_gem_object_needs_bit17_swizzle(obj)))
283 /* Always aligning to the object size, allows a single allocation
284 * to handle all possible callers, and given typical object sizes,
285 * the alignment of the buddy allocation will naturally match.
287 phys = drm_pci_alloc(obj->base.dev,
288 roundup_pow_of_two(obj->base.size),
289 roundup_pow_of_two(obj->base.size));
294 for (i = 0; i < obj->base.size / PAGE_SIZE; i++) {
298 page = shmem_read_mapping_page(mapping, i);
304 src = kmap_atomic(page);
305 memcpy(vaddr, src, PAGE_SIZE);
306 drm_clflush_virt_range(vaddr, PAGE_SIZE);
313 i915_gem_chipset_flush(to_i915(obj->base.dev));
315 st = kmalloc(sizeof(*st), GFP_KERNEL);
321 if (sg_alloc_table(st, 1, GFP_KERNEL)) {
329 sg->length = obj->base.size;
331 sg_dma_address(sg) = phys->busaddr;
332 sg_dma_len(sg) = obj->base.size;
334 obj->phys_handle = phys;
336 __i915_gem_object_set_pages(obj, st, sg->length);
341 drm_pci_free(obj->base.dev, phys);
346 static void __start_cpu_write(struct drm_i915_gem_object *obj)
348 obj->read_domains = I915_GEM_DOMAIN_CPU;
349 obj->write_domain = I915_GEM_DOMAIN_CPU;
350 if (cpu_write_needs_clflush(obj))
351 obj->cache_dirty = true;
355 __i915_gem_object_release_shmem(struct drm_i915_gem_object *obj,
356 struct sg_table *pages,
359 GEM_BUG_ON(obj->mm.madv == __I915_MADV_PURGED);
361 if (obj->mm.madv == I915_MADV_DONTNEED)
362 obj->mm.dirty = false;
365 (obj->read_domains & I915_GEM_DOMAIN_CPU) == 0 &&
366 !(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ))
367 drm_clflush_sg(pages);
369 __start_cpu_write(obj);
373 i915_gem_object_put_pages_phys(struct drm_i915_gem_object *obj,
374 struct sg_table *pages)
376 __i915_gem_object_release_shmem(obj, pages, false);
379 struct address_space *mapping = obj->base.filp->f_mapping;
380 char *vaddr = obj->phys_handle->vaddr;
383 for (i = 0; i < obj->base.size / PAGE_SIZE; i++) {
387 page = shmem_read_mapping_page(mapping, i);
391 dst = kmap_atomic(page);
392 drm_clflush_virt_range(vaddr, PAGE_SIZE);
393 memcpy(dst, vaddr, PAGE_SIZE);
396 set_page_dirty(page);
397 if (obj->mm.madv == I915_MADV_WILLNEED)
398 mark_page_accessed(page);
402 obj->mm.dirty = false;
405 sg_free_table(pages);
408 drm_pci_free(obj->base.dev, obj->phys_handle);
412 i915_gem_object_release_phys(struct drm_i915_gem_object *obj)
414 i915_gem_object_unpin_pages(obj);
417 static const struct drm_i915_gem_object_ops i915_gem_phys_ops = {
418 .get_pages = i915_gem_object_get_pages_phys,
419 .put_pages = i915_gem_object_put_pages_phys,
420 .release = i915_gem_object_release_phys,
423 static const struct drm_i915_gem_object_ops i915_gem_object_ops;
425 int i915_gem_object_unbind(struct drm_i915_gem_object *obj)
427 struct i915_vma *vma;
428 LIST_HEAD(still_in_list);
431 lockdep_assert_held(&obj->base.dev->struct_mutex);
433 /* Closed vma are removed from the obj->vma_list - but they may
434 * still have an active binding on the object. To remove those we
435 * must wait for all rendering to complete to the object (as unbinding
436 * must anyway), and retire the requests.
438 ret = i915_gem_object_set_to_cpu_domain(obj, false);
442 spin_lock(&obj->vma.lock);
443 while (!ret && (vma = list_first_entry_or_null(&obj->vma.list,
446 list_move_tail(&vma->obj_link, &still_in_list);
447 spin_unlock(&obj->vma.lock);
449 ret = i915_vma_unbind(vma);
451 spin_lock(&obj->vma.lock);
453 list_splice(&still_in_list, &obj->vma.list);
454 spin_unlock(&obj->vma.lock);
460 i915_gem_object_wait_fence(struct dma_fence *fence,
463 struct intel_rps_client *rps_client)
465 struct i915_request *rq;
467 BUILD_BUG_ON(I915_WAIT_INTERRUPTIBLE != 0x1);
469 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
472 if (!dma_fence_is_i915(fence))
473 return dma_fence_wait_timeout(fence,
474 flags & I915_WAIT_INTERRUPTIBLE,
477 rq = to_request(fence);
478 if (i915_request_completed(rq))
482 * This client is about to stall waiting for the GPU. In many cases
483 * this is undesirable and limits the throughput of the system, as
484 * many clients cannot continue processing user input/output whilst
485 * blocked. RPS autotuning may take tens of milliseconds to respond
486 * to the GPU load and thus incurs additional latency for the client.
487 * We can circumvent that by promoting the GPU frequency to maximum
488 * before we wait. This makes the GPU throttle up much more quickly
489 * (good for benchmarks and user experience, e.g. window animations),
490 * but at a cost of spending more power processing the workload
491 * (bad for battery). Not all clients even want their results
492 * immediately and for them we should just let the GPU select its own
493 * frequency to maximise efficiency. To prevent a single client from
494 * forcing the clocks too high for the whole system, we only allow
495 * each client to waitboost once in a busy period.
497 if (rps_client && !i915_request_started(rq)) {
498 if (INTEL_GEN(rq->i915) >= 6)
499 gen6_rps_boost(rq, rps_client);
502 timeout = i915_request_wait(rq, flags, timeout);
505 if (flags & I915_WAIT_LOCKED && i915_request_completed(rq))
506 i915_request_retire_upto(rq);
512 i915_gem_object_wait_reservation(struct reservation_object *resv,
515 struct intel_rps_client *rps_client)
517 unsigned int seq = __read_seqcount_begin(&resv->seq);
518 struct dma_fence *excl;
519 bool prune_fences = false;
521 if (flags & I915_WAIT_ALL) {
522 struct dma_fence **shared;
523 unsigned int count, i;
526 ret = reservation_object_get_fences_rcu(resv,
527 &excl, &count, &shared);
531 for (i = 0; i < count; i++) {
532 timeout = i915_gem_object_wait_fence(shared[i],
538 dma_fence_put(shared[i]);
541 for (; i < count; i++)
542 dma_fence_put(shared[i]);
546 * If both shared fences and an exclusive fence exist,
547 * then by construction the shared fences must be later
548 * than the exclusive fence. If we successfully wait for
549 * all the shared fences, we know that the exclusive fence
550 * must all be signaled. If all the shared fences are
551 * signaled, we can prune the array and recover the
552 * floating references on the fences/requests.
554 prune_fences = count && timeout >= 0;
556 excl = reservation_object_get_excl_rcu(resv);
559 if (excl && timeout >= 0)
560 timeout = i915_gem_object_wait_fence(excl, flags, timeout,
566 * Opportunistically prune the fences iff we know they have *all* been
567 * signaled and that the reservation object has not been changed (i.e.
568 * no new fences have been added).
570 if (prune_fences && !__read_seqcount_retry(&resv->seq, seq)) {
571 if (reservation_object_trylock(resv)) {
572 if (!__read_seqcount_retry(&resv->seq, seq))
573 reservation_object_add_excl_fence(resv, NULL);
574 reservation_object_unlock(resv);
581 static void __fence_set_priority(struct dma_fence *fence,
582 const struct i915_sched_attr *attr)
584 struct i915_request *rq;
585 struct intel_engine_cs *engine;
587 if (dma_fence_is_signaled(fence) || !dma_fence_is_i915(fence))
590 rq = to_request(fence);
594 rcu_read_lock(); /* RCU serialisation for set-wedged protection */
595 if (engine->schedule)
596 engine->schedule(rq, attr);
598 local_bh_enable(); /* kick the tasklets if queues were reprioritised */
601 static void fence_set_priority(struct dma_fence *fence,
602 const struct i915_sched_attr *attr)
604 /* Recurse once into a fence-array */
605 if (dma_fence_is_array(fence)) {
606 struct dma_fence_array *array = to_dma_fence_array(fence);
609 for (i = 0; i < array->num_fences; i++)
610 __fence_set_priority(array->fences[i], attr);
612 __fence_set_priority(fence, attr);
617 i915_gem_object_wait_priority(struct drm_i915_gem_object *obj,
619 const struct i915_sched_attr *attr)
621 struct dma_fence *excl;
623 if (flags & I915_WAIT_ALL) {
624 struct dma_fence **shared;
625 unsigned int count, i;
628 ret = reservation_object_get_fences_rcu(obj->resv,
629 &excl, &count, &shared);
633 for (i = 0; i < count; i++) {
634 fence_set_priority(shared[i], attr);
635 dma_fence_put(shared[i]);
640 excl = reservation_object_get_excl_rcu(obj->resv);
644 fence_set_priority(excl, attr);
651 * Waits for rendering to the object to be completed
652 * @obj: i915 gem object
653 * @flags: how to wait (under a lock, for all rendering or just for writes etc)
654 * @timeout: how long to wait
655 * @rps_client: client (user process) to charge for any waitboosting
658 i915_gem_object_wait(struct drm_i915_gem_object *obj,
661 struct intel_rps_client *rps_client)
664 GEM_BUG_ON(timeout < 0);
666 timeout = i915_gem_object_wait_reservation(obj->resv,
669 return timeout < 0 ? timeout : 0;
672 static struct intel_rps_client *to_rps_client(struct drm_file *file)
674 struct drm_i915_file_private *fpriv = file->driver_priv;
676 return &fpriv->rps_client;
680 i915_gem_phys_pwrite(struct drm_i915_gem_object *obj,
681 struct drm_i915_gem_pwrite *args,
682 struct drm_file *file)
684 void *vaddr = obj->phys_handle->vaddr + args->offset;
685 char __user *user_data = u64_to_user_ptr(args->data_ptr);
687 /* We manually control the domain here and pretend that it
688 * remains coherent i.e. in the GTT domain, like shmem_pwrite.
690 intel_fb_obj_invalidate(obj, ORIGIN_CPU);
691 if (copy_from_user(vaddr, user_data, args->size))
694 drm_clflush_virt_range(vaddr, args->size);
695 i915_gem_chipset_flush(to_i915(obj->base.dev));
697 intel_fb_obj_flush(obj, ORIGIN_CPU);
701 void *i915_gem_object_alloc(struct drm_i915_private *dev_priv)
703 return kmem_cache_zalloc(dev_priv->objects, GFP_KERNEL);
706 void i915_gem_object_free(struct drm_i915_gem_object *obj)
708 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
709 kmem_cache_free(dev_priv->objects, obj);
713 i915_gem_create(struct drm_file *file,
714 struct drm_i915_private *dev_priv,
718 struct drm_i915_gem_object *obj;
722 size = roundup(size, PAGE_SIZE);
726 /* Allocate the new object */
727 obj = i915_gem_object_create(dev_priv, size);
731 ret = drm_gem_handle_create(file, &obj->base, &handle);
732 /* drop reference from allocate - handle holds it now */
733 i915_gem_object_put(obj);
742 i915_gem_dumb_create(struct drm_file *file,
743 struct drm_device *dev,
744 struct drm_mode_create_dumb *args)
746 /* have to work out size/pitch and return them */
747 args->pitch = ALIGN(args->width * DIV_ROUND_UP(args->bpp, 8), 64);
748 args->size = args->pitch * args->height;
749 return i915_gem_create(file, to_i915(dev),
750 args->size, &args->handle);
753 static bool gpu_write_needs_clflush(struct drm_i915_gem_object *obj)
755 return !(obj->cache_level == I915_CACHE_NONE ||
756 obj->cache_level == I915_CACHE_WT);
760 * Creates a new mm object and returns a handle to it.
761 * @dev: drm device pointer
762 * @data: ioctl data blob
763 * @file: drm file pointer
766 i915_gem_create_ioctl(struct drm_device *dev, void *data,
767 struct drm_file *file)
769 struct drm_i915_private *dev_priv = to_i915(dev);
770 struct drm_i915_gem_create *args = data;
772 i915_gem_flush_free_objects(dev_priv);
774 return i915_gem_create(file, dev_priv,
775 args->size, &args->handle);
778 static inline enum fb_op_origin
779 fb_write_origin(struct drm_i915_gem_object *obj, unsigned int domain)
781 return (domain == I915_GEM_DOMAIN_GTT ?
782 obj->frontbuffer_ggtt_origin : ORIGIN_CPU);
785 void i915_gem_flush_ggtt_writes(struct drm_i915_private *dev_priv)
787 intel_wakeref_t wakeref;
790 * No actual flushing is required for the GTT write domain for reads
791 * from the GTT domain. Writes to it "immediately" go to main memory
792 * as far as we know, so there's no chipset flush. It also doesn't
793 * land in the GPU render cache.
795 * However, we do have to enforce the order so that all writes through
796 * the GTT land before any writes to the device, such as updates to
799 * We also have to wait a bit for the writes to land from the GTT.
800 * An uncached read (i.e. mmio) seems to be ideal for the round-trip
801 * timing. This issue has only been observed when switching quickly
802 * between GTT writes and CPU reads from inside the kernel on recent hw,
803 * and it appears to only affect discrete GTT blocks (i.e. on LLC
804 * system agents we cannot reproduce this behaviour, until Cannonlake
810 if (INTEL_INFO(dev_priv)->has_coherent_ggtt)
813 i915_gem_chipset_flush(dev_priv);
815 with_intel_runtime_pm(dev_priv, wakeref) {
816 spin_lock_irq(&dev_priv->uncore.lock);
818 POSTING_READ_FW(RING_HEAD(RENDER_RING_BASE));
820 spin_unlock_irq(&dev_priv->uncore.lock);
825 flush_write_domain(struct drm_i915_gem_object *obj, unsigned int flush_domains)
827 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
828 struct i915_vma *vma;
830 if (!(obj->write_domain & flush_domains))
833 switch (obj->write_domain) {
834 case I915_GEM_DOMAIN_GTT:
835 i915_gem_flush_ggtt_writes(dev_priv);
837 intel_fb_obj_flush(obj,
838 fb_write_origin(obj, I915_GEM_DOMAIN_GTT));
840 for_each_ggtt_vma(vma, obj) {
844 i915_vma_unset_ggtt_write(vma);
848 case I915_GEM_DOMAIN_WC:
852 case I915_GEM_DOMAIN_CPU:
853 i915_gem_clflush_object(obj, I915_CLFLUSH_SYNC);
856 case I915_GEM_DOMAIN_RENDER:
857 if (gpu_write_needs_clflush(obj))
858 obj->cache_dirty = true;
862 obj->write_domain = 0;
866 * Pins the specified object's pages and synchronizes the object with
867 * GPU accesses. Sets needs_clflush to non-zero if the caller should
868 * flush the object from the CPU cache.
870 int i915_gem_obj_prepare_shmem_read(struct drm_i915_gem_object *obj,
871 unsigned int *needs_clflush)
875 lockdep_assert_held(&obj->base.dev->struct_mutex);
878 if (!i915_gem_object_has_struct_page(obj))
881 ret = i915_gem_object_wait(obj,
882 I915_WAIT_INTERRUPTIBLE |
884 MAX_SCHEDULE_TIMEOUT,
889 ret = i915_gem_object_pin_pages(obj);
893 if (obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ ||
894 !static_cpu_has(X86_FEATURE_CLFLUSH)) {
895 ret = i915_gem_object_set_to_cpu_domain(obj, false);
902 flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
904 /* If we're not in the cpu read domain, set ourself into the gtt
905 * read domain and manually flush cachelines (if required). This
906 * optimizes for the case when the gpu will dirty the data
907 * anyway again before the next pread happens.
909 if (!obj->cache_dirty &&
910 !(obj->read_domains & I915_GEM_DOMAIN_CPU))
911 *needs_clflush = CLFLUSH_BEFORE;
914 /* return with the pages pinned */
918 i915_gem_object_unpin_pages(obj);
922 int i915_gem_obj_prepare_shmem_write(struct drm_i915_gem_object *obj,
923 unsigned int *needs_clflush)
927 lockdep_assert_held(&obj->base.dev->struct_mutex);
930 if (!i915_gem_object_has_struct_page(obj))
933 ret = i915_gem_object_wait(obj,
934 I915_WAIT_INTERRUPTIBLE |
937 MAX_SCHEDULE_TIMEOUT,
942 ret = i915_gem_object_pin_pages(obj);
946 if (obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_WRITE ||
947 !static_cpu_has(X86_FEATURE_CLFLUSH)) {
948 ret = i915_gem_object_set_to_cpu_domain(obj, true);
955 flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
957 /* If we're not in the cpu write domain, set ourself into the
958 * gtt write domain and manually flush cachelines (as required).
959 * This optimizes for the case when the gpu will use the data
960 * right away and we therefore have to clflush anyway.
962 if (!obj->cache_dirty) {
963 *needs_clflush |= CLFLUSH_AFTER;
966 * Same trick applies to invalidate partially written
967 * cachelines read before writing.
969 if (!(obj->read_domains & I915_GEM_DOMAIN_CPU))
970 *needs_clflush |= CLFLUSH_BEFORE;
974 intel_fb_obj_invalidate(obj, ORIGIN_CPU);
975 obj->mm.dirty = true;
976 /* return with the pages pinned */
980 i915_gem_object_unpin_pages(obj);
985 shmem_pread(struct page *page, int offset, int len, char __user *user_data,
994 drm_clflush_virt_range(vaddr + offset, len);
996 ret = __copy_to_user(user_data, vaddr + offset, len);
1000 return ret ? -EFAULT : 0;
1004 i915_gem_shmem_pread(struct drm_i915_gem_object *obj,
1005 struct drm_i915_gem_pread *args)
1007 char __user *user_data;
1009 unsigned int needs_clflush;
1010 unsigned int idx, offset;
1013 ret = mutex_lock_interruptible(&obj->base.dev->struct_mutex);
1017 ret = i915_gem_obj_prepare_shmem_read(obj, &needs_clflush);
1018 mutex_unlock(&obj->base.dev->struct_mutex);
1022 remain = args->size;
1023 user_data = u64_to_user_ptr(args->data_ptr);
1024 offset = offset_in_page(args->offset);
1025 for (idx = args->offset >> PAGE_SHIFT; remain; idx++) {
1026 struct page *page = i915_gem_object_get_page(obj, idx);
1027 unsigned int length = min_t(u64, remain, PAGE_SIZE - offset);
1029 ret = shmem_pread(page, offset, length, user_data,
1035 user_data += length;
1039 i915_gem_obj_finish_shmem_access(obj);
1044 gtt_user_read(struct io_mapping *mapping,
1045 loff_t base, int offset,
1046 char __user *user_data, int length)
1048 void __iomem *vaddr;
1049 unsigned long unwritten;
1051 /* We can use the cpu mem copy function because this is X86. */
1052 vaddr = io_mapping_map_atomic_wc(mapping, base);
1053 unwritten = __copy_to_user_inatomic(user_data,
1054 (void __force *)vaddr + offset,
1056 io_mapping_unmap_atomic(vaddr);
1058 vaddr = io_mapping_map_wc(mapping, base, PAGE_SIZE);
1059 unwritten = copy_to_user(user_data,
1060 (void __force *)vaddr + offset,
1062 io_mapping_unmap(vaddr);
1068 i915_gem_gtt_pread(struct drm_i915_gem_object *obj,
1069 const struct drm_i915_gem_pread *args)
1071 struct drm_i915_private *i915 = to_i915(obj->base.dev);
1072 struct i915_ggtt *ggtt = &i915->ggtt;
1073 intel_wakeref_t wakeref;
1074 struct drm_mm_node node;
1075 struct i915_vma *vma;
1076 void __user *user_data;
1080 ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
1084 wakeref = intel_runtime_pm_get(i915);
1085 vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
1090 node.start = i915_ggtt_offset(vma);
1091 node.allocated = false;
1092 ret = i915_vma_put_fence(vma);
1094 i915_vma_unpin(vma);
1099 ret = insert_mappable_node(ggtt, &node, PAGE_SIZE);
1102 GEM_BUG_ON(!node.allocated);
1105 ret = i915_gem_object_set_to_gtt_domain(obj, false);
1109 mutex_unlock(&i915->drm.struct_mutex);
1111 user_data = u64_to_user_ptr(args->data_ptr);
1112 remain = args->size;
1113 offset = args->offset;
1115 while (remain > 0) {
1116 /* Operation in this page
1118 * page_base = page offset within aperture
1119 * page_offset = offset within page
1120 * page_length = bytes to copy for this page
1122 u32 page_base = node.start;
1123 unsigned page_offset = offset_in_page(offset);
1124 unsigned page_length = PAGE_SIZE - page_offset;
1125 page_length = remain < page_length ? remain : page_length;
1126 if (node.allocated) {
1128 ggtt->vm.insert_page(&ggtt->vm,
1129 i915_gem_object_get_dma_address(obj, offset >> PAGE_SHIFT),
1130 node.start, I915_CACHE_NONE, 0);
1133 page_base += offset & PAGE_MASK;
1136 if (gtt_user_read(&ggtt->iomap, page_base, page_offset,
1137 user_data, page_length)) {
1142 remain -= page_length;
1143 user_data += page_length;
1144 offset += page_length;
1147 mutex_lock(&i915->drm.struct_mutex);
1149 if (node.allocated) {
1151 ggtt->vm.clear_range(&ggtt->vm, node.start, node.size);
1152 remove_mappable_node(&node);
1154 i915_vma_unpin(vma);
1157 intel_runtime_pm_put(i915, wakeref);
1158 mutex_unlock(&i915->drm.struct_mutex);
1164 * Reads data from the object referenced by handle.
1165 * @dev: drm device pointer
1166 * @data: ioctl data blob
1167 * @file: drm file pointer
1169 * On error, the contents of *data are undefined.
1172 i915_gem_pread_ioctl(struct drm_device *dev, void *data,
1173 struct drm_file *file)
1175 struct drm_i915_gem_pread *args = data;
1176 struct drm_i915_gem_object *obj;
1179 if (args->size == 0)
1182 if (!access_ok(u64_to_user_ptr(args->data_ptr),
1186 obj = i915_gem_object_lookup(file, args->handle);
1190 /* Bounds check source. */
1191 if (range_overflows_t(u64, args->offset, args->size, obj->base.size)) {
1196 trace_i915_gem_object_pread(obj, args->offset, args->size);
1198 ret = i915_gem_object_wait(obj,
1199 I915_WAIT_INTERRUPTIBLE,
1200 MAX_SCHEDULE_TIMEOUT,
1201 to_rps_client(file));
1205 ret = i915_gem_object_pin_pages(obj);
1209 ret = i915_gem_shmem_pread(obj, args);
1210 if (ret == -EFAULT || ret == -ENODEV)
1211 ret = i915_gem_gtt_pread(obj, args);
1213 i915_gem_object_unpin_pages(obj);
1215 i915_gem_object_put(obj);
1219 /* This is the fast write path which cannot handle
1220 * page faults in the source data
1224 ggtt_write(struct io_mapping *mapping,
1225 loff_t base, int offset,
1226 char __user *user_data, int length)
1228 void __iomem *vaddr;
1229 unsigned long unwritten;
1231 /* We can use the cpu mem copy function because this is X86. */
1232 vaddr = io_mapping_map_atomic_wc(mapping, base);
1233 unwritten = __copy_from_user_inatomic_nocache((void __force *)vaddr + offset,
1235 io_mapping_unmap_atomic(vaddr);
1237 vaddr = io_mapping_map_wc(mapping, base, PAGE_SIZE);
1238 unwritten = copy_from_user((void __force *)vaddr + offset,
1240 io_mapping_unmap(vaddr);
1247 * This is the fast pwrite path, where we copy the data directly from the
1248 * user into the GTT, uncached.
1249 * @obj: i915 GEM object
1250 * @args: pwrite arguments structure
1253 i915_gem_gtt_pwrite_fast(struct drm_i915_gem_object *obj,
1254 const struct drm_i915_gem_pwrite *args)
1256 struct drm_i915_private *i915 = to_i915(obj->base.dev);
1257 struct i915_ggtt *ggtt = &i915->ggtt;
1258 intel_wakeref_t wakeref;
1259 struct drm_mm_node node;
1260 struct i915_vma *vma;
1262 void __user *user_data;
1265 ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
1269 if (i915_gem_object_has_struct_page(obj)) {
1271 * Avoid waking the device up if we can fallback, as
1272 * waking/resuming is very slow (worst-case 10-100 ms
1273 * depending on PCI sleeps and our own resume time).
1274 * This easily dwarfs any performance advantage from
1275 * using the cache bypass of indirect GGTT access.
1277 wakeref = intel_runtime_pm_get_if_in_use(i915);
1283 /* No backing pages, no fallback, we must force GGTT access */
1284 wakeref = intel_runtime_pm_get(i915);
1287 vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
1292 node.start = i915_ggtt_offset(vma);
1293 node.allocated = false;
1294 ret = i915_vma_put_fence(vma);
1296 i915_vma_unpin(vma);
1301 ret = insert_mappable_node(ggtt, &node, PAGE_SIZE);
1304 GEM_BUG_ON(!node.allocated);
1307 ret = i915_gem_object_set_to_gtt_domain(obj, true);
1311 mutex_unlock(&i915->drm.struct_mutex);
1313 intel_fb_obj_invalidate(obj, ORIGIN_CPU);
1315 user_data = u64_to_user_ptr(args->data_ptr);
1316 offset = args->offset;
1317 remain = args->size;
1319 /* Operation in this page
1321 * page_base = page offset within aperture
1322 * page_offset = offset within page
1323 * page_length = bytes to copy for this page
1325 u32 page_base = node.start;
1326 unsigned int page_offset = offset_in_page(offset);
1327 unsigned int page_length = PAGE_SIZE - page_offset;
1328 page_length = remain < page_length ? remain : page_length;
1329 if (node.allocated) {
1330 wmb(); /* flush the write before we modify the GGTT */
1331 ggtt->vm.insert_page(&ggtt->vm,
1332 i915_gem_object_get_dma_address(obj, offset >> PAGE_SHIFT),
1333 node.start, I915_CACHE_NONE, 0);
1334 wmb(); /* flush modifications to the GGTT (insert_page) */
1336 page_base += offset & PAGE_MASK;
1338 /* If we get a fault while copying data, then (presumably) our
1339 * source page isn't available. Return the error and we'll
1340 * retry in the slow path.
1341 * If the object is non-shmem backed, we retry again with the
1342 * path that handles page fault.
1344 if (ggtt_write(&ggtt->iomap, page_base, page_offset,
1345 user_data, page_length)) {
1350 remain -= page_length;
1351 user_data += page_length;
1352 offset += page_length;
1354 intel_fb_obj_flush(obj, ORIGIN_CPU);
1356 mutex_lock(&i915->drm.struct_mutex);
1358 if (node.allocated) {
1360 ggtt->vm.clear_range(&ggtt->vm, node.start, node.size);
1361 remove_mappable_node(&node);
1363 i915_vma_unpin(vma);
1366 intel_runtime_pm_put(i915, wakeref);
1368 mutex_unlock(&i915->drm.struct_mutex);
1372 /* Per-page copy function for the shmem pwrite fastpath.
1373 * Flushes invalid cachelines before writing to the target if
1374 * needs_clflush_before is set and flushes out any written cachelines after
1375 * writing if needs_clflush is set.
1378 shmem_pwrite(struct page *page, int offset, int len, char __user *user_data,
1379 bool needs_clflush_before,
1380 bool needs_clflush_after)
1387 if (needs_clflush_before)
1388 drm_clflush_virt_range(vaddr + offset, len);
1390 ret = __copy_from_user(vaddr + offset, user_data, len);
1391 if (!ret && needs_clflush_after)
1392 drm_clflush_virt_range(vaddr + offset, len);
1396 return ret ? -EFAULT : 0;
1400 i915_gem_shmem_pwrite(struct drm_i915_gem_object *obj,
1401 const struct drm_i915_gem_pwrite *args)
1403 struct drm_i915_private *i915 = to_i915(obj->base.dev);
1404 void __user *user_data;
1406 unsigned int partial_cacheline_write;
1407 unsigned int needs_clflush;
1408 unsigned int offset, idx;
1411 ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
1415 ret = i915_gem_obj_prepare_shmem_write(obj, &needs_clflush);
1416 mutex_unlock(&i915->drm.struct_mutex);
1420 /* If we don't overwrite a cacheline completely we need to be
1421 * careful to have up-to-date data by first clflushing. Don't
1422 * overcomplicate things and flush the entire patch.
1424 partial_cacheline_write = 0;
1425 if (needs_clflush & CLFLUSH_BEFORE)
1426 partial_cacheline_write = boot_cpu_data.x86_clflush_size - 1;
1428 user_data = u64_to_user_ptr(args->data_ptr);
1429 remain = args->size;
1430 offset = offset_in_page(args->offset);
1431 for (idx = args->offset >> PAGE_SHIFT; remain; idx++) {
1432 struct page *page = i915_gem_object_get_page(obj, idx);
1433 unsigned int length = min_t(u64, remain, PAGE_SIZE - offset);
1435 ret = shmem_pwrite(page, offset, length, user_data,
1436 (offset | length) & partial_cacheline_write,
1437 needs_clflush & CLFLUSH_AFTER);
1442 user_data += length;
1446 intel_fb_obj_flush(obj, ORIGIN_CPU);
1447 i915_gem_obj_finish_shmem_access(obj);
1452 * Writes data to the object referenced by handle.
1454 * @data: ioctl data blob
1457 * On error, the contents of the buffer that were to be modified are undefined.
1460 i915_gem_pwrite_ioctl(struct drm_device *dev, void *data,
1461 struct drm_file *file)
1463 struct drm_i915_gem_pwrite *args = data;
1464 struct drm_i915_gem_object *obj;
1467 if (args->size == 0)
1470 if (!access_ok(u64_to_user_ptr(args->data_ptr), args->size))
1473 obj = i915_gem_object_lookup(file, args->handle);
1477 /* Bounds check destination. */
1478 if (range_overflows_t(u64, args->offset, args->size, obj->base.size)) {
1483 /* Writes not allowed into this read-only object */
1484 if (i915_gem_object_is_readonly(obj)) {
1489 trace_i915_gem_object_pwrite(obj, args->offset, args->size);
1492 if (obj->ops->pwrite)
1493 ret = obj->ops->pwrite(obj, args);
1497 ret = i915_gem_object_wait(obj,
1498 I915_WAIT_INTERRUPTIBLE |
1500 MAX_SCHEDULE_TIMEOUT,
1501 to_rps_client(file));
1505 ret = i915_gem_object_pin_pages(obj);
1510 /* We can only do the GTT pwrite on untiled buffers, as otherwise
1511 * it would end up going through the fenced access, and we'll get
1512 * different detiling behavior between reading and writing.
1513 * pread/pwrite currently are reading and writing from the CPU
1514 * perspective, requiring manual detiling by the client.
1516 if (!i915_gem_object_has_struct_page(obj) ||
1517 cpu_write_needs_clflush(obj))
1518 /* Note that the gtt paths might fail with non-page-backed user
1519 * pointers (e.g. gtt mappings when moving data between
1520 * textures). Fallback to the shmem path in that case.
1522 ret = i915_gem_gtt_pwrite_fast(obj, args);
1524 if (ret == -EFAULT || ret == -ENOSPC) {
1525 if (obj->phys_handle)
1526 ret = i915_gem_phys_pwrite(obj, args, file);
1528 ret = i915_gem_shmem_pwrite(obj, args);
1531 i915_gem_object_unpin_pages(obj);
1533 i915_gem_object_put(obj);
1537 static void i915_gem_object_bump_inactive_ggtt(struct drm_i915_gem_object *obj)
1539 struct drm_i915_private *i915 = to_i915(obj->base.dev);
1540 struct list_head *list;
1541 struct i915_vma *vma;
1543 GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
1545 mutex_lock(&i915->ggtt.vm.mutex);
1546 for_each_ggtt_vma(vma, obj) {
1547 if (!drm_mm_node_allocated(&vma->node))
1550 list_move_tail(&vma->vm_link, &vma->vm->bound_list);
1552 mutex_unlock(&i915->ggtt.vm.mutex);
1554 spin_lock(&i915->mm.obj_lock);
1555 list = obj->bind_count ? &i915->mm.bound_list : &i915->mm.unbound_list;
1556 list_move_tail(&obj->mm.link, list);
1557 spin_unlock(&i915->mm.obj_lock);
1561 * Called when user space prepares to use an object with the CPU, either
1562 * through the mmap ioctl's mapping or a GTT mapping.
1564 * @data: ioctl data blob
1568 i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
1569 struct drm_file *file)
1571 struct drm_i915_gem_set_domain *args = data;
1572 struct drm_i915_gem_object *obj;
1573 u32 read_domains = args->read_domains;
1574 u32 write_domain = args->write_domain;
1577 /* Only handle setting domains to types used by the CPU. */
1578 if ((write_domain | read_domains) & I915_GEM_GPU_DOMAINS)
1581 /* Having something in the write domain implies it's in the read
1582 * domain, and only that read domain. Enforce that in the request.
1584 if (write_domain != 0 && read_domains != write_domain)
1587 obj = i915_gem_object_lookup(file, args->handle);
1591 /* Try to flush the object off the GPU without holding the lock.
1592 * We will repeat the flush holding the lock in the normal manner
1593 * to catch cases where we are gazumped.
1595 err = i915_gem_object_wait(obj,
1596 I915_WAIT_INTERRUPTIBLE |
1597 I915_WAIT_PRIORITY |
1598 (write_domain ? I915_WAIT_ALL : 0),
1599 MAX_SCHEDULE_TIMEOUT,
1600 to_rps_client(file));
1605 * Proxy objects do not control access to the backing storage, ergo
1606 * they cannot be used as a means to manipulate the cache domain
1607 * tracking for that backing storage. The proxy object is always
1608 * considered to be outside of any cache domain.
1610 if (i915_gem_object_is_proxy(obj)) {
1616 * Flush and acquire obj->pages so that we are coherent through
1617 * direct access in memory with previous cached writes through
1618 * shmemfs and that our cache domain tracking remains valid.
1619 * For example, if the obj->filp was moved to swap without us
1620 * being notified and releasing the pages, we would mistakenly
1621 * continue to assume that the obj remained out of the CPU cached
1624 err = i915_gem_object_pin_pages(obj);
1628 err = i915_mutex_lock_interruptible(dev);
1632 if (read_domains & I915_GEM_DOMAIN_WC)
1633 err = i915_gem_object_set_to_wc_domain(obj, write_domain);
1634 else if (read_domains & I915_GEM_DOMAIN_GTT)
1635 err = i915_gem_object_set_to_gtt_domain(obj, write_domain);
1637 err = i915_gem_object_set_to_cpu_domain(obj, write_domain);
1639 /* And bump the LRU for this access */
1640 i915_gem_object_bump_inactive_ggtt(obj);
1642 mutex_unlock(&dev->struct_mutex);
1644 if (write_domain != 0)
1645 intel_fb_obj_invalidate(obj,
1646 fb_write_origin(obj, write_domain));
1649 i915_gem_object_unpin_pages(obj);
1651 i915_gem_object_put(obj);
1656 * Called when user space has done writes to this buffer
1658 * @data: ioctl data blob
1662 i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
1663 struct drm_file *file)
1665 struct drm_i915_gem_sw_finish *args = data;
1666 struct drm_i915_gem_object *obj;
1668 obj = i915_gem_object_lookup(file, args->handle);
1673 * Proxy objects are barred from CPU access, so there is no
1674 * need to ban sw_finish as it is a nop.
1677 /* Pinned buffers may be scanout, so flush the cache */
1678 i915_gem_object_flush_if_display(obj);
1679 i915_gem_object_put(obj);
1685 __vma_matches(struct vm_area_struct *vma, struct file *filp,
1686 unsigned long addr, unsigned long size)
1688 if (vma->vm_file != filp)
1691 return vma->vm_start == addr &&
1692 (vma->vm_end - vma->vm_start) == PAGE_ALIGN(size);
1696 * i915_gem_mmap_ioctl - Maps the contents of an object, returning the address
1699 * @data: ioctl data blob
1702 * While the mapping holds a reference on the contents of the object, it doesn't
1703 * imply a ref on the object itself.
1707 * DRM driver writers who look a this function as an example for how to do GEM
1708 * mmap support, please don't implement mmap support like here. The modern way
1709 * to implement DRM mmap support is with an mmap offset ioctl (like
1710 * i915_gem_mmap_gtt) and then using the mmap syscall on the DRM fd directly.
1711 * That way debug tooling like valgrind will understand what's going on, hiding
1712 * the mmap call in a driver private ioctl will break that. The i915 driver only
1713 * does cpu mmaps this way because we didn't know better.
1716 i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
1717 struct drm_file *file)
1719 struct drm_i915_gem_mmap *args = data;
1720 struct drm_i915_gem_object *obj;
1723 if (args->flags & ~(I915_MMAP_WC))
1726 if (args->flags & I915_MMAP_WC && !boot_cpu_has(X86_FEATURE_PAT))
1729 obj = i915_gem_object_lookup(file, args->handle);
1733 /* prime objects have no backing filp to GEM mmap
1736 if (!obj->base.filp) {
1737 i915_gem_object_put(obj);
1741 addr = vm_mmap(obj->base.filp, 0, args->size,
1742 PROT_READ | PROT_WRITE, MAP_SHARED,
1744 if (IS_ERR_VALUE(addr))
1747 if (args->flags & I915_MMAP_WC) {
1748 struct mm_struct *mm = current->mm;
1749 struct vm_area_struct *vma;
1751 if (down_write_killable(&mm->mmap_sem)) {
1752 i915_gem_object_put(obj);
1755 vma = find_vma(mm, addr);
1756 if (vma && __vma_matches(vma, obj->base.filp, addr, args->size))
1758 pgprot_writecombine(vm_get_page_prot(vma->vm_flags));
1761 up_write(&mm->mmap_sem);
1762 if (IS_ERR_VALUE(addr))
1765 /* This may race, but that's ok, it only gets set */
1766 WRITE_ONCE(obj->frontbuffer_ggtt_origin, ORIGIN_CPU);
1768 i915_gem_object_put(obj);
1770 args->addr_ptr = (u64)addr;
1775 i915_gem_object_put(obj);
1780 static unsigned int tile_row_pages(const struct drm_i915_gem_object *obj)
1782 return i915_gem_object_get_tile_row_size(obj) >> PAGE_SHIFT;
1786 * i915_gem_mmap_gtt_version - report the current feature set for GTT mmaps
1788 * A history of the GTT mmap interface:
1790 * 0 - Everything had to fit into the GTT. Both parties of a memcpy had to
1791 * aligned and suitable for fencing, and still fit into the available
1792 * mappable space left by the pinned display objects. A classic problem
1793 * we called the page-fault-of-doom where we would ping-pong between
1794 * two objects that could not fit inside the GTT and so the memcpy
1795 * would page one object in at the expense of the other between every
1798 * 1 - Objects can be any size, and have any compatible fencing (X Y, or none
1799 * as set via i915_gem_set_tiling() [DRM_I915_GEM_SET_TILING]). If the
1800 * object is too large for the available space (or simply too large
1801 * for the mappable aperture!), a view is created instead and faulted
1802 * into userspace. (This view is aligned and sized appropriately for
1805 * 2 - Recognise WC as a separate cache domain so that we can flush the
1806 * delayed writes via GTT before performing direct access via WC.
1810 * * snoopable objects cannot be accessed via the GTT. It can cause machine
1811 * hangs on some architectures, corruption on others. An attempt to service
1812 * a GTT page fault from a snoopable object will generate a SIGBUS.
1814 * * the object must be able to fit into RAM (physical memory, though no
1815 * limited to the mappable aperture).
1820 * * a new GTT page fault will synchronize rendering from the GPU and flush
1821 * all data to system memory. Subsequent access will not be synchronized.
1823 * * all mappings are revoked on runtime device suspend.
1825 * * there are only 8, 16 or 32 fence registers to share between all users
1826 * (older machines require fence register for display and blitter access
1827 * as well). Contention of the fence registers will cause the previous users
1828 * to be unmapped and any new access will generate new page faults.
1830 * * running out of memory while servicing a fault may generate a SIGBUS,
1831 * rather than the expected SIGSEGV.
1833 int i915_gem_mmap_gtt_version(void)
1838 static inline struct i915_ggtt_view
1839 compute_partial_view(const struct drm_i915_gem_object *obj,
1840 pgoff_t page_offset,
1843 struct i915_ggtt_view view;
1845 if (i915_gem_object_is_tiled(obj))
1846 chunk = roundup(chunk, tile_row_pages(obj));
1848 view.type = I915_GGTT_VIEW_PARTIAL;
1849 view.partial.offset = rounddown(page_offset, chunk);
1851 min_t(unsigned int, chunk,
1852 (obj->base.size >> PAGE_SHIFT) - view.partial.offset);
1854 /* If the partial covers the entire object, just create a normal VMA. */
1855 if (chunk >= obj->base.size >> PAGE_SHIFT)
1856 view.type = I915_GGTT_VIEW_NORMAL;
1862 * i915_gem_fault - fault a page into the GTT
1865 * The fault handler is set up by drm_gem_mmap() when a object is GTT mapped
1866 * from userspace. The fault handler takes care of binding the object to
1867 * the GTT (if needed), allocating and programming a fence register (again,
1868 * only if needed based on whether the old reg is still valid or the object
1869 * is tiled) and inserting a new PTE into the faulting process.
1871 * Note that the faulting process may involve evicting existing objects
1872 * from the GTT and/or fence registers to make room. So performance may
1873 * suffer if the GTT working set is large or there are few fence registers
1876 * The current feature set supported by i915_gem_fault() and thus GTT mmaps
1877 * is exposed via I915_PARAM_MMAP_GTT_VERSION (see i915_gem_mmap_gtt_version).
1879 vm_fault_t i915_gem_fault(struct vm_fault *vmf)
1881 #define MIN_CHUNK_PAGES (SZ_1M >> PAGE_SHIFT)
1882 struct vm_area_struct *area = vmf->vma;
1883 struct drm_i915_gem_object *obj = to_intel_bo(area->vm_private_data);
1884 struct drm_device *dev = obj->base.dev;
1885 struct drm_i915_private *dev_priv = to_i915(dev);
1886 struct i915_ggtt *ggtt = &dev_priv->ggtt;
1887 bool write = area->vm_flags & VM_WRITE;
1888 intel_wakeref_t wakeref;
1889 struct i915_vma *vma;
1890 pgoff_t page_offset;
1893 /* Sanity check that we allow writing into this object */
1894 if (i915_gem_object_is_readonly(obj) && write)
1895 return VM_FAULT_SIGBUS;
1897 /* We don't use vmf->pgoff since that has the fake offset */
1898 page_offset = (vmf->address - area->vm_start) >> PAGE_SHIFT;
1900 trace_i915_gem_object_fault(obj, page_offset, true, write);
1902 /* Try to flush the object off the GPU first without holding the lock.
1903 * Upon acquiring the lock, we will perform our sanity checks and then
1904 * repeat the flush holding the lock in the normal manner to catch cases
1905 * where we are gazumped.
1907 ret = i915_gem_object_wait(obj,
1908 I915_WAIT_INTERRUPTIBLE,
1909 MAX_SCHEDULE_TIMEOUT,
1914 ret = i915_gem_object_pin_pages(obj);
1918 wakeref = intel_runtime_pm_get(dev_priv);
1920 ret = i915_mutex_lock_interruptible(dev);
1924 /* Access to snoopable pages through the GTT is incoherent. */
1925 if (obj->cache_level != I915_CACHE_NONE && !HAS_LLC(dev_priv)) {
1931 /* Now pin it into the GTT as needed */
1932 vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
1937 /* Use a partial view if it is bigger than available space */
1938 struct i915_ggtt_view view =
1939 compute_partial_view(obj, page_offset, MIN_CHUNK_PAGES);
1942 flags = PIN_MAPPABLE;
1943 if (view.type == I915_GGTT_VIEW_NORMAL)
1944 flags |= PIN_NONBLOCK; /* avoid warnings for pinned */
1947 * Userspace is now writing through an untracked VMA, abandon
1948 * all hope that the hardware is able to track future writes.
1950 obj->frontbuffer_ggtt_origin = ORIGIN_CPU;
1952 vma = i915_gem_object_ggtt_pin(obj, &view, 0, 0, flags);
1953 if (IS_ERR(vma) && !view.type) {
1954 flags = PIN_MAPPABLE;
1955 view.type = I915_GGTT_VIEW_PARTIAL;
1956 vma = i915_gem_object_ggtt_pin(obj, &view, 0, 0, flags);
1964 ret = i915_gem_object_set_to_gtt_domain(obj, write);
1968 ret = i915_vma_pin_fence(vma);
1972 /* Finally, remap it using the new GTT offset */
1973 ret = remap_io_mapping(area,
1974 area->vm_start + (vma->ggtt_view.partial.offset << PAGE_SHIFT),
1975 (ggtt->gmadr.start + vma->node.start) >> PAGE_SHIFT,
1976 min_t(u64, vma->size, area->vm_end - area->vm_start),
1981 /* Mark as being mmapped into userspace for later revocation */
1982 assert_rpm_wakelock_held(dev_priv);
1983 if (!i915_vma_set_userfault(vma) && !obj->userfault_count++)
1984 list_add(&obj->userfault_link, &dev_priv->mm.userfault_list);
1985 GEM_BUG_ON(!obj->userfault_count);
1987 i915_vma_set_ggtt_write(vma);
1990 i915_vma_unpin_fence(vma);
1992 __i915_vma_unpin(vma);
1994 mutex_unlock(&dev->struct_mutex);
1996 intel_runtime_pm_put(dev_priv, wakeref);
1997 i915_gem_object_unpin_pages(obj);
2002 * We eat errors when the gpu is terminally wedged to avoid
2003 * userspace unduly crashing (gl has no provisions for mmaps to
2004 * fail). But any other -EIO isn't ours (e.g. swap in failure)
2005 * and so needs to be reported.
2007 if (!i915_terminally_wedged(&dev_priv->gpu_error))
2008 return VM_FAULT_SIGBUS;
2009 /* else: fall through */
2012 * EAGAIN means the gpu is hung and we'll wait for the error
2013 * handler to reset everything when re-faulting in
2014 * i915_mutex_lock_interruptible.
2021 * EBUSY is ok: this just means that another thread
2022 * already did the job.
2024 return VM_FAULT_NOPAGE;
2026 return VM_FAULT_OOM;
2029 return VM_FAULT_SIGBUS;
2031 WARN_ONCE(ret, "unhandled error in i915_gem_fault: %i\n", ret);
2032 return VM_FAULT_SIGBUS;
2036 static void __i915_gem_object_release_mmap(struct drm_i915_gem_object *obj)
2038 struct i915_vma *vma;
2040 GEM_BUG_ON(!obj->userfault_count);
2042 obj->userfault_count = 0;
2043 list_del(&obj->userfault_link);
2044 drm_vma_node_unmap(&obj->base.vma_node,
2045 obj->base.dev->anon_inode->i_mapping);
2047 for_each_ggtt_vma(vma, obj)
2048 i915_vma_unset_userfault(vma);
2052 * i915_gem_release_mmap - remove physical page mappings
2053 * @obj: obj in question
2055 * Preserve the reservation of the mmapping with the DRM core code, but
2056 * relinquish ownership of the pages back to the system.
2058 * It is vital that we remove the page mapping if we have mapped a tiled
2059 * object through the GTT and then lose the fence register due to
2060 * resource pressure. Similarly if the object has been moved out of the
2061 * aperture, than pages mapped into userspace must be revoked. Removing the
2062 * mapping will then trigger a page fault on the next user access, allowing
2063 * fixup by i915_gem_fault().
2066 i915_gem_release_mmap(struct drm_i915_gem_object *obj)
2068 struct drm_i915_private *i915 = to_i915(obj->base.dev);
2069 intel_wakeref_t wakeref;
2071 /* Serialisation between user GTT access and our code depends upon
2072 * revoking the CPU's PTE whilst the mutex is held. The next user
2073 * pagefault then has to wait until we release the mutex.
2075 * Note that RPM complicates somewhat by adding an additional
2076 * requirement that operations to the GGTT be made holding the RPM
2079 lockdep_assert_held(&i915->drm.struct_mutex);
2080 wakeref = intel_runtime_pm_get(i915);
2082 if (!obj->userfault_count)
2085 __i915_gem_object_release_mmap(obj);
2087 /* Ensure that the CPU's PTE are revoked and there are not outstanding
2088 * memory transactions from userspace before we return. The TLB
2089 * flushing implied above by changing the PTE above *should* be
2090 * sufficient, an extra barrier here just provides us with a bit
2091 * of paranoid documentation about our requirement to serialise
2092 * memory writes before touching registers / GSM.
2097 intel_runtime_pm_put(i915, wakeref);
2100 void i915_gem_runtime_suspend(struct drm_i915_private *dev_priv)
2102 struct drm_i915_gem_object *obj, *on;
2106 * Only called during RPM suspend. All users of the userfault_list
2107 * must be holding an RPM wakeref to ensure that this can not
2108 * run concurrently with themselves (and use the struct_mutex for
2109 * protection between themselves).
2112 list_for_each_entry_safe(obj, on,
2113 &dev_priv->mm.userfault_list, userfault_link)
2114 __i915_gem_object_release_mmap(obj);
2116 /* The fence will be lost when the device powers down. If any were
2117 * in use by hardware (i.e. they are pinned), we should not be powering
2118 * down! All other fences will be reacquired by the user upon waking.
2120 for (i = 0; i < dev_priv->num_fence_regs; i++) {
2121 struct drm_i915_fence_reg *reg = &dev_priv->fence_regs[i];
2123 /* Ideally we want to assert that the fence register is not
2124 * live at this point (i.e. that no piece of code will be
2125 * trying to write through fence + GTT, as that both violates
2126 * our tracking of activity and associated locking/barriers,
2127 * but also is illegal given that the hw is powered down).
2129 * Previously we used reg->pin_count as a "liveness" indicator.
2130 * That is not sufficient, and we need a more fine-grained
2131 * tool if we want to have a sanity check here.
2137 GEM_BUG_ON(i915_vma_has_userfault(reg->vma));
2142 static int i915_gem_object_create_mmap_offset(struct drm_i915_gem_object *obj)
2144 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
2147 err = drm_gem_create_mmap_offset(&obj->base);
2151 /* Attempt to reap some mmap space from dead objects */
2153 err = i915_gem_wait_for_idle(dev_priv,
2154 I915_WAIT_INTERRUPTIBLE,
2155 MAX_SCHEDULE_TIMEOUT);
2159 i915_gem_drain_freed_objects(dev_priv);
2160 err = drm_gem_create_mmap_offset(&obj->base);
2164 } while (flush_delayed_work(&dev_priv->gt.retire_work));
2169 static void i915_gem_object_free_mmap_offset(struct drm_i915_gem_object *obj)
2171 drm_gem_free_mmap_offset(&obj->base);
2175 i915_gem_mmap_gtt(struct drm_file *file,
2176 struct drm_device *dev,
2180 struct drm_i915_gem_object *obj;
2183 obj = i915_gem_object_lookup(file, handle);
2187 ret = i915_gem_object_create_mmap_offset(obj);
2189 *offset = drm_vma_node_offset_addr(&obj->base.vma_node);
2191 i915_gem_object_put(obj);
2196 * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
2198 * @data: GTT mapping ioctl data
2199 * @file: GEM object info
2201 * Simply returns the fake offset to userspace so it can mmap it.
2202 * The mmap call will end up in drm_gem_mmap(), which will set things
2203 * up so we can get faults in the handler above.
2205 * The fault handler will take care of binding the object into the GTT
2206 * (since it may have been evicted to make room for something), allocating
2207 * a fence register, and mapping the appropriate aperture address into
2211 i915_gem_mmap_gtt_ioctl(struct drm_device *dev, void *data,
2212 struct drm_file *file)
2214 struct drm_i915_gem_mmap_gtt *args = data;
2216 return i915_gem_mmap_gtt(file, dev, args->handle, &args->offset);
2219 /* Immediately discard the backing storage */
2221 i915_gem_object_truncate(struct drm_i915_gem_object *obj)
2223 i915_gem_object_free_mmap_offset(obj);
2225 if (obj->base.filp == NULL)
2228 /* Our goal here is to return as much of the memory as
2229 * is possible back to the system as we are called from OOM.
2230 * To do this we must instruct the shmfs to drop all of its
2231 * backing pages, *now*.
2233 shmem_truncate_range(file_inode(obj->base.filp), 0, (loff_t)-1);
2234 obj->mm.madv = __I915_MADV_PURGED;
2235 obj->mm.pages = ERR_PTR(-EFAULT);
2238 /* Try to discard unwanted pages */
2239 void __i915_gem_object_invalidate(struct drm_i915_gem_object *obj)
2241 struct address_space *mapping;
2243 lockdep_assert_held(&obj->mm.lock);
2244 GEM_BUG_ON(i915_gem_object_has_pages(obj));
2246 switch (obj->mm.madv) {
2247 case I915_MADV_DONTNEED:
2248 i915_gem_object_truncate(obj);
2249 case __I915_MADV_PURGED:
2253 if (obj->base.filp == NULL)
2256 mapping = obj->base.filp->f_mapping,
2257 invalidate_mapping_pages(mapping, 0, (loff_t)-1);
2261 * Move pages to appropriate lru and release the pagevec, decrementing the
2262 * ref count of those pages.
2264 static void check_release_pagevec(struct pagevec *pvec)
2266 check_move_unevictable_pages(pvec);
2267 __pagevec_release(pvec);
2272 i915_gem_object_put_pages_gtt(struct drm_i915_gem_object *obj,
2273 struct sg_table *pages)
2275 struct sgt_iter sgt_iter;
2276 struct pagevec pvec;
2279 __i915_gem_object_release_shmem(obj, pages, true);
2281 i915_gem_gtt_finish_pages(obj, pages);
2283 if (i915_gem_object_needs_bit17_swizzle(obj))
2284 i915_gem_object_save_bit_17_swizzle(obj, pages);
2286 mapping_clear_unevictable(file_inode(obj->base.filp)->i_mapping);
2288 pagevec_init(&pvec);
2289 for_each_sgt_page(page, sgt_iter, pages) {
2291 set_page_dirty(page);
2293 if (obj->mm.madv == I915_MADV_WILLNEED)
2294 mark_page_accessed(page);
2296 if (!pagevec_add(&pvec, page))
2297 check_release_pagevec(&pvec);
2299 if (pagevec_count(&pvec))
2300 check_release_pagevec(&pvec);
2301 obj->mm.dirty = false;
2303 sg_free_table(pages);
2307 static void __i915_gem_object_reset_page_iter(struct drm_i915_gem_object *obj)
2309 struct radix_tree_iter iter;
2313 radix_tree_for_each_slot(slot, &obj->mm.get_page.radix, &iter, 0)
2314 radix_tree_delete(&obj->mm.get_page.radix, iter.index);
2318 static struct sg_table *
2319 __i915_gem_object_unset_pages(struct drm_i915_gem_object *obj)
2321 struct drm_i915_private *i915 = to_i915(obj->base.dev);
2322 struct sg_table *pages;
2324 pages = fetch_and_zero(&obj->mm.pages);
2325 if (IS_ERR_OR_NULL(pages))
2328 spin_lock(&i915->mm.obj_lock);
2329 list_del(&obj->mm.link);
2330 spin_unlock(&i915->mm.obj_lock);
2332 if (obj->mm.mapping) {
2335 ptr = page_mask_bits(obj->mm.mapping);
2336 if (is_vmalloc_addr(ptr))
2339 kunmap(kmap_to_page(ptr));
2341 obj->mm.mapping = NULL;
2344 __i915_gem_object_reset_page_iter(obj);
2345 obj->mm.page_sizes.phys = obj->mm.page_sizes.sg = 0;
2350 int __i915_gem_object_put_pages(struct drm_i915_gem_object *obj,
2351 enum i915_mm_subclass subclass)
2353 struct sg_table *pages;
2356 if (i915_gem_object_has_pinned_pages(obj))
2359 GEM_BUG_ON(obj->bind_count);
2361 /* May be called by shrinker from within get_pages() (on another bo) */
2362 mutex_lock_nested(&obj->mm.lock, subclass);
2363 if (unlikely(atomic_read(&obj->mm.pages_pin_count))) {
2369 * ->put_pages might need to allocate memory for the bit17 swizzle
2370 * array, hence protect them from being reaped by removing them from gtt
2373 pages = __i915_gem_object_unset_pages(obj);
2376 * XXX Temporary hijinx to avoid updating all backends to handle
2377 * NULL pages. In the future, when we have more asynchronous
2378 * get_pages backends we should be better able to handle the
2379 * cancellation of the async task in a more uniform manner.
2381 if (!pages && !i915_gem_object_needs_async_cancel(obj))
2382 pages = ERR_PTR(-EINVAL);
2385 obj->ops->put_pages(obj, pages);
2389 mutex_unlock(&obj->mm.lock);
2394 bool i915_sg_trim(struct sg_table *orig_st)
2396 struct sg_table new_st;
2397 struct scatterlist *sg, *new_sg;
2400 if (orig_st->nents == orig_st->orig_nents)
2403 if (sg_alloc_table(&new_st, orig_st->nents, GFP_KERNEL | __GFP_NOWARN))
2406 new_sg = new_st.sgl;
2407 for_each_sg(orig_st->sgl, sg, orig_st->nents, i) {
2408 sg_set_page(new_sg, sg_page(sg), sg->length, 0);
2409 sg_dma_address(new_sg) = sg_dma_address(sg);
2410 sg_dma_len(new_sg) = sg_dma_len(sg);
2412 new_sg = sg_next(new_sg);
2414 GEM_BUG_ON(new_sg); /* Should walk exactly nents and hit the end */
2416 sg_free_table(orig_st);
2422 static int i915_gem_object_get_pages_gtt(struct drm_i915_gem_object *obj)
2424 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
2425 const unsigned long page_count = obj->base.size / PAGE_SIZE;
2427 struct address_space *mapping;
2428 struct sg_table *st;
2429 struct scatterlist *sg;
2430 struct sgt_iter sgt_iter;
2432 unsigned long last_pfn = 0; /* suppress gcc warning */
2433 unsigned int max_segment = i915_sg_segment_size();
2434 unsigned int sg_page_sizes;
2435 struct pagevec pvec;
2440 * Assert that the object is not currently in any GPU domain. As it
2441 * wasn't in the GTT, there shouldn't be any way it could have been in
2444 GEM_BUG_ON(obj->read_domains & I915_GEM_GPU_DOMAINS);
2445 GEM_BUG_ON(obj->write_domain & I915_GEM_GPU_DOMAINS);
2448 * If there's no chance of allocating enough pages for the whole
2449 * object, bail early.
2451 if (page_count > totalram_pages())
2454 st = kmalloc(sizeof(*st), GFP_KERNEL);
2459 if (sg_alloc_table(st, page_count, GFP_KERNEL)) {
2465 * Get the list of pages out of our struct file. They'll be pinned
2466 * at this point until we release them.
2468 * Fail silently without starting the shrinker
2470 mapping = obj->base.filp->f_mapping;
2471 mapping_set_unevictable(mapping);
2472 noreclaim = mapping_gfp_constraint(mapping, ~__GFP_RECLAIM);
2473 noreclaim |= __GFP_NORETRY | __GFP_NOWARN;
2478 for (i = 0; i < page_count; i++) {
2479 const unsigned int shrink[] = {
2480 I915_SHRINK_BOUND | I915_SHRINK_UNBOUND | I915_SHRINK_PURGEABLE,
2483 gfp_t gfp = noreclaim;
2487 page = shmem_read_mapping_page_gfp(mapping, i, gfp);
2488 if (likely(!IS_ERR(page)))
2492 ret = PTR_ERR(page);
2496 i915_gem_shrink(dev_priv, 2 * page_count, NULL, *s++);
2499 * We've tried hard to allocate the memory by reaping
2500 * our own buffer, now let the real VM do its job and
2501 * go down in flames if truly OOM.
2503 * However, since graphics tend to be disposable,
2504 * defer the oom here by reporting the ENOMEM back
2508 /* reclaim and warn, but no oom */
2509 gfp = mapping_gfp_mask(mapping);
2512 * Our bo are always dirty and so we require
2513 * kswapd to reclaim our pages (direct reclaim
2514 * does not effectively begin pageout of our
2515 * buffers on its own). However, direct reclaim
2516 * only waits for kswapd when under allocation
2517 * congestion. So as a result __GFP_RECLAIM is
2518 * unreliable and fails to actually reclaim our
2519 * dirty pages -- unless you try over and over
2520 * again with !__GFP_NORETRY. However, we still
2521 * want to fail this allocation rather than
2522 * trigger the out-of-memory killer and for
2523 * this we want __GFP_RETRY_MAYFAIL.
2525 gfp |= __GFP_RETRY_MAYFAIL;
2530 sg->length >= max_segment ||
2531 page_to_pfn(page) != last_pfn + 1) {
2533 sg_page_sizes |= sg->length;
2537 sg_set_page(sg, page, PAGE_SIZE, 0);
2539 sg->length += PAGE_SIZE;
2541 last_pfn = page_to_pfn(page);
2543 /* Check that the i965g/gm workaround works. */
2544 WARN_ON((gfp & __GFP_DMA32) && (last_pfn >= 0x00100000UL));
2546 if (sg) { /* loop terminated early; short sg table */
2547 sg_page_sizes |= sg->length;
2551 /* Trim unused sg entries to avoid wasting memory. */
2554 ret = i915_gem_gtt_prepare_pages(obj, st);
2557 * DMA remapping failed? One possible cause is that
2558 * it could not reserve enough large entries, asking
2559 * for PAGE_SIZE chunks instead may be helpful.
2561 if (max_segment > PAGE_SIZE) {
2562 for_each_sgt_page(page, sgt_iter, st)
2566 max_segment = PAGE_SIZE;
2569 dev_warn(&dev_priv->drm.pdev->dev,
2570 "Failed to DMA remap %lu pages\n",
2576 if (i915_gem_object_needs_bit17_swizzle(obj))
2577 i915_gem_object_do_bit_17_swizzle(obj, st);
2579 __i915_gem_object_set_pages(obj, st, sg_page_sizes);
2586 mapping_clear_unevictable(mapping);
2587 pagevec_init(&pvec);
2588 for_each_sgt_page(page, sgt_iter, st) {
2589 if (!pagevec_add(&pvec, page))
2590 check_release_pagevec(&pvec);
2592 if (pagevec_count(&pvec))
2593 check_release_pagevec(&pvec);
2598 * shmemfs first checks if there is enough memory to allocate the page
2599 * and reports ENOSPC should there be insufficient, along with the usual
2600 * ENOMEM for a genuine allocation failure.
2602 * We use ENOSPC in our driver to mean that we have run out of aperture
2603 * space and so want to translate the error from shmemfs back to our
2604 * usual understanding of ENOMEM.
2612 void __i915_gem_object_set_pages(struct drm_i915_gem_object *obj,
2613 struct sg_table *pages,
2614 unsigned int sg_page_sizes)
2616 struct drm_i915_private *i915 = to_i915(obj->base.dev);
2617 unsigned long supported = INTEL_INFO(i915)->page_sizes;
2620 lockdep_assert_held(&obj->mm.lock);
2622 obj->mm.get_page.sg_pos = pages->sgl;
2623 obj->mm.get_page.sg_idx = 0;
2625 obj->mm.pages = pages;
2627 if (i915_gem_object_is_tiled(obj) &&
2628 i915->quirks & QUIRK_PIN_SWIZZLED_PAGES) {
2629 GEM_BUG_ON(obj->mm.quirked);
2630 __i915_gem_object_pin_pages(obj);
2631 obj->mm.quirked = true;
2634 GEM_BUG_ON(!sg_page_sizes);
2635 obj->mm.page_sizes.phys = sg_page_sizes;
2638 * Calculate the supported page-sizes which fit into the given
2639 * sg_page_sizes. This will give us the page-sizes which we may be able
2640 * to use opportunistically when later inserting into the GTT. For
2641 * example if phys=2G, then in theory we should be able to use 1G, 2M,
2642 * 64K or 4K pages, although in practice this will depend on a number of
2645 obj->mm.page_sizes.sg = 0;
2646 for_each_set_bit(i, &supported, ilog2(I915_GTT_MAX_PAGE_SIZE) + 1) {
2647 if (obj->mm.page_sizes.phys & ~0u << i)
2648 obj->mm.page_sizes.sg |= BIT(i);
2650 GEM_BUG_ON(!HAS_PAGE_SIZES(i915, obj->mm.page_sizes.sg));
2652 spin_lock(&i915->mm.obj_lock);
2653 list_add(&obj->mm.link, &i915->mm.unbound_list);
2654 spin_unlock(&i915->mm.obj_lock);
2657 static int ____i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
2661 if (unlikely(obj->mm.madv != I915_MADV_WILLNEED)) {
2662 DRM_DEBUG("Attempting to obtain a purgeable object\n");
2666 err = obj->ops->get_pages(obj);
2667 GEM_BUG_ON(!err && !i915_gem_object_has_pages(obj));
2672 /* Ensure that the associated pages are gathered from the backing storage
2673 * and pinned into our object. i915_gem_object_pin_pages() may be called
2674 * multiple times before they are released by a single call to
2675 * i915_gem_object_unpin_pages() - once the pages are no longer referenced
2676 * either as a result of memory pressure (reaping pages under the shrinker)
2677 * or as the object is itself released.
2679 int __i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
2683 err = mutex_lock_interruptible(&obj->mm.lock);
2687 if (unlikely(!i915_gem_object_has_pages(obj))) {
2688 GEM_BUG_ON(i915_gem_object_has_pinned_pages(obj));
2690 err = ____i915_gem_object_get_pages(obj);
2694 smp_mb__before_atomic();
2696 atomic_inc(&obj->mm.pages_pin_count);
2699 mutex_unlock(&obj->mm.lock);
2703 /* The 'mapping' part of i915_gem_object_pin_map() below */
2704 static void *i915_gem_object_map(const struct drm_i915_gem_object *obj,
2705 enum i915_map_type type)
2707 unsigned long n_pages = obj->base.size >> PAGE_SHIFT;
2708 struct sg_table *sgt = obj->mm.pages;
2709 struct sgt_iter sgt_iter;
2711 struct page *stack_pages[32];
2712 struct page **pages = stack_pages;
2713 unsigned long i = 0;
2717 /* A single page can always be kmapped */
2718 if (n_pages == 1 && type == I915_MAP_WB)
2719 return kmap(sg_page(sgt->sgl));
2721 if (n_pages > ARRAY_SIZE(stack_pages)) {
2722 /* Too big for stack -- allocate temporary array instead */
2723 pages = kvmalloc_array(n_pages, sizeof(*pages), GFP_KERNEL);
2728 for_each_sgt_page(page, sgt_iter, sgt)
2731 /* Check that we have the expected number of pages */
2732 GEM_BUG_ON(i != n_pages);
2737 /* fallthrough to use PAGE_KERNEL anyway */
2739 pgprot = PAGE_KERNEL;
2742 pgprot = pgprot_writecombine(PAGE_KERNEL_IO);
2745 addr = vmap(pages, n_pages, 0, pgprot);
2747 if (pages != stack_pages)
2753 /* get, pin, and map the pages of the object into kernel space */
2754 void *i915_gem_object_pin_map(struct drm_i915_gem_object *obj,
2755 enum i915_map_type type)
2757 enum i915_map_type has_type;
2762 if (unlikely(!i915_gem_object_has_struct_page(obj)))
2763 return ERR_PTR(-ENXIO);
2765 ret = mutex_lock_interruptible(&obj->mm.lock);
2767 return ERR_PTR(ret);
2769 pinned = !(type & I915_MAP_OVERRIDE);
2770 type &= ~I915_MAP_OVERRIDE;
2772 if (!atomic_inc_not_zero(&obj->mm.pages_pin_count)) {
2773 if (unlikely(!i915_gem_object_has_pages(obj))) {
2774 GEM_BUG_ON(i915_gem_object_has_pinned_pages(obj));
2776 ret = ____i915_gem_object_get_pages(obj);
2780 smp_mb__before_atomic();
2782 atomic_inc(&obj->mm.pages_pin_count);
2785 GEM_BUG_ON(!i915_gem_object_has_pages(obj));
2787 ptr = page_unpack_bits(obj->mm.mapping, &has_type);
2788 if (ptr && has_type != type) {
2794 if (is_vmalloc_addr(ptr))
2797 kunmap(kmap_to_page(ptr));
2799 ptr = obj->mm.mapping = NULL;
2803 ptr = i915_gem_object_map(obj, type);
2809 obj->mm.mapping = page_pack_bits(ptr, type);
2813 mutex_unlock(&obj->mm.lock);
2817 atomic_dec(&obj->mm.pages_pin_count);
2824 i915_gem_object_pwrite_gtt(struct drm_i915_gem_object *obj,
2825 const struct drm_i915_gem_pwrite *arg)
2827 struct address_space *mapping = obj->base.filp->f_mapping;
2828 char __user *user_data = u64_to_user_ptr(arg->data_ptr);
2832 /* Before we instantiate/pin the backing store for our use, we
2833 * can prepopulate the shmemfs filp efficiently using a write into
2834 * the pagecache. We avoid the penalty of instantiating all the
2835 * pages, important if the user is just writing to a few and never
2836 * uses the object on the GPU, and using a direct write into shmemfs
2837 * allows it to avoid the cost of retrieving a page (either swapin
2838 * or clearing-before-use) before it is overwritten.
2840 if (i915_gem_object_has_pages(obj))
2843 if (obj->mm.madv != I915_MADV_WILLNEED)
2846 /* Before the pages are instantiated the object is treated as being
2847 * in the CPU domain. The pages will be clflushed as required before
2848 * use, and we can freely write into the pages directly. If userspace
2849 * races pwrite with any other operation; corruption will ensue -
2850 * that is userspace's prerogative!
2854 offset = arg->offset;
2855 pg = offset_in_page(offset);
2858 unsigned int len, unwritten;
2863 len = PAGE_SIZE - pg;
2867 err = pagecache_write_begin(obj->base.filp, mapping,
2874 unwritten = copy_from_user(vaddr + pg, user_data, len);
2877 err = pagecache_write_end(obj->base.filp, mapping,
2878 offset, len, len - unwritten,
2895 static bool match_ring(struct i915_request *rq)
2897 struct drm_i915_private *dev_priv = rq->i915;
2898 u32 ring = I915_READ(RING_START(rq->engine->mmio_base));
2900 return ring == i915_ggtt_offset(rq->ring->vma);
2903 struct i915_request *
2904 i915_gem_find_active_request(struct intel_engine_cs *engine)
2906 struct i915_request *request, *active = NULL;
2907 unsigned long flags;
2910 * We are called by the error capture, reset and to dump engine
2911 * state at random points in time. In particular, note that neither is
2912 * crucially ordered with an interrupt. After a hang, the GPU is dead
2913 * and we assume that no more writes can happen (we waited long enough
2914 * for all writes that were in transaction to be flushed) - adding an
2915 * extra delay for a recent interrupt is pointless. Hence, we do
2916 * not need an engine->irq_seqno_barrier() before the seqno reads.
2917 * At all other times, we must assume the GPU is still running, but
2918 * we only care about the snapshot of this moment.
2920 spin_lock_irqsave(&engine->timeline.lock, flags);
2921 list_for_each_entry(request, &engine->timeline.requests, link) {
2922 if (i915_request_completed(request))
2925 if (!i915_request_started(request))
2928 /* More than one preemptible request may match! */
2929 if (!match_ring(request))
2935 spin_unlock_irqrestore(&engine->timeline.lock, flags);
2941 i915_gem_retire_work_handler(struct work_struct *work)
2943 struct drm_i915_private *dev_priv =
2944 container_of(work, typeof(*dev_priv), gt.retire_work.work);
2945 struct drm_device *dev = &dev_priv->drm;
2947 /* Come back later if the device is busy... */
2948 if (mutex_trylock(&dev->struct_mutex)) {
2949 i915_retire_requests(dev_priv);
2950 mutex_unlock(&dev->struct_mutex);
2954 * Keep the retire handler running until we are finally idle.
2955 * We do not need to do this test under locking as in the worst-case
2956 * we queue the retire worker once too often.
2958 if (READ_ONCE(dev_priv->gt.awake))
2959 queue_delayed_work(dev_priv->wq,
2960 &dev_priv->gt.retire_work,
2961 round_jiffies_up_relative(HZ));
2964 static void shrink_caches(struct drm_i915_private *i915)
2967 * kmem_cache_shrink() discards empty slabs and reorders partially
2968 * filled slabs to prioritise allocating from the mostly full slabs,
2969 * with the aim of reducing fragmentation.
2971 kmem_cache_shrink(i915->priorities);
2972 kmem_cache_shrink(i915->dependencies);
2973 kmem_cache_shrink(i915->requests);
2974 kmem_cache_shrink(i915->luts);
2975 kmem_cache_shrink(i915->vmas);
2976 kmem_cache_shrink(i915->objects);
2979 struct sleep_rcu_work {
2981 struct rcu_head rcu;
2982 struct work_struct work;
2984 struct drm_i915_private *i915;
2989 same_epoch(struct drm_i915_private *i915, unsigned int epoch)
2992 * There is a small chance that the epoch wrapped since we started
2993 * sleeping. If we assume that epoch is at least a u32, then it will
2994 * take at least 2^32 * 100ms for it to wrap, or about 326 years.
2996 return epoch == READ_ONCE(i915->gt.epoch);
2999 static void __sleep_work(struct work_struct *work)
3001 struct sleep_rcu_work *s = container_of(work, typeof(*s), work);
3002 struct drm_i915_private *i915 = s->i915;
3003 unsigned int epoch = s->epoch;
3006 if (same_epoch(i915, epoch))
3007 shrink_caches(i915);
3010 static void __sleep_rcu(struct rcu_head *rcu)
3012 struct sleep_rcu_work *s = container_of(rcu, typeof(*s), rcu);
3013 struct drm_i915_private *i915 = s->i915;
3015 destroy_rcu_head(&s->rcu);
3017 if (same_epoch(i915, s->epoch)) {
3018 INIT_WORK(&s->work, __sleep_work);
3019 queue_work(i915->wq, &s->work);
3026 new_requests_since_last_retire(const struct drm_i915_private *i915)
3028 return (READ_ONCE(i915->gt.active_requests) ||
3029 work_pending(&i915->gt.idle_work.work));
3032 static void assert_kernel_context_is_current(struct drm_i915_private *i915)
3034 struct intel_engine_cs *engine;
3035 enum intel_engine_id id;
3037 if (i915_terminally_wedged(&i915->gpu_error))
3040 GEM_BUG_ON(i915->gt.active_requests);
3041 for_each_engine(engine, i915, id) {
3042 GEM_BUG_ON(__i915_active_request_peek(&engine->timeline.last_request));
3043 GEM_BUG_ON(engine->last_retired_context !=
3044 to_intel_context(i915->kernel_context, engine));
3049 i915_gem_idle_work_handler(struct work_struct *work)
3051 struct drm_i915_private *dev_priv =
3052 container_of(work, typeof(*dev_priv), gt.idle_work.work);
3053 unsigned int epoch = I915_EPOCH_INVALID;
3054 bool rearm_hangcheck;
3056 if (!READ_ONCE(dev_priv->gt.awake))
3059 if (READ_ONCE(dev_priv->gt.active_requests))
3063 * Flush out the last user context, leaving only the pinned
3064 * kernel context resident. When we are idling on the kernel_context,
3065 * no more new requests (with a context switch) are emitted and we
3066 * can finally rest. A consequence is that the idle work handler is
3067 * always called at least twice before idling (and if the system is
3068 * idle that implies a round trip through the retire worker).
3070 mutex_lock(&dev_priv->drm.struct_mutex);
3071 i915_gem_switch_to_kernel_context(dev_priv);
3072 mutex_unlock(&dev_priv->drm.struct_mutex);
3074 GEM_TRACE("active_requests=%d (after switch-to-kernel-context)\n",
3075 READ_ONCE(dev_priv->gt.active_requests));
3078 * Wait for last execlists context complete, but bail out in case a
3079 * new request is submitted. As we don't trust the hardware, we
3080 * continue on if the wait times out. This is necessary to allow
3081 * the machine to suspend even if the hardware dies, and we will
3082 * try to recover in resume (after depriving the hardware of power,
3083 * it may be in a better mmod).
3085 __wait_for(if (new_requests_since_last_retire(dev_priv)) return,
3086 intel_engines_are_idle(dev_priv),
3087 I915_IDLE_ENGINES_TIMEOUT * 1000,
3091 cancel_delayed_work_sync(&dev_priv->gpu_error.hangcheck_work);
3093 if (!mutex_trylock(&dev_priv->drm.struct_mutex)) {
3094 /* Currently busy, come back later */
3095 mod_delayed_work(dev_priv->wq,
3096 &dev_priv->gt.idle_work,
3097 msecs_to_jiffies(50));
3102 * New request retired after this work handler started, extend active
3103 * period until next instance of the work.
3105 if (new_requests_since_last_retire(dev_priv))
3108 epoch = __i915_gem_park(dev_priv);
3110 assert_kernel_context_is_current(dev_priv);
3112 rearm_hangcheck = false;
3114 mutex_unlock(&dev_priv->drm.struct_mutex);
3117 if (rearm_hangcheck) {
3118 GEM_BUG_ON(!dev_priv->gt.awake);
3119 i915_queue_hangcheck(dev_priv);
3123 * When we are idle, it is an opportune time to reap our caches.
3124 * However, we have many objects that utilise RCU and the ordered
3125 * i915->wq that this work is executing on. To try and flush any
3126 * pending frees now we are idle, we first wait for an RCU grace
3127 * period, and then queue a task (that will run last on the wq) to
3128 * shrink and re-optimize the caches.
3130 if (same_epoch(dev_priv, epoch)) {
3131 struct sleep_rcu_work *s = kmalloc(sizeof(*s), GFP_KERNEL);
3133 init_rcu_head(&s->rcu);
3136 call_rcu(&s->rcu, __sleep_rcu);
3141 void i915_gem_close_object(struct drm_gem_object *gem, struct drm_file *file)
3143 struct drm_i915_private *i915 = to_i915(gem->dev);
3144 struct drm_i915_gem_object *obj = to_intel_bo(gem);
3145 struct drm_i915_file_private *fpriv = file->driver_priv;
3146 struct i915_lut_handle *lut, *ln;
3148 mutex_lock(&i915->drm.struct_mutex);
3150 list_for_each_entry_safe(lut, ln, &obj->lut_list, obj_link) {
3151 struct i915_gem_context *ctx = lut->ctx;
3152 struct i915_vma *vma;
3154 GEM_BUG_ON(ctx->file_priv == ERR_PTR(-EBADF));
3155 if (ctx->file_priv != fpriv)
3158 vma = radix_tree_delete(&ctx->handles_vma, lut->handle);
3159 GEM_BUG_ON(vma->obj != obj);
3161 /* We allow the process to have multiple handles to the same
3162 * vma, in the same fd namespace, by virtue of flink/open.
3164 GEM_BUG_ON(!vma->open_count);
3165 if (!--vma->open_count && !i915_vma_is_ggtt(vma))
3166 i915_vma_close(vma);
3168 list_del(&lut->obj_link);
3169 list_del(&lut->ctx_link);
3171 kmem_cache_free(i915->luts, lut);
3172 __i915_gem_object_release_unless_active(obj);
3175 mutex_unlock(&i915->drm.struct_mutex);
3178 static unsigned long to_wait_timeout(s64 timeout_ns)
3181 return MAX_SCHEDULE_TIMEOUT;
3183 if (timeout_ns == 0)
3186 return nsecs_to_jiffies_timeout(timeout_ns);
3190 * i915_gem_wait_ioctl - implements DRM_IOCTL_I915_GEM_WAIT
3191 * @dev: drm device pointer
3192 * @data: ioctl data blob
3193 * @file: drm file pointer
3195 * Returns 0 if successful, else an error is returned with the remaining time in
3196 * the timeout parameter.
3197 * -ETIME: object is still busy after timeout
3198 * -ERESTARTSYS: signal interrupted the wait
3199 * -ENONENT: object doesn't exist
3200 * Also possible, but rare:
3201 * -EAGAIN: incomplete, restart syscall
3203 * -ENODEV: Internal IRQ fail
3204 * -E?: The add request failed
3206 * The wait ioctl with a timeout of 0 reimplements the busy ioctl. With any
3207 * non-zero timeout parameter the wait ioctl will wait for the given number of
3208 * nanoseconds on an object becoming unbusy. Since the wait itself does so
3209 * without holding struct_mutex the object may become re-busied before this
3210 * function completes. A similar but shorter * race condition exists in the busy
3214 i915_gem_wait_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
3216 struct drm_i915_gem_wait *args = data;
3217 struct drm_i915_gem_object *obj;
3221 if (args->flags != 0)
3224 obj = i915_gem_object_lookup(file, args->bo_handle);
3228 start = ktime_get();
3230 ret = i915_gem_object_wait(obj,
3231 I915_WAIT_INTERRUPTIBLE |
3232 I915_WAIT_PRIORITY |
3234 to_wait_timeout(args->timeout_ns),
3235 to_rps_client(file));
3237 if (args->timeout_ns > 0) {
3238 args->timeout_ns -= ktime_to_ns(ktime_sub(ktime_get(), start));
3239 if (args->timeout_ns < 0)
3240 args->timeout_ns = 0;
3243 * Apparently ktime isn't accurate enough and occasionally has a
3244 * bit of mismatch in the jiffies<->nsecs<->ktime loop. So patch
3245 * things up to make the test happy. We allow up to 1 jiffy.
3247 * This is a regression from the timespec->ktime conversion.
3249 if (ret == -ETIME && !nsecs_to_jiffies(args->timeout_ns))
3250 args->timeout_ns = 0;
3252 /* Asked to wait beyond the jiffie/scheduler precision? */
3253 if (ret == -ETIME && args->timeout_ns)
3257 i915_gem_object_put(obj);
3261 static int wait_for_engines(struct drm_i915_private *i915)
3263 if (wait_for(intel_engines_are_idle(i915), I915_IDLE_ENGINES_TIMEOUT)) {
3264 dev_err(i915->drm.dev,
3265 "Failed to idle engines, declaring wedged!\n");
3267 i915_gem_set_wedged(i915);
3275 wait_for_timelines(struct drm_i915_private *i915,
3276 unsigned int flags, long timeout)
3278 struct i915_gt_timelines *gt = &i915->gt.timelines;
3279 struct i915_timeline *tl;
3281 if (!READ_ONCE(i915->gt.active_requests))
3284 mutex_lock(>->mutex);
3285 list_for_each_entry(tl, >->active_list, link) {
3286 struct i915_request *rq;
3288 rq = i915_active_request_get_unlocked(&tl->last_request);
3292 mutex_unlock(>->mutex);
3297 * Switching to the kernel context is often used a synchronous
3298 * step prior to idling, e.g. in suspend for flushing all
3299 * current operations to memory before sleeping. These we
3300 * want to complete as quickly as possible to avoid prolonged
3301 * stalls, so allow the gpu to boost to maximum clocks.
3303 if (flags & I915_WAIT_FOR_IDLE_BOOST)
3304 gen6_rps_boost(rq, NULL);
3306 timeout = i915_request_wait(rq, flags, timeout);
3307 i915_request_put(rq);
3311 /* restart after reacquiring the lock */
3312 mutex_lock(>->mutex);
3313 tl = list_entry(>->active_list, typeof(*tl), link);
3315 mutex_unlock(>->mutex);
3320 int i915_gem_wait_for_idle(struct drm_i915_private *i915,
3321 unsigned int flags, long timeout)
3323 GEM_TRACE("flags=%x (%s), timeout=%ld%s\n",
3324 flags, flags & I915_WAIT_LOCKED ? "locked" : "unlocked",
3325 timeout, timeout == MAX_SCHEDULE_TIMEOUT ? " (forever)" : "");
3327 /* If the device is asleep, we have no requests outstanding */
3328 if (!READ_ONCE(i915->gt.awake))
3331 timeout = wait_for_timelines(i915, flags, timeout);
3335 if (flags & I915_WAIT_LOCKED) {
3338 lockdep_assert_held(&i915->drm.struct_mutex);
3340 if (GEM_SHOW_DEBUG() && !timeout) {
3341 /* Presume that timeout was non-zero to begin with! */
3342 dev_warn(&i915->drm.pdev->dev,
3343 "Missed idle-completion interrupt!\n");
3347 err = wait_for_engines(i915);
3351 i915_retire_requests(i915);
3352 GEM_BUG_ON(i915->gt.active_requests);
3358 static void __i915_gem_object_flush_for_display(struct drm_i915_gem_object *obj)
3361 * We manually flush the CPU domain so that we can override and
3362 * force the flush for the display, and perform it asyncrhonously.
3364 flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
3365 if (obj->cache_dirty)
3366 i915_gem_clflush_object(obj, I915_CLFLUSH_FORCE);
3367 obj->write_domain = 0;
3370 void i915_gem_object_flush_if_display(struct drm_i915_gem_object *obj)
3372 if (!READ_ONCE(obj->pin_global))
3375 mutex_lock(&obj->base.dev->struct_mutex);
3376 __i915_gem_object_flush_for_display(obj);
3377 mutex_unlock(&obj->base.dev->struct_mutex);
3381 * Moves a single object to the WC read, and possibly write domain.
3382 * @obj: object to act on
3383 * @write: ask for write access or read only
3385 * This function returns when the move is complete, including waiting on
3389 i915_gem_object_set_to_wc_domain(struct drm_i915_gem_object *obj, bool write)
3393 lockdep_assert_held(&obj->base.dev->struct_mutex);
3395 ret = i915_gem_object_wait(obj,
3396 I915_WAIT_INTERRUPTIBLE |
3398 (write ? I915_WAIT_ALL : 0),
3399 MAX_SCHEDULE_TIMEOUT,
3404 if (obj->write_domain == I915_GEM_DOMAIN_WC)
3407 /* Flush and acquire obj->pages so that we are coherent through
3408 * direct access in memory with previous cached writes through
3409 * shmemfs and that our cache domain tracking remains valid.
3410 * For example, if the obj->filp was moved to swap without us
3411 * being notified and releasing the pages, we would mistakenly
3412 * continue to assume that the obj remained out of the CPU cached
3415 ret = i915_gem_object_pin_pages(obj);
3419 flush_write_domain(obj, ~I915_GEM_DOMAIN_WC);
3421 /* Serialise direct access to this object with the barriers for
3422 * coherent writes from the GPU, by effectively invalidating the
3423 * WC domain upon first access.
3425 if ((obj->read_domains & I915_GEM_DOMAIN_WC) == 0)
3428 /* It should now be out of any other write domains, and we can update
3429 * the domain values for our changes.
3431 GEM_BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_WC) != 0);
3432 obj->read_domains |= I915_GEM_DOMAIN_WC;
3434 obj->read_domains = I915_GEM_DOMAIN_WC;
3435 obj->write_domain = I915_GEM_DOMAIN_WC;
3436 obj->mm.dirty = true;
3439 i915_gem_object_unpin_pages(obj);
3444 * Moves a single object to the GTT read, and possibly write domain.
3445 * @obj: object to act on
3446 * @write: ask for write access or read only
3448 * This function returns when the move is complete, including waiting on
3452 i915_gem_object_set_to_gtt_domain(struct drm_i915_gem_object *obj, bool write)
3456 lockdep_assert_held(&obj->base.dev->struct_mutex);
3458 ret = i915_gem_object_wait(obj,
3459 I915_WAIT_INTERRUPTIBLE |
3461 (write ? I915_WAIT_ALL : 0),
3462 MAX_SCHEDULE_TIMEOUT,
3467 if (obj->write_domain == I915_GEM_DOMAIN_GTT)
3470 /* Flush and acquire obj->pages so that we are coherent through
3471 * direct access in memory with previous cached writes through
3472 * shmemfs and that our cache domain tracking remains valid.
3473 * For example, if the obj->filp was moved to swap without us
3474 * being notified and releasing the pages, we would mistakenly
3475 * continue to assume that the obj remained out of the CPU cached
3478 ret = i915_gem_object_pin_pages(obj);
3482 flush_write_domain(obj, ~I915_GEM_DOMAIN_GTT);
3484 /* Serialise direct access to this object with the barriers for
3485 * coherent writes from the GPU, by effectively invalidating the
3486 * GTT domain upon first access.
3488 if ((obj->read_domains & I915_GEM_DOMAIN_GTT) == 0)
3491 /* It should now be out of any other write domains, and we can update
3492 * the domain values for our changes.
3494 GEM_BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
3495 obj->read_domains |= I915_GEM_DOMAIN_GTT;
3497 obj->read_domains = I915_GEM_DOMAIN_GTT;
3498 obj->write_domain = I915_GEM_DOMAIN_GTT;
3499 obj->mm.dirty = true;
3502 i915_gem_object_unpin_pages(obj);
3507 * Changes the cache-level of an object across all VMA.
3508 * @obj: object to act on
3509 * @cache_level: new cache level to set for the object
3511 * After this function returns, the object will be in the new cache-level
3512 * across all GTT and the contents of the backing storage will be coherent,
3513 * with respect to the new cache-level. In order to keep the backing storage
3514 * coherent for all users, we only allow a single cache level to be set
3515 * globally on the object and prevent it from being changed whilst the
3516 * hardware is reading from the object. That is if the object is currently
3517 * on the scanout it will be set to uncached (or equivalent display
3518 * cache coherency) and all non-MOCS GPU access will also be uncached so
3519 * that all direct access to the scanout remains coherent.
3521 int i915_gem_object_set_cache_level(struct drm_i915_gem_object *obj,
3522 enum i915_cache_level cache_level)
3524 struct i915_vma *vma;
3527 lockdep_assert_held(&obj->base.dev->struct_mutex);
3529 if (obj->cache_level == cache_level)
3532 /* Inspect the list of currently bound VMA and unbind any that would
3533 * be invalid given the new cache-level. This is principally to
3534 * catch the issue of the CS prefetch crossing page boundaries and
3535 * reading an invalid PTE on older architectures.
3538 list_for_each_entry(vma, &obj->vma.list, obj_link) {
3539 if (!drm_mm_node_allocated(&vma->node))
3542 if (i915_vma_is_pinned(vma)) {
3543 DRM_DEBUG("can not change the cache level of pinned objects\n");
3547 if (!i915_vma_is_closed(vma) &&
3548 i915_gem_valid_gtt_space(vma, cache_level))
3551 ret = i915_vma_unbind(vma);
3555 /* As unbinding may affect other elements in the
3556 * obj->vma_list (due to side-effects from retiring
3557 * an active vma), play safe and restart the iterator.
3562 /* We can reuse the existing drm_mm nodes but need to change the
3563 * cache-level on the PTE. We could simply unbind them all and
3564 * rebind with the correct cache-level on next use. However since
3565 * we already have a valid slot, dma mapping, pages etc, we may as
3566 * rewrite the PTE in the belief that doing so tramples upon less
3567 * state and so involves less work.
3569 if (obj->bind_count) {
3570 /* Before we change the PTE, the GPU must not be accessing it.
3571 * If we wait upon the object, we know that all the bound
3572 * VMA are no longer active.
3574 ret = i915_gem_object_wait(obj,
3575 I915_WAIT_INTERRUPTIBLE |
3578 MAX_SCHEDULE_TIMEOUT,
3583 if (!HAS_LLC(to_i915(obj->base.dev)) &&
3584 cache_level != I915_CACHE_NONE) {
3585 /* Access to snoopable pages through the GTT is
3586 * incoherent and on some machines causes a hard
3587 * lockup. Relinquish the CPU mmaping to force
3588 * userspace to refault in the pages and we can
3589 * then double check if the GTT mapping is still
3590 * valid for that pointer access.
3592 i915_gem_release_mmap(obj);
3594 /* As we no longer need a fence for GTT access,
3595 * we can relinquish it now (and so prevent having
3596 * to steal a fence from someone else on the next
3597 * fence request). Note GPU activity would have
3598 * dropped the fence as all snoopable access is
3599 * supposed to be linear.
3601 for_each_ggtt_vma(vma, obj) {
3602 ret = i915_vma_put_fence(vma);
3607 /* We either have incoherent backing store and
3608 * so no GTT access or the architecture is fully
3609 * coherent. In such cases, existing GTT mmaps
3610 * ignore the cache bit in the PTE and we can
3611 * rewrite it without confusing the GPU or having
3612 * to force userspace to fault back in its mmaps.
3616 list_for_each_entry(vma, &obj->vma.list, obj_link) {
3617 if (!drm_mm_node_allocated(&vma->node))
3620 ret = i915_vma_bind(vma, cache_level, PIN_UPDATE);
3626 list_for_each_entry(vma, &obj->vma.list, obj_link)
3627 vma->node.color = cache_level;
3628 i915_gem_object_set_cache_coherency(obj, cache_level);
3629 obj->cache_dirty = true; /* Always invalidate stale cachelines */
3634 int i915_gem_get_caching_ioctl(struct drm_device *dev, void *data,
3635 struct drm_file *file)
3637 struct drm_i915_gem_caching *args = data;
3638 struct drm_i915_gem_object *obj;
3642 obj = i915_gem_object_lookup_rcu(file, args->handle);
3648 switch (obj->cache_level) {
3649 case I915_CACHE_LLC:
3650 case I915_CACHE_L3_LLC:
3651 args->caching = I915_CACHING_CACHED;
3655 args->caching = I915_CACHING_DISPLAY;
3659 args->caching = I915_CACHING_NONE;
3667 int i915_gem_set_caching_ioctl(struct drm_device *dev, void *data,
3668 struct drm_file *file)
3670 struct drm_i915_private *i915 = to_i915(dev);
3671 struct drm_i915_gem_caching *args = data;
3672 struct drm_i915_gem_object *obj;
3673 enum i915_cache_level level;
3676 switch (args->caching) {
3677 case I915_CACHING_NONE:
3678 level = I915_CACHE_NONE;
3680 case I915_CACHING_CACHED:
3682 * Due to a HW issue on BXT A stepping, GPU stores via a
3683 * snooped mapping may leave stale data in a corresponding CPU
3684 * cacheline, whereas normally such cachelines would get
3687 if (!HAS_LLC(i915) && !HAS_SNOOP(i915))
3690 level = I915_CACHE_LLC;
3692 case I915_CACHING_DISPLAY:
3693 level = HAS_WT(i915) ? I915_CACHE_WT : I915_CACHE_NONE;
3699 obj = i915_gem_object_lookup(file, args->handle);
3704 * The caching mode of proxy object is handled by its generator, and
3705 * not allowed to be changed by userspace.
3707 if (i915_gem_object_is_proxy(obj)) {
3712 if (obj->cache_level == level)
3715 ret = i915_gem_object_wait(obj,
3716 I915_WAIT_INTERRUPTIBLE,
3717 MAX_SCHEDULE_TIMEOUT,
3718 to_rps_client(file));
3722 ret = i915_mutex_lock_interruptible(dev);
3726 ret = i915_gem_object_set_cache_level(obj, level);
3727 mutex_unlock(&dev->struct_mutex);
3730 i915_gem_object_put(obj);
3735 * Prepare buffer for display plane (scanout, cursors, etc). Can be called from
3736 * an uninterruptible phase (modesetting) and allows any flushes to be pipelined
3737 * (for pageflips). We only flush the caches while preparing the buffer for
3738 * display, the callers are responsible for frontbuffer flush.
3741 i915_gem_object_pin_to_display_plane(struct drm_i915_gem_object *obj,
3743 const struct i915_ggtt_view *view,
3746 struct i915_vma *vma;
3749 lockdep_assert_held(&obj->base.dev->struct_mutex);
3751 /* Mark the global pin early so that we account for the
3752 * display coherency whilst setting up the cache domains.
3756 /* The display engine is not coherent with the LLC cache on gen6. As
3757 * a result, we make sure that the pinning that is about to occur is
3758 * done with uncached PTEs. This is lowest common denominator for all
3761 * However for gen6+, we could do better by using the GFDT bit instead
3762 * of uncaching, which would allow us to flush all the LLC-cached data
3763 * with that bit in the PTE to main memory with just one PIPE_CONTROL.
3765 ret = i915_gem_object_set_cache_level(obj,
3766 HAS_WT(to_i915(obj->base.dev)) ?
3767 I915_CACHE_WT : I915_CACHE_NONE);
3770 goto err_unpin_global;
3773 /* As the user may map the buffer once pinned in the display plane
3774 * (e.g. libkms for the bootup splash), we have to ensure that we
3775 * always use map_and_fenceable for all scanout buffers. However,
3776 * it may simply be too big to fit into mappable, in which case
3777 * put it anyway and hope that userspace can cope (but always first
3778 * try to preserve the existing ABI).
3780 vma = ERR_PTR(-ENOSPC);
3781 if ((flags & PIN_MAPPABLE) == 0 &&
3782 (!view || view->type == I915_GGTT_VIEW_NORMAL))
3783 vma = i915_gem_object_ggtt_pin(obj, view, 0, alignment,
3788 vma = i915_gem_object_ggtt_pin(obj, view, 0, alignment, flags);
3790 goto err_unpin_global;
3792 vma->display_alignment = max_t(u64, vma->display_alignment, alignment);
3794 __i915_gem_object_flush_for_display(obj);
3796 /* It should now be out of any other write domains, and we can update
3797 * the domain values for our changes.
3799 obj->read_domains |= I915_GEM_DOMAIN_GTT;
3809 i915_gem_object_unpin_from_display_plane(struct i915_vma *vma)
3811 lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
3813 if (WARN_ON(vma->obj->pin_global == 0))
3816 if (--vma->obj->pin_global == 0)
3817 vma->display_alignment = I915_GTT_MIN_ALIGNMENT;
3819 /* Bump the LRU to try and avoid premature eviction whilst flipping */
3820 i915_gem_object_bump_inactive_ggtt(vma->obj);
3822 i915_vma_unpin(vma);
3826 * Moves a single object to the CPU read, and possibly write domain.
3827 * @obj: object to act on
3828 * @write: requesting write or read-only access
3830 * This function returns when the move is complete, including waiting on
3834 i915_gem_object_set_to_cpu_domain(struct drm_i915_gem_object *obj, bool write)
3838 lockdep_assert_held(&obj->base.dev->struct_mutex);
3840 ret = i915_gem_object_wait(obj,
3841 I915_WAIT_INTERRUPTIBLE |
3843 (write ? I915_WAIT_ALL : 0),
3844 MAX_SCHEDULE_TIMEOUT,
3849 flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
3851 /* Flush the CPU cache if it's still invalid. */
3852 if ((obj->read_domains & I915_GEM_DOMAIN_CPU) == 0) {
3853 i915_gem_clflush_object(obj, I915_CLFLUSH_SYNC);
3854 obj->read_domains |= I915_GEM_DOMAIN_CPU;
3857 /* It should now be out of any other write domains, and we can update
3858 * the domain values for our changes.
3860 GEM_BUG_ON(obj->write_domain & ~I915_GEM_DOMAIN_CPU);
3862 /* If we're writing through the CPU, then the GPU read domains will
3863 * need to be invalidated at next use.
3866 __start_cpu_write(obj);
3871 /* Throttle our rendering by waiting until the ring has completed our requests
3872 * emitted over 20 msec ago.
3874 * Note that if we were to use the current jiffies each time around the loop,
3875 * we wouldn't escape the function with any frames outstanding if the time to
3876 * render a frame was over 20ms.
3878 * This should get us reasonable parallelism between CPU and GPU but also
3879 * relatively low latency when blocking on a particular request to finish.
3882 i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file)
3884 struct drm_i915_private *dev_priv = to_i915(dev);
3885 struct drm_i915_file_private *file_priv = file->driver_priv;
3886 unsigned long recent_enough = jiffies - DRM_I915_THROTTLE_JIFFIES;
3887 struct i915_request *request, *target = NULL;
3890 /* ABI: return -EIO if already wedged */
3891 if (i915_terminally_wedged(&dev_priv->gpu_error))
3894 spin_lock(&file_priv->mm.lock);
3895 list_for_each_entry(request, &file_priv->mm.request_list, client_link) {
3896 if (time_after_eq(request->emitted_jiffies, recent_enough))
3900 list_del(&target->client_link);
3901 target->file_priv = NULL;
3907 i915_request_get(target);
3908 spin_unlock(&file_priv->mm.lock);
3913 ret = i915_request_wait(target,
3914 I915_WAIT_INTERRUPTIBLE,
3915 MAX_SCHEDULE_TIMEOUT);
3916 i915_request_put(target);
3918 return ret < 0 ? ret : 0;
3922 i915_gem_object_ggtt_pin(struct drm_i915_gem_object *obj,
3923 const struct i915_ggtt_view *view,
3928 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
3929 struct i915_address_space *vm = &dev_priv->ggtt.vm;
3930 struct i915_vma *vma;
3933 lockdep_assert_held(&obj->base.dev->struct_mutex);
3935 if (flags & PIN_MAPPABLE &&
3936 (!view || view->type == I915_GGTT_VIEW_NORMAL)) {
3937 /* If the required space is larger than the available
3938 * aperture, we will not able to find a slot for the
3939 * object and unbinding the object now will be in
3940 * vain. Worse, doing so may cause us to ping-pong
3941 * the object in and out of the Global GTT and
3942 * waste a lot of cycles under the mutex.
3944 if (obj->base.size > dev_priv->ggtt.mappable_end)
3945 return ERR_PTR(-E2BIG);
3947 /* If NONBLOCK is set the caller is optimistically
3948 * trying to cache the full object within the mappable
3949 * aperture, and *must* have a fallback in place for
3950 * situations where we cannot bind the object. We
3951 * can be a little more lax here and use the fallback
3952 * more often to avoid costly migrations of ourselves
3953 * and other objects within the aperture.
3955 * Half-the-aperture is used as a simple heuristic.
3956 * More interesting would to do search for a free
3957 * block prior to making the commitment to unbind.
3958 * That caters for the self-harm case, and with a
3959 * little more heuristics (e.g. NOFAULT, NOEVICT)
3960 * we could try to minimise harm to others.
3962 if (flags & PIN_NONBLOCK &&
3963 obj->base.size > dev_priv->ggtt.mappable_end / 2)
3964 return ERR_PTR(-ENOSPC);
3967 vma = i915_vma_instance(obj, vm, view);
3968 if (unlikely(IS_ERR(vma)))
3971 if (i915_vma_misplaced(vma, size, alignment, flags)) {
3972 if (flags & PIN_NONBLOCK) {
3973 if (i915_vma_is_pinned(vma) || i915_vma_is_active(vma))
3974 return ERR_PTR(-ENOSPC);
3976 if (flags & PIN_MAPPABLE &&
3977 vma->fence_size > dev_priv->ggtt.mappable_end / 2)
3978 return ERR_PTR(-ENOSPC);
3981 WARN(i915_vma_is_pinned(vma),
3982 "bo is already pinned in ggtt with incorrect alignment:"
3983 " offset=%08x, req.alignment=%llx,"
3984 " req.map_and_fenceable=%d, vma->map_and_fenceable=%d\n",
3985 i915_ggtt_offset(vma), alignment,
3986 !!(flags & PIN_MAPPABLE),
3987 i915_vma_is_map_and_fenceable(vma));
3988 ret = i915_vma_unbind(vma);
3990 return ERR_PTR(ret);
3993 ret = i915_vma_pin(vma, size, alignment, flags | PIN_GLOBAL);
3995 return ERR_PTR(ret);
4000 static __always_inline unsigned int __busy_read_flag(unsigned int id)
4002 /* Note that we could alias engines in the execbuf API, but
4003 * that would be very unwise as it prevents userspace from
4004 * fine control over engine selection. Ahem.
4006 * This should be something like EXEC_MAX_ENGINE instead of
4009 BUILD_BUG_ON(I915_NUM_ENGINES > 16);
4010 return 0x10000 << id;
4013 static __always_inline unsigned int __busy_write_id(unsigned int id)
4015 /* The uABI guarantees an active writer is also amongst the read
4016 * engines. This would be true if we accessed the activity tracking
4017 * under the lock, but as we perform the lookup of the object and
4018 * its activity locklessly we can not guarantee that the last_write
4019 * being active implies that we have set the same engine flag from
4020 * last_read - hence we always set both read and write busy for
4023 return id | __busy_read_flag(id);
4026 static __always_inline unsigned int
4027 __busy_set_if_active(const struct dma_fence *fence,
4028 unsigned int (*flag)(unsigned int id))
4030 struct i915_request *rq;
4032 /* We have to check the current hw status of the fence as the uABI
4033 * guarantees forward progress. We could rely on the idle worker
4034 * to eventually flush us, but to minimise latency just ask the
4037 * Note we only report on the status of native fences.
4039 if (!dma_fence_is_i915(fence))
4042 /* opencode to_request() in order to avoid const warnings */
4043 rq = container_of(fence, struct i915_request, fence);
4044 if (i915_request_completed(rq))
4047 return flag(rq->engine->uabi_id);
4050 static __always_inline unsigned int
4051 busy_check_reader(const struct dma_fence *fence)
4053 return __busy_set_if_active(fence, __busy_read_flag);
4056 static __always_inline unsigned int
4057 busy_check_writer(const struct dma_fence *fence)
4062 return __busy_set_if_active(fence, __busy_write_id);
4066 i915_gem_busy_ioctl(struct drm_device *dev, void *data,
4067 struct drm_file *file)
4069 struct drm_i915_gem_busy *args = data;
4070 struct drm_i915_gem_object *obj;
4071 struct reservation_object_list *list;
4077 obj = i915_gem_object_lookup_rcu(file, args->handle);
4081 /* A discrepancy here is that we do not report the status of
4082 * non-i915 fences, i.e. even though we may report the object as idle,
4083 * a call to set-domain may still stall waiting for foreign rendering.
4084 * This also means that wait-ioctl may report an object as busy,
4085 * where busy-ioctl considers it idle.
4087 * We trade the ability to warn of foreign fences to report on which
4088 * i915 engines are active for the object.
4090 * Alternatively, we can trade that extra information on read/write
4093 * !reservation_object_test_signaled_rcu(obj->resv, true);
4094 * to report the overall busyness. This is what the wait-ioctl does.
4098 seq = raw_read_seqcount(&obj->resv->seq);
4100 /* Translate the exclusive fence to the READ *and* WRITE engine */
4101 args->busy = busy_check_writer(rcu_dereference(obj->resv->fence_excl));
4103 /* Translate shared fences to READ set of engines */
4104 list = rcu_dereference(obj->resv->fence);
4106 unsigned int shared_count = list->shared_count, i;
4108 for (i = 0; i < shared_count; ++i) {
4109 struct dma_fence *fence =
4110 rcu_dereference(list->shared[i]);
4112 args->busy |= busy_check_reader(fence);
4116 if (args->busy && read_seqcount_retry(&obj->resv->seq, seq))
4126 i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
4127 struct drm_file *file_priv)
4129 return i915_gem_ring_throttle(dev, file_priv);
4133 i915_gem_madvise_ioctl(struct drm_device *dev, void *data,
4134 struct drm_file *file_priv)
4136 struct drm_i915_private *dev_priv = to_i915(dev);
4137 struct drm_i915_gem_madvise *args = data;
4138 struct drm_i915_gem_object *obj;
4141 switch (args->madv) {
4142 case I915_MADV_DONTNEED:
4143 case I915_MADV_WILLNEED:
4149 obj = i915_gem_object_lookup(file_priv, args->handle);
4153 err = mutex_lock_interruptible(&obj->mm.lock);
4157 if (i915_gem_object_has_pages(obj) &&
4158 i915_gem_object_is_tiled(obj) &&
4159 dev_priv->quirks & QUIRK_PIN_SWIZZLED_PAGES) {
4160 if (obj->mm.madv == I915_MADV_WILLNEED) {
4161 GEM_BUG_ON(!obj->mm.quirked);
4162 __i915_gem_object_unpin_pages(obj);
4163 obj->mm.quirked = false;
4165 if (args->madv == I915_MADV_WILLNEED) {
4166 GEM_BUG_ON(obj->mm.quirked);
4167 __i915_gem_object_pin_pages(obj);
4168 obj->mm.quirked = true;
4172 if (obj->mm.madv != __I915_MADV_PURGED)
4173 obj->mm.madv = args->madv;
4175 /* if the object is no longer attached, discard its backing storage */
4176 if (obj->mm.madv == I915_MADV_DONTNEED &&
4177 !i915_gem_object_has_pages(obj))
4178 i915_gem_object_truncate(obj);
4180 args->retained = obj->mm.madv != __I915_MADV_PURGED;
4181 mutex_unlock(&obj->mm.lock);
4184 i915_gem_object_put(obj);
4189 frontbuffer_retire(struct i915_active_request *active,
4190 struct i915_request *request)
4192 struct drm_i915_gem_object *obj =
4193 container_of(active, typeof(*obj), frontbuffer_write);
4195 intel_fb_obj_flush(obj, ORIGIN_CS);
4198 void i915_gem_object_init(struct drm_i915_gem_object *obj,
4199 const struct drm_i915_gem_object_ops *ops)
4201 mutex_init(&obj->mm.lock);
4203 spin_lock_init(&obj->vma.lock);
4204 INIT_LIST_HEAD(&obj->vma.list);
4206 INIT_LIST_HEAD(&obj->lut_list);
4207 INIT_LIST_HEAD(&obj->batch_pool_link);
4209 init_rcu_head(&obj->rcu);
4213 reservation_object_init(&obj->__builtin_resv);
4214 obj->resv = &obj->__builtin_resv;
4216 obj->frontbuffer_ggtt_origin = ORIGIN_GTT;
4217 i915_active_request_init(&obj->frontbuffer_write,
4218 NULL, frontbuffer_retire);
4220 obj->mm.madv = I915_MADV_WILLNEED;
4221 INIT_RADIX_TREE(&obj->mm.get_page.radix, GFP_KERNEL | __GFP_NOWARN);
4222 mutex_init(&obj->mm.get_page.lock);
4224 i915_gem_info_add_obj(to_i915(obj->base.dev), obj->base.size);
4227 static const struct drm_i915_gem_object_ops i915_gem_object_ops = {
4228 .flags = I915_GEM_OBJECT_HAS_STRUCT_PAGE |
4229 I915_GEM_OBJECT_IS_SHRINKABLE,
4231 .get_pages = i915_gem_object_get_pages_gtt,
4232 .put_pages = i915_gem_object_put_pages_gtt,
4234 .pwrite = i915_gem_object_pwrite_gtt,
4237 static int i915_gem_object_create_shmem(struct drm_device *dev,
4238 struct drm_gem_object *obj,
4241 struct drm_i915_private *i915 = to_i915(dev);
4242 unsigned long flags = VM_NORESERVE;
4245 drm_gem_private_object_init(dev, obj, size);
4248 filp = shmem_file_setup_with_mnt(i915->mm.gemfs, "i915", size,
4251 filp = shmem_file_setup("i915", size, flags);
4254 return PTR_ERR(filp);
4261 struct drm_i915_gem_object *
4262 i915_gem_object_create(struct drm_i915_private *dev_priv, u64 size)
4264 struct drm_i915_gem_object *obj;
4265 struct address_space *mapping;
4266 unsigned int cache_level;
4270 /* There is a prevalence of the assumption that we fit the object's
4271 * page count inside a 32bit _signed_ variable. Let's document this and
4272 * catch if we ever need to fix it. In the meantime, if you do spot
4273 * such a local variable, please consider fixing!
4275 if (size >> PAGE_SHIFT > INT_MAX)
4276 return ERR_PTR(-E2BIG);
4278 if (overflows_type(size, obj->base.size))
4279 return ERR_PTR(-E2BIG);
4281 obj = i915_gem_object_alloc(dev_priv);
4283 return ERR_PTR(-ENOMEM);
4285 ret = i915_gem_object_create_shmem(&dev_priv->drm, &obj->base, size);
4289 mask = GFP_HIGHUSER | __GFP_RECLAIMABLE;
4290 if (IS_I965GM(dev_priv) || IS_I965G(dev_priv)) {
4291 /* 965gm cannot relocate objects above 4GiB. */
4292 mask &= ~__GFP_HIGHMEM;
4293 mask |= __GFP_DMA32;
4296 mapping = obj->base.filp->f_mapping;
4297 mapping_set_gfp_mask(mapping, mask);
4298 GEM_BUG_ON(!(mapping_gfp_mask(mapping) & __GFP_RECLAIM));
4300 i915_gem_object_init(obj, &i915_gem_object_ops);
4302 obj->write_domain = I915_GEM_DOMAIN_CPU;
4303 obj->read_domains = I915_GEM_DOMAIN_CPU;
4305 if (HAS_LLC(dev_priv))
4306 /* On some devices, we can have the GPU use the LLC (the CPU
4307 * cache) for about a 10% performance improvement
4308 * compared to uncached. Graphics requests other than
4309 * display scanout are coherent with the CPU in
4310 * accessing this cache. This means in this mode we
4311 * don't need to clflush on the CPU side, and on the
4312 * GPU side we only need to flush internal caches to
4313 * get data visible to the CPU.
4315 * However, we maintain the display planes as UC, and so
4316 * need to rebind when first used as such.
4318 cache_level = I915_CACHE_LLC;
4320 cache_level = I915_CACHE_NONE;
4322 i915_gem_object_set_cache_coherency(obj, cache_level);
4324 trace_i915_gem_object_create(obj);
4329 i915_gem_object_free(obj);
4330 return ERR_PTR(ret);
4333 static bool discard_backing_storage(struct drm_i915_gem_object *obj)
4335 /* If we are the last user of the backing storage (be it shmemfs
4336 * pages or stolen etc), we know that the pages are going to be
4337 * immediately released. In this case, we can then skip copying
4338 * back the contents from the GPU.
4341 if (obj->mm.madv != I915_MADV_WILLNEED)
4344 if (obj->base.filp == NULL)
4347 /* At first glance, this looks racy, but then again so would be
4348 * userspace racing mmap against close. However, the first external
4349 * reference to the filp can only be obtained through the
4350 * i915_gem_mmap_ioctl() which safeguards us against the user
4351 * acquiring such a reference whilst we are in the middle of
4352 * freeing the object.
4354 return atomic_long_read(&obj->base.filp->f_count) == 1;
4357 static void __i915_gem_free_objects(struct drm_i915_private *i915,
4358 struct llist_node *freed)
4360 struct drm_i915_gem_object *obj, *on;
4361 intel_wakeref_t wakeref;
4363 wakeref = intel_runtime_pm_get(i915);
4364 llist_for_each_entry_safe(obj, on, freed, freed) {
4365 struct i915_vma *vma, *vn;
4367 trace_i915_gem_object_destroy(obj);
4369 mutex_lock(&i915->drm.struct_mutex);
4371 GEM_BUG_ON(i915_gem_object_is_active(obj));
4372 list_for_each_entry_safe(vma, vn, &obj->vma.list, obj_link) {
4373 GEM_BUG_ON(i915_vma_is_active(vma));
4374 vma->flags &= ~I915_VMA_PIN_MASK;
4375 i915_vma_destroy(vma);
4377 GEM_BUG_ON(!list_empty(&obj->vma.list));
4378 GEM_BUG_ON(!RB_EMPTY_ROOT(&obj->vma.tree));
4380 /* This serializes freeing with the shrinker. Since the free
4381 * is delayed, first by RCU then by the workqueue, we want the
4382 * shrinker to be able to free pages of unreferenced objects,
4383 * or else we may oom whilst there are plenty of deferred
4386 if (i915_gem_object_has_pages(obj)) {
4387 spin_lock(&i915->mm.obj_lock);
4388 list_del_init(&obj->mm.link);
4389 spin_unlock(&i915->mm.obj_lock);
4392 mutex_unlock(&i915->drm.struct_mutex);
4394 GEM_BUG_ON(obj->bind_count);
4395 GEM_BUG_ON(obj->userfault_count);
4396 GEM_BUG_ON(atomic_read(&obj->frontbuffer_bits));
4397 GEM_BUG_ON(!list_empty(&obj->lut_list));
4399 if (obj->ops->release)
4400 obj->ops->release(obj);
4402 if (WARN_ON(i915_gem_object_has_pinned_pages(obj)))
4403 atomic_set(&obj->mm.pages_pin_count, 0);
4404 __i915_gem_object_put_pages(obj, I915_MM_NORMAL);
4405 GEM_BUG_ON(i915_gem_object_has_pages(obj));
4407 if (obj->base.import_attach)
4408 drm_prime_gem_destroy(&obj->base, NULL);
4410 reservation_object_fini(&obj->__builtin_resv);
4411 drm_gem_object_release(&obj->base);
4412 i915_gem_info_remove_obj(i915, obj->base.size);
4415 i915_gem_object_free(obj);
4417 GEM_BUG_ON(!atomic_read(&i915->mm.free_count));
4418 atomic_dec(&i915->mm.free_count);
4423 intel_runtime_pm_put(i915, wakeref);
4426 static void i915_gem_flush_free_objects(struct drm_i915_private *i915)
4428 struct llist_node *freed;
4430 /* Free the oldest, most stale object to keep the free_list short */
4432 if (!llist_empty(&i915->mm.free_list)) { /* quick test for hotpath */
4433 /* Only one consumer of llist_del_first() allowed */
4434 spin_lock(&i915->mm.free_lock);
4435 freed = llist_del_first(&i915->mm.free_list);
4436 spin_unlock(&i915->mm.free_lock);
4438 if (unlikely(freed)) {
4440 __i915_gem_free_objects(i915, freed);
4444 static void __i915_gem_free_work(struct work_struct *work)
4446 struct drm_i915_private *i915 =
4447 container_of(work, struct drm_i915_private, mm.free_work);
4448 struct llist_node *freed;
4451 * All file-owned VMA should have been released by this point through
4452 * i915_gem_close_object(), or earlier by i915_gem_context_close().
4453 * However, the object may also be bound into the global GTT (e.g.
4454 * older GPUs without per-process support, or for direct access through
4455 * the GTT either for the user or for scanout). Those VMA still need to
4459 spin_lock(&i915->mm.free_lock);
4460 while ((freed = llist_del_all(&i915->mm.free_list))) {
4461 spin_unlock(&i915->mm.free_lock);
4463 __i915_gem_free_objects(i915, freed);
4467 spin_lock(&i915->mm.free_lock);
4469 spin_unlock(&i915->mm.free_lock);
4472 static void __i915_gem_free_object_rcu(struct rcu_head *head)
4474 struct drm_i915_gem_object *obj =
4475 container_of(head, typeof(*obj), rcu);
4476 struct drm_i915_private *i915 = to_i915(obj->base.dev);
4479 * We reuse obj->rcu for the freed list, so we had better not treat
4480 * it like a rcu_head from this point forwards. And we expect all
4481 * objects to be freed via this path.
4483 destroy_rcu_head(&obj->rcu);
4486 * Since we require blocking on struct_mutex to unbind the freed
4487 * object from the GPU before releasing resources back to the
4488 * system, we can not do that directly from the RCU callback (which may
4489 * be a softirq context), but must instead then defer that work onto a
4490 * kthread. We use the RCU callback rather than move the freed object
4491 * directly onto the work queue so that we can mix between using the
4492 * worker and performing frees directly from subsequent allocations for
4493 * crude but effective memory throttling.
4495 if (llist_add(&obj->freed, &i915->mm.free_list))
4496 queue_work(i915->wq, &i915->mm.free_work);
4499 void i915_gem_free_object(struct drm_gem_object *gem_obj)
4501 struct drm_i915_gem_object *obj = to_intel_bo(gem_obj);
4503 if (obj->mm.quirked)
4504 __i915_gem_object_unpin_pages(obj);
4506 if (discard_backing_storage(obj))
4507 obj->mm.madv = I915_MADV_DONTNEED;
4510 * Before we free the object, make sure any pure RCU-only
4511 * read-side critical sections are complete, e.g.
4512 * i915_gem_busy_ioctl(). For the corresponding synchronized
4513 * lookup see i915_gem_object_lookup_rcu().
4515 atomic_inc(&to_i915(obj->base.dev)->mm.free_count);
4516 call_rcu(&obj->rcu, __i915_gem_free_object_rcu);
4519 void __i915_gem_object_release_unless_active(struct drm_i915_gem_object *obj)
4521 lockdep_assert_held(&obj->base.dev->struct_mutex);
4523 if (!i915_gem_object_has_active_reference(obj) &&
4524 i915_gem_object_is_active(obj))
4525 i915_gem_object_set_active_reference(obj);
4527 i915_gem_object_put(obj);
4530 void i915_gem_sanitize(struct drm_i915_private *i915)
4532 intel_wakeref_t wakeref;
4536 wakeref = intel_runtime_pm_get(i915);
4537 intel_uncore_forcewake_get(i915, FORCEWAKE_ALL);
4540 * As we have just resumed the machine and woken the device up from
4541 * deep PCI sleep (presumably D3_cold), assume the HW has been reset
4542 * back to defaults, recovering from whatever wedged state we left it
4543 * in and so worth trying to use the device once more.
4545 if (i915_terminally_wedged(&i915->gpu_error))
4546 i915_gem_unset_wedged(i915);
4549 * If we inherit context state from the BIOS or earlier occupants
4550 * of the GPU, the GPU may be in an inconsistent state when we
4551 * try to take over. The only way to remove the earlier state
4552 * is by resetting. However, resetting on earlier gen is tricky as
4553 * it may impact the display and we are uncertain about the stability
4554 * of the reset, so this could be applied to even earlier gen.
4556 intel_engines_sanitize(i915, false);
4558 intel_uncore_forcewake_put(i915, FORCEWAKE_ALL);
4559 intel_runtime_pm_put(i915, wakeref);
4561 mutex_lock(&i915->drm.struct_mutex);
4562 i915_gem_contexts_lost(i915);
4563 mutex_unlock(&i915->drm.struct_mutex);
4566 int i915_gem_suspend(struct drm_i915_private *i915)
4568 intel_wakeref_t wakeref;
4573 wakeref = intel_runtime_pm_get(i915);
4574 intel_suspend_gt_powersave(i915);
4576 flush_workqueue(i915->wq);
4578 mutex_lock(&i915->drm.struct_mutex);
4581 * We have to flush all the executing contexts to main memory so
4582 * that they can saved in the hibernation image. To ensure the last
4583 * context image is coherent, we have to switch away from it. That
4584 * leaves the i915->kernel_context still active when
4585 * we actually suspend, and its image in memory may not match the GPU
4586 * state. Fortunately, the kernel_context is disposable and we do
4587 * not rely on its state.
4589 if (!i915_terminally_wedged(&i915->gpu_error)) {
4590 ret = i915_gem_switch_to_kernel_context(i915);
4594 ret = i915_gem_wait_for_idle(i915,
4595 I915_WAIT_INTERRUPTIBLE |
4597 I915_WAIT_FOR_IDLE_BOOST,
4598 MAX_SCHEDULE_TIMEOUT);
4599 if (ret && ret != -EIO)
4602 assert_kernel_context_is_current(i915);
4604 i915_retire_requests(i915); /* ensure we flush after wedging */
4606 mutex_unlock(&i915->drm.struct_mutex);
4607 i915_reset_flush(i915);
4609 drain_delayed_work(&i915->gt.retire_work);
4612 * As the idle_work is rearming if it detects a race, play safe and
4613 * repeat the flush until it is definitely idle.
4615 drain_delayed_work(&i915->gt.idle_work);
4617 intel_uc_suspend(i915);
4620 * Assert that we successfully flushed all the work and
4621 * reset the GPU back to its idle, low power state.
4623 WARN_ON(i915->gt.awake);
4624 if (WARN_ON(!intel_engines_are_idle(i915)))
4625 i915_gem_set_wedged(i915); /* no hope, discard everything */
4627 intel_runtime_pm_put(i915, wakeref);
4631 mutex_unlock(&i915->drm.struct_mutex);
4632 intel_runtime_pm_put(i915, wakeref);
4636 void i915_gem_suspend_late(struct drm_i915_private *i915)
4638 struct drm_i915_gem_object *obj;
4639 struct list_head *phases[] = {
4640 &i915->mm.unbound_list,
4641 &i915->mm.bound_list,
4646 * Neither the BIOS, ourselves or any other kernel
4647 * expects the system to be in execlists mode on startup,
4648 * so we need to reset the GPU back to legacy mode. And the only
4649 * known way to disable logical contexts is through a GPU reset.
4651 * So in order to leave the system in a known default configuration,
4652 * always reset the GPU upon unload and suspend. Afterwards we then
4653 * clean up the GEM state tracking, flushing off the requests and
4654 * leaving the system in a known idle state.
4656 * Note that is of the upmost importance that the GPU is idle and
4657 * all stray writes are flushed *before* we dismantle the backing
4658 * storage for the pinned objects.
4660 * However, since we are uncertain that resetting the GPU on older
4661 * machines is a good idea, we don't - just in case it leaves the
4662 * machine in an unusable condition.
4665 mutex_lock(&i915->drm.struct_mutex);
4666 for (phase = phases; *phase; phase++) {
4667 list_for_each_entry(obj, *phase, mm.link)
4668 WARN_ON(i915_gem_object_set_to_gtt_domain(obj, false));
4670 mutex_unlock(&i915->drm.struct_mutex);
4672 intel_uc_sanitize(i915);
4673 i915_gem_sanitize(i915);
4676 void i915_gem_resume(struct drm_i915_private *i915)
4680 WARN_ON(i915->gt.awake);
4682 mutex_lock(&i915->drm.struct_mutex);
4683 intel_uncore_forcewake_get(i915, FORCEWAKE_ALL);
4685 i915_gem_restore_gtt_mappings(i915);
4686 i915_gem_restore_fences(i915);
4689 * As we didn't flush the kernel context before suspend, we cannot
4690 * guarantee that the context image is complete. So let's just reset
4691 * it and start again.
4693 i915->gt.resume(i915);
4695 if (i915_gem_init_hw(i915))
4698 intel_uc_resume(i915);
4700 /* Always reload a context for powersaving. */
4701 if (i915_gem_switch_to_kernel_context(i915))
4705 intel_uncore_forcewake_put(i915, FORCEWAKE_ALL);
4706 mutex_unlock(&i915->drm.struct_mutex);
4710 if (!i915_terminally_wedged(&i915->gpu_error)) {
4711 DRM_ERROR("failed to re-initialize GPU, declaring wedged!\n");
4712 i915_gem_set_wedged(i915);
4717 void i915_gem_init_swizzling(struct drm_i915_private *dev_priv)
4719 if (INTEL_GEN(dev_priv) < 5 ||
4720 dev_priv->mm.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_NONE)
4723 I915_WRITE(DISP_ARB_CTL, I915_READ(DISP_ARB_CTL) |
4724 DISP_TILE_SURFACE_SWIZZLING);
4726 if (IS_GEN(dev_priv, 5))
4729 I915_WRITE(TILECTL, I915_READ(TILECTL) | TILECTL_SWZCTL);
4730 if (IS_GEN(dev_priv, 6))
4731 I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_SNB));
4732 else if (IS_GEN(dev_priv, 7))
4733 I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_IVB));
4734 else if (IS_GEN(dev_priv, 8))
4735 I915_WRITE(GAMTARBMODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_BDW));
4740 static void init_unused_ring(struct drm_i915_private *dev_priv, u32 base)
4742 I915_WRITE(RING_CTL(base), 0);
4743 I915_WRITE(RING_HEAD(base), 0);
4744 I915_WRITE(RING_TAIL(base), 0);
4745 I915_WRITE(RING_START(base), 0);
4748 static void init_unused_rings(struct drm_i915_private *dev_priv)
4750 if (IS_I830(dev_priv)) {
4751 init_unused_ring(dev_priv, PRB1_BASE);
4752 init_unused_ring(dev_priv, SRB0_BASE);
4753 init_unused_ring(dev_priv, SRB1_BASE);
4754 init_unused_ring(dev_priv, SRB2_BASE);
4755 init_unused_ring(dev_priv, SRB3_BASE);
4756 } else if (IS_GEN(dev_priv, 2)) {
4757 init_unused_ring(dev_priv, SRB0_BASE);
4758 init_unused_ring(dev_priv, SRB1_BASE);
4759 } else if (IS_GEN(dev_priv, 3)) {
4760 init_unused_ring(dev_priv, PRB1_BASE);
4761 init_unused_ring(dev_priv, PRB2_BASE);
4765 static int __i915_gem_restart_engines(void *data)
4767 struct drm_i915_private *i915 = data;
4768 struct intel_engine_cs *engine;
4769 enum intel_engine_id id;
4772 for_each_engine(engine, i915, id) {
4773 err = engine->init_hw(engine);
4775 DRM_ERROR("Failed to restart %s (%d)\n",
4784 int i915_gem_init_hw(struct drm_i915_private *dev_priv)
4788 dev_priv->gt.last_init_time = ktime_get();
4790 /* Double layer security blanket, see i915_gem_init() */
4791 intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
4793 if (HAS_EDRAM(dev_priv) && INTEL_GEN(dev_priv) < 9)
4794 I915_WRITE(HSW_IDICR, I915_READ(HSW_IDICR) | IDIHASHMSK(0xf));
4796 if (IS_HASWELL(dev_priv))
4797 I915_WRITE(MI_PREDICATE_RESULT_2, IS_HSW_GT3(dev_priv) ?
4798 LOWER_SLICE_ENABLED : LOWER_SLICE_DISABLED);
4800 /* Apply the GT workarounds... */
4801 intel_gt_apply_workarounds(dev_priv);
4802 /* ...and determine whether they are sticking. */
4803 intel_gt_verify_workarounds(dev_priv, "init");
4805 i915_gem_init_swizzling(dev_priv);
4808 * At least 830 can leave some of the unused rings
4809 * "active" (ie. head != tail) after resume which
4810 * will prevent c3 entry. Makes sure all unused rings
4813 init_unused_rings(dev_priv);
4815 BUG_ON(!dev_priv->kernel_context);
4816 if (i915_terminally_wedged(&dev_priv->gpu_error)) {
4821 ret = i915_ppgtt_init_hw(dev_priv);
4823 DRM_ERROR("Enabling PPGTT failed (%d)\n", ret);
4827 ret = intel_wopcm_init_hw(&dev_priv->wopcm);
4829 DRM_ERROR("Enabling WOPCM failed (%d)\n", ret);
4833 /* We can't enable contexts until all firmware is loaded */
4834 ret = intel_uc_init_hw(dev_priv);
4836 DRM_ERROR("Enabling uc failed (%d)\n", ret);
4840 intel_mocs_init_l3cc_table(dev_priv);
4842 /* Only when the HW is re-initialised, can we replay the requests */
4843 ret = __i915_gem_restart_engines(dev_priv);
4847 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
4852 intel_uc_fini_hw(dev_priv);
4854 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
4859 static int __intel_engines_record_defaults(struct drm_i915_private *i915)
4861 struct i915_gem_context *ctx;
4862 struct intel_engine_cs *engine;
4863 enum intel_engine_id id;
4867 * As we reset the gpu during very early sanitisation, the current
4868 * register state on the GPU should reflect its defaults values.
4869 * We load a context onto the hw (with restore-inhibit), then switch
4870 * over to a second context to save that default register state. We
4871 * can then prime every new context with that state so they all start
4872 * from the same default HW values.
4875 ctx = i915_gem_context_create_kernel(i915, 0);
4877 return PTR_ERR(ctx);
4879 for_each_engine(engine, i915, id) {
4880 struct i915_request *rq;
4882 rq = i915_request_alloc(engine, ctx);
4889 if (engine->init_context)
4890 err = engine->init_context(rq);
4892 i915_request_add(rq);
4897 err = i915_gem_switch_to_kernel_context(i915);
4901 if (i915_gem_wait_for_idle(i915, I915_WAIT_LOCKED, HZ / 5)) {
4902 i915_gem_set_wedged(i915);
4903 err = -EIO; /* Caller will declare us wedged */
4907 assert_kernel_context_is_current(i915);
4910 * Immediately park the GPU so that we enable powersaving and
4911 * treat it as idle. The next time we issue a request, we will
4912 * unpark and start using the engine->pinned_default_state, otherwise
4913 * it is in limbo and an early reset may fail.
4915 __i915_gem_park(i915);
4917 for_each_engine(engine, i915, id) {
4918 struct i915_vma *state;
4921 GEM_BUG_ON(to_intel_context(ctx, engine)->pin_count);
4923 state = to_intel_context(ctx, engine)->state;
4928 * As we will hold a reference to the logical state, it will
4929 * not be torn down with the context, and importantly the
4930 * object will hold onto its vma (making it possible for a
4931 * stray GTT write to corrupt our defaults). Unmap the vma
4932 * from the GTT to prevent such accidents and reclaim the
4935 err = i915_vma_unbind(state);
4939 err = i915_gem_object_set_to_cpu_domain(state->obj, false);
4943 engine->default_state = i915_gem_object_get(state->obj);
4945 /* Check we can acquire the image of the context state */
4946 vaddr = i915_gem_object_pin_map(engine->default_state,
4948 if (IS_ERR(vaddr)) {
4949 err = PTR_ERR(vaddr);
4953 i915_gem_object_unpin_map(engine->default_state);
4956 if (IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM)) {
4957 unsigned int found = intel_engines_has_context_isolation(i915);
4960 * Make sure that classes with multiple engine instances all
4961 * share the same basic configuration.
4963 for_each_engine(engine, i915, id) {
4964 unsigned int bit = BIT(engine->uabi_class);
4965 unsigned int expected = engine->default_state ? bit : 0;
4967 if ((found & bit) != expected) {
4968 DRM_ERROR("mismatching default context state for class %d on engine %s\n",
4969 engine->uabi_class, engine->name);
4975 i915_gem_context_set_closed(ctx);
4976 i915_gem_context_put(ctx);
4981 * If we have to abandon now, we expect the engines to be idle
4982 * and ready to be torn-down. First try to flush any remaining
4983 * request, ensure we are pointing at the kernel context and
4986 if (WARN_ON(i915_gem_switch_to_kernel_context(i915)))
4989 if (WARN_ON(i915_gem_wait_for_idle(i915,
4991 MAX_SCHEDULE_TIMEOUT)))
4994 i915_gem_contexts_lost(i915);
4999 i915_gem_init_scratch(struct drm_i915_private *i915, unsigned int size)
5001 struct drm_i915_gem_object *obj;
5002 struct i915_vma *vma;
5005 obj = i915_gem_object_create_stolen(i915, size);
5007 obj = i915_gem_object_create_internal(i915, size);
5009 DRM_ERROR("Failed to allocate scratch page\n");
5010 return PTR_ERR(obj);
5013 vma = i915_vma_instance(obj, &i915->ggtt.vm, NULL);
5019 ret = i915_vma_pin(vma, 0, 0, PIN_GLOBAL | PIN_HIGH);
5023 i915->gt.scratch = vma;
5027 i915_gem_object_put(obj);
5031 static void i915_gem_fini_scratch(struct drm_i915_private *i915)
5033 i915_vma_unpin_and_release(&i915->gt.scratch, 0);
5036 int i915_gem_init(struct drm_i915_private *dev_priv)
5040 /* We need to fallback to 4K pages if host doesn't support huge gtt. */
5041 if (intel_vgpu_active(dev_priv) && !intel_vgpu_has_huge_gtt(dev_priv))
5042 mkwrite_device_info(dev_priv)->page_sizes =
5043 I915_GTT_PAGE_SIZE_4K;
5045 dev_priv->mm.unordered_timeline = dma_fence_context_alloc(1);
5047 if (HAS_LOGICAL_RING_CONTEXTS(dev_priv)) {
5048 dev_priv->gt.resume = intel_lr_context_resume;
5049 dev_priv->gt.cleanup_engine = intel_logical_ring_cleanup;
5051 dev_priv->gt.resume = intel_legacy_submission_resume;
5052 dev_priv->gt.cleanup_engine = intel_engine_cleanup;
5055 i915_timelines_init(dev_priv);
5057 ret = i915_gem_init_userptr(dev_priv);
5061 ret = intel_uc_init_misc(dev_priv);
5065 ret = intel_wopcm_init(&dev_priv->wopcm);
5069 /* This is just a security blanket to placate dragons.
5070 * On some systems, we very sporadically observe that the first TLBs
5071 * used by the CS may be stale, despite us poking the TLB reset. If
5072 * we hold the forcewake during initialisation these problems
5073 * just magically go away.
5075 mutex_lock(&dev_priv->drm.struct_mutex);
5076 intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
5078 ret = i915_gem_init_ggtt(dev_priv);
5080 GEM_BUG_ON(ret == -EIO);
5084 ret = i915_gem_init_scratch(dev_priv,
5085 IS_GEN(dev_priv, 2) ? SZ_256K : PAGE_SIZE);
5087 GEM_BUG_ON(ret == -EIO);
5091 ret = i915_gem_contexts_init(dev_priv);
5093 GEM_BUG_ON(ret == -EIO);
5097 ret = intel_engines_init(dev_priv);
5099 GEM_BUG_ON(ret == -EIO);
5103 intel_init_gt_powersave(dev_priv);
5105 ret = intel_uc_init(dev_priv);
5109 ret = i915_gem_init_hw(dev_priv);
5114 * Despite its name intel_init_clock_gating applies both display
5115 * clock gating workarounds; GT mmio workarounds and the occasional
5116 * GT power context workaround. Worse, sometimes it includes a context
5117 * register workaround which we need to apply before we record the
5118 * default HW state for all contexts.
5120 * FIXME: break up the workarounds and apply them at the right time!
5122 intel_init_clock_gating(dev_priv);
5124 ret = __intel_engines_record_defaults(dev_priv);
5128 if (i915_inject_load_failure()) {
5133 if (i915_inject_load_failure()) {
5138 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
5139 mutex_unlock(&dev_priv->drm.struct_mutex);
5144 * Unwinding is complicated by that we want to handle -EIO to mean
5145 * disable GPU submission but keep KMS alive. We want to mark the
5146 * HW as irrevisibly wedged, but keep enough state around that the
5147 * driver doesn't explode during runtime.
5150 mutex_unlock(&dev_priv->drm.struct_mutex);
5152 WARN_ON(i915_gem_suspend(dev_priv));
5153 i915_gem_suspend_late(dev_priv);
5155 i915_gem_drain_workqueue(dev_priv);
5157 mutex_lock(&dev_priv->drm.struct_mutex);
5158 intel_uc_fini_hw(dev_priv);
5160 intel_uc_fini(dev_priv);
5163 intel_cleanup_gt_powersave(dev_priv);
5164 i915_gem_cleanup_engines(dev_priv);
5168 i915_gem_contexts_fini(dev_priv);
5170 i915_gem_fini_scratch(dev_priv);
5173 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
5174 mutex_unlock(&dev_priv->drm.struct_mutex);
5177 intel_uc_fini_misc(dev_priv);
5180 i915_gem_cleanup_userptr(dev_priv);
5181 i915_timelines_fini(dev_priv);
5185 mutex_lock(&dev_priv->drm.struct_mutex);
5188 * Allow engine initialisation to fail by marking the GPU as
5189 * wedged. But we only want to do this where the GPU is angry,
5190 * for all other failure, such as an allocation failure, bail.
5192 if (!i915_terminally_wedged(&dev_priv->gpu_error)) {
5193 i915_load_error(dev_priv,
5194 "Failed to initialize GPU, declaring it wedged!\n");
5195 i915_gem_set_wedged(dev_priv);
5198 /* Minimal basic recovery for KMS */
5199 ret = i915_ggtt_enable_hw(dev_priv);
5200 i915_gem_restore_gtt_mappings(dev_priv);
5201 i915_gem_restore_fences(dev_priv);
5202 intel_init_clock_gating(dev_priv);
5204 mutex_unlock(&dev_priv->drm.struct_mutex);
5207 i915_gem_drain_freed_objects(dev_priv);
5211 void i915_gem_fini(struct drm_i915_private *dev_priv)
5213 i915_gem_suspend_late(dev_priv);
5214 intel_disable_gt_powersave(dev_priv);
5216 /* Flush any outstanding unpin_work. */
5217 i915_gem_drain_workqueue(dev_priv);
5219 mutex_lock(&dev_priv->drm.struct_mutex);
5220 intel_uc_fini_hw(dev_priv);
5221 intel_uc_fini(dev_priv);
5222 i915_gem_cleanup_engines(dev_priv);
5223 i915_gem_contexts_fini(dev_priv);
5224 i915_gem_fini_scratch(dev_priv);
5225 mutex_unlock(&dev_priv->drm.struct_mutex);
5227 intel_wa_list_free(&dev_priv->gt_wa_list);
5229 intel_cleanup_gt_powersave(dev_priv);
5231 intel_uc_fini_misc(dev_priv);
5232 i915_gem_cleanup_userptr(dev_priv);
5233 i915_timelines_fini(dev_priv);
5235 i915_gem_drain_freed_objects(dev_priv);
5237 WARN_ON(!list_empty(&dev_priv->contexts.list));
5240 void i915_gem_init_mmio(struct drm_i915_private *i915)
5242 i915_gem_sanitize(i915);
5246 i915_gem_cleanup_engines(struct drm_i915_private *dev_priv)
5248 struct intel_engine_cs *engine;
5249 enum intel_engine_id id;
5251 for_each_engine(engine, dev_priv, id)
5252 dev_priv->gt.cleanup_engine(engine);
5256 i915_gem_load_init_fences(struct drm_i915_private *dev_priv)
5260 if (INTEL_GEN(dev_priv) >= 7 && !IS_VALLEYVIEW(dev_priv) &&
5261 !IS_CHERRYVIEW(dev_priv))
5262 dev_priv->num_fence_regs = 32;
5263 else if (INTEL_GEN(dev_priv) >= 4 ||
5264 IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
5265 IS_G33(dev_priv) || IS_PINEVIEW(dev_priv))
5266 dev_priv->num_fence_regs = 16;
5268 dev_priv->num_fence_regs = 8;
5270 if (intel_vgpu_active(dev_priv))
5271 dev_priv->num_fence_regs =
5272 I915_READ(vgtif_reg(avail_rs.fence_num));
5274 /* Initialize fence registers to zero */
5275 for (i = 0; i < dev_priv->num_fence_regs; i++) {
5276 struct drm_i915_fence_reg *fence = &dev_priv->fence_regs[i];
5278 fence->i915 = dev_priv;
5280 list_add_tail(&fence->link, &dev_priv->mm.fence_list);
5282 i915_gem_restore_fences(dev_priv);
5284 i915_gem_detect_bit_6_swizzle(dev_priv);
5287 static void i915_gem_init__mm(struct drm_i915_private *i915)
5289 spin_lock_init(&i915->mm.object_stat_lock);
5290 spin_lock_init(&i915->mm.obj_lock);
5291 spin_lock_init(&i915->mm.free_lock);
5293 init_llist_head(&i915->mm.free_list);
5295 INIT_LIST_HEAD(&i915->mm.unbound_list);
5296 INIT_LIST_HEAD(&i915->mm.bound_list);
5297 INIT_LIST_HEAD(&i915->mm.fence_list);
5298 INIT_LIST_HEAD(&i915->mm.userfault_list);
5300 INIT_WORK(&i915->mm.free_work, __i915_gem_free_work);
5303 int i915_gem_init_early(struct drm_i915_private *dev_priv)
5307 dev_priv->objects = KMEM_CACHE(drm_i915_gem_object, SLAB_HWCACHE_ALIGN);
5308 if (!dev_priv->objects)
5311 dev_priv->vmas = KMEM_CACHE(i915_vma, SLAB_HWCACHE_ALIGN);
5312 if (!dev_priv->vmas)
5315 dev_priv->luts = KMEM_CACHE(i915_lut_handle, 0);
5316 if (!dev_priv->luts)
5319 dev_priv->requests = KMEM_CACHE(i915_request,
5320 SLAB_HWCACHE_ALIGN |
5321 SLAB_RECLAIM_ACCOUNT |
5322 SLAB_TYPESAFE_BY_RCU);
5323 if (!dev_priv->requests)
5326 dev_priv->dependencies = KMEM_CACHE(i915_dependency,
5327 SLAB_HWCACHE_ALIGN |
5328 SLAB_RECLAIM_ACCOUNT);
5329 if (!dev_priv->dependencies)
5332 dev_priv->priorities = KMEM_CACHE(i915_priolist, SLAB_HWCACHE_ALIGN);
5333 if (!dev_priv->priorities)
5334 goto err_dependencies;
5336 INIT_LIST_HEAD(&dev_priv->gt.active_rings);
5337 INIT_LIST_HEAD(&dev_priv->gt.closed_vma);
5339 i915_gem_init__mm(dev_priv);
5341 INIT_DELAYED_WORK(&dev_priv->gt.retire_work,
5342 i915_gem_retire_work_handler);
5343 INIT_DELAYED_WORK(&dev_priv->gt.idle_work,
5344 i915_gem_idle_work_handler);
5345 init_waitqueue_head(&dev_priv->gpu_error.wait_queue);
5346 init_waitqueue_head(&dev_priv->gpu_error.reset_queue);
5347 mutex_init(&dev_priv->gpu_error.wedge_mutex);
5349 atomic_set(&dev_priv->mm.bsd_engine_dispatch_index, 0);
5351 spin_lock_init(&dev_priv->fb_tracking.lock);
5353 err = i915_gemfs_init(dev_priv);
5355 DRM_NOTE("Unable to create a private tmpfs mount, hugepage support will be disabled(%d).\n", err);
5360 kmem_cache_destroy(dev_priv->dependencies);
5362 kmem_cache_destroy(dev_priv->requests);
5364 kmem_cache_destroy(dev_priv->luts);
5366 kmem_cache_destroy(dev_priv->vmas);
5368 kmem_cache_destroy(dev_priv->objects);
5373 void i915_gem_cleanup_early(struct drm_i915_private *dev_priv)
5375 i915_gem_drain_freed_objects(dev_priv);
5376 GEM_BUG_ON(!llist_empty(&dev_priv->mm.free_list));
5377 GEM_BUG_ON(atomic_read(&dev_priv->mm.free_count));
5378 WARN_ON(dev_priv->mm.object_count);
5380 kmem_cache_destroy(dev_priv->priorities);
5381 kmem_cache_destroy(dev_priv->dependencies);
5382 kmem_cache_destroy(dev_priv->requests);
5383 kmem_cache_destroy(dev_priv->luts);
5384 kmem_cache_destroy(dev_priv->vmas);
5385 kmem_cache_destroy(dev_priv->objects);
5387 /* And ensure that our DESTROY_BY_RCU slabs are truly destroyed */
5390 i915_gemfs_fini(dev_priv);
5393 int i915_gem_freeze(struct drm_i915_private *dev_priv)
5395 /* Discard all purgeable objects, let userspace recover those as
5396 * required after resuming.
5398 i915_gem_shrink_all(dev_priv);
5403 int i915_gem_freeze_late(struct drm_i915_private *i915)
5405 struct drm_i915_gem_object *obj;
5406 struct list_head *phases[] = {
5407 &i915->mm.unbound_list,
5408 &i915->mm.bound_list,
5413 * Called just before we write the hibernation image.
5415 * We need to update the domain tracking to reflect that the CPU
5416 * will be accessing all the pages to create and restore from the
5417 * hibernation, and so upon restoration those pages will be in the
5420 * To make sure the hibernation image contains the latest state,
5421 * we update that state just before writing out the image.
5423 * To try and reduce the hibernation image, we manually shrink
5424 * the objects as well, see i915_gem_freeze()
5427 i915_gem_shrink(i915, -1UL, NULL, I915_SHRINK_UNBOUND);
5428 i915_gem_drain_freed_objects(i915);
5430 mutex_lock(&i915->drm.struct_mutex);
5431 for (phase = phases; *phase; phase++) {
5432 list_for_each_entry(obj, *phase, mm.link)
5433 WARN_ON(i915_gem_object_set_to_cpu_domain(obj, true));
5435 mutex_unlock(&i915->drm.struct_mutex);
5440 void i915_gem_release(struct drm_device *dev, struct drm_file *file)
5442 struct drm_i915_file_private *file_priv = file->driver_priv;
5443 struct i915_request *request;
5445 /* Clean up our request list when the client is going away, so that
5446 * later retire_requests won't dereference our soon-to-be-gone
5449 spin_lock(&file_priv->mm.lock);
5450 list_for_each_entry(request, &file_priv->mm.request_list, client_link)
5451 request->file_priv = NULL;
5452 spin_unlock(&file_priv->mm.lock);
5455 int i915_gem_open(struct drm_i915_private *i915, struct drm_file *file)
5457 struct drm_i915_file_private *file_priv;
5462 file_priv = kzalloc(sizeof(*file_priv), GFP_KERNEL);
5466 file->driver_priv = file_priv;
5467 file_priv->dev_priv = i915;
5468 file_priv->file = file;
5470 spin_lock_init(&file_priv->mm.lock);
5471 INIT_LIST_HEAD(&file_priv->mm.request_list);
5473 file_priv->bsd_engine = -1;
5474 file_priv->hang_timestamp = jiffies;
5476 ret = i915_gem_context_open(i915, file);
5484 * i915_gem_track_fb - update frontbuffer tracking
5485 * @old: current GEM buffer for the frontbuffer slots
5486 * @new: new GEM buffer for the frontbuffer slots
5487 * @frontbuffer_bits: bitmask of frontbuffer slots
5489 * This updates the frontbuffer tracking bits @frontbuffer_bits by clearing them
5490 * from @old and setting them in @new. Both @old and @new can be NULL.
5492 void i915_gem_track_fb(struct drm_i915_gem_object *old,
5493 struct drm_i915_gem_object *new,
5494 unsigned frontbuffer_bits)
5496 /* Control of individual bits within the mask are guarded by
5497 * the owning plane->mutex, i.e. we can never see concurrent
5498 * manipulation of individual bits. But since the bitfield as a whole
5499 * is updated using RMW, we need to use atomics in order to update
5502 BUILD_BUG_ON(INTEL_FRONTBUFFER_BITS_PER_PIPE * I915_MAX_PIPES >
5503 BITS_PER_TYPE(atomic_t));
5506 WARN_ON(!(atomic_read(&old->frontbuffer_bits) & frontbuffer_bits));
5507 atomic_andnot(frontbuffer_bits, &old->frontbuffer_bits);
5511 WARN_ON(atomic_read(&new->frontbuffer_bits) & frontbuffer_bits);
5512 atomic_or(frontbuffer_bits, &new->frontbuffer_bits);
5516 /* Allocate a new GEM object and fill it with the supplied data */
5517 struct drm_i915_gem_object *
5518 i915_gem_object_create_from_data(struct drm_i915_private *dev_priv,
5519 const void *data, size_t size)
5521 struct drm_i915_gem_object *obj;
5526 obj = i915_gem_object_create(dev_priv, round_up(size, PAGE_SIZE));
5530 GEM_BUG_ON(obj->write_domain != I915_GEM_DOMAIN_CPU);
5532 file = obj->base.filp;
5535 unsigned int len = min_t(typeof(size), size, PAGE_SIZE);
5537 void *pgdata, *vaddr;
5539 err = pagecache_write_begin(file, file->f_mapping,
5546 memcpy(vaddr, data, len);
5549 err = pagecache_write_end(file, file->f_mapping,
5563 i915_gem_object_put(obj);
5564 return ERR_PTR(err);
5567 struct scatterlist *
5568 i915_gem_object_get_sg(struct drm_i915_gem_object *obj,
5570 unsigned int *offset)
5572 struct i915_gem_object_page_iter *iter = &obj->mm.get_page;
5573 struct scatterlist *sg;
5574 unsigned int idx, count;
5577 GEM_BUG_ON(n >= obj->base.size >> PAGE_SHIFT);
5578 GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
5580 /* As we iterate forward through the sg, we record each entry in a
5581 * radixtree for quick repeated (backwards) lookups. If we have seen
5582 * this index previously, we will have an entry for it.
5584 * Initial lookup is O(N), but this is amortized to O(1) for
5585 * sequential page access (where each new request is consecutive
5586 * to the previous one). Repeated lookups are O(lg(obj->base.size)),
5587 * i.e. O(1) with a large constant!
5589 if (n < READ_ONCE(iter->sg_idx))
5592 mutex_lock(&iter->lock);
5594 /* We prefer to reuse the last sg so that repeated lookup of this
5595 * (or the subsequent) sg are fast - comparing against the last
5596 * sg is faster than going through the radixtree.
5601 count = __sg_page_count(sg);
5603 while (idx + count <= n) {
5608 /* If we cannot allocate and insert this entry, or the
5609 * individual pages from this range, cancel updating the
5610 * sg_idx so that on this lookup we are forced to linearly
5611 * scan onwards, but on future lookups we will try the
5612 * insertion again (in which case we need to be careful of
5613 * the error return reporting that we have already inserted
5616 ret = radix_tree_insert(&iter->radix, idx, sg);
5617 if (ret && ret != -EEXIST)
5620 entry = xa_mk_value(idx);
5621 for (i = 1; i < count; i++) {
5622 ret = radix_tree_insert(&iter->radix, idx + i, entry);
5623 if (ret && ret != -EEXIST)
5628 sg = ____sg_next(sg);
5629 count = __sg_page_count(sg);
5636 mutex_unlock(&iter->lock);
5638 if (unlikely(n < idx)) /* insertion completed by another thread */
5641 /* In case we failed to insert the entry into the radixtree, we need
5642 * to look beyond the current sg.
5644 while (idx + count <= n) {
5646 sg = ____sg_next(sg);
5647 count = __sg_page_count(sg);
5656 sg = radix_tree_lookup(&iter->radix, n);
5659 /* If this index is in the middle of multi-page sg entry,
5660 * the radix tree will contain a value entry that points
5661 * to the start of that range. We will return the pointer to
5662 * the base page and the offset of this page within the
5666 if (unlikely(xa_is_value(sg))) {
5667 unsigned long base = xa_to_value(sg);
5669 sg = radix_tree_lookup(&iter->radix, base);
5681 i915_gem_object_get_page(struct drm_i915_gem_object *obj, unsigned int n)
5683 struct scatterlist *sg;
5684 unsigned int offset;
5686 GEM_BUG_ON(!i915_gem_object_has_struct_page(obj));
5688 sg = i915_gem_object_get_sg(obj, n, &offset);
5689 return nth_page(sg_page(sg), offset);
5692 /* Like i915_gem_object_get_page(), but mark the returned page dirty */
5694 i915_gem_object_get_dirty_page(struct drm_i915_gem_object *obj,
5699 page = i915_gem_object_get_page(obj, n);
5701 set_page_dirty(page);
5707 i915_gem_object_get_dma_address(struct drm_i915_gem_object *obj,
5710 struct scatterlist *sg;
5711 unsigned int offset;
5713 sg = i915_gem_object_get_sg(obj, n, &offset);
5714 return sg_dma_address(sg) + (offset << PAGE_SHIFT);
5717 int i915_gem_object_attach_phys(struct drm_i915_gem_object *obj, int align)
5719 struct sg_table *pages;
5722 if (align > obj->base.size)
5725 if (obj->ops == &i915_gem_phys_ops)
5728 if (obj->ops != &i915_gem_object_ops)
5731 err = i915_gem_object_unbind(obj);
5735 mutex_lock(&obj->mm.lock);
5737 if (obj->mm.madv != I915_MADV_WILLNEED) {
5742 if (obj->mm.quirked) {
5747 if (obj->mm.mapping) {
5752 pages = __i915_gem_object_unset_pages(obj);
5754 obj->ops = &i915_gem_phys_ops;
5756 err = ____i915_gem_object_get_pages(obj);
5760 /* Perma-pin (until release) the physical set of pages */
5761 __i915_gem_object_pin_pages(obj);
5763 if (!IS_ERR_OR_NULL(pages))
5764 i915_gem_object_ops.put_pages(obj, pages);
5765 mutex_unlock(&obj->mm.lock);
5769 obj->ops = &i915_gem_object_ops;
5770 if (!IS_ERR_OR_NULL(pages)) {
5771 unsigned int sg_page_sizes = i915_sg_page_sizes(pages->sgl);
5773 __i915_gem_object_set_pages(obj, pages, sg_page_sizes);
5776 mutex_unlock(&obj->mm.lock);
5780 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
5781 #include "selftests/scatterlist.c"
5782 #include "selftests/mock_gem_device.c"
5783 #include "selftests/huge_gem_object.c"
5784 #include "selftests/huge_pages.c"
5785 #include "selftests/i915_gem_object.c"
5786 #include "selftests/i915_gem_coherency.c"
5787 #include "selftests/i915_gem.c"